From 4b3ae6befeb1da74ba1bf531b533c5701d300ee0 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:20:22 +1300 Subject: [PATCH 1/9] feat(host): Cindy background service, phase 1 (personal migration M1) Adds the Node Host (apps/host) so ordinary local tasks can run without a desktop window and behave as they do on the desktop, using the shared desktop code that the desktop prep PR (#11535) extracted. This is the same change as #11536, carried as one commit. #11536 has 717 commits, more than the DCO app can read (it retrieves 250 and reports that it cannot evaluate the pull request), so the required DCO check could not pass there. All 629 non-merge commits in #11536 are signed off by their author; the 88 merge commits are exempt. The full commit history, review threads and per-commit verification remain on #11536 at 8874aafb219a15a093948a5adcc14130fbf1dcc7. The tree of this commit is identical to merging 8874aafb219a15a093948a5adcc14130fbf1dcc7 into main at 3af7adb40e68a49d5ad872ac7ebc7dc31c6c92e2. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- .github/workflows/ci.yml | 17 + .../workflows/macos-system-proxy-compare.yml | 122 + .../__tests__/authColdStartRecovery.test.ts | 268 +- .../__tests__/hostToolSlot.test.ts | 1 + .../hostDesktopSourceContracts.guard.test.ts | 927 ++- apps/host/cindy-host.service | 10 +- apps/host/package.json | 4 +- apps/host/scripts/build.mjs | 24 +- apps/host/scripts/check-e2e-imports.mjs | 108 + .../scripts/chromium-proxy-worker.e2e.mjs | 352 ++ apps/host/scripts/claude-proxy.e2e.mjs | 62 + apps/host/scripts/codex-runtime.e2e.mjs | 58 +- apps/host/scripts/electron-import-guard.mjs | 24 + apps/host/scripts/lifecycle.e2e.mjs | 16 +- .../scripts/macos-system-proxy-compare.mjs | 188 + .../scripts/macos-system-proxy-electron.cjs | 19 + .../scripts/macos-system-proxy-keychain.swift | 32 + .../scripts/macos-system-proxy-reference.mjs | 22 + apps/host/scripts/pi-native.e2e.mjs | 57 + apps/host/scripts/release-region.e2e.mjs | 106 + .../scripts/windows-system-proxy-compare.mjs | 117 + apps/host/src/agent/agent-deps-engines.ts | 111 + apps/host/src/agent/agent-skills.ts | 49 + apps/host/src/agent/auto-resume.ts | 209 + apps/host/src/agent/auto-review.ts | 38 +- apps/host/src/agent/codex-runtime.ts | 183 +- .../src/agent/codex-system-login.test.mjs | 525 +- apps/host/src/agent/codex-system-login.ts | 30 +- .../src/agent/context-recovery-assembly.ts | 64 +- .../host/src/agent/context-recovery-wiring.ts | 11 +- apps/host/src/agent/context-recovery.ts | 34 +- apps/host/src/agent/context-usage.ts | 28 + apps/host/src/agent/coordinator-deps.ts | 310 + apps/host/src/agent/create-runtime-session.ts | 54 + apps/host/src/agent/engine-deps.test.mjs | 160 + apps/host/src/agent/event-persistence.ts | 48 +- apps/host/src/agent/explicit-ports.ts | 30 + apps/host/src/agent/generated-images.ts | 113 + apps/host/src/agent/git-snapshot.test.mjs | 57 +- apps/host/src/agent/harness-binary.ts | 118 + apps/host/src/agent/held-credentials.ts | 59 + apps/host/src/agent/history.ts | 91 +- apps/host/src/agent/host-tools.ts | 54 +- apps/host/src/agent/idle-release.test.mjs | 212 + apps/host/src/agent/idle-release.ts | 120 + apps/host/src/agent/input-queue.mjs | 392 +- apps/host/src/agent/input-queue.test.mjs | 5414 ++++++++++++++++- apps/host/src/agent/interactions.mjs | 27 +- apps/host/src/agent/interactions.test.mjs | 20 + apps/host/src/agent/learn-send.test.mjs | 4 + apps/host/src/agent/mcp-runtime.ts | 7 +- apps/host/src/agent/memory-manager-ports.ts | 61 + apps/host/src/agent/memory-mcp-ports.ts | 133 + apps/host/src/agent/memory.mjs | 64 +- apps/host/src/agent/memory.test.mjs | 372 +- apps/host/src/agent/model-window-gate.ts | 79 - apps/host/src/agent/native-auth.test.mjs | 47 + .../src/agent/outbound-path-fact.test.mjs | 136 + apps/host/src/agent/owner-boundary.ts | 83 + apps/host/src/agent/pi-native-providers.ts | 4 +- apps/host/src/agent/product-turn.ts | 91 + .../src/agent/profile-coexistence.test.mjs | 169 + apps/host/src/agent/profile-coexistence.ts | 385 ++ apps/host/src/agent/provider-config.ts | 24 +- .../src/agent/provider-credentials.test.mjs | 158 + apps/host/src/agent/providers.mjs | 80 +- apps/host/src/agent/runtime-selection.ts | 1072 ++++ apps/host/src/agent/runtime.ts | 256 +- apps/host/src/agent/send-preflight.ts | 18 + apps/host/src/agent/session-activity.ts | 34 + apps/host/src/agent/session-move.ts | 119 + apps/host/src/agent/session-route-lock.mjs | 6 +- apps/host/src/agent/session-update.test.mjs | 1118 +++- apps/host/src/agent/session-update.ts | 342 +- apps/host/src/agent/shared-global-skills.ts | 54 + apps/host/src/agent/silent-stop.ts | 214 + .../src/agent/skill-projection-boundary.ts | 71 + apps/host/src/agent/skill-projection-owner.ts | 145 + apps/host/src/agent/start-options.ts | 2 + apps/host/src/agent/task-restore.ts | 87 + apps/host/src/agent/task-runtime-plugins.ts | 95 + apps/host/src/agent/touch-user-send.ts | 36 + apps/host/src/agent/turn-executor.mjs | 834 ++- apps/host/src/agent/turn-settlement.ts | 215 + apps/host/src/agent/usage-pricing.test.mjs | 309 + apps/host/src/agent/usage-pricing.ts | 53 + apps/host/src/agent/usage-push-channels.ts | 50 + apps/host/src/agent/usage-recording.test.mjs | 474 ++ apps/host/src/agent/usage-recording.ts | 346 ++ apps/host/src/agent/user-input.ts | 21 + apps/host/src/agent/working-directory.ts | 92 + apps/host/src/agent/xai-held-login.ts | 62 + apps/host/src/auth-state.ts | 5 + apps/host/src/auth/device-identity.test.mjs | 6 +- apps/host/src/auth/login.loopback.test.mjs | 130 + apps/host/src/auth/login.mjs | 51 +- apps/host/src/auth/refresh.mjs | 264 +- apps/host/src/auth/refresh.test.mjs | 260 +- apps/host/src/auth/region-policy.ts | 44 + apps/host/src/boundary.test.mjs | 537 +- apps/host/src/chat.interactions.test.mjs | 83 + apps/host/src/chat.mjs | 40 +- apps/host/src/chromium-proxy-worker.cjs | 88 + apps/host/src/chromium-proxy.test.mjs | 557 ++ apps/host/src/chromium-proxy.ts | 357 ++ apps/host/src/control.mjs | 5 + apps/host/src/credentials/native-codec.mjs | 16 +- apps/host/src/credentials/store.test.mjs | 36 + apps/host/src/desktop-module-setters.ts | 164 + apps/host/src/desktop-region-readers.ts | 33 + apps/host/src/device-link.test.mjs | 304 +- apps/host/src/device-link.ts | 230 +- apps/host/src/host-network-modules.ts | 78 + apps/host/src/host-tools.test.mjs | 140 +- apps/host/src/ipc-route.mjs | 12 +- apps/host/src/ipc-route.test.mjs | 20 + apps/host/src/loaders/raw-hook.mjs | 36 +- apps/host/src/loaders/raw-hook.test.mjs | 20 + apps/host/src/loaders/test-region.mjs | 7 + apps/host/src/login-cli.mjs | 92 +- apps/host/src/macos-system-proxy.test.mjs | 302 + apps/host/src/macos-system-proxy.ts | 613 ++ apps/host/src/main.ts | 1193 ++-- apps/host/src/message-store.ts | 33 +- apps/host/src/outbound-proxy.test.mjs | 77 + apps/host/src/outbound-proxy.ts | 119 + apps/host/src/outbound.d.mts | 4 +- apps/host/src/outbound.mjs | 16 +- apps/host/src/platform/assets.mjs | 6 +- apps/host/src/plugins.test.mjs | 110 +- apps/host/src/plugins/authorization.ts | 22 +- apps/host/src/plugins/chromium-sandbox.ts | 122 +- .../src/plugins/gateway-delivery.test.mjs | 115 + apps/host/src/plugins/gateway.ts | 15 +- apps/host/src/plugins/legacy-approvals.ts | 82 + apps/host/src/plugins/managed-skills.test.mjs | 169 +- apps/host/src/plugins/profile-pause.test.mjs | 549 ++ apps/host/src/plugins/runtime.ts | 268 +- apps/host/src/profile-path.mjs | 35 +- apps/host/src/profile-path.test.mjs | 29 + apps/host/src/project-icon.test.mjs | 60 + apps/host/src/project-icon.ts | 14 + apps/host/src/project-info.ts | 38 + apps/host/src/release-region.mjs | 66 + apps/host/src/release-region.test.mjs | 109 + apps/host/src/runtime-layout.mjs | 26 + apps/host/src/server-api.test.mjs | 28 + apps/host/src/server-api.ts | 5 +- apps/host/src/server.mjs | 60 +- apps/host/src/server.test.mjs | 207 +- apps/host/src/service.mjs | 67 +- apps/host/src/service.test.mjs | 109 + apps/host/src/sessions.test.mjs | 223 + apps/host/src/start-failure.ts | 49 + apps/host/src/startup-account.test.mjs | 786 ++- .../src/test-support/hook-plugin-fixture.mjs | 115 + .../test-support/hook-plugin-fixture.test.mjs | 47 + .../src/test-support/source-electron-tree.mjs | 41 + apps/host/src/typed-error.mjs | 54 + apps/host/src/ui-text.test.mjs | 22 + apps/host/src/ui-text.ts | 18 + apps/host/src/web-client-build.mjs | 11 + apps/host/src/web-shim.test.mjs | 125 + apps/web/analytics-region-guard.js | 86 + apps/web/shim.js | 95 +- .../host-web-adapter-experimental.md | 2 + docs/handoff/debian-a1-plan.md | 12 +- docs/host/README.md | 2 + docs/host/architecture-and-status.md | 4 +- docs/host/channel-coverage.md | 78 +- docs/host/client-handoff-foundation.md | 15 + docs/host/client-mode-account-switch.md | 547 ++ docs/host/feature-parity.md | 2 +- docs/host/owned-machine-verification.md | 296 + docs/host/personal-migration-release-table.md | 602 +- docs/host/systemd.md | 2 +- package.json | 2 +- .../host-agent-deps-contract.test.mjs | 22 +- .../host-server-hold-classification.test.mjs | 42 + .../host-skill-projection-owner.test.mjs | 47 + scripts/check-test-hygiene.mjs | 86 +- 181 files changed, 29115 insertions(+), 1718 deletions(-) create mode 100644 .github/workflows/macos-system-proxy-compare.yml create mode 100644 apps/host/scripts/check-e2e-imports.mjs create mode 100644 apps/host/scripts/chromium-proxy-worker.e2e.mjs create mode 100644 apps/host/scripts/electron-import-guard.mjs create mode 100644 apps/host/scripts/macos-system-proxy-compare.mjs create mode 100644 apps/host/scripts/macos-system-proxy-electron.cjs create mode 100644 apps/host/scripts/macos-system-proxy-keychain.swift create mode 100644 apps/host/scripts/macos-system-proxy-reference.mjs create mode 100644 apps/host/scripts/release-region.e2e.mjs create mode 100644 apps/host/scripts/windows-system-proxy-compare.mjs create mode 100644 apps/host/src/agent/agent-deps-engines.ts create mode 100644 apps/host/src/agent/agent-skills.ts create mode 100644 apps/host/src/agent/auto-resume.ts create mode 100644 apps/host/src/agent/context-usage.ts create mode 100644 apps/host/src/agent/coordinator-deps.ts create mode 100644 apps/host/src/agent/create-runtime-session.ts create mode 100644 apps/host/src/agent/explicit-ports.ts create mode 100644 apps/host/src/agent/generated-images.ts create mode 100644 apps/host/src/agent/harness-binary.ts create mode 100644 apps/host/src/agent/held-credentials.ts create mode 100644 apps/host/src/agent/idle-release.test.mjs create mode 100644 apps/host/src/agent/idle-release.ts create mode 100644 apps/host/src/agent/memory-manager-ports.ts create mode 100644 apps/host/src/agent/memory-mcp-ports.ts delete mode 100644 apps/host/src/agent/model-window-gate.ts create mode 100644 apps/host/src/agent/outbound-path-fact.test.mjs create mode 100644 apps/host/src/agent/owner-boundary.ts create mode 100644 apps/host/src/agent/product-turn.ts create mode 100644 apps/host/src/agent/profile-coexistence.test.mjs create mode 100644 apps/host/src/agent/profile-coexistence.ts create mode 100644 apps/host/src/agent/runtime-selection.ts create mode 100644 apps/host/src/agent/session-activity.ts create mode 100644 apps/host/src/agent/session-move.ts create mode 100644 apps/host/src/agent/shared-global-skills.ts create mode 100644 apps/host/src/agent/silent-stop.ts create mode 100644 apps/host/src/agent/skill-projection-boundary.ts create mode 100644 apps/host/src/agent/skill-projection-owner.ts create mode 100644 apps/host/src/agent/task-restore.ts create mode 100644 apps/host/src/agent/task-runtime-plugins.ts create mode 100644 apps/host/src/agent/touch-user-send.ts create mode 100644 apps/host/src/agent/turn-settlement.ts create mode 100644 apps/host/src/agent/usage-pricing.test.mjs create mode 100644 apps/host/src/agent/usage-pricing.ts create mode 100644 apps/host/src/agent/usage-push-channels.ts create mode 100644 apps/host/src/agent/usage-recording.test.mjs create mode 100644 apps/host/src/agent/usage-recording.ts create mode 100644 apps/host/src/agent/user-input.ts create mode 100644 apps/host/src/agent/working-directory.ts create mode 100644 apps/host/src/agent/xai-held-login.ts create mode 100644 apps/host/src/auth/region-policy.ts create mode 100644 apps/host/src/chromium-proxy-worker.cjs create mode 100644 apps/host/src/chromium-proxy.test.mjs create mode 100644 apps/host/src/chromium-proxy.ts create mode 100644 apps/host/src/desktop-module-setters.ts create mode 100644 apps/host/src/desktop-region-readers.ts create mode 100644 apps/host/src/host-network-modules.ts create mode 100644 apps/host/src/loaders/test-region.mjs create mode 100644 apps/host/src/macos-system-proxy.test.mjs create mode 100644 apps/host/src/macos-system-proxy.ts create mode 100644 apps/host/src/outbound-proxy.test.mjs create mode 100644 apps/host/src/outbound-proxy.ts create mode 100644 apps/host/src/plugins/gateway-delivery.test.mjs create mode 100644 apps/host/src/plugins/legacy-approvals.ts create mode 100644 apps/host/src/plugins/profile-pause.test.mjs create mode 100644 apps/host/src/project-icon.test.mjs create mode 100644 apps/host/src/project-icon.ts create mode 100644 apps/host/src/project-info.ts create mode 100644 apps/host/src/release-region.mjs create mode 100644 apps/host/src/release-region.test.mjs create mode 100644 apps/host/src/server-api.test.mjs create mode 100644 apps/host/src/service.test.mjs create mode 100644 apps/host/src/start-failure.ts create mode 100644 apps/host/src/test-support/hook-plugin-fixture.mjs create mode 100644 apps/host/src/test-support/hook-plugin-fixture.test.mjs create mode 100644 apps/host/src/test-support/source-electron-tree.mjs create mode 100644 apps/host/src/typed-error.mjs create mode 100644 apps/host/src/ui-text.test.mjs create mode 100644 apps/host/src/ui-text.ts create mode 100644 apps/web/analytics-region-guard.js create mode 100644 docs/host/client-mode-account-switch.md create mode 100644 docs/host/owned-machine-verification.md create mode 100644 scripts/__tests__/host-server-hold-classification.test.mjs create mode 100644 scripts/__tests__/host-skill-projection-owner.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 00826ee90d8..d99e85ddbb3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -312,6 +312,23 @@ jobs: run: pnpm install --frozen-lockfile - name: Run Host regressions run: pnpm --filter @cindy/host test + # Most acceptance scripts in apps/host/scripts need native engines or a browser and + # are not run here. Load each one's imports without running it, so a shared desktop + # module that starts importing Electron fails here rather than on the next manual run. + - name: Load Host acceptance scripts (imports only) + working-directory: apps/host + run: node scripts/check-e2e-imports.mjs + # These three need no engine, browser, account or network. + - name: Host acceptance - provider configuration + working-directory: apps/host + run: node --import tsx --import ./src/loaders/register-raw.mjs scripts/provider-config.e2e.mjs + - name: Host acceptance - IPC route + run: pnpm --filter @cindy/host test:ipc-route + # Not on Windows: stopping the background Host is refused there (ECONNREFUSED in the + # final stop), a recorded baseline gap (docs/host/personal-migration-release-table.md). + - name: Host acceptance - lifecycle + if: matrix.os != 'windows-latest' + run: pnpm --filter @cindy/host test:lifecycle # Types are platform independent: once is enough. A shared desktop body that # gains a port wired only in the desktop assembly passes the desktop checks # and fails here instead of at runtime in the Host. diff --git a/.github/workflows/macos-system-proxy-compare.yml b/.github/workflows/macos-system-proxy-compare.yml new file mode 100644 index 00000000000..6535455befe --- /dev/null +++ b/.github/workflows/macos-system-proxy-compare.yml @@ -0,0 +1,122 @@ +# System proxy comparison, macOS and Windows (docs/host/personal-migration-release-table.md, row 28, 28b and 28c). +# +# Compares the Host's outbound proxy answers with Electron's session.resolveProxy, under groups of settings the +# jobs set themselves: on macOS the static settings (apps/host/src/macos-system-proxy.ts) and, for PAC and +# auto-discovery, the Host's Chromium proxy helper (apps/host/src/chromium-proxy.ts); on Windows the helper for +# everything. Both jobs first run the helper's acceptance (apps/host/scripts/chromium-proxy-worker.e2e.mjs), which +# needs the Electron binary these jobs install; the macOS job then asserts that the helper, started the production +# way, added no keychain item ending in "Safe Storage". +# +# The jobs CHANGE THE RUNNER'S SYSTEM PROXY SETTINGS (networksetup with sudo; the current user's Internet +# Settings on Windows). They therefore run only on GitHub-hosted runners, which are discarded afterwards, and +# only when needed: started by hand, or for a pull request that changes this implementation (the paths below). +# Ordinary pull requests do not run them. An Electron upgrade reaches it through a guard test: CHROMIUM_RULES_ELECTRON_VERSION in +# macos-system-proxy.ts must equal the Electron version in apps/desktop/package.json, so the upgrade changes +# that file and this comparison runs on the upgrade's pull request. +# Never change system proxy settings on a development machine or your own computer to reproduce it; the +# scripts refuse to start anywhere but a GitHub-hosted runner. +name: System proxy comparison + +on: + workflow_dispatch: + pull_request: + paths: + - 'apps/host/src/macos-system-proxy.ts' + - 'apps/host/src/outbound-proxy.ts' + - 'apps/host/src/chromium-proxy.ts' + - 'apps/host/src/chromium-proxy-worker.cjs' + - 'apps/host/scripts/macos-system-proxy-*' + - 'apps/host/scripts/windows-system-proxy-compare.mjs' + - 'apps/host/scripts/chromium-proxy-worker.e2e.mjs' + - '.github/workflows/macos-system-proxy-compare.yml' + +permissions: + contents: read + +concurrency: + group: macos-system-proxy-compare-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + compare: + name: Host vs Electron system proxy results + runs-on: macos-15 + timeout-minutes: 30 + env: + XDT_SKIP_AGENT_BIN_INSTALL: '1' + steps: + - name: Checkout client + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Setup pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + with: + run_install: false + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + # With the Electron binary: the comparison runs the repository's Electron. + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Chromium proxy helper acceptance (loopback PAC; changes no settings) + working-directory: apps/host + run: node --import tsx --import ./src/loaders/register-raw.mjs scripts/chromium-proxy-worker.e2e.mjs + - name: Compare (changes this runner's system proxy settings, then restores them) + working-directory: apps/host + env: + CINDY_SYSTEM_PROXY_COMPARE: '1' + run: node --import tsx --import ./src/loaders/register-raw.mjs scripts/macos-system-proxy-compare.mjs "$RUNNER_TEMP/system-proxy-compare" + - name: Upload scutil samples and the report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: macos-system-proxy-compare + path: ${{ runner.temp }}/system-proxy-compare + if-no-files-found: warn + + compare-windows: + name: Host vs Electron system proxy results (Windows) + runs-on: windows-latest + timeout-minutes: 30 + env: + XDT_SKIP_AGENT_BIN_INSTALL: '1' + steps: + - name: Checkout client + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Setup pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + with: + run_install: false + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 22 + cache: pnpm + cache-dependency-path: pnpm-lock.yaml + # With the Electron binary: the helper and the comparison run the repository's Electron. + - name: Install dependencies + run: pnpm install --frozen-lockfile + - name: Chromium proxy helper acceptance (loopback PAC; changes no settings) + working-directory: apps/host + run: node --import tsx --import ./src/loaders/register-raw.mjs scripts/chromium-proxy-worker.e2e.mjs + - name: Compare (changes this runner's proxy settings, then restores them) + working-directory: apps/host + env: + CINDY_SYSTEM_PROXY_COMPARE: '1' + run: node --import tsx --import ./src/loaders/register-raw.mjs scripts/windows-system-proxy-compare.mjs "$env:RUNNER_TEMP/system-proxy-compare" + - name: Upload the report + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: windows-system-proxy-compare + path: ${{ runner.temp }}/system-proxy-compare + if-no-files-found: warn + - name: Upload Chromium proxy helper diagnostics + if: ${{ always() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: windows-chromium-proxy-helper-diagnostics + path: ${{ runner.temp }}/cindy-proxy-helper-logs-*/ + if-no-files-found: warn diff --git a/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts b/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts index 02a2258adf3..79ad61f9dc8 100644 --- a/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts +++ b/apps/desktop/src/main/__tests__/authColdStartRecovery.test.ts @@ -2,19 +2,37 @@ import { readFileSync } from 'node:fs'; import ts from 'typescript'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { AuthRefreshBackoff } from '../authRefreshBackoff'; -import { accountVaultKey, AuthApiError, retryAfterDeadline } from '@cindy/auth-client'; +import { + accountVaultKey, + AuthApiError, + parseAuthSessionRecord, + retryAfterDeadline, + serializeAuthSessionRecord, +} from '@cindy/auth-client'; import { runRefreshWithReplacementRetry } from '../authRefreshFailure'; -import { applyRefreshedCredentialsToVault } from '../authRefreshCommit'; +import { + applyRefreshedCredentialsToVault, + AUTH_ACCOUNT_VAULT_VERSION, + writeResourceSessionToVault, +} from '../authRefreshCommit'; +import { loggedOutAccountKeySet } from '../authAccountLogoutPolicy'; +import { reconcileSavedAccountMetadata } from '../authAccountMetadata'; +import { isDefinitiveRefreshError } from '../authRefreshError'; import { awaitWithStartupTimeout, resolveColdStartTimeoutRecovery, ColdStartAuthFallbackRegistry, commitColdStartRefreshIfCurrent, } from '../authStartupGate'; -import { loginPreparingErrorState, parseDesktopLoginAction } from '../../shared/authIpc'; +import { loginPreparingErrorState, parseDesktopAccountKey, parseDesktopLoginAction } from '../../shared/authIpc'; import { HOST_NOT_STARTED, readHostUnavailableReason } from '../../shared/hostStartFailure'; import { createIpcError } from '../../shared/ipc-errors'; import { accessTokenRefreshDelayMs } from '../authTokenClaims'; +import { + AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, + AUTH_ACCOUNT_VAULT_KEY, + AUTH_SESSION_KEY, +} from '../authCredentialKeys'; // Test value (unit): execute the production cold-start and login-action entrypoints with // in-memory credentials/network. On 2026-10-29 three DNS failures stranded a valid login; @@ -47,6 +65,12 @@ const names = new Set([ 'hostNotStartedInClientMode', 'dispatchLoginAction', 'enterLocalMode', + // The step of switchSavedAccount that renews a saved account from its vault copy. + 'refreshSavedResourceSession', + 'bindResourcePairToSavedAccount', + 'replaceResourceSessionIfCurrent', + 'removeRejectedResourceSession', + 'mutateAuthAccountVault', ]); const compiled = ts.transpileModule( ` @@ -104,6 +128,7 @@ return { vault.resources['["global","other"]'] = { realm: 'global', refreshToken: 'other-refresh' }; }, stop: stopColdStartRecovery, + renewSavedAccount: (input) => refreshSavedResourceSession({ ...input, expectedLoginFlowEpoch: loginFlowEpoch }), logoutForTest: () => { stopColdStartRecovery(); authStateEpoch++; saved.session = null; vault.resources = {}; vault.activeAccountKey = null; vault.signedOutAt = Date.now(); }, };`, @@ -145,6 +170,9 @@ function setup(random = 0) { transactAuthAccountVault: transaction, accountVaultKey, applyRefreshedCredentialsToVault, + writeResourceSessionToVault, + isDefinitiveRefreshError, + readAuthAccountVault: () => vault, readSafe: () => null, writePersistedAuthSessionOrThrow: (refreshToken: string, realm: string) => { saved.session = { version: 1, realm, refreshToken }; @@ -706,3 +734,237 @@ describe('delegated Host owner state', () => { expect(h.deps.commitVolatileAppSession).not.toHaveBeenCalled(); }); }); + +/* + * C (reviewer, 2026-11-17): a login the Host renewed, then used by this desktop on the same data. + * The Host renews with its production refreshHostSession (apps/host/src/auth/refresh.mjs) on the + * records this harness keeps: the v1 session (`saved.session`) and the account vault (`vault`). + * Reproduced on 2026-11-17 before the fix: the Host wrote only the v1 record, so the vault copy of + * the account stayed at the token the server had already rotated out. Scenario 1: switching back to + * that account loads it from the vault copy, which the server rejects, so the saved account is + * removed and the switch asks for a new sign-in. Scenario 2: the desktop's cold start reads v1 and + * recovered even then. Production entry for scenario 1: switchSavedAccount (authManager.ts) renews + * the account with refreshSavedResourceSession, run here as switchSavedAccount calls it; + * switchSavedAccount itself is not compiled into this harness (its completeLogin runs the owner + * commit, teardown and renderer), so this is the closest production entry. Unit; a fake auth server, + * no real account or store. + */ +describe('a login the Host renewed, then used by the desktop', () => { + // A non-literal specifier keeps the Host sources out of the desktop typecheck. + const hostRefreshModule = '../../../../host/src/auth/refresh.mjs'; + type RefreshHostSession = (deps: Record) => Promise; + let refreshHostSession: RefreshHostSession; + beforeEach(async () => { + ({ refreshHostSession } = (await import(/* @vite-ignore */ hostRefreshModule)) as { refreshHostSession: RefreshHostSession }); + vi.useFakeTimers(); + }); + afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); }); + + const membership = { id: 'original', kind: 'personal', role: 'owner', displayName: 'Fixture', email: null, + orgId: null, orgName: null, passportId: 'passport-original' }; + + /** One account server: only the latest refresh token works; each refresh rotates it. */ + function fakeServer() { + let current = 'test-refresh'; + let next = 0; + const rotate = (token: string) => { + if (token !== current) return null; + current = `rotated-${++next}`; + return { accessToken: `access-${next}`, refreshToken: current, membership }; + }; + return { + current: () => current, + desktop: async (token: string) => { + const pair = rotate(token); + return pair ? { ok: true, status: 200, data: pair } + : { ok: false, status: 401, data: { error: { code: 'INVALID_REFRESH_TOKEN', message: 'rotated' } } }; + }, + client: { + refresh: async (token: string) => { + const pair = rotate(token); + if (!pair) throw new AuthApiError('INVALID_REFRESH_TOKEN', 401, 'rotated'); + return pair; + }, + }, + }; + } + + /** The Host's production renewal over the records the harness keeps. */ + async function hostRenews(h: ReturnType, server: ReturnType, times: number) { + const store = { + read: (key: string) => { + if (key === AUTH_SESSION_KEY) return h.saved.session ? serializeAuthSessionRecord(h.saved.session.realm, h.saved.session.refreshToken) : null; + if (key === AUTH_ACCOUNT_VAULT_KEY) return JSON.stringify({ version: 1, passports: {}, ...h.vault }); + return null; + }, + write: (key: string, raw: string) => { + if (key === AUTH_SESSION_KEY) { + const record = parseAuthSessionRecord(raw)!; + h.saved.session = { version: 1, realm: record.realm, refreshToken: record.refreshToken }; + } else if (key === AUTH_ACCOUNT_VAULT_KEY) { + const next = JSON.parse(raw); + h.vault.activeAccountKey = next.activeAccountKey; + h.vault.resources = next.resources; + } else throw new Error(`unexpected Host write ${key}`); + }, + }; + for (let i = 0; i < times; i++) { + await refreshHostSession({ store, refresh: server.client.refresh, withVaultLock: (task: () => unknown) => task(), + buildRegion: 'global', sleep: async () => {} }); + } + } + + it('scenario 1: switching back to the account from its vault copy still works after Host renewals', async () => { + const server = fakeServer(); + const h = setup(); + await hostRenews(h, server, 3); + expect(h.vault.resources[ORIGINAL_KEY].refreshToken).toBe('rotated-3'); + const pair = await h.renewSavedAccount({ + client: server.client, accountKey: ORIGINAL_KEY, realm: 'global', + metadata: { membershipId: 'original', passportId: 'passport-original' }, + initialRefreshToken: h.vault.resources[ORIGINAL_KEY].refreshToken, + }); + expect(pair).toMatchObject({ refreshToken: 'rotated-4', membership: { id: 'original' } }); + expect(h.vault.resources[ORIGINAL_KEY].refreshToken).toBe('rotated-4'); + expect(server.current()).toBe('rotated-4'); + }); + + it('scenario 2: the desktop cold start after Host renewals finds v1 and the vault current', async () => { + const server = fakeServer(); + const h = setup(); + h.request.mockImplementation((token: unknown) => server.desktop(String(token))); + await hostRenews(h, server, 3); + expect([h.saved.session.refreshToken, h.vault.resources[ORIGINAL_KEY].refreshToken]).toEqual(['rotated-3', 'rotated-3']); + await expect(h.start()).resolves.toMatchObject({ isAuthenticated: true, user: { id: 'original' } }); + expect(h.request).toHaveBeenCalledTimes(1); + expect([h.saved.session.refreshToken, h.vault.resources[ORIGINAL_KEY].refreshToken]).toEqual(['rotated-4', 'rotated-4']); + }); + + // An account signed in only on the Host (`cindy-host login` writes only v1): the vault has no + // account. The cold start's commit may claim an uninitialized vault (canClaimUninitializedVault). + it('an account signed in only on the Host is taken over by the desktop cold start, which claims the empty vault', async () => { + const server = fakeServer(); + const h = setup(); + h.vault.activeAccountKey = null; + h.vault.resources = {}; + h.request.mockImplementation((token: unknown) => server.desktop(String(token))); + await hostRenews(h, server, 2); + expect(h.saved.session.refreshToken).toBe('rotated-2'); + expect(h.vault.resources).toEqual({}); + await expect(h.start()).resolves.toMatchObject({ isAuthenticated: true, user: { id: 'original' } }); + expect(h.vault.activeAccountKey).toBe(ORIGINAL_KEY); + expect([h.saved.session.refreshToken, h.vault.resources[ORIGINAL_KEY].refreshToken]).toEqual(['rotated-3', 'rotated-3']); + }); +}); + +/* + * C (reviewer, 2026-11-17): the saved-account vault after a Host renewal. The vault holds every + * saved account's credentials and the Host writes it with its own read and write (auth/refresh.mjs), + * so this is the riskiest write of the line. The vault and the logout tombstones are made and read + * back by the desktop's production functions (writePassportSessionToVault, writeAuthAccountVault, + * readAuthAccountVault, listSavedAccounts, compiled from authManager.ts); only the encrypted record + * store under them is an in-memory map, shared with the Host's store as the profile's + * safe-storage files are. Rule: apart from the renewed account's refreshToken, metadata and + * lastUsedAt, the vault stays byte for byte, and the tombstones are untouched. Gap: the Host tests + * use hand-written vaults. Minimal failure: writing back the normalized view drops a field the Host + * does not know. Unit; no real account or store. + */ +describe('the saved-account vault after a Host renewal', () => { + const hostRefreshModule = '../../../../host/src/auth/refresh.mjs'; + const vaultNames = new Set([ + 'readAuthAccountVault', 'readAuthAccountLogoutTombstones', 'writeAuthAccountVault', + 'writeAuthAccountLogoutTombstones', 'emptyAuthAccountVault', 'writePassportSessionToVault', + 'isStoredAccountMetadata', 'savedAccountSummaries', 'accountSummaryFromMetadata', 'listSavedAccounts', + 'metadataFromMembership', 'accountVaultKey', 'passportVaultKey', + ]); + const vaultParts = source.statements + .filter((node) => (ts.isFunctionDeclaration(node) && vaultNames.has(node.name?.text ?? '')) + || (ts.isVariableStatement(node) && node.declarationList.declarations + .some((d) => d.name.getText(source) === 'AUTH_ACCOUNT_LOGOUT_TOMBSTONES_VERSION'))) + .map((node) => node.getText(source).replace(/^export /, '')); + const vaultCompiled = ts.transpileModule(` +let currentUser = { id: 'member-a' }; +const activeAuthRealm = 'global'; +const isPassiveSharedUserDataInstance = () => false; +${vaultParts.join('\n')} +return { readAuthAccountVault, writeAuthAccountVault, emptyAuthAccountVault, writePassportSessionToVault, listSavedAccounts }; +`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText; + + const records = new Map(); + const desktop = new Function( + 'readAtomicSafe', 'isAtomicPersistedSecretAbsent', 'writeAtomicSafe', 'removeAtomicSafeOrThrow', + 'readAtomicSafeCiphertext', 'writeAtomicSafeCiphertext', 'logUnreadableEncryptedRecord', 'log', 'AuthApiError', + 'AUTH_ACCOUNT_VAULT_KEY', 'AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY', 'AUTH_ACCOUNT_VAULT_VERSION', + 'parseDesktopAccountKey', 'reconcileSavedAccountMetadata', 'loggedOutAccountKeySet', 'writeResourceSessionToVault', + vaultCompiled, + )( + (key: string) => records.get(key) ?? null, (key: string) => !records.has(key), + (key: string, value: string) => { records.set(key, value); return true; }, (key: string) => { records.delete(key); }, + () => null, () => false, () => undefined, { warn: () => undefined }, AuthApiError, + AUTH_ACCOUNT_VAULT_KEY, AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, AUTH_ACCOUNT_VAULT_VERSION, + parseDesktopAccountKey, reconcileSavedAccountMetadata, loggedOutAccountKeySet, writeResourceSessionToVault, + ); + + const member = (id: string, displayName: string) => ({ id, passportId: 'passport-1', kind: 'personal' as const, role: 'owner' as const, + displayName, email: `${id}@example.invalid`, avatarUrl: null, orgId: null, orgName: null, orgLogoUrl: null }); + const keyOf = (id: string) => accountVaultKey('global', id); + + it('keeps every other account, the passport, unknown fields and the tombstones byte for byte', async () => { + const { refreshHostSession } = (await import(/* @vite-ignore */ hostRefreshModule)) as { + refreshHostSession: (deps: Record) => Promise }; + records.clear(); + // Three accounts on one passport: A current, B saved, C logged out on this device. + const vault = desktop.emptyAuthAccountVault(); + vault.loggedOutAccountKeys = [keyOf('member-c')]; + writeResourceSessionToVault(vault, { accessToken: 'a', refreshToken: 'a-token', membership: member('member-a', 'A') }, + 'global', 'passport-1', { lastUsedAt: 200 }); + writeResourceSessionToVault(vault, { accessToken: 'b', refreshToken: 'b-token', membership: member('member-b', 'B') }, + 'global', 'passport-1', { markActive: false, lastUsedAt: 100 }); + desktop.writePassportSessionToVault(vault, { realm: 'global', passportId: 'passport-1', accountRefreshToken: 'passport-token', + memberships: [member('member-a', 'A'), member('member-b', 'B'), member('member-c', 'C')] }); + expect(desktop.writeAuthAccountVault(vault)).toBe(true); + // Fields a later desktop may add: one at the top level, one in a saved account. + const written = JSON.parse(records.get(AUTH_ACCOUNT_VAULT_KEY)!); + written.laterTopLevelField = { kept: true }; + written.resources[keyOf('member-b')].laterResourceField = 'kept'; + records.set(AUTH_ACCOUNT_VAULT_KEY, JSON.stringify(written)); + records.set(AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'a-token')); + const vaultBefore = records.get(AUTH_ACCOUNT_VAULT_KEY)!; + const tombstonesBefore = records.get(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY); + expect(JSON.parse(tombstonesBefore!).accountKeys).toEqual([keyOf('member-c')]); + const accountsBefore = desktop.listSavedAccounts().accounts; + expect(accountsBefore.map((account: { accountKey: string }) => account.accountKey)).toEqual([keyOf('member-a'), keyOf('member-b')]); + + await refreshHostSession({ + store: { read: (key: string) => records.get(key) ?? null, write: (key: string, value: string) => records.set(key, value) }, + refresh: async (token: string) => { + expect(token).toBe('a-token'); + return { accessToken: 'access', refreshToken: 'a-rotated', membership: { ...member('member-a', 'A renamed') } }; + }, + withVaultLock: (task: () => unknown) => task(), buildRegion: 'global', + }); + + const after = JSON.parse(records.get(AUTH_ACCOUNT_VAULT_KEY)!); + const renewed = after.resources[keyOf('member-a')]; + expect(renewed.refreshToken).toBe('a-rotated'); + expect(renewed.metadata.displayName).toBe('A renamed'); + // Everything else, byte for byte: the vault before with only those three fields replaced. + const expected = JSON.parse(vaultBefore); + Object.assign(expected.resources[keyOf('member-a')], + { refreshToken: renewed.refreshToken, metadata: renewed.metadata, lastUsedAt: renewed.lastUsedAt }); + expect(records.get(AUTH_ACCOUNT_VAULT_KEY)).toBe(JSON.stringify(expected)); + expect(after.laterTopLevelField).toEqual({ kept: true }); + expect(after.resources[keyOf('member-b')]).toMatchObject({ refreshToken: 'b-token', laterResourceField: 'kept' }); + expect(Object.values(after.passports)).toMatchObject([{ accountRefreshToken: 'passport-token' }]); + expect(records.get(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY)).toBe(tombstonesBefore); + + // Read back by the desktop: the same accounts, the current one with the new token. + const readBack = desktop.readAuthAccountVault(); + expect(readBack.activeAccountKey).toBe(keyOf('member-a')); + expect(readBack.resources[keyOf('member-a')].refreshToken).toBe('a-rotated'); + expect(readBack.loggedOutAccountKeys).toEqual([keyOf('member-c')]); + expect(desktop.listSavedAccounts().accounts.map((account: { accountKey: string; isCurrent: boolean }) => + [account.accountKey, account.isCurrent])).toEqual(accountsBefore.map((account: { accountKey: string; isCurrent: boolean }) => + [account.accountKey, account.isCurrent])); + }); +}); diff --git a/apps/desktop/src/main/cindy-brain/__tests__/hostToolSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/hostToolSlot.test.ts index 27fc457185b..927cf2e25b3 100644 --- a/apps/desktop/src/main/cindy-brain/__tests__/hostToolSlot.test.ts +++ b/apps/desktop/src/main/cindy-brain/__tests__/hostToolSlot.test.ts @@ -297,6 +297,7 @@ describe('plugin Host tool entry', () => { GhostRuntime, sandbox: { adapter: deps.electronSandboxAdapter }, log: deps.log, network: { disposeGhost: noop }, fsSlot: { disposePlugin: noop }, options: { publish: noop, onPluginStopped: disposePluginHostTools }, dispatcher: { onRuntimeState: noop }, + profileHoldMessage: () => null, desktopPause: null, closed: false, publish: noop, }).runtime; const ghost = fixture().ghost; try { diff --git a/apps/desktop/src/main/maker-host/__tests__/hostDesktopSourceContracts.guard.test.ts b/apps/desktop/src/main/maker-host/__tests__/hostDesktopSourceContracts.guard.test.ts index b5ead3d091e..d485a3cf2fd 100644 --- a/apps/desktop/src/main/maker-host/__tests__/hostDesktopSourceContracts.guard.test.ts +++ b/apps/desktop/src/main/maker-host/__tests__/hostDesktopSourceContracts.guard.test.ts @@ -9,8 +9,13 @@ * 上同一任务的行为悄悄分叉,对照测试与放行表的“已对齐”结论随之失效。 */ import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; import fs from 'node:fs'; +import { createRequire, isBuiltin } from 'node:module'; +import os from 'node:os'; import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { build } from 'esbuild'; import ts from 'typescript'; import { describe, expect, it } from 'vitest'; @@ -47,6 +52,17 @@ function call(source: string, start: string): string { } describe('Host main.ts wiring', () => { + // 放行表第 33 项:两端必须共享同一个裁决、超时和熔断工厂。行为测试能证明单个输入的 + // 结果相同,不能隔离“另一端改用独立工厂”的结构变化。 + it('builds the desktop and Host plugin controls from the same factory', () => { + const desktop = read(path.join(desktopMain, 'cindy-brain/runtimePluginHost.desktop.ts')); + const host = read(path.join(hostSrc, 'plugins/runtime.ts')); + assert.match(desktop, /import \{ createRuntimePluginHost, [^\n]+ from '\.\/runtimePluginHostCore\.js'/); + assert.match(host, /import \{ createRuntimePluginHost, [^\n]+ from '\.\.\/\.\.\/\.\.\/desktop\/src\/main\/cindy-brain\/runtimePluginHostCore\.js'/); + assert.match(desktop, /return createRuntimePluginHost\(/); + assert.match(host, /const taskPlugins = createRuntimePluginHost\(/); + }); + // MCP 注册协议:platformTools 已并入 hostTools,最终交给引擎时不能再次展开。 // Bug:main 合并冲突会重复注册同名服务;main 顶层会启动 Host,故在 guard 层保护组装边界。 it('registers platform providers once through the shared Host tools list', () => { @@ -57,6 +73,40 @@ describe('Host main.ts wiring', () => { assert.equal(registration.includes('platformTools.providers'), false); }); + // 规则:放行表第五节“甲:账号边界停止提前置位”。退出登录、会话失效、有序关闭都经 runOwnerBoundary + // (agent/owner-boundary.ts),它的 begin 是这条路的第一步,早于任何拆除;退出登录的登出与吊销在 dispose 之后; + // HTTP 退出登录入口先 begin、再关平台客户端。失效后果:拆依赖时失败的回合写下结束时间与错误行,显示成错误。 + // main 顶层会启动 Host,单测只能驱动 runOwnerBoundary 本身,故接线在 guard 层钉住。 + it('begins every owner boundary through runOwnerBoundary, before its teardown', () => { + const main = read(path.join(hostSrc, 'main.ts')); + assert.equal(main.split('runOwnerBoundary(ownerBoundary, {').length - 1, 3); + assert.equal(main.split('ownerBoundary.begin()').length - 1, 1, 'the only direct begin is the HTTP logout dep'); + const logout = main.slice(main.indexOf(' logout: async () => {'), main.indexOf(' listSessions: async')); + const logoutBoundary = logout.indexOf('runOwnerBoundary(ownerBoundary, {'); + assert.ok(logoutBoundary > 0); + for (const teardown of ['disposeOwnerRuntime', 'logoutHostSession(', 'withCrossProcessLock(']) { + assert.ok(logout.indexOf(teardown) > logoutBoundary, `${teardown} runs inside the logout boundary`); + } + assert.ok(logout.indexOf('dispose: disposeOwnerRuntime') < logout.indexOf('afterDispose:'), 'sign out after dispose'); + assert.ok(logout.indexOf('logoutHostSession(') > logout.indexOf('afterDispose:')); + const invalidate = main.slice(main.indexOf('function invalidateHostSession('), main.indexOf('const serverApi = ')); + const invalidateBoundary = invalidate.indexOf('runOwnerBoundary(ownerBoundary, {'); + assert.ok(invalidateBoundary > 0); + for (const teardown of ['beginAppSessionBoundary()', 'pauseOwnerRequests()', 'interactionBroker.dispose()', 'disposeOwnerRuntime']) { + assert.ok(invalidate.indexOf(teardown) > invalidateBoundary, `${teardown} runs inside the invalidation boundary`); + } + const stop = main.slice(main.indexOf('const stop = () => {'), main.indexOf("process.once('SIGINT', stop);")); + const stopBoundary = stop.indexOf('runOwnerBoundary(ownerBoundary, {'); + assert.ok(stopBoundary > 0); + for (const teardown of ['server.stopAccepting()', 'beginAppSessionBoundary()', 'reapCodexToolTreesSync();', 'await disposeOwnerRuntime();']) { + assert.ok(stop.indexOf(teardown) > stopBoundary, `${teardown} runs inside the shutdown boundary`); + } + const server = read(path.join(hostSrc, 'server.mjs')); + const httpLogout = server.slice(server.indexOf(' const logout = () => {'), server.indexOf(' const server = createServer(')); + assert.ok(httpLogout.indexOf('deps.beginOwnerBoundaryStop?.()') > 0); + assert.ok(httpLogout.indexOf('deps.beginOwnerBoundaryStop?.()') < httpLogout.indexOf('deps.platformClient?.()?.close()')); + }); + // 规则:Host 的 main.ts 先加载 boot-env(清掉终端继承来的 Anthropic 变量),紧接着 boot-settings // (读不懂的设置文件保留)。失效后果:别的模块先读到继承来的凭据,或在默认值设好之前删掉用户的设置文件。 it('loads boot-env first and boot-settings right after it', () => { @@ -76,6 +126,36 @@ describe('Host main.ts wiring', () => { assert.ok(helper.includes('export const hostAuthFetch = (input, init) => hostOutbound.outboundFetch(input, init);')); }); + // 规则:Host 进程启动时在 macOS 上读静态系统代理设置(放行表第 28 行 28b):main.ts 在分发命令之前调一次 + // startHostSystemProxySettings(登录命令也走出口代理),它只在 darwin 上接 scutil 读取,scutil 写死绝对路径。 + // 单测注入固定的 scutil 输出,走不到这一行。失效后果:Host 不再跟随系统代理,只靠系统代理才能连出去的 + // 用户全部直连;或 scutil 经 PATH 查找、被同名程序顶替。 + it('reads the macOS system proxy settings at startup, with the system scutil', () => { + const main = read(path.join(hostSrc, 'main.ts')); + assert.ok(main.includes("import { describeHostOutboundProxy, describeOutboundProxyLine, startHostSystemProxySettings, stopHostSystemProxySettings } from './outbound-proxy.ts';\n")); + assert.equal(main.split('startHostSystemProxySettings()').length - 1, 1); + assert.ok(main.includes("command === undefined || command === 'serve' || command === 'login'\n ? startHostSystemProxySettings().catch(")); + assert.ok(main.includes('await proxyWarmup;\n await runLoginCommand(process.argv.slice(3));')); + const rules = read(path.join(hostSrc, 'macos-system-proxy.ts')); + assert.ok(rules.includes("const SCUTIL_PATH = '/usr/sbin/scutil';\n")); + assert.equal(rules.split('execFile(').length - 1, 1); + assert.ok(rules.includes(" execFile(SCUTIL_PATH, ['--proxy'], {\n")); + }); + + // 规则:Host 进程只装一次桌面在启动时填的三个运行时选择槽(owner 提交边界的清理、任务读取的投影器、归档与 + // 删除时的清理,runtime-selection.ts bindHostSessionRuntimeHooks),在模块顶层、建好运行时选择之后(早于 + // 任何 owner 提交);删除任务时与归档一样在路线锁里调清理。行为测试经 bindHostSessionRuntimeHooks 本身, + // 走不到 main.ts 这几行。失效后果:换账号后残留运行时调整、读到的模型与实际路线不一致、删除的任务留着调整。 + it('binds the runtime selection slots once at top level and cleans a deleted task', () => { + const main = read(path.join(hostSrc, 'main.ts')); + assert.equal(main.split('bindHostSessionRuntimeHooks(').length - 1, 1, 'one call'); + const bind = main.indexOf('\nbindHostSessionRuntimeHooks(runtimeSelection);\n'); + assert.ok(bind > main.indexOf('\nconst runtimeSelection = createHostRuntimeSelection({\n'), 'a top-level call after the runtime selection'); + const remove = main.slice(main.indexOf(' deleteSession: lockSessionRoute(async (sessionId: string) => {')); + const body = remove.slice(0, remove.indexOf('\n }),\n')); + assert.ok(body.indexOf("cleanupSessionRuntimeForTerminalStatus(sessionId, 'deleted');") > body.indexOf('await sessionStorage.delete(sessionId);')); + }); + // 规则:Pi 包的退役钩子要拿到 Host 的 Maker(Maker 建好后 attach),Host 退出时关闭。 // 失效后果:包变更后运行中的 Pi 任务不退役,或进程退出时留下监听。 it('attaches the Pi packages to the Maker and closes them on teardown', () => { @@ -136,6 +216,18 @@ describe('Host main.ts wiring', () => { assert.ok(desktop.includes("import { resolveLocalMcpDuplicateChoices } from './mcp-duplicate-preferences.js';")); assert.ok(desktop.includes(' const claudeAgent = new ClaudeCodeAgent({\n resolveLocalMcpDuplicateChoices,\n')); }); + + // 规则:放行表第 13 行 3a。账号凭据的每个状态,model access 的 publish 既推给窗口,也交给目录的 + // noteCredentialStatus,照桌面 model-access/index.ts 的 onStatusChange(failed / disabled / unsupported / idle + // 清价并挂起,ok 解除)。usage-pricing.test.mjs 照这一行接线来测,测不到 main.ts 本身。 + // 失效后果:凭据失败后 Host 继续答复失效账号的价格,恢复后也不会让目录过期重拉。 + it('hands every credential status the model access publishes to the provider catalog', () => { + const access = call(read(path.join(hostSrc, 'main.ts')), 'modelAccess = createHostModelAccess('); + const publish = access.slice(access.indexOf('publish:status=>'), access.indexOf(',onKeyChanged:')); + assert.ok(publish.startsWith('publish:status=>{'), 'the publish callback'); + assert.ok(publish.includes("eventHub.publish({type:'plugin_push',channel:MODEL_ACCESS_STATUS_CHANNEL,payload:status});")); + assert.ok(publish.includes('listProviders.noteCredentialStatus(status);')); + }); }); describe('Host engine assembly (runtime.ts) against the desktop construction sites', () => { @@ -197,7 +289,7 @@ describe('Host engine assembly (runtime.ts) against the desktop construction sit const desktopModels = between(desktop, 'resolvePiRuntimeModels: () =>', 'mcpProviders: piMcpProviders,', true).replaceAll('getDesktopSelectableCatalog()', 'modelContext.getSelectableCatalog()'); // The Host lists the three resolvers before its loopback-proxy line. (The unit test this came // from ended its Host slice at a marker that no longer occurred, so it compared nothing.) - const hostModels = between(runtime, 'resolvePiRuntimeModels: () =>', '...(claudeProxy ? { registerPiProxySession', true); + const hostModels = between(runtime, 'resolvePiRuntimeModels: () =>', 'registerPiProxySession: claudeProxy?.registerPiProxySession,', true); assert.equal(hostModels, desktopModels, 'the three model resolvers are the desktop lines'); assert.equal(between(runtime, 'resolvePiGlobalContextHome: (remoteHostId) => {', ' },', true), between(piHost, 'resolvePiGlobalContextHome: (remoteHostId) => {', ' },', true)); @@ -333,6 +425,59 @@ describe('Host copies of desktop expressions', () => { shape(cut(desktop, "req.kind === 'permission'", ': req;')).replaceAll('...req,', '...request,').replaceAll('req.', 'request.').replace(' as Record', '')); }); + // 规则:Host 的生成图读来源(apps/host/src/agent/generated-images.ts 的 readSource)是 Host 自己的一份, + // 照桌面 register.ts createDesktopGeneratedImageDelivery 的 readSource 写,去掉了 SSH 文件服务与旧的 + // xdt-image 两支(放行表第七节第 31 项)。这里钉住桌面那段的文本(去掉缩进、空行与注释后的 sha256)。 + // 失效后果:桌面改了读来源的次序、回落或限制,Host 那份不跟着改,同一张图在两边读法不同。 + // 变红时:对照桌面新文本改 Host 那份(或在第 31 项写明为什么不跟),再更新这里的指纹。 + it('pins the desktop generated-image readSource that the Host copy follows', () => { + const desktop = read(path.join(desktopMain, 'maker-ipc/register.ts')); + const text = between(desktop, 'readSource: async (_sessionId, image, session) => {', 'setGeneratedImageRecovery((sessionId)'); + const fingerprint = createHash('sha256').update(text).digest('hex'); + expect(fingerprint, 'register.ts readSource changed: compare apps/host/src/agent/generated-images.ts readSource ' + + '(release table section 7, item 31), then update this fingerprint').toBe( + '0cb159a4a79191099771e36a47a9157da6d63ad9f41d1221c8d60130e139536f'); + }); + + // 规则:Host 的 deliverCodexGeneratedImage(apps/host/src/agent/generated-images.ts)与桌面 register.ts 的 + // 同名函数逐行相同,只有交付实例的名字不同(放行表第七节第 32 项)。 + // 失效后果:一边改了开始交付、失败记录或交出事件的方式,另一边没跟上。 + it('starts a live generated-image delivery with the desktop function, line for line', () => { + const signature = 'function deliverCodexGeneratedImage(sessionId: string, event: AgentEvent): Promise {'; + const desktop = between(read(path.join(desktopMain, 'maker-ipc/register.ts')), signature, '\nfunction broadcastSyntheticToolEvent('); + const host = between(read(path.join(hostAgent, 'generated-images.ts')), signature, 'return { delivery, deliverCodexGeneratedImage };'); + assert.ok(desktop.split('\n').length > 8); + expect(host, 'compare apps/host/src/agent/generated-images.ts with register.ts deliverCodexGeneratedImage ' + + '(release table section 7, item 32)').toBe(desktop.replaceAll('generatedImageDelivery.start(', 'delivery.start(')); + }); + + // 规则:Host 的静默停止排期(apps/host/src/agent/silent-stop.ts 的 schedule)照桌面回合观察的终态分支写: + // 当前代次的静默停止终态排一次决策、重复的不再排,并留住这一代次给续跑(放行表第七节第 36 项)。这里钉住桌面那段的 + // 文本(去掉缩进、空行与注释后的 sha256)。 + // 失效后果:桌面改了排期或留住代次的条件,Host 那份不跟着改,静默停止在两边续不续、何时被丢弃不同。 + // 变红时:对照桌面新文本改 Host 的 schedule(或在第 36 项写明为什么不跟),再更新这里的指纹。 + it('pins the desktop silent-stop terminal scheduling that the Host copy follows', () => { + const text = between(read(path.join(desktopMain, 'maker-ipc/sessionTurnObserver.ts')), 'const isSilentStop =', + 'if (isCurrentGeneration) deps.silentStopTurnLeaseGate.supersede(session.id);'); + const fingerprint = createHash('sha256').update(text).digest('hex'); + expect(fingerprint, 'sessionTurnObserver.ts silent-stop terminal changed: compare apps/host/src/agent/silent-stop.ts schedule ' + + '(release table section 7, item 36), then update this fingerprint').toBe( + 'c5c91ef223262768c2b9dd12b137e0a70a82711985cc8618646a03c3488bae0b'); + }); + + // 规则:Host 的静默停止决策时机(silent-stop.ts 的 decideLater,以及 turn-executor.mjs 对静默停止 done 不收尾、 + // 不交给协调器、延后结算改动记录)照桌面事件准备的静默停止分支写(放行表第七节第 36 项)。钉住桌面那段的文本。 + // 失效后果:桌面改了静默停止 done 的处理或决策的延时,Host 那份不跟着改。 + // 变红时:对照桌面新文本改 Host 那份(或在第 36 项写明为什么不跟),再更新这里的指纹。 + it('pins the desktop silent-stop decision timing that the Host copy follows', () => { + const text = between(read(path.join(desktopMain, 'maker-ipc/sessionEventPreparation.ts')), 'const carriesSilentStop =', + '}, SILENT_STOP_DECISION_DELAY_MS);'); + const fingerprint = createHash('sha256').update(text).digest('hex'); + expect(fingerprint, 'sessionEventPreparation.ts silent-stop branch changed: compare apps/host/src/agent/silent-stop.ts decideLater ' + + 'and the silent-stop done in turn-executor.mjs (release table section 7, item 36), then update this fingerprint').toBe( + '26b5e363262ad7e18d1b5f2cc350fe39a6b158ea4af6519ae54e7a290e1f887e'); + }); + // 规则:Host 的 Pi 持久子代理入口与桌面入口逐行相同,只有 ready 帧的发法、断开通道和父进程监视不同。 // 失效后果:Host 上的 runner 行为与桌面分叉(P4、m1-cp18c 审核方定乙)。 it('starts the Pi subagent runner with the desktop entry, except the ready frame, the channel and the watchdog', () => { @@ -384,6 +529,76 @@ describe('Host copies of desktop expressions', () => { assert.ok(desktopDeps.length > 0); assert.equal(copied, desktopDeps); }); + + // 规则:cindy_memory 每次调用前的账号数据检查(Host `hostAccountDataAccess`)与 session_search 的调用方 + // 检查(Host `createHostSessionSearch`),照抄桌面 mcp-providers.ts 里的两段内联闭包(`withAccountDataAccess`、 + // memory 依赖的 `searchSessions`;放行表第七节第 26、25 项)。两段都内联在桌面的 provider 装配里 + // (`searchSessions` 在 createLiziMcpProviders 的参数里),pluginTaskHelperScope.test.ts 按源码截取它们来测, + // 暂时不能搬成共用。 + // 失效后果:桌面收紧了检查而 Host 没跟上,Host 的记忆工具悄悄比桌面松(换账号后上一个账号的任务读写数据)。 + // 缺口:Host 的行为测试(memory.test.mjs)只验证现有的几种拒绝,看不到桌面以后加的检查。 + // 最小失败输入:Host 副本里任一行与桌面不同。比较去掉缩进、空行与注释;session_search 只允许检索那一处不同。 + it('keeps the cindy_memory caller checks line for line with the desktop closures', () => { + const fn = (file: string, pick: (node: ts.Node) => ts.Node | undefined) => { + const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.ESNext, true); + const found: (ts.ArrowFunction | ts.FunctionDeclaration)[] = []; + const visit = (node: ts.Node) => { + const hit = pick(node); + if (hit && (ts.isArrowFunction(hit) || ts.isFunctionDeclaration(hit))) found.push(hit); + ts.forEachChild(node, visit); + }; + visit(source); + assert.equal(found.length, 1, file); + const [hit] = found; + const lines = (text: string) => text.split('\n').map(line => line.trim()).filter(line => line && !line.startsWith('//')); + return { params: hit.parameters.map(p => p.getText(source)).join(', '), body: lines(hit.body!.getText(source)) }; + }; + const named = (node: ts.Node, name: string) => (ts.isVariableDeclaration(node) || ts.isPropertyAssignment(node) || ts.isFunctionDeclaration(node)) + && node.name?.getText() === name; + const desktopFile = path.join(desktopMain, 'mcp-integrations/mcp-providers.ts'); + const hostFile = path.join(hostAgent, 'memory-mcp-ports.ts'); + + const desktopAccess = fn(desktopFile, node => named(node, 'withAccountDataAccess') && ts.isVariableDeclaration(node) ? node.initializer : undefined); + const hostAccess = fn(hostFile, node => named(node, 'hostAccountDataAccess') ? node : undefined); + assert.ok(desktopAccess.body.length > 10); + assert.equal(hostAccess.params, desktopAccess.params); + assert.deepEqual(hostAccess.body, desktopAccess.body); + + const desktopSearch = fn(desktopFile, node => named(node, 'searchSessions') && ts.isPropertyAssignment(node) ? node.initializer : undefined); + const hostSearch = fn(hostFile, node => ts.isReturnStatement(node) && node.parent.parent && named(node.parent.parent, 'createHostSessionSearch') + ? node.expression : undefined); + // The one difference: the search runs on the shared core with this Host's device id. + const search = new Map([ + ['const hits = await searchSessionsWithBotScopeCore(query, opts, {', 'const hits = await searchSessionsWithBotScope(query, opts, {'], + ['botAccountWide: await input.readsAccountHistory(opts.callerSessionId),', 'botAccountWide: await botReadsAccountHistory(opts.callerSessionId),'], + ]); + assert.ok(desktopSearch.body.length > 10); + assert.equal(hostSearch.params, desktopSearch.params); + assert.deepEqual(hostSearch.body.filter(line => line !== 'readDeviceId: input.deviceId,').map(line => search.get(line) ?? line), desktopSearch.body); + }); + + // 规则:并存方案 A(审核方 2026-11-17)。闸门关着时,Host 交给订阅桥的登录端口拒绝桥会提前续期的令牌 + // (apps/host/src/agent/codex-runtime.ts 的 BRIDGE_REFRESH_MARGIN_SEC),这个秒数照抄桥自己的续期提前量 + // (anthropicResponsesBridgeHostCore.ts 的 REFRESH_MARGIN_SEC)。失效后果:桥的提前量改大而 Host 没跟上时, + // 闸门关着时 Host 会放行一个桥随后就续期的令牌,续期结果写回桌面也在用的登录文件;改小时 Host 会拒掉桥不会续期的令牌。 + it('refuses the tokens the subscription bridge would renew, with the bridge\'s own margin', () => { + const bridge = /^const REFRESH_MARGIN_SEC = (\d+);$/m.exec(read(path.join(desktopMain, 'maker-host/anthropicResponsesBridgeHostCore.ts')))?.[1]; + const host = /^export const BRIDGE_REFRESH_MARGIN_SEC = (\d+);$/m.exec(read(path.join(hostAgent, 'codex-runtime.ts')))?.[1]; + assert.ok(bridge, 'REFRESH_MARGIN_SEC is declared in anthropicResponsesBridgeHostCore.ts'); + assert.ok(host, 'BRIDGE_REFRESH_MARGIN_SEC is declared in apps/host/src/agent/codex-runtime.ts'); + assert.equal(host, bridge, `桥的续期提前量是 ${bridge} 秒,Host 的 BRIDGE_REFRESH_MARGIN_SEC 是 ${host} 秒:两边要一起改`); + }); + + // 规则:并存方案 A(审核方 2026-11-17)。闸门关着时,Host 的 xAI 登录包装拒绝 Grok 服务会提前续期的令牌 + // (apps/host/src/agent/xai-held-login.ts 的 GROK_REFRESH_MARGIN_SEC),这个秒数照抄 grok-oauth-login.ts 的 REFRESH_MARGIN_SEC。 + // 失效后果:服务的提前量改大而 Host 没跟上时,闸门关着时 Host 会放行一个服务随后就续期的令牌,续期结果写回桌面也在用的 safe-storage。 + it('refuses the xAI tokens the Grok service would renew, with the service\'s own margin', () => { + const service = /^const REFRESH_MARGIN_SEC = (\d+);$/m.exec(read(path.join(desktopMain, 'maker-host/grok-oauth-login.ts')))?.[1]; + const host = /^export const GROK_REFRESH_MARGIN_SEC = (\d+);$/m.exec(read(path.join(hostAgent, 'xai-held-login.ts')))?.[1]; + assert.ok(service, 'REFRESH_MARGIN_SEC is declared in grok-oauth-login.ts'); + assert.ok(host, 'GROK_REFRESH_MARGIN_SEC is declared in apps/host/src/agent/xai-held-login.ts'); + assert.equal(host, service, `Grok 服务的续期提前量是 ${service} 秒,Host 的 GROK_REFRESH_MARGIN_SEC 是 ${host} 秒:两边要一起改`); + }); }); // 以下断言原在桌面普通单测里读 register.ts;第一批桌面准备把被守护的代码原样搬进共用文件 @@ -536,17 +751,17 @@ describe('event types the desktop pipeline acts on, classified for the Host', () gaps: ['A9 turn-end seal', 'A10 last activity', 'A13 list preview and pinned summary', 'checkpoint 4 and 5 (auto-resume)'], }, error: { - host: 'turn-executor.mjs finish: error row, Codex plan failure, change record partial, Git abort; context recovery claim', - gaps: ['A15 Opus plan error reason', 'checkpoint 4 (terminal to the coordinator first, auto-resume)'], + host: 'turn-executor.mjs finish: error row, Codex plan failure, change record partial, Git abort; context recovery claim; claudeOpusPlanTerminalErrorData (sessionEventPreparationSteps.ts, shared)', + gaps: ['checkpoint 4 (terminal to the coordinator first, auto-resume)'], }, - image: { gaps: ['A11 Codex generated images'] }, - interaction_dismissed: { gaps: ['A12 runtime interaction_dismissed'] }, + image: { host: 'turn-executor.mjs deliverCodexGeneratedImage (agent/generated-images.ts over the shared generatedImageDelivery.ts)' }, + interaction_dismissed: { host: 'turn-executor.mjs handleInteractionDismissedEvent (sessionEventPreparationSteps.ts, shared), in or out of a turn' }, plan_mode_changed: { host: 'turn-executor.mjs persistAgentPlanModeChange (shared persistAgentPlanModeChangeWith)' }, status: { host: 'turn-executor.mjs context snapshot (shared), background activity', gaps: ['smaller difference: running=false alone does not write the turn end time'], }, - text: { host: 'history.event (sessionEventStreamCore, shared)', gaps: ['A14 standaloneText notices'] }, + text: { host: 'history.event (sessionEventStreamCore, shared); turn-executor.mjs routeStandaloneTextEvent (sessionEventPreparationSteps.ts, shared)' }, turn_diff: { host: 'turn-executor.mjs noteTurnDiffEvent, not published' }, }; @@ -590,6 +805,100 @@ describe('event types the desktop pipeline acts on, classified for the Host', () }); }); +// Rule: AgentDeps is one interface for the three engines, and the Host writes every optional port of +// each engine's bag out (runtime.ts, explicitPorts). The ports only another engine reads are written +// once, in apps/host/src/agent/agent-deps-engines.ts, grouped by which engines read them. That grouping +// was read off maker-core by hand. If an engine later starts reading a port grouped as another engine's, +// the Host's bag for it keeps `undefined` there and nothing fails; this recomputes the grouping from the +// agents' source and compares. Failure: a port the engine now reads stays unbound on the Host. +describe('the Host\'s grouping of AgentDeps ports by the engines that read them', () => { + const coreAgents = path.join(repo, 'packages/maker-core/src/agents'); + const ENGINES = { 'claude-code': 'claude', codex: 'codex', pi: 'pi' } as const; + type Engine = (typeof ENGINES)[keyof typeof ENGINES]; + const BAGS: Record = { + PORTS_ONLY_CODEX_READS: ['codex'], + PORTS_ONLY_PI_READS: ['pi'], + PORTS_ONLY_CLAUDE_READS: ['claude'], + PORTS_ONLY_CLAUDE_AND_PI_READ: ['claude', 'pi'], + PORTS_ONLY_CLAUDE_AND_CODEX_READ: ['claude', 'codex'], + }; + + /** + * The AgentDeps members a file reads: `deps.x`, `this.deps.x` (also with `?.`), and names destructured + * from either. Read from the syntax tree, so a port named in a comment or a string is not a read. + */ + function readsIn(file: string): Set { + const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true); + const isDeps = (node: ts.Expression) => (ts.isIdentifier(node) && node.text === 'deps') + || (ts.isPropertyAccessExpression(node) && node.name.text === 'deps' && node.expression.kind === ts.SyntaxKind.ThisKeyword); + const names = new Set(); + const visit = (node: ts.Node) => { + if (ts.isPropertyAccessExpression(node) && isDeps(node.expression)) names.add(node.name.text); + if (ts.isVariableDeclaration(node) && node.initializer && isDeps(node.initializer) && ts.isObjectBindingPattern(node.name)) { + for (const element of node.name.elements) { + const key = element.propertyName ?? element.name; + if (ts.isIdentifier(key)) names.add(key.text); + } + } + ts.forEachChild(node, visit); + }; + visit(source); + return names; + } + function files(dir: string): string[] { + return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return entry.name === '__tests__' ? [] : files(full); + return entry.name.endsWith('.ts') && !entry.name.includes('.test.') ? [full] : []; + }); + } + function optionalAgentDepsPorts(): string[] { + const file = path.join(coreAgents, 'base-agent.ts'); + const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true); + const decl = source.statements.find((node): node is ts.InterfaceDeclaration => + ts.isInterfaceDeclaration(node) && node.name.text === 'AgentDeps'); + assert.ok(decl, 'AgentDeps'); + return decl.members.filter(member => member.questionToken && member.name && ts.isIdentifier(member.name)) + .map(member => (member.name as ts.Identifier).text); + } + function hostBags(): Record { + const file = path.join(hostAgent, 'agent-deps-engines.ts'); + const source = ts.createSourceFile(file, read(file), ts.ScriptTarget.Latest, true); + const bags: Record = {}; + const visit = (node: ts.Node) => { + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) { + let init: ts.Expression = node.initializer; + while (ts.isSatisfiesExpression(init) || ts.isAsExpression(init)) init = init.expression; + if (ts.isObjectLiteralExpression(init)) { + bags[node.name.text] = init.properties.map(property => (property.name as ts.Identifier).text); + } + } + ts.forEachChild(node, visit); + }; + visit(source); + return bags; + } + + it('matches the engines that read each port in maker-core', () => { + const ports = optionalAgentDepsPorts(); + // A port the base agent reads (base-agent.ts) is read by all three engines. Only agents/ is read: + // maker.ts reads MakerDeps, whose own `toolLoopReviewer` is not the AgentDeps member of that name + // (the Claude agent reads that one; Codex and Pi take Maker's). + const sources = [ + { engines: ['claude', 'codex', 'pi'] as Engine[], files: [path.join(coreAgents, 'base-agent.ts'), ...files(path.join(coreAgents, 'shared'))] }, + ...Object.entries(ENGINES).map(([dir, engine]) => ({ engines: [engine] as Engine[], files: files(path.join(coreAgents, dir)) })), + ].map(entry => ({ ...entry, reads: new Set(entry.files.flatMap(file => [...readsIn(file)])) })); + const readers = new Map>(ports.map(port => + [port, new Set(sources.filter(source => source.reads.has(port)).flatMap(source => source.engines))])); + const expected: Record = Object.fromEntries(Object.entries(BAGS).map(([bag, engines]) => [bag, + ports.filter(port => { const set = readers.get(port)!; return set.size === engines.length && engines.every(e => set.has(e)); }).sort()])); + const actual = Object.fromEntries(Object.entries(hostBags()).map(([bag, keys]) => [bag, [...keys].sort()])); + expect(actual).toEqual(expected); + // Every optional port is read by some engine; one read by none would be grouped nowhere. + expect(ports.filter(port => readers.get(port)!.size === 0)).toEqual([]); + }); +}); + // 测试价值 // - 生产入口与可观察结果:桌面的 XD 报价投影(usage/modelPricing.ts)与账本币种存储 // (usage/accountCurrencyStore.ts)。这两个壳在模块加载时各建一个工厂实例,桌面的用量记账、价格显示 @@ -661,3 +970,609 @@ describe('the desktop builds one instance of each usage pricing factory', () => for (const name of names) expect(calls[name], name).toEqual([FACTORIES[name]]); }); }); + +describe('Host macOS system proxy rules', () => { + // 规则:Host 读 macOS 系统代理时照的是某一版 Electron 里 Chromium 的规则(apps/host/src/macos-system-proxy.ts, + // 放行表第 28 行 28b),常量 CHROMIUM_RULES_ELECTRON_VERSION 写明是哪一版。桌面升级 Electron 时这条变红; + // 升级的人改这个常量就会改到实现文件,macOS 比对(.github/workflows/macos-system-proxy-compare.yml)随之在 + // 那个 PR 上运行。失效后果:Chromium 的代理规则变了(例如新增的隐式例外),Host 与桌面悄悄分叉。 + it('follows the Electron version the desktop ships', () => { + const rules = read(path.join(hostSrc, 'macos-system-proxy.ts')); + const declared = /^export const CHROMIUM_RULES_ELECTRON_VERSION = '([^']+)';$/m.exec(rules)?.[1]; + assert.ok(declared, 'CHROMIUM_RULES_ELECTRON_VERSION is declared in apps/host/src/macos-system-proxy.ts'); + const desktop = JSON.parse(read(path.join(repo, 'apps/desktop/package.json'))); + const electron = desktop.devDependencies?.electron ?? desktop.dependencies?.electron; + assert.equal(declared, electron, + `apps/desktop/package.json 的 Electron 是 ${electron},apps/host/src/macos-system-proxy.ts 的 ` + + `CHROMIUM_RULES_ELECTRON_VERSION 是 ${declared}:改这个常量,并等 macOS 系统代理比对 ` + + '(.github/workflows/macos-system-proxy-compare.yml) 在这个 PR 上通过'); + }); +}); + +let hostImportGraphResult: Promise | undefined; + +/** + * The modules the Host bundles (apps/host/scripts/build.mjs entries) and the acceptance scripts load, built + * once and shared by the guards below that classify what the Host loads. + */ +function hostImportGraph(): Promise { + return hostImportGraphResult ??= (async () => { + const scripts = fs.readdirSync(path.join(repo, 'apps/host/scripts')).filter(name => name.endsWith('.e2e.mjs')).sort() + .map(name => `apps/host/scripts/${name}`); + const result = await build({ + absWorkingDir: repo, bundle: true, write: false, metafile: true, splitting: true, platform: 'node', format: 'esm', + target: 'node22', outdir: path.join(os.tmpdir(), 'cindy-host-graph-unused'), logLevel: 'silent', + entryPoints: ['apps/host/src/main.ts', 'apps/host/src/plugins/node-worker.ts', 'apps/host/src/agent/pi-subagent-runner-process.cts', + 'apps/desktop/src/main/cindy-brain/libraryDbWorker.ts', 'apps/desktop/src/main/cindy-brain/ghostSnapshotWorkerProcess.ts', ...scripts], + plugins: [{ name: 'host-graph', setup(builder) { + builder.onResolve({ filter: /\?raw$/ }, () => ({ path: 'raw', namespace: 'raw' })); + builder.onLoad({ filter: /.*/, namespace: 'raw' }, () => ({ contents: '', loader: 'text' })); + builder.onResolve({ filter: /^[^./]/ }, args => (isBuiltin(args.path) + || !(args.path.startsWith('@cindy/') || /^cindy-tools(\/|$)/.test(args.path) || args.path.startsWith('#')) + ? { path: args.path, external: true } : undefined)); + } }], + }); + return Object.keys(result.metafile.inputs).filter(file => /\.(ts|tsx|mts|cts|js|mjs|cjs)$/.test(file)); + })(); +} + +/** + * Rule: a shared module may keep a port in a module variable that the desktop fills once at startup + * (setX(impl)). Unlike a factory port it fails nothing when unbound: the module falls back to null, a + * no-op, an empty table or a refusal, so a port the Host never binds goes unnoticed (甲 5 found + * claude-transcript-relocation.ts's liveCcSessionBridge only by reading the code). Every such setter in + * the modules the Host loads is classified in apps/host/src/desktop-module-setters.ts. + * Collection: the Host's static import graph from the entries of apps/host/scripts/build.mjs plus the + * acceptance scripts, resolved by esbuild without running any module (workspace packages followed, + * third-party packages external). In its desktop and package sources (generated and vendored code + * excluded): exported functions named set|register|bind|configure|install|init… that write a + * module-level slot, and exported empty containers that another file in the graph mutates. + * A slot is any module-level binding, whatever it starts as: a let/var may be reassigned, and any binding (const + * too) may have its contents replaced. The initial value is not looked at: a plain `let enabled = false` is as + * much a port the Host can leave at its default as a `let reader = null` (active-catalog.ts + * openAiImagesApiKeyConfigured). Destructured declarations (`let [a, b] = …`) count by each name. Wrapped + * forms (`as`, `satisfies`, `!`, ``, parentheses) are unwrapped. + * Imported values (default, named, namespace; not types) are const bindings of the importing module. + * A write is any assignment operator (`=`, `+=`, `|=`, `<<=`, `??=`, …) or `++` / `--` on a let/var, the same on a + * property of any binding (logger.ts + * `mainSlot.dir = …`), a container mutation (`.set`, `.push`, …) or `Object.assign(binding, …)` (projectAutomaticIcon.ts), + * anywhere in the setter including its callbacks, or in a module function it calls, followed transitively + * (active-catalog.ts setters through markChanged, codex-process-registry.ts registerCodexProcessRole through + * registerAgentProcess); a result reached by skipping a function already on the call path (mutual recursion) is + * not remembered, so a setter that enters the cycle elsewhere is judged afresh. This reaches some setters that are + * not ports in practice (read_sheet.ts: the tool's worker pool); the table records them as internal with why. + * Failure: a new setter (or a newly loaded module with one) that the table does not classify, or a table + * entry whose setter is gone, turns this red until the table is updated. A `bound` entry must bind it in + * the Host file it names (bindsIn: a call, a container mutation, or the setter handed over as a value); + * `where: '#'` narrows that to one function of the file, for a file that binds the same + * setter more than once (skill-projection-owner.ts: serve refuses, `cindy-host login` allows) or binds it from a + * startup function (project-icon.ts bindHostProjectIconRuntime); such a function must be called by another Host + * file the Host loads (main.ts), so dropping that call fails too. + * Not seen, by form: + * - slots declared other than at module level (inside a block, an IIFE, a namespace or a class body, + * static fields included); + * - writes through destructuring assignment (`({ a: slot } = x)`), through an alias (`const s = state; s.x = …`), + * through a function the module imports from another file, or through Reflect/defineProperty; + * - state on globalThis or process, or reached through createRequire or a dynamic import at run time; + * - setters not exported as a function: a method of an exported object or class, a default export, + * a setter not named this way; + * - closure state of factories; + * and, for a setter handed over as a port value, whether the receiving code really calls it; for + * `#`, whether the caller found is itself reached at run time (one call level is checked). + */ +describe('Host Chromium proxy helper (row 28, 28c)', () => { + const worker = () => read(path.join(hostSrc, 'chromium-proxy-worker.cjs')); + const launcher = () => read(path.join(hostSrc, 'chromium-proxy.ts')); + const TEST_SWITCHES = ['use-mock-keychain', 'proxy-pac-url', 'no-proxy-server', 'proxy-server', 'CINDY_PROXY_WORKER_TEST_CONFIG']; + + // 规则:生产启动不带任何测试开关(审核方 2026-11-18):Host 只以 `[脚本]` 起辅助进程,环境经 helperEnv 筛选系统目录和 + // 语言变量后只加 profile 目录;测试配置与 Chromium 开关只出现在辅助进程脚本(读测试配置)和验收脚本里。 + // 失效后果:生产里的辅助进程用了 mock 钥匙串或固定代理配置,与系统设置不一致,或测试配置经环境漏进生产。 + it('starts the helper the production way: no switch, no test configuration', () => { + const source = launcher(); + assert.equal(source.split('spawnImpl(').length - 1, 1); + assert.ok(source.includes('child = spawnImpl(found.binary, [found.script], {\n env: helperEnv(profile), stdio:')); + assert.ok(source.includes("if (SYSTEM_ENV.has(key.toUpperCase())) env[key] = value;")); + const production = fs.readdirSync(hostSrc, { recursive: true }).map(String) + .filter(file => /\.(ts|mts|cts|mjs|cjs|js)$/.test(file) && !/\.test\.|[\\/]loaders[\\/]/.test(file) && file !== 'chromium-proxy-worker.cjs') + .map(file => path.join(hostSrc, file)); + for (const file of [...production, path.join(repo, 'apps/host/scripts/build.mjs')]) { + const text = read(file); + for (const name of TEST_SWITCHES) assert.equal(text.includes(name), false, `${path.relative(repo, file)} mentions ${name}`); + } + assert.equal(worker().split('process.env.CINDY_PROXY_WORKER_TEST_CONFIG').length - 1, 1); + }); + + // 规则:辅助进程只用不落盘的内存分区,不碰 defaultSession、safeStorage、单实例锁、窗口或端口;先应用配置、强制重载、 + // 解析一次再报 ready,ready 之前一律回 not_ready(审核方 2026-11-18)。失效后果:写 cookie 或触发 Safe Storage + // 钥匙串条目;开了端口或窗口;PAC 未就绪时回 DIRECT。 + it('the helper asks an in-memory session and keeps off the keychain, windows and ports', () => { + const source = worker(); + assert.ok(source.includes(" const candidate = session.fromPartition('cindy-proxy-helper', { cache: false });\n")); + const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, ''); + for (const banned of ['persist:', 'defaultSession', 'safeStorage', 'requestSingleInstanceLock', 'BrowserWindow', 'loadURL', + 'createServer', "require('node:http')", "require('node:net')", 'appendSwitch']) { + assert.equal(code.includes(banned), false, banned); + } + assert.ok(source.includes('app.disableHardwareAcceleration();\n')); + assert.ok(source.includes("app.setPath('userData', profile);\n")); + assert.ok(source.includes("lines.on('close', () => app.quit());\n")); + assert.ok(source.includes(" if (!ses) return send({ id: request.id, error: 'not_ready' });\n")); + const ready = between(source, ' await candidate.setProxy(', " send({ ready: true, pid: process.pid });"); + assert.deepEqual(ready.split('\n').filter(line => !line.startsWith('//')), [ + "await candidate.setProxy(testConfig ? JSON.parse(testConfig) : { mode: 'system' });", + 'await candidate.forceReloadProxyConfig();', + 'await candidate.resolveProxy(READINESS_PROBE);', + 'ses = candidate;', + ]); + }); + + // 规则:Host 包里的 Electron 是 npm 原版(build.mjs 从 desktopRequire('electron') 拷贝),apps/host 里没有翻 fuse 的代码 + // (flipFuses;验收脚本只读 fuse),cookie 加密默认关闭;装了二进制时直接读它的 fuse(CI 的桌面任务不下载二进制,那里只核对源码;macOS/Windows 的比对 + // workflow 在验收脚本里读同一个 fuse)。失效后果:换成翻过 fuse 的 Electron 后,辅助进程启动即触发钥匙串。 + it('ships the npm Electron, with cookie encryption off', async () => { + const build = read(path.join(repo, 'apps/host/scripts/build.mjs')); + assert.ok(build.includes(" const executable = desktopRequire('electron');\n")); + assert.ok(build.includes(" await fs.copyFile(path.join(host, 'src/chromium-proxy-worker.cjs'), path.join(bin, 'chromium-proxy-worker.cjs'));\n")); + const hostFiles = fs.readdirSync(path.join(repo, 'apps/host'), { recursive: true }).map(String) + .filter(file => !file.includes('node_modules') && /\.(ts|mts|cts|mjs|cjs|js|json)$/.test(file)); + for (const file of hostFiles) assert.equal(read(path.join(repo, 'apps/host', file)).includes('flipFuses'), false, file); + let executable: string | null = null; + try { executable = createRequire(path.join(repo, 'apps/desktop/package.json'))('electron') as string; } catch { executable = null; } + if (!executable || !fs.existsSync(executable)) return; + const fuses = await import('@electron/fuses'); + const wire = await fuses.getCurrentFuseWire(process.platform === 'darwin' ? path.resolve(executable, '../../..') : executable); + expect(String.fromCharCode(wire[fuses.FuseV1Options.EnableCookieEncryption] as number), 'EnableCookieEncryption').toBe('0'); + }); +}); + +/** + * Rule: every module the Host loads that opens network connections itself is classified in + * apps/host/src/host-network-modules.ts: whether its traffic to other machines takes the outbound proxy resolver + * (release table row 28). Collection over the Host's import graph (as for the setters below): a value import of + * node:http, https, net, tls, http2, dgram, undici or ws (import, require or dynamic import), a reference to the + * global fetch, a direct fetch call, or `new WebSocket(…)`. Counts also catch additional calls through an + * existing network import, fetch or WebSocket constructor in an already classified file. Failure without it: a new + * outbound call that bypasses the resolver (direct in a network that needs a proxy) lands unnoticed. + */ +describe('network modules the Host loads, classified for the Host', () => { + const NETWORK = new Set(['http', 'https', 'net', 'tls', 'http2', 'dgram', 'undici', 'ws']); + const bare = (name: string) => name.replace(/^node:/, ''); + + function networkUses(file: string, text: string): string[] { + const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true); + const uses = new Set(); + let declaresFetch = false; + let fetchReferences = 0; + let qualifiedFetches = 0; + let socketConstructors = 0; + let fetchCalls = 0; + let networkCalls = 0; + const importedNames = new Set(); + const declares = (n: ts.Node): n is ts.ParameterDeclaration | ts.VariableDeclaration | ts.BindingElement | ts.FunctionDeclaration => + ts.isParameter(n) || ts.isVariableDeclaration(n) || ts.isBindingElement(n) || ts.isFunctionDeclaration(n); + const visit = (n: ts.Node): void => { + if (ts.isTypeNode(n)) return; + if (ts.isImportDeclaration(n) && ts.isStringLiteral(n.moduleSpecifier) && NETWORK.has(bare(n.moduleSpecifier.text))) { + const clause = n.importClause; + const typeOnly = !!clause && (clause.isTypeOnly || (!clause.name && !!clause.namedBindings && ts.isNamedImports(clause.namedBindings) + && clause.namedBindings.elements.every(element => element.isTypeOnly))); + if (!typeOnly) { + uses.add(`imports ${bare(n.moduleSpecifier.text)}`); + if (clause?.name) importedNames.add(clause.name.text); + if (clause?.namedBindings && ts.isNamespaceImport(clause.namedBindings)) importedNames.add(clause.namedBindings.name.text); + if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) { + for (const element of clause.namedBindings.elements) if (!element.isTypeOnly) importedNames.add(element.name.text); + } + } + } + if (ts.isCallExpression(n) && n.arguments[0] && ts.isStringLiteral(n.arguments[0]) && NETWORK.has(bare(n.arguments[0].text)) + && ((ts.isIdentifier(n.expression) && n.expression.text === 'require') || n.expression.kind === ts.SyntaxKind.ImportKeyword)) { + uses.add(`imports ${bare(n.arguments[0].text)}`); + } + if (declares(n) && n.name && ts.isIdentifier(n.name) && n.name.text === 'fetch') declaresFetch = true; + if (ts.isIdentifier(n) && n.text === 'fetch') { + const p = n.parent; + const name = (ts.isPropertyAccessExpression(p) && p.name === n) + || ((ts.isPropertyAssignment(p) || ts.isMethodDeclaration(p) || ts.isMethodSignature(p) || ts.isPropertySignature(p) + || ts.isPropertyDeclaration(p)) && p.name === n) + || ts.isTypeQueryNode(p) || ts.isQualifiedName(p) || (declares(p) && p.name === n) || (ts.isBindingElement(p) && p.propertyName === n); + if (!name) fetchReferences++; + } + if (ts.isPropertyAccessExpression(n) && n.name.text === 'fetch' && ts.isIdentifier(n.expression) + && ['globalThis', 'global'].includes(n.expression.text)) qualifiedFetches++; + if (ts.isElementAccessExpression(n) && ts.isStringLiteral(n.argumentExpression) && n.argumentExpression.text === 'fetch' + && ts.isIdentifier(n.expression) && ['globalThis', 'global'].includes(n.expression.text)) qualifiedFetches++; + if (ts.isNewExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === 'WebSocket') socketConstructors++; + if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === 'fetch') fetchCalls++; + if (ts.isCallExpression(n) || ts.isNewExpression(n)) { + let base: ts.Expression = n.expression; + while (ts.isPropertyAccessExpression(base) || ts.isElementAccessExpression(base)) base = base.expression; + if (ts.isIdentifier(base) && importedNames.has(base.text)) networkCalls++; + } + ts.forEachChild(n, visit); + }; + visit(sf); + const fetchUses = qualifiedFetches + (declaresFetch ? fetchCalls : fetchReferences); + if (fetchUses) uses.add(`fetch ×${fetchUses}`); + if (socketConstructors) uses.add(`new WebSocket ×${socketConstructors}`); + if (networkCalls) uses.add(`network API calls ×${networkCalls}`); + return [...uses].sort(); + } + + it('classifies every network module the Host loads, with exactly what it uses', async () => { + const { HOST_NETWORK_MODULES } = await import(pathToFileURL(path.join(hostSrc, 'host-network-modules.ts')).href) as + { HOST_NETWORK_MODULES: Record }; + const found = new Map(); + for (const file of await hostImportGraph()) { + if (/^apps\/host\/scripts\//.test(file)) continue; + const uses = networkUses(file, read(path.join(repo, file))); + if (uses.length) found.set(file, uses); + } + const table = new Map(Object.entries(HOST_NETWORK_MODULES).map(([file, row]) => [file, [...row.uses].sort()])); + expect([...found.keys()].filter(file => !table.has(file)).sort(), 'network modules missing from apps/host/src/host-network-modules.ts').toEqual([]); + expect([...table.keys()].filter(file => !found.has(file)).sort(), 'entries whose module opens no connection any more').toEqual([]); + for (const [file, uses] of found) expect(table.get(file), file).toEqual(uses); + const keys = Object.keys(HOST_NETWORK_MODULES); + expect(keys, 'sorted').toEqual([...keys].sort()); + for (const [file, row] of Object.entries(HOST_NETWORK_MODULES)) { + expect(['resolver', 'injected', 'loopback', 'no-connection', 'same-as-desktop'], file).toContain(row.route); + expect(row.reason.length, file).toBeGreaterThan(10); + } + }, 60_000); +}); + +describe('module-level port setters the Host loads, classified for the Host', () => { + const tableFile = path.join(hostSrc, 'desktop-module-setters.ts'); + const SETTER = /^(set|register|bind|configure|install|init)[A-Z]/; + const MUTATORS = new Set(['set', 'push', 'add', 'unshift', 'splice', 'delete', 'clear']); + type Entry = { status: string; where?: string; reason?: string }; + + function settersIn(file: string): { setters: string[]; containers: string[] } { + const sf = ts.createSourceFile(file, read(path.join(repo, file)), ts.ScriptTarget.Latest, true); + const exported = new Set(); + for (const statement of sf.statements) { + if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) + for (const element of statement.exportClause.elements) exported.add((element.propertyName ?? element.name).text); + } + const isExported = (node: ts.Statement) => !!ts.canHaveModifiers(node) && !!ts.getModifiers(node)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword); + // Every module-level binding, whatever it starts as (null, a function, an import, a plain `false`): the desktop + // may replace a let/var, or the contents of any binding, and the Host may not. true = can be reassigned. + const slots = new Map(); + const functions: Array<{ name: string; node: ts.Node }> = []; + const containers: string[] = []; + const unwrap = (n: ts.Expression | undefined): ts.Expression | undefined => { + while (n && (ts.isAsExpression(n) || ts.isSatisfiesExpression(n) || ts.isParenthesizedExpression(n) + || ts.isNonNullExpression(n) || ts.isTypeAssertionExpression(n))) n = n.expression; + return n; + }; + // Imported values are const bindings of this module too: `import { state } from './x'` then `state.y = v`. + for (const statement of sf.statements) { + const clause = ts.isImportDeclaration(statement) ? statement.importClause : undefined; + if (!clause || clause.isTypeOnly) continue; + if (clause.name) slots.set(clause.name.text, false); + const named = clause.namedBindings; + if (named && ts.isNamespaceImport(named)) slots.set(named.name.text, false); + if (named && ts.isNamedImports(named)) for (const element of named.elements) if (!element.isTypeOnly) slots.set(element.name.text, false); + } + const bindingNames = (name: ts.BindingName): string[] => (ts.isIdentifier(name) ? [name.text] + : name.elements.flatMap(element => (ts.isOmittedExpression(element) ? [] : bindingNames(element.name)))); + for (const statement of sf.statements) { + if (ts.isVariableStatement(statement)) { + const isConst = (statement.declarationList.flags & ts.NodeFlags.Const) !== 0; + for (const declaration of statement.declarationList.declarations) { + const init = unwrap(declaration.initializer); + if (ts.isIdentifier(declaration.name)) { + const name = declaration.name.text; + const isFunction = !!init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init)); + if (isFunction && (isExported(statement) || exported.has(name))) { + functions.push({ name, node: init! }); + continue; + } + const emptyContainer = !!init && ((ts.isNewExpression(init) && ts.isIdentifier(init.expression) + && /^(Map|Set|WeakMap|WeakSet)$/.test(init.expression.text) && !init.arguments?.length) + || (ts.isArrayLiteralExpression(init) && init.elements.length === 0)); + if (isExported(statement) && isConst && emptyContainer) containers.push(name); + } + for (const name of bindingNames(declaration.name)) slots.set(name, !isConst); + } + } else if (ts.isFunctionDeclaration(statement) && statement.name && (isExported(statement) || exported.has(statement.name.text))) { + functions.push({ name: statement.name.text, node: statement }); + } + } + // Every assignment operator TypeScript has (`=` through `??=`: `+=`, `|=`, `<<=`, …), as numbers and bit flags are slots too. + const isAssignment = (kind: ts.SyntaxKind) => kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment; + /** `slot = …` for a let/var; `slot.x = …` or `slot[k] = …` for any binding. */ + const isSlotTarget = (raw: ts.Expression | undefined): boolean => { + const n = unwrap(raw); + if (!n) return false; + if (ts.isIdentifier(n)) return slots.get(n.text) === true; + if (ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n)) { + const target = unwrap(n.expression); + return !!target && ts.isIdentifier(target) && slots.has(target.text); + } + return false; + }; + const moduleFunctions = new Map(); + for (const statement of sf.statements) { + if (ts.isFunctionDeclaration(statement) && statement.name) moduleFunctions.set(statement.name.text, statement); + if (ts.isVariableStatement(statement)) for (const declaration of statement.declarationList.declarations) { + const init = unwrap(declaration.initializer); + if (ts.isIdentifier(declaration.name) && init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) + moduleFunctions.set(declaration.name.text, init); + } + } + /** Writes in a function body: assignment (`=`, `??=`, `||=`, `&&=`), a container mutation or `Object.assign(slot, …)` + * on a module binding, anywhere in the body including callbacks; or a call to a module function that writes (a + * private `apply(impl)` helper), followed transitively. A result reached while skipping a function already on the + * path (mutual recursion) is partial: it is passed up but not remembered, so a later setter that enters the cycle + * elsewhere is judged afresh. */ + const writesMemo = new Map(); + const writesSlot = (node: ts.Node, path: Set): { writes: boolean; partial: boolean } => { + let writes = false; + let partial = false; + const visit = (n: ts.Node): void => { + if (writes) return; + if (ts.isBinaryExpression(n) && isAssignment(n.operatorToken.kind) && isSlotTarget(n.left)) writes = true; + if ((ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) + && (n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken) && isSlotTarget(n.operand)) writes = true; + if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression)) { + const callee = n.expression; + if (ts.isIdentifier(callee.expression) && MUTATORS.has(callee.name.text) && slots.has(callee.expression.text)) writes = true; + if (ts.isIdentifier(callee.expression) && callee.expression.text === 'Object' && callee.name.text === 'assign') { + const target = unwrap(n.arguments[0]); + if (target && ts.isIdentifier(target) && slots.has(target.text)) writes = true; + } + } + if (ts.isCallExpression(n) && ts.isIdentifier(n.expression) && moduleFunctions.has(n.expression.text)) { + const helper = n.expression.text; + if (path.has(helper)) partial = true; + else if (writesMemo.has(helper)) writes ||= writesMemo.get(helper)!; + else { + const result = writesSlot(moduleFunctions.get(helper)!, new Set([...path, helper])); + if (result.writes || !result.partial) writesMemo.set(helper, result.writes); + else partial = true; + writes ||= result.writes; + } + } + ts.forEachChild(n, visit); + }; + visit(node); + return { writes, partial }; + }; + const setters = functions + .filter(({ name, node }) => SETTER.test(name) && !/ForTest|ForTesting|^__/.test(name) && writesSlot(node, new Set([name])).writes) + .map(({ name }) => name); + return { setters, containers }; + } + + /** Whether a Host file binds `name`: calls it (`name(…)`, `x.name(…)`), mutates the container + * (`name.set(…)`, …), or hands it over as a port value (a call argument or an object property). + * A call that only passes null or undefined (the teardown `setX(null)`) does not bind. With `inFunction`, + * only that function of the file (a declaration or a const initialised to a function) counts. */ + function bindsIn(file: string, name: string, inFunction?: string): boolean { + const source = ts.createSourceFile(file, read(path.join(repo, file)), ts.ScriptTarget.Latest, true); + const named = (n: ts.Node): ts.Node | undefined => + (ts.isFunctionDeclaration(n) && n.name?.text === inFunction) + || (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.name.text === inFunction && n.initializer) + ? n : ts.forEachChild(n, named); + const sf = inFunction ? named(source) : source; + if (!sf) return false; + const isName = (n: ts.Node) => (ts.isIdentifier(n) && n.text === name) || (ts.isPropertyAccessExpression(n) && n.name.text === name); + const isNullish = (n: ts.Node) => n.kind === ts.SyntaxKind.NullKeyword || (ts.isIdentifier(n) && n.text === 'undefined'); + let binds = false; + const visit = (n: ts.Node): void => { + if (ts.isCallExpression(n) && ((isName(n.expression) && !(n.arguments.length > 0 && n.arguments.every(isNullish))) || n.arguments.some(isName) + || (ts.isPropertyAccessExpression(n.expression) && MUTATORS.has(n.expression.name.text) && isName(n.expression.expression)))) binds = true; + if ((ts.isShorthandPropertyAssignment(n) && n.name.text === name) || (ts.isPropertyAssignment(n) && isName(n.initializer))) binds = true; + ts.forEachChild(n, visit); + }; + visit(sf); + return binds; + } + + /** The table as written: key, entry, and whether the entry sits on one line. */ + function table(): Array<{ key: string; entry: Entry; oneLine: boolean }> { + const sf = ts.createSourceFile(tableFile, read(tableFile), ts.ScriptTarget.Latest, true); + let literal: ts.ObjectLiteralExpression | undefined; + const visit = (n: ts.Node): void => { + if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.name.text === 'DESKTOP_MODULE_SETTERS' + && n.initializer && ts.isObjectLiteralExpression(n.initializer)) literal = n.initializer; + ts.forEachChild(n, visit); + }; + visit(sf); + assert.ok(literal, 'DESKTOP_MODULE_SETTERS not found'); + const line = (pos: number) => sf.getLineAndCharacterOfPosition(pos).line; + return literal.properties.map(property => { + assert.ok(ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name) && ts.isObjectLiteralExpression(property.initializer), + `unexpected entry ${property.getText(sf)}`); + const entry: Entry = { status: '' }; + for (const field of property.initializer.properties) { + assert.ok(ts.isPropertyAssignment(field) && ts.isIdentifier(field.name) && ts.isStringLiteral(field.initializer)); + (entry as Record)[field.name.text] = field.initializer.text; + } + return { key: property.name.text, entry, oneLine: line(property.getStart(sf)) === line(property.getEnd()) }; + }); + } + + it('classifies every setter the Host loads, and only those', async () => { + const graph = await hostImportGraph(); + const texts = new Map(graph.map(file => [file, read(path.join(repo, file))])); + const collected = new Set(); + for (const file of graph) { + if (!/^(apps\/desktop\/src|packages\/[^/]+\/src)\//.test(file) || /\/(_generated|vendor)\//.test(file)) continue; + const { setters, containers } = settersIn(file); + for (const name of setters) collected.add(`${file}#${name}`); + for (const name of containers) { + const mutation = new RegExp(`\\b${name}\\.(set|add|delete|clear|push|splice|unshift)\\(`); + if ([...texts].some(([other, text]) => other !== file && mutation.test(text))) collected.add(`${file}#${name}`); + } + } + const rows = table(); + const keys = rows.map(row => row.key); + expect([...collected].filter(key => !keys.includes(key)).sort(), 'setters missing from desktop-module-setters.ts').toEqual([]); + expect(keys.filter(key => !collected.has(key)), 'entries whose setter is gone').toEqual([]); + }, 60_000); + + /** Host files the Host loads, other than `file`, that call `fn` (`fn(…)` or `x.fn(…)`). */ + async function hostCallersOf(file: string, fn: string): Promise { + const callers: string[] = []; + for (const other of await hostImportGraph()) { + if (other === file || !/^apps\/host\/src\//.test(other)) continue; + const text = read(path.join(repo, other)); + if (!text.includes(fn)) continue; + const sf = ts.createSourceFile(other, text, ts.ScriptTarget.Latest, true); + let calls = false; + const visit = (n: ts.Node): void => { + if (ts.isCallExpression(n) && ((ts.isIdentifier(n.expression) && n.expression.text === fn) + || (ts.isPropertyAccessExpression(n.expression) && n.expression.name.text === fn))) calls = true; + if (!calls) ts.forEachChild(n, visit); + }; + visit(sf); + if (calls) callers.push(other); + } + return callers; + } + + it('keeps the table sorted, one entry per line, each status with its evidence', async () => { + const rows = table(); + const keys = rows.map(row => row.key); + expect(keys).toEqual([...keys].sort()); + expect(rows.filter(row => !row.oneLine).map(row => row.key)).toEqual([]); + for (const { key, entry } of rows) { + expect(['bound', 'pending', 'not-applicable', 'internal'], key).toContain(entry.status); + // No entry waits on an id or a row nobody has given it yet. + expect(entry.reason ?? '', key).not.toMatch(/\bto be (assigned|decided|added)\b/i); + if (entry.status === 'bound') { + // The Host file named must really bind it: a mention in a comment, string, type or import does not count. + expect(entry.where, key).toMatch(/^apps\/host\//); + const [whereFile, whereFunction] = entry.where!.split('#'); + expect(bindsIn(whereFile, key.split('#')[1], whereFunction), `${key} not bound in ${entry.where}`).toBe(true); + // A binding inside a function binds only if the Host calls it (main.ts bindHostProjectIconRuntime()). + if (whereFunction) expect((await hostCallersOf(whereFile, whereFunction)).length, `${entry.where} is never called`).toBeGreaterThan(0); + } else { + expect(entry.reason?.trim(), key).toBeTruthy(); + // Release table file lines drift with every edit; point at row ids, 甲/乙 gaps or section names. + expect(entry.reason, key).not.toMatch(/release table[^)]*\bline\s*\d/); + // Source line numbers drift too: name the file (and function), not `file.ts:12`. + expect(entry.reason, key).not.toMatch(/\.(ts|tsx|mts|cts|js|mjs|cjs):\d/); + if (entry.status === 'pending') expect(entry.reason, key).toMatch(/\brow \w+|[甲乙]/); + } + } + }, 60_000); +}); + +/** + * Rule: the build region is fixed per Host release (release table 甲 20, region-and-editions.md §2.4): + * scripts/build.mjs bakes --region into shared/brandRegion.ts, loaders/raw-hook.mjs follows + * CINDY_HOST_REGION from source. A desktop module that reads it therefore behaves as the Host's edition, + * not as the desktop build it was written for; each one the Host loads is judged and listed in + * apps/host/src/desktop-region-readers.ts. + * Collection: the Host's import graph of the setter guard above (hostImportGraph); in its desktop and + * package sources (generated and vendored code excluded), imports and re-exports of CURRENT_CINDY_REGION + * or CURRENT_APP_ID from shared/brandRegion, and direct reads of VITE_CINDY_AUTH_REGION or + * CINDY_AUTH_REGION on import.meta.env or process.env (comments and strings do not count); in the Host's + * own sources, region fallbacks `x === 'cn' ? 'cn' : 'global'` (either way round), keyed by the enclosing + * function: they fall to a fixed region rather than the release's, and are listed with why they cannot be + * reached (startDeviceLink and disableShareAvailability: only after sign-in sets the realm). + * Failure: a module that starts reading the region, or a reader that comes into the graph (the desktop + * inventory's 40 files outside it today), fails until the table says how it behaves on the Host; an entry + * whose file no longer reads fails too, so a fallback that moves to another function is judged again. + * Not seen: values derived from the region and exported under other names (regionalMoney.ts's + * DEFAULT_USAGE_CURRENCY, legalLinks.ts's LEGAL_LINKS): their modules are the listed readers. + */ +describe('desktop modules the Host loads that read the build region, classified for the Host', () => { + const tableFile = path.join(hostSrc, 'desktop-region-readers.ts'); + const REGION_CONSTANTS = new Set(['CURRENT_CINDY_REGION', 'CURRENT_APP_ID']); + const REGION_ENV = /^(VITE_)?CINDY_AUTH_REGION$/; + + /** The Host's own `x === 'cn' ? 'cn' : 'global'` fallbacks, by enclosing function. */ + function fallbacksIn(file: string): string[] { + const sf = ts.createSourceFile(file, read(path.join(repo, file)), ts.ScriptTarget.Latest, true); + const found = new Set(); + const isRegion = (n: ts.Expression) => ts.isStringLiteralLike(n) && (n.text === 'cn' || n.text === 'global'); + const enclosing = (n: ts.Node): string => { + for (let at: ts.Node | undefined = n.parent; at; at = at.parent) { + if ((ts.isFunctionDeclaration(at) || ts.isMethodDeclaration(at)) && at.name) return at.name.getText(sf); + if ((ts.isArrowFunction(at) || ts.isFunctionExpression(at)) && ts.isVariableDeclaration(at.parent)) return at.parent.name.getText(sf); + } + return ''; + }; + const visit = (n: ts.Node): void => { + if (ts.isConditionalExpression(n) && isRegion(n.whenTrue) && isRegion(n.whenFalse) + && (n.whenTrue as ts.StringLiteralLike).text !== (n.whenFalse as ts.StringLiteralLike).text + && ts.isBinaryExpression(n.condition) && n.condition.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken + && isRegion(n.condition.right) && (n.condition.right as ts.StringLiteralLike).text === (n.whenTrue as ts.StringLiteralLike).text) { + found.add(`${enclosing(n)}:realm-fallback`); + } + ts.forEachChild(n, visit); + }; + visit(sf); + return [...found]; + } + + function readsIn(file: string): string[] { + const sf = ts.createSourceFile(file, read(path.join(repo, file)), ts.ScriptTarget.Latest, true); + const found = new Set(); + const isEnv = (n: ts.Expression) => /^(import\.meta\.env|process\.env)$/.test(n.getText(sf).replace(/\?/g, '')); + const visit = (n: ts.Node): void => { + if ((ts.isImportDeclaration(n) || ts.isExportDeclaration(n)) && n.moduleSpecifier && ts.isStringLiteral(n.moduleSpecifier) + && /(^|\/)brandRegion(\.(js|ts))?$/.test(n.moduleSpecifier.text)) { + const named = ts.isImportDeclaration(n) ? n.importClause?.namedBindings : n.exportClause; + if (named && ts.isNamespaceImport(named)) found.add('*'); + if (named && (ts.isNamedImports(named) || ts.isNamedExports(named))) { + for (const element of named.elements) { + const name = (element.propertyName ?? element.name).text; + if (REGION_CONSTANTS.has(name)) found.add(name); + } + } + if (ts.isExportDeclaration(n) && !n.exportClause) found.add('*'); + } + if (ts.isPropertyAccessExpression(n) && REGION_ENV.test(n.name.text) && isEnv(n.expression)) found.add('env'); + if (ts.isElementAccessExpression(n) && ts.isStringLiteralLike(n.argumentExpression) + && REGION_ENV.test(n.argumentExpression.text) && isEnv(n.expression)) found.add('env'); + ts.forEachChild(n, visit); + }; + visit(sf); + return [...found]; + } + + /** The table as written: key, its `host` note, and whether the entry sits on one line. */ + function table(): Array<{ key: string; host: string; oneLine: boolean }> { + const sf = ts.createSourceFile(tableFile, read(tableFile), ts.ScriptTarget.Latest, true); + let literal: ts.ObjectLiteralExpression | undefined; + const visit = (n: ts.Node): void => { + if (ts.isVariableDeclaration(n) && ts.isIdentifier(n.name) && n.name.text === 'DESKTOP_REGION_READERS' + && n.initializer && ts.isObjectLiteralExpression(n.initializer)) literal = n.initializer; + ts.forEachChild(n, visit); + }; + visit(sf); + assert.ok(literal, 'DESKTOP_REGION_READERS not found'); + const line = (pos: number) => sf.getLineAndCharacterOfPosition(pos).line; + return literal.properties.map(property => { + assert.ok(ts.isPropertyAssignment(property) && ts.isStringLiteral(property.name) && ts.isObjectLiteralExpression(property.initializer), + `unexpected entry ${property.getText(sf)}`); + let host = ''; + for (const field of property.initializer.properties) { + assert.ok(ts.isPropertyAssignment(field) && ts.isIdentifier(field.name) && field.name.text === 'host' + && ts.isStringLiteral(field.initializer), `unexpected field in ${property.name.text}`); + host = field.initializer.text; + } + return { key: property.name.text, host, oneLine: line(property.getStart(sf)) === line(property.getEnd()) }; + }); + } + + it('lists every region reader the Host loads, and only those', async () => { + const collected = new Set(); + for (const file of await hostImportGraph()) { + // Parse only files that can match: each rule needs one of these words in the text. + const text = read(path.join(repo, file)); + if (/^apps\/host\/src\//.test(file) && /['"`]cn['"`]/.test(text)) for (const what of fallbacksIn(file)) collected.add(`${file}#${what}`); + if (!/^(apps\/desktop\/src|packages\/[^/]+\/src)\//.test(file) || /\/(_generated|vendor)\//.test(file)) continue; + if (/brandRegion|CINDY_AUTH_REGION/.test(text)) for (const what of readsIn(file)) collected.add(`${file}#${what}`); + } + const keys = table().map(row => row.key); + expect([...collected].filter(key => !keys.includes(key)).sort(), 'region readers missing from desktop-region-readers.ts').toEqual([]); + expect(keys.filter(key => !collected.has(key)), 'entries that no longer read the region').toEqual([]); + }, 60_000); +}); diff --git a/apps/host/cindy-host.service b/apps/host/cindy-host.service index 047c89d4aac..e142ab8b4dd 100644 --- a/apps/host/cindy-host.service +++ b/apps/host/cindy-host.service @@ -20,9 +20,13 @@ RestartSec=3 # SIGTERM, which is what systemd sends first. KillSignal=SIGTERM TimeoutStopSec=30 -# Environment the host reads. Set your region and profile explicitly so the -# service never guesses a different data root than your logged-in profile. -Environment=CINDY_HOST_REGION=global +# Environment the host reads. Set your profile explicitly so the service never +# guesses a different data root than your logged-in profile. +# Region: an installed release is built for one edition (cn or global) and +# needs nothing here; a CINDY_HOST_REGION naming the other edition makes it +# refuse to start. From a checkout (this unit's ExecStart) it chooses the +# edition, global when unset. +# Environment=CINDY_HOST_REGION=global # Environment=CINDY_HOST_DATA_DIR=%h/.config/CindyGlobal # Environment=CINDY_HOST_OWNER= diff --git a/apps/host/package.json b/apps/host/package.json index 403d3b52161..8e79012e8ea 100644 --- a/apps/host/package.json +++ b/apps/host/package.json @@ -8,9 +8,9 @@ "cindy-host-login": "./src/main.ts" }, "scripts": { - "typecheck": "tsc --noEmit -p tsconfig.json", + "typecheck": "cross-env NODE_OPTIONS=--max-old-space-size=8192 tsc --noEmit -p tsconfig.json", "start": "node --import tsx --import ./src/loaders/register-raw.mjs src/main.ts", - "test": "node --import tsx --import ./src/loaders/register-raw.mjs --test \"src/**/*.test.mjs\"", + "test": "node --import ./src/loaders/test-region.mjs --import tsx --import ./src/loaders/register-raw.mjs --test \"src/**/*.test.mjs\"", "build": "node scripts/build.mjs", "test:ipc-route": "node --import tsx --import ./src/loaders/register-raw.mjs scripts/ipc-route.e2e.mjs", "test:lifecycle": "node scripts/lifecycle.e2e.mjs", diff --git a/apps/host/scripts/build.mjs b/apps/host/scripts/build.mjs index efedf9948f5..184ae3d6235 100644 --- a/apps/host/scripts/build.mjs +++ b/apps/host/scripts/build.mjs @@ -11,18 +11,22 @@ import os from 'node:os'; import { execFileSync } from 'node:child_process'; import { parseArgs } from 'node:util'; import { build } from 'esbuild'; +import { WEB_SHIM_DEFINE } from '../src/web-client-build.mjs'; import { chromium } from 'playwright-core'; import { clientMigrationContract } from '../src/client-migration-contract.mjs'; import { selectReleaseHarnesses } from '../src/release-harnesses.mjs'; +import { assertWebRegion, selectReleaseRegion } from '../src/release-region.mjs'; import { redundantCopies } from '../src/release-dependency-copies.mjs'; const repo = fileURLToPath(new URL('../../..', import.meta.url)); const host = path.join(repo, 'apps/host'); const desktop = path.join(repo, 'apps/desktop'); const { values } = parseArgs({ options: { - output: { type: 'string' }, 'web-dir': { type: 'string' }, harnesses: { type: 'string' }, + output: { type: 'string' }, region: { type: 'string' }, 'web-dir': { type: 'string' }, harnesses: { type: 'string' }, } }); -if (!values.output) throw new Error('Usage: pnpm --filter @cindy/host build --output [--web-dir ] [--harnesses ]'); +if (!values.output) throw new Error('Usage: pnpm --filter @cindy/host build --output --region [--web-dir ] [--harnesses ]'); +// One release per edition, as the desktop: required, fixed at build time, checked before any work. +const region = selectReleaseRegion(values.region); // Resolved before any build work so an invalid selection fails immediately. const harnessSelection = selectReleaseHarnesses({ option: values.harnesses }); for (const warning of harnessSelection.warnings) console.warn(`Warning: ${warning}`); @@ -164,8 +168,10 @@ const nodePlugins = createNodePlugins(packages); try { const web = values['web-dir'] ? path.resolve(values['web-dir']) : path.join(desktop, '.vite/renderer/main_window'); await fs.access(path.join(web, 'index.html')); + // The web client is the desktop renderer, which bakes its region when it is built. + assertWebRegion(web, region); const metadata = { - version: (await readJson(path.join(desktop, 'package.json'))).version, + version: (await readJson(path.join(desktop, 'package.json'))).version, region, platform: process.platform, arch: process.arch, modules: process.versions.modules, nodeVersion: process.versions.node, }; @@ -177,6 +183,8 @@ try { await fs.cp(path.join(desktop, 'drizzle'), path.join(resources, 'drizzle'), { recursive: true, filter: file => !/[/\\]meta[/\\]\d+_snapshot\.json$/.test(file), }); + // The built-in Skill bundle, as the desktop packages it (forge extraResource system-skills). + await fs.cp(path.join(desktop, 'resources', 'system-skills'), path.join(resources, 'system-skills'), { recursive: true, dereference: true }); // Migration companion scripts remain byte-for-byte identical CommonJS, even // with .ts extensions. This must not change their frozen runtime hashes. await fs.mkdir(path.join(resources, 'config')); @@ -220,11 +228,17 @@ try { await fs.cp(electronRoot, path.join(resources, 'credential-runtime'), { recursive: true, dereference: true }); metadata.electronBinary = path.join('resources', 'credential-runtime', path.relative(electronRoot, executable)); await fs.copyFile(path.join(host, 'src/credentials/electron-codec.cjs'), path.join(bin, 'electron-codec.cjs')); + // Row 28c: the Chromium proxy helper, run by the same Electron (system proxy, PAC and auto-discovery). + await fs.copyFile(path.join(host, 'src/chromium-proxy-worker.cjs'), path.join(bin, 'chromium-proxy-worker.cjs')); await build({ absWorkingDir: repo, entryPoints: ['apps/desktop/src/main/host-platform/power-worker.desktop.ts'], outfile: path.join(bin, 'power-worker.cjs'), bundle: true, platform: 'node', format: 'cjs', target: 'node22', external: ['electron'] }); } const common = { absWorkingDir: repo, bundle: true, platform: 'node', target: 'node22', - plugins: nodePlugins, define: { __CINDY_HOST_RELEASE__: JSON.stringify(metadata) }, logLevel: 'warning' }; + plugins: nodePlugins, logLevel: 'warning', define: { + __CINDY_HOST_RELEASE__: JSON.stringify(metadata), + // The desktop modules' build region (shared/brandRegion.ts), as vite.main.config.ts bakes it. + 'import.meta.env.VITE_CINDY_AUTH_REGION': JSON.stringify(region), + } }; await build({ ...common, entryPoints: ['apps/host/src/main.ts'], outfile: path.join(bin, 'host.mjs'), format: 'esm', banner: { js: 'import { createRequire as hostCreateRequire } from "node:module"; const require = hostCreateRequire(import.meta.url);' }, }); @@ -243,7 +257,7 @@ try { await fs.mkdir(path.join(resources, 'agent-net'), { recursive: true }); await fs.copyFile(path.join(repo, 'packages/agent-net-core/dist/core.wasm'), path.join(resources, 'agent-net', 'core.wasm')); await build({ absWorkingDir: repo, entryPoints: ['apps/web/shim.js'], outfile: path.join(resources, 'web/shim.js'), - bundle: true, platform: 'browser', format: 'iife', target: 'es2022', nodePaths: [path.join(host, 'node_modules')] }); + bundle: true, platform: 'browser', format: 'iife', target: 'es2022', nodePaths: [path.join(host, 'node_modules')], define: WEB_SHIM_DEFINE }); await build({ absWorkingDir: repo, entryPoints: ['apps/desktop/src/shared/ghostPageBridge.ts'], outfile: path.join(resources, 'plugin-bridge.js'), bundle: true, platform: 'browser', format: 'iife', globalName: 'CindyPluginBridge', target: 'es2022' }); diff --git a/apps/host/scripts/check-e2e-imports.mjs b/apps/host/scripts/check-e2e-imports.mjs new file mode 100644 index 00000000000..d663e50bacf --- /dev/null +++ b/apps/host/scripts/check-e2e-imports.mjs @@ -0,0 +1,108 @@ +#!/usr/bin/env node +// Load-only check of the acceptance scripts in this directory (CI: Host regressions). +// +// Most *.e2e.mjs scripts are not run in CI (native engines, browsers, long runs), so nothing +// noticed when scheduler-runtime.e2e.mjs stopped loading: a shared desktop module it reaches +// started importing Electron. This loads every module each script imports, statically or by a +// literal dynamic import(), through the loaders the scripts use, without running the script +// bodies. An Electron import fails with the chain of importers (electron-import-guard.mjs). +// +// Each script loads in its own process, with HOME, USERPROFILE and the temporary directory in a +// new empty directory; no account, credential, engine, browser or network is involved. +// usage: node scripts/check-e2e-imports.mjs (from apps/host) +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { register } from 'node:module'; +import { fileURLToPath } from 'node:url'; + +const scriptsDir = path.dirname(fileURLToPath(import.meta.url)); +const hostDir = path.dirname(scriptsDir); + +/** Scripts that are known not to load yet. Each entry says why; remove it once fixed. */ +const KNOWN_LOAD_FAILURES = { + 'scheduler-runtime.e2e.mjs': 'Since main 41ed3b9f40 the desktop scheduler runner reaches electron through ' + + 'im/shared/turnRetryNotice.ts -> im/shared/imText.ts -> i18n.desktop.ts ' + + '(docs/host/personal-migration-release-table.md, row 乙 1).', +}; + +if (process.argv[2] === '--load') { + // Child: load the given specifiers as the script would (this file sits in the same directory, + // so relative and package specifiers resolve exactly as they do from the script). + register('./electron-import-guard.mjs', import.meta.url); + try { + for (const specifier of process.argv.slice(4)) await import(specifier); + } catch (error) { + // Report and exit here: a production logger loaded above may hold an uncaught-exception listener. + console.error(error instanceof Error ? (error.stack ?? error.message) : String(error)); + process.exit(1); + } + // Module top-level code may leave handles open; loading is all this child checks. + process.exit(0); +} + +const { build } = await import('esbuild'); + +/** The specifiers a script imports itself: static imports, re-exports and literal import(). */ +async function importsOf(file) { + const found = []; + await build({ + entryPoints: [file], bundle: true, write: false, platform: 'node', format: 'esm', logLevel: 'silent', + plugins: [{ + name: 'collect-entry-imports', + setup(b) { + b.onResolve({ filter: /.*/ }, (args) => { + if (args.kind === 'entry-point') return undefined; + if (path.resolve(args.importer) === path.resolve(file) && (args.kind === 'import-statement' || args.kind === 'dynamic-import')) { + found.push(args.path); + } + return { path: args.path, external: true }; + }); + }, + }], + }); + return [...new Set(found)]; +} + +const scripts = fs.readdirSync(scriptsDir).filter((name) => name.endsWith('.e2e.mjs')).sort(); +const stale = Object.keys(KNOWN_LOAD_FAILURES).filter((name) => !scripts.includes(name)); +let failed = stale.length > 0; +for (const name of stale) console.error(`FAIL ${name}: listed as a known load failure but the script no longer exists`); + +for (const name of scripts) { + const file = path.join(scriptsDir, name); + const known = KNOWN_LOAD_FAILURES[name]; + if (known) { + console.log(`SKIP ${name}: known load failure, remove it from KNOWN_LOAD_FAILURES once it loads. ${known}`); + continue; + } + const specifiers = await importsOf(file); + if (specifiers.length === 0) { + // Every script imports something; none found means the collection itself broke. + failed = true; + console.error(`FAIL ${name}: no imports found; the import collection did not see this script`); + continue; + } + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-e2e-imports-')); + const started = Date.now(); + const env = { ...process.env, HOME: home, USERPROFILE: home, TMPDIR: home, TEMP: home, TMP: home, + ELECTRON_SKIP_BINARY_DOWNLOAD: '1' }; + delete env.XDT_OFFICIAL_SHARED_PROFILE; + const result = spawnSync(process.execPath, [ + '--import', 'tsx', '--import', './src/loaders/register-raw.mjs', + fileURLToPath(import.meta.url), '--load', name, ...specifiers, + ], { cwd: hostDir, env, encoding: 'utf8', timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }); + fs.rmSync(home, { recursive: true, force: true }); + const seconds = ((Date.now() - started) / 1000).toFixed(1); + if (result.status === 0) { + console.log(`PASS ${name}: ${specifiers.length} imports loaded (${seconds}s)`); + continue; + } + failed = true; + const output = `${result.stderr ?? ''}${result.stdout ?? ''}`.trim(); + const reason = result.error ? result.error.message : `exit ${result.status ?? result.signal}`; + console.error(`FAIL ${name}: ${reason} (${seconds}s)\n${output.split('\n').slice(0, 40).join('\n')}`); +} + +process.exitCode = failed ? 1 : 0; diff --git a/apps/host/scripts/chromium-proxy-worker.e2e.mjs b/apps/host/scripts/chromium-proxy-worker.e2e.mjs new file mode 100644 index 00000000000..26a1416e9b1 --- /dev/null +++ b/apps/host/scripts/chromium-proxy-worker.e2e.mjs @@ -0,0 +1,352 @@ +// Acceptance for the Chromium proxy helper (release table row 28, 28c) with the repository's real Electron: +// src/chromium-proxy-worker.cjs and its Host side, src/chromium-proxy.ts. macOS and Windows only (the platforms +// whose Host release carries Electron); elsewhere it says so and exits 0. +// +// Changes no system settings and reads none: every helper started here uses a PAC script served from loopback +// (CINDY_PROXY_WORKER_TEST_CONFIG, session.setProxy) and Chromium's --no-proxy-server, plus --use-mock-keychain. +// Those are test switches; the production launcher passes none of them (guarded in +// hostDesktopSourceContracts.guard.test.ts), and the macOS comparison workflow starts it the production way. +// +// usage (from apps/host): node --import tsx --import ./src/loaders/register-raw.mjs scripts/chromium-proxy-worker.e2e.mjs +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import fs from 'node:fs'; +import { createServer } from 'node:http'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +import { + chromiumProxyWorkerStdio, createChromiumProxyHelper, createChromiumProxyWorkerTransport, FIRST_BACKOFF_MS, +} from '../src/chromium-proxy.ts'; + +if (process.platform !== 'darwin' && process.platform !== 'win32') { + console.log('The Chromium proxy helper runs on macOS and Windows only; nothing to check here.'); + process.exit(0); +} + +const hostDir = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const electron = createRequire(path.join(hostDir, '../desktop/package.json'))('electron'); +const script = path.join(hostDir, 'src/chromium-proxy-worker.cjs'); +const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-proxy-helper-e2e-')); +const diagnostics = fs.mkdtempSync(path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'cindy-proxy-helper-logs-')); +console.log(`Chromium proxy helper diagnostics: ${diagnostics}`); +const TEST_ARGS = ['--use-mock-keychain', '--no-proxy-server']; +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); +const STDERR_MODE = 'pipe'; +const TAIL_LINES = 50; + +// The PAC file arrives after 400 ms, so a helper that answered before loading it would answer DIRECT. +const PAC = 'function FindProxyForURL(url, host) { if (dnsDomainIs(host, ".intranet.test")) return "DIRECT"; return "PROXY 127.0.0.1:9"; }'; +const pacServer = createServer((_request, response) => setTimeout(() => { + response.writeHead(200, { 'content-type': 'application/x-ns-proxy-autoconfig' }); + response.end(PAC); +}, 400)); +let testConfig; + +/** The production launcher's spawn, with the test configuration and switches added. */ +const testSpawn = (binary, args, options) => spawn(binary, [...args, ...TEST_ARGS], + { ...options, env: { ...options.env, CINDY_PROXY_WORKER_TEST_CONFIG: testConfig } }); + +async function check(name, run) { + const started = Date.now(); + console.log(`START ${name}`); + try { + await run(); + console.log(`ok ${name} (${Date.now() - started} ms)`); + } catch (error) { + console.error(`FAIL ${name}: ${error instanceof Error ? error.message : String(error)}`); + process.exitCode = 1; + } +} + +const childRunning = child => child.pid !== undefined && child.exitCode === null && child.signalCode === null; + +function trackChild(child) { + const ipc = child.channel != null; + let exit = null; + let stdioClosed = false; + let stderrClosed = !child.stderr; + let cleanupComplete = false; + const exited = new Promise(resolve => { + child.once('exit', (code, signal) => { + exit = { code, signal, at: performance.now() }; + resolve(); + }); + child.on('error', () => { if (child.pid === undefined) resolve(); }); + }); + const closed = new Promise(resolve => child.once('close', () => { + stdioClosed = true; + resolve(); + })); + const stderrDone = child.stderr && new Promise(resolve => child.stderr.once('close', () => { + stderrClosed = true; + resolve(); + })); + // Node can omit ChildProcess 'close' after a parent-side IPC disconnect even after the child and + // its streams close (nodejs/node#65646). For IPC, any stderr pipe must close on its own after exit. + const cleanedUp = (ipc ? Promise.all([exited, stderrDone]) : closed).then(() => { cleanupComplete = true; }); + return { child, exited, cleanedUp, observation: () => ({ exit, stdioClosed, stderrClosed, cleanupComplete }) }; +} + +async function within(promise, timeoutMs, message) { + let timer; + try { + return await Promise.race([promise, new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(message)), timeoutMs); + })]); + } finally { clearTimeout(timer); } +} + +async function stopTestChild({ child, cleanedUp }) { + if (childRunning(child)) child.kill('SIGKILL'); + try { + await within(cleanedUp, 3000, `child ${child.pid} did not finish cleanup`); + } finally { + if (child.connected) child.disconnect(); + child.stdin?.destroy(); + child.stdout?.destroy(); + child.stderr?.destroy(); + child.unref(); + } +} + +async function closeTestHelper(helper, children) { + try { await helper.close(); } + finally { await Promise.all(children.map(stopTestChild)); } +} + +const isAlive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } }; +async function gone(pid, ms) { + for (const until = Date.now() + ms; Date.now() < until; await delay(100)) if (!isAlive(pid)) return true; + return !isAlive(pid); +} + +async function waitForRound(condition, timeoutMs) { + const until = Date.now() + timeoutMs; + while (!condition() && Date.now() < until) await delay(20); + return condition(); +} + +async function checkStartupRound(run) { + const profile = path.join(root, `race-${run}`); + fs.mkdirSync(profile); + const env = { ...process.env, CINDY_PROXY_WORKER_PROFILE: profile, CINDY_PROXY_WORKER_TEST_CONFIG: testConfig }; + delete env.ELECTRON_RUN_AS_NODE; + const name = `round-${String(run).padStart(2, '0')}`; + const logFile = path.join(diagnostics, `${name}.chromium.log`); + const started = performance.now(); + const child = spawn(electron, [script, ...TEST_ARGS, '--enable-logging=file', `--log-file=${logFile}`], + { stdio: chromiumProxyWorkerStdio(process.platform, STDERR_MODE), env }); + const tracked = trackChild(child); + const transport = createChromiumProxyWorkerTransport(child, process.platform); + let closeRequestedAt = null; + let streamError = null; + let cleanupTimedOut = false; + let forcedStop = false; + const stderr = []; + const onError = error => { streamError ??= error; }; + child.on('error', onError); + const errors = createInterface({ input: child.stderr }); + errors.on('error', onError); + errors.on('line', line => { + stderr.push(line.slice(-4096)); + if (stderr.length > TAIL_LINES) stderr.shift(); + }); + + const answers = []; + let readyAt = null; + let id = 0; + transport.listen((line) => { + // The stream transport's stdout may also contain non-protocol lines. + let value; + try { value = JSON.parse(line); } catch { return; } + if (!value || typeof value !== 'object') return; + if (value.ready === true && value.pid === child.pid) readyAt = answers.length; + else if (Number.isSafeInteger(value.id) && value.id > 0 && value.id <= id) answers.push(value); + }, onError); + const ask = setInterval(() => { + if (!childRunning(child) || streamError || !transport.canWrite()) return; + transport.write(JSON.stringify({ id: ++id, method: 'resolve', url: 'https://api.example.test/v1' }), + error => { if (error) onError(error); }); + }, 20); + try { + await waitForRound(() => { + const { exit, cleanupComplete } = tracked.observation(); + return exit || cleanupComplete || streamError || (readyAt !== null && answers.slice(readyAt).some(a => a.result)); + }, 15_000); + } finally { + clearInterval(ask); + if (transport.canWrite()) { + closeRequestedAt = performance.now(); + transport.close(); + } + if (!await waitForRound(() => tracked.observation().cleanupComplete, 1500)) { + cleanupTimedOut = true; + if (childRunning(child)) forcedStop = child.kill('SIGKILL'); + if (!await waitForRound(() => tracked.observation().cleanupComplete, 1500)) { + child.stdin?.destroy(); + child.stdout?.destroy(); + child.stderr.destroy(); + transport.unref(); + child.unref(); + } + } + } + + const { exit, stdioClosed, stderrClosed, cleanupComplete } = tracked.observation(); + const summary = { run, pid: child.pid ?? null, stderrMode: STDERR_MODE, + exitCode: exit?.code ?? null, signal: exit?.signal ?? null, elapsedMs: exit && Math.round(exit.at - started), + closeToExitMs: exit && closeRequestedAt !== null && exit.at >= closeRequestedAt ? Math.round(exit.at - closeRequestedAt) : null, + stdioClosed, stderrClosed, cleanupComplete, cleanupTimedOut, forcedStop, + streamError: streamError?.code ?? streamError?.message ?? null }; + console.log(`Chromium proxy helper ${JSON.stringify(summary)}`); + fs.appendFileSync(path.join(diagnostics, 'rounds.jsonl'), `${JSON.stringify(summary)}\n`); + fs.writeFileSync(path.join(diagnostics, `${name}.stderr.log`), stderr.join('\n')); + + try { + assert.notEqual(readyAt, null, `run ${run}: ready`); + const before = answers.slice(0, readyAt); + assert.ok(before.length > 0, `run ${run}: received at least one answer before ready`); + assert.ok(before.every(a => a.error === 'not_ready'), `run ${run}: before ready only not_ready (${JSON.stringify(before.slice(0, 3))})`); + assert.ok(!answers.some(a => typeof a.result === 'string' && /DIRECT/.test(a.result)), `run ${run}: never DIRECT`); + assert.ok(answers.some(a => a.result === 'PROXY 127.0.0.1:9'), `run ${run}: the PAC result`); + if (streamError) throw streamError; + if (forcedStop || exit?.signal === 'SIGKILL') throw new Error('helper was forcibly stopped instead of exiting after its transport closed'); + if (cleanupTimedOut) throw new Error('helper cleanup timed out after its transport closed'); + } catch (error) { + const logTail = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8').trimEnd().split(/\r?\n/).slice(-TAIL_LINES).join('\n') : ''; + console.error(`Chromium proxy helper run ${run} failed (stderr=${STDERR_MODE}): ${error.message}\n` + + `stderr tail:\n${stderr.join('\n') || '(empty)'}\nChromium log tail:\n${logTail || '(empty or missing)'}`); + throw error; + } +} + +try { + await new Promise((resolve, reject) => { + pacServer.once('error', reject); + pacServer.listen(0, '127.0.0.1', resolve); + }); + testConfig = JSON.stringify({ mode: 'pac_script', pacScript: `http://127.0.0.1:${pacServer.address().port}/proxy.pac` }); + + // The Electron the Host release copies (scripts/build.mjs) is this one: cookie encryption must be off, so that the + // helper's Chromium never sets up Safe Storage (a keychain item on macOS). + await check('the Electron the Host ships has cookie encryption off', async () => { + const fuses = createRequire(path.join(hostDir, '../desktop/package.json'))('@electron/fuses'); + const wire = await fuses.getCurrentFuseWire(process.platform === 'darwin' ? path.resolve(electron, '../../..') : electron); + assert.equal(String.fromCharCode(wire[fuses.FuseV1Options.EnableCookieEncryption]), '0'); + }); + + // The helper's own promise, asked over its line protocol from the moment it starts: before it is ready every + // answer is not_ready, never DIRECT, and once ready it answers what the PAC script says. + await check('20 starts: no answer before ready, never DIRECT, then the PAC result', async () => { + const failed = []; + for (let run = 1; run <= 20; run++) { + try { await checkStartupRound(run); } + catch (error) { failed.push(`run ${run}: ${error.message}`); } + } + if (failed.length) throw new Error(failed.join('; ')); + }); + + await check('the Host side answers through Chromium and the PAC script, per host', async () => { + const home = path.join(root, 'host-side'); + fs.mkdirSync(home); + const children = []; + const helper = createChromiumProxyHelper({ profileDir: home, + spawnImpl: (binary, args, options) => { + const child = testSpawn(binary, args, { ...options, env: { + ...options.env, HOME: home, USERPROFILE: home, APPDATA: home, LOCALAPPDATA: home, + } }); + children.push(trackChild(child)); + return child; + }, + }); + try { + await helper.warmUp(); + assert.equal(await helper.resolveProxy('https://api.example.test/v1'), 'PROXY 127.0.0.1:9'); + assert.equal(await helper.resolveProxy('https://wiki.intranet.test/'), 'DIRECT'); + assert.equal(helper.state(), 'ready'); + // In memory: no cookie store or partition on disk under the helper's own directory. + const files = fs.readdirSync(path.join(root, 'host-side', 'proxy-helper'), { recursive: true }).map(String); + assert.ok(!files.some(file => /(^|[\\/])Cookies$/.test(file) || file.includes('cindy-proxy-helper')), files.join(', ')); + } finally { await closeTestHelper(helper, children); } + assert.equal(helper.state(), 'stopped'); + assert.deepEqual(fs.readdirSync(home), ['proxy-helper'], 'no caches, logs or saved state elsewhere in HOME'); + }); + + await check('a crashed helper: no answer meanwhile, started again after the backoff', async () => { + const children = []; + const helper = createChromiumProxyHelper({ profileDir: path.join(root, 'crash'), + spawnImpl: (...args) => { + const child = testSpawn(...args); + children.push(trackChild(child)); + return child; + } }); + try { + for (const until = Date.now() + 15_000; Date.now() < until; await delay(100)) { + if (await helper.resolveProxy('https://api.example.test/').catch(() => null)) break; + } + const first = children[0]; + if (!first || !childRunning(first.child) || !first.child.kill('SIGKILL')) { + throw new Error('the first helper exited before the crash step'); + } + await within(first.exited, 3000, 'the crashed helper did not exit'); + await delay(50); + assert.equal(helper.state(), 'backoff'); + await assert.rejects(helper.resolveProxy('https://api.example.test/'), /restarting/); + await delay(FIRST_BACKOFF_MS + 100); + let answer; + for (const until = Date.now() + 15_000; Date.now() < until && !answer; await delay(100)) { + answer = await helper.resolveProxy('https://api.example.test/').catch(() => undefined); + } + assert.equal(answer, 'PROXY 127.0.0.1:9'); + assert.equal(children.length, 2); + } finally { await closeTestHelper(helper, children); } + }); + + await check('the helper does not outlive a Host that is killed', async () => { + const parentScript = path.join(root, 'parent.mjs'); + fs.writeFileSync(parentScript, ` + import { spawn } from 'node:child_process'; + const { createChromiumProxyHelper } = await import(${JSON.stringify(new URL('../src/chromium-proxy.ts', import.meta.url).href)}); + let pid; + const helper = createChromiumProxyHelper({ profileDir: ${JSON.stringify(path.join(root, 'orphan'))}, + spawnImpl: (binary, args, options) => { const c = spawn(binary, [...args, ${TEST_ARGS.map(a => JSON.stringify(a)).join(', ')}], + { ...options, env: { ...options.env, CINDY_PROXY_WORKER_TEST_CONFIG: ${JSON.stringify(testConfig)} } }); pid = c.pid; return c; } }); + let answer; + for (const until = Date.now() + 15_000; Date.now() < until && !answer; ) { + answer = await helper.resolveProxy('https://api.example.test/').catch(() => null); + if (!answer) await new Promise(r => setTimeout(r, 100)); + } + if (!answer) { await helper.close(); throw new Error('helper did not answer before the parent-death test'); } + console.log(JSON.stringify({ pid })); + setInterval(() => {}, 1000); + `); + const parent = spawn(process.execPath, ['--import', 'tsx', '--import', './src/loaders/register-raw.mjs', parentScript], + { cwd: hostDir, stdio: ['ignore', 'pipe', 'inherit'] }); + const trackedParent = trackChild(parent); + try { + const output = createInterface({ input: parent.stdout }); + const line = await within(new Promise((resolve, reject) => { + output.once('line', resolve); + output.once('error', reject); + trackedParent.exited.then(() => reject(new Error('the parent exited early'))); + }), 25_000, 'the parent did not report a helper pid'); + const { pid } = JSON.parse(line); + assert.ok(isAlive(pid), 'the helper runs'); + parent.kill('SIGKILL'); + assert.ok(await gone(pid, 10_000), 'the helper quit after its Host was killed'); + } finally { await stopTestChild(trackedParent); } + }); +} finally { + if (pacServer.listening) { + const closed = new Promise(resolve => pacServer.close(resolve)); + pacServer.closeAllConnections(); + await closed; + } + fs.rmSync(root, { recursive: true, force: true }); +} + +console.log(process.exitCode ? 'Chromium proxy helper acceptance FAILED' : 'Chromium proxy helper acceptance passed'); diff --git a/apps/host/scripts/claude-proxy.e2e.mjs b/apps/host/scripts/claude-proxy.e2e.mjs index bf460dba487..9979da400cc 100644 --- a/apps/host/scripts/claude-proxy.e2e.mjs +++ b/apps/host/scripts/claude-proxy.e2e.mjs @@ -479,6 +479,68 @@ try { console.log('PASS Claude context overflow recovery on the gateway through the production wiring: the key changed during the rebuild and the replay used the new key, carrying the summary once; no client error; the next message carries no summary; a message sent through /api/chat is recovered and its stream ends on the replay'); } + // ---- Idle runtime release, through the queue as main.ts wires it (idle-release.ts) ---- + // An ordinary Claude task idle for its configured minutes (a test clock, no real wait) releases + // its Claude process; the next message resumes the same native session, whose history reaches + // the gateway. + { + const idleTask = 'claude-idle-release'; + await new OwnerSessionStorage({ db: () => database }).create({ id: idleTask, + title: 'Idle release fixture', agentKind: 'claude-code', model: 'claude-sonnet-4-5', workDir: root }); + await database.drizzle.update(sessions).set({ providerId: 'xd' }).where(eq(sessions.id, idleTask)); + const hub = createEventHub(); + const readSession = async id => (await database.drizzle.select().from(sessions).where(eq(sessions.id, id)).limit(1))[0]; + const clock = { monotonic: 0, wall: Date.now() }; + const queue = createInputQueue({ getMaker: () => graph.maker, hub, readSession, + getOwner: getCurrentDbClientSnapshot, + persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: event => hub.publish(event) }), + markStarted: async id => { markSessionTurnStarted(id); await drainSessionActiveTurnWrites(id); }, + markEnded: async (id, at) => { markSessionTurnEnded(id, at); await drainSessionActiveTurnWrites(id); }, + readClaudeIdleMinutes: () => 30, + idleReleaseClock: { monotonic: () => clock.monotonic, wall: () => clock.wall }, + }); + const seen = []; + const unsubscribe = hub.subscribe(event => { if (event.sessionId === idleTask) seen.push(event); }); + const doneCount = () => seen.filter(event => event.event?.type === 'done').length; + const until = async (predicate, what) => { + const deadline = Date.now() + 90_000; + // real-wait: the Claude process answers on its own schedule. + while (!predicate()) { + if (Date.now() > deadline) throw new Error(`Timed out waiting for ${what}`); + await new Promise(resolve => setTimeout(resolve, 50)); + } + }; + try { + await queue.enqueue(idleTask, { clientId: 'claude-idle-first', text: 'remember the word heron' }); + await until(() => doneCount() === 1, 'the first turn'); + const live = graph.maker.getSession(idleTask); + assert.ok(live?.sdkSessionId, 'the first turn has a native session'); + const nativeId = live.sdkSessionId; + await queue.scanIdleRelease(); + assert.equal(graph.maker.getSession(idleTask), live, 'not released before 30 idle minutes'); + clock.monotonic += 31 * 60_000; + clock.wall = Date.now() + 31 * 60_000; + await queue.scanIdleRelease(); + assert.equal(graph.maker.getSession(idleTask), undefined, 'released after 30 idle minutes'); + const beforeNext = requests.length; + await queue.enqueue(idleTask, { clientId: 'claude-idle-second', text: 'now return synthetic complete' }); + await until(() => doneCount() === 2, 'the resumed turn'); + assert.equal(graph.maker.getSession(idleTask)?.sdkSessionId, nativeId, 'the next message resumes the same native session'); + const resumed = requests.slice(beforeNext).filter(r => r.url.startsWith('/v1/messages') && !r.url.includes('count_tokens') + && /now return synthetic complete/.test(JSON.stringify(r.messages ?? []))); + assert.ok(resumed.length > 0, 'the resumed turn reached the gateway'); + assert.match(JSON.stringify(resumed[0].messages), /remember the word heron/, 'the resumed request carries the first turn'); + } finally { + unsubscribe(); + await queue.dispose(); + await graph.maker.closeSession(idleTask).catch(() => {}); + const exitDeadline = Date.now() + 10_000; + // real-wait: the process exits on its own schedule. + while ((await childPids()).length > 0 && Date.now() < exitDeadline) await new Promise(resolve => setTimeout(resolve, 100)); + } + console.log('PASS Claude idle release through the production wiring: released after 30 idle minutes (test clock); the next message resumes the same native session with its history'); + } + // Neither proxy secret is written anywhere: logs, the CLI's home and config, the profile. const secrets = [proxy.inboundSecret(), proxy.gatewayInboundSecret()]; let scanned = 0; diff --git a/apps/host/scripts/codex-runtime.e2e.mjs b/apps/host/scripts/codex-runtime.e2e.mjs index f4ab4d47a13..024487b5212 100644 --- a/apps/host/scripts/codex-runtime.e2e.mjs +++ b/apps/host/scripts/codex-runtime.e2e.mjs @@ -212,7 +212,9 @@ try { }; graph = createHostAgentGraph({ userDataDir: profile, providerConfig: config, gateway: modelAccess.gateway, codexBinaryPath: binary, codexRuntime: runtime, mcpRuntime: mcp, makerMemory: memory, - mcpProviders: createHostMemoryMcpProviders(memory), + // main.ts passes the helper's history decision (hostTools.readsAccountHistory); this run has no + // helper and never calls session_search, so every task reads as its own history only. + mcpProviders: createHostMemoryMcpProviders(memory, { readsAccountHistory: async () => false, deviceId: () => '' }), storage: new OwnerSessionStorage({ db: () => database }), }); attachAgentsToMakerMemory(memory, graph.instances); @@ -592,6 +594,60 @@ try { // The desktop product system prompt reaches the real Codex request (runtimeConfigsCore.ts). assert.ok(requests.some(request => JSON.stringify(request.body).includes('You are Cindy, an open-source AI assistant.')), 'Codex upstream request carries the Cindy product prompt'); + + // ---- Idle runtime release, through the queue as main.ts wires it (idle-release.ts) ---- + // An ordinary task idle for 30 minutes (a test clock, no real wait) releases its native Codex + // runtime; the next message resumes the same native thread, whose history reaches the upstream. + { + const idleTask = 'idle-release-native-fixture'; + await new OwnerSessionStorage({ db: () => database }).create({ id: idleTask, + title: 'Idle release fixture', agentKind: 'codex', model: 'fixture-model', workDir: root }); + await database.drizzle.update(sessions).set({ providerId: 'cprov-fixture' }).where(eq(sessions.id, idleTask)); + const clock = { monotonic: 0, wall: Date.now() }; + const idleQueue = createInputQueue({ getMaker: () => graph.maker, hub, readSession, + getOwner: getCurrentDbClientSnapshot, + persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: event => hub.publish(event) }), + markStarted: async id => { markSessionTurnStarted(id); await drainSessionActiveTurnWrites(id); }, + markEnded: async (id, at) => { markSessionTurnEnded(id, at); await drainSessionActiveTurnWrites(id); }, + readClaudeIdleMinutes: () => 30, + idleReleaseClock: { monotonic: () => clock.monotonic, wall: () => clock.wall }, + }); + const turnDone = () => { + let timer, unsubscribe; + return new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error('Idle release turn timed out')), 45_000); + unsubscribe = hub.subscribe(event => { + if (event.sessionId !== idleTask) return; + if (event.event?.type === 'done') resolve(); + if (event.event?.type === 'error') reject(new Error(`Idle release turn failed: ${JSON.stringify(event.event.data)}`)); + }); + }).finally(() => { clearTimeout(timer); unsubscribe?.(); }); + }; + try { + let done = turnDone(); + await idleQueue.enqueue(idleTask, { clientId: 'idle-first', text: 'remember the word heron' }); + await done; + const live = graph.maker.getSession(idleTask); + assert.ok(live?.sdkSessionId, 'the first turn has a native thread'); + const thread = live.sdkSessionId; + await idleQueue.scanIdleRelease(); + assert.equal(graph.maker.getSession(idleTask), live, 'not released before 30 idle minutes'); + clock.monotonic += 31 * 60_000; + clock.wall = Date.now() + 31 * 60_000; + await idleQueue.scanIdleRelease(); + assert.equal(graph.maker.getSession(idleTask), undefined, 'released after 30 idle minutes'); + const [row] = await database.drizzle.select().from(sessions).where(eq(sessions.id, idleTask)).limit(1); + assert.equal(row.sdkSessionId, thread, 'the task keeps its native thread'); + const before = requests.length; + done = turnDone(); + await idleQueue.enqueue(idleTask, { clientId: 'idle-second', text: 'return synthetic complete' }); + await done; + assert.equal(graph.maker.getSession(idleTask)?.sdkSessionId, thread, 'the next message resumes the same native thread'); + const resumed = JSON.stringify(requests.slice(before).map(request => request.body.input)); + assert.match(resumed, /remember the word heron/, 'the resumed request carries the first turn'); + } finally { await idleQueue.dispose(); } + console.log('PASS native Codex idle release through the production wiring: released after 30 idle minutes (test clock); the next message resumes the same native thread with its history'); + } console.log('PASS the Codex upstream request carries the Cindy product system prompt'); console.log('PASS native Codex + production Host: gateway and custom provider turns; key rotation during a live turn preserves completion and the next gateway task uses the new key'); diff --git a/apps/host/scripts/electron-import-guard.mjs b/apps/host/scripts/electron-import-guard.mjs new file mode 100644 index 00000000000..5f42f3e2dbb --- /dev/null +++ b/apps/host/scripts/electron-import-guard.mjs @@ -0,0 +1,24 @@ +// Module resolve hook for check-e2e-imports.mjs: an import of electron fails with the chain of +// importers that reached it. Registered by that script's child process, after tsx and the raw +// loader, so it sees every specifier first. +// Covers ESM imports (static and dynamic), which is how the shared desktop modules load under tsx. + +const root = new URL('../../../', import.meta.url).href; +/** First importer seen for each resolved module URL. */ +const parents = new Map(); +const short = (url) => (url.startsWith(root) ? url.slice(root.length) : url); + +export async function resolve(specifier, context, next) { + if (specifier === 'electron' || specifier.startsWith('electron/')) { + const chain = [specifier]; + const seen = new Set(); + for (let at = context.parentURL; at && !seen.has(at); at = parents.get(at)) { + seen.add(at); + chain.push(short(at)); + } + throw new Error(`ELECTRON_IMPORT: ${chain.reverse().join(' -> ')}`); + } + const result = await next(specifier, context); + if (context.parentURL && !parents.has(result.url)) parents.set(result.url, context.parentURL); + return result; +} diff --git a/apps/host/scripts/lifecycle.e2e.mjs b/apps/host/scripts/lifecycle.e2e.mjs index 37cbec05291..cc4d95881c5 100644 --- a/apps/host/scripts/lifecycle.e2e.mjs +++ b/apps/host/scripts/lifecycle.e2e.mjs @@ -68,10 +68,18 @@ function launch() { listening.catch(() => undefined); return { child, exit, listening }; } +const LIFECYCLE_TIMEOUT_MS = 90_000; +const timings = new Map(); +let stageStarted; +function beginStage(name) { + if (stageStarted) timings.set(stageStarted.name, performance.now() - stageStarted.time); + stageStarted = { name, time: performance.now() }; +} const deadline = setTimeout(() => { for (const child of children) child.kill('SIGTERM'); -}, 30_000); +}, LIFECYCLE_TIMEOUT_MS); try { + beginStage('first'); const first = launch(); await first.listening; const endpoint = readHostEndpoint(profile); @@ -85,6 +93,7 @@ try { assert.match(shim.headers.get('content-type'), /javascript/); assert.match(await shim.text(), /electronAPI/); } + beginStage('busy'); const second = launch(); const secondExit = await second.exit; assert.notEqual(secondExit.code, 0); @@ -95,16 +104,19 @@ try { assert.equal(readHostEndpoint(profile), null); assert.deepEqual(await readHostProcessStatus(profile), { running: false }); // The operating-system lease must be reusable after an orderly stop. + beginStage('replacement'); const replacement = launch(); await replacement.listening; assert.notEqual(readHostEndpoint(profile).instanceId, endpoint.instanceId); replacement.child.kill('SIGTERM'); assert.equal((await replacement.exit).code, 0); assert.equal(readHostEndpoint(profile), null); + beginStage('background'); background = await attachFromShortLivedLauncher(); assert.equal(background.started, true); assert.equal((await readHostProcessStatus(profile)).instanceId, background.instanceId); // New launcher (possibly from a new source checkout) reuses the live backend. + beginStage('reattach'); const reattached = await attachFromShortLivedLauncher(); assert.equal(reattached.started, false); assert.equal(reattached.pid, background.pid); @@ -114,6 +126,8 @@ try { console.log('PASS: background Host survives launcher exit; replacement launcher attaches to the same process and instance'); } finally { clearTimeout(deadline); + if (stageStarted) timings.set(stageStarted.name, performance.now() - stageStarted.time); + for (const [stage, ms] of timings) console.log(`lifecycle ${stage}: ${Math.round(ms)} ms`); const remaining = [...children]; const exits = remaining.map(child => child.exitCode !== null || child.signalCode !== null ? Promise.resolve() : once(child, 'exit')); diff --git a/apps/host/scripts/macos-system-proxy-compare.mjs b/apps/host/scripts/macos-system-proxy-compare.mjs new file mode 100644 index 00000000000..a86c74965b0 --- /dev/null +++ b/apps/host/scripts/macos-system-proxy-compare.mjs @@ -0,0 +1,188 @@ +#!/usr/bin/env node +// macOS system proxy comparison (release table row 28, 28b; .github/workflows/macos-system-proxy-compare.yml). +// +// THIS SCRIPT CHANGES THE MACHINE'S SYSTEM PROXY SETTINGS (networksetup, with sudo). It runs only on a +// GitHub-hosted macOS runner, which is thrown away afterwards; it refuses to start anywhere else. Never +// run it on a development machine or on your own computer. +// +// For each group of settings it sets them on every network service, then compares, URL by URL, the +// Host's result (src/macos-system-proxy.ts, reading the live settings through /usr/sbin/scutil --proxy) +// with Electron's session.defaultSession.resolveProxy (the repository's Electron, as the desktop asks it). +// It saves each group's scutil output as a sample (the runner holds no real settings or credentials; the +// authenticated group uses a fixture user and password), writes a report, and restores the settings. +// +// With PAC or auto-discovery the Host asks its Chromium proxy helper (28c, src/chromium-proxy.ts), started here +// exactly as in production (no test switch), so those groups must agree too. If scutil publishes a username +// for the selected HTTPS proxy, the Host must report it unresolved. Otherwise only routing is compared. +// Under PAC and auto-discovery, compare all Safe Storage item identities before and after the production helper. +// +// usage (on the runner, from apps/host): +// node --import tsx --import ./src/loaders/register-raw.mjs scripts/macos-system-proxy-compare.mjs +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import { createServer } from 'node:http'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { electronProxyResults } from './macos-system-proxy-reference.mjs'; + +import { createChromiumProxyHelper } from '../src/chromium-proxy.ts'; +import { createMacSystemProxySession, readScutilProxyOutput } from '../src/macos-system-proxy.ts'; + +function sampleNamesHttpsProxyUser(sample) { + // The fixture gives HTTPS and HTTP distinct addresses. Only the top-level HTTPSUser is relevant. + // SCPrint indents top-level keys by two spaces. As in the Host parser, a blank value names no one. + const user = /^ {2}HTTPSUser :(?: ([^\r\n]*))?\r?$/m.exec(sample)?.[1]; + return Boolean(user?.trim()); +} + +function compareProxyResult(group, url, host, chromium, namesHttpsProxyUser) { + const row = { group: group.name, url, chromium, host, ok: host === chromium }; + if (group.expect !== 'auth' || chromium !== group.authenticatedProxy) return row; + if (!namesHttpsProxyUser) return { ...row, authenticationRefusal: 'skipped-precondition' }; + const ok = host.startsWith('ERROR: the system proxy for this request requires authentication;'); + return { ...row, ok, authenticationRefusal: ok ? 'passed' : 'failed' }; +} + +function formatReport(report) { + return ['| group | url | Chromium | Host | Result | Authentication refusal |', '|---|---|---|---|---|---|', + ...report.map(row => `| ${row.group} | ${row.url} | ${row.chromium} | ${row.host} | ${row.ok ? 'ok' : 'MISMATCH'} | ${row.authenticationRefusal ?? ''} |`)].join('\n'); +} + +if (process.platform !== 'darwin' || process.env.GITHUB_ACTIONS !== 'true' + || process.env.RUNNER_ENVIRONMENT !== 'github-hosted' || process.env.CINDY_SYSTEM_PROXY_COMPARE !== '1') { + console.error('Refusing to run: this script changes the system proxy settings and runs only in the macOS ' + + 'system proxy comparison workflow on a GitHub-hosted runner.'); + process.exit(2); +} + +const outDir = path.resolve(process.argv[2] ?? 'system-proxy-compare'); +fs.mkdirSync(outDir, { recursive: true }); +const scriptsDir = path.dirname(fileURLToPath(import.meta.url)); +const desktopRequire = createRequire(path.join(scriptsDir, '../../desktop/package.json')); +const electronDir = path.dirname(desktopRequire.resolve('electron/package.json')); +const electronBinary = path.join(electronDir, 'dist', fs.readFileSync(path.join(electronDir, 'path.txt'), 'utf8').trim()); + +const URLS = [ + 'http://api.example.test/', 'https://api.example.test/', 'wss://api.example.test/', + 'https://example.com/', 'http://example.com/', 'https://www.example.com/', 'https://example.com:8443/', + 'https://exmple.com/', 'https://exaample.com/', 'https://a.example.com/', + 'https://intranet/', 'https://intranet.corp/', 'https://printer.local/', + 'https://localhost/', 'https://foo.localhost/', 'https://127.0.0.5/', 'https://[::1]/', 'https://[::ffff:127.0.0.1]/', + 'https://169.254.1.1/', 'https://169.0.3.4/', 'https://169.1.0.1/', 'https://[fe80::1]/', 'https://0.0.0.0/', + 'https://10.1.2.3/', 'https://10.9.9.9/', 'https://[fd12::1]/', +]; + +function networksetup(...args) { + execFileSync('/usr/bin/sudo', ['-n', '/usr/sbin/networksetup', ...args], { stdio: ['ignore', 'pipe', 'pipe'] }); +} + +const services = execFileSync('/usr/sbin/networksetup', ['-listallnetworkservices'], { encoding: 'utf8' }) + .split('\n').slice(1).map(line => line.replace(/^\*/, '').trim()).filter(Boolean); +if (services.length === 0) throw new Error('no network services'); + +function resetSettings() { + for (const service of services) { + for (const flag of ['-setwebproxystate', '-setsecurewebproxystate', '-setsocksfirewallproxystate', '-setautoproxystate', '-setproxyautodiscovery']) { + networksetup(flag, service, 'off'); + } + networksetup('-setproxybypassdomains', service, 'Empty'); + } +} + +const pacServer = createServer((_req, res) => { + res.writeHead(200, { 'content-type': 'application/x-ns-proxy-autoconfig' }); + res.end('function FindProxyForURL(url, host) { return "PROXY 10.9.9.9:8080"; }\n'); +}); +await new Promise(resolve => pacServer.listen(0, '127.0.0.1', resolve)); +const pacUrl = `http://127.0.0.1:${pacServer.address().port}/proxy.pac`; + +const HTTP = ['-setwebproxy', '10.0.0.1', '3128']; +const HTTPS = ['-setsecurewebproxy', '10.0.0.2', '3129']; +const SOCKS = ['-setsocksfirewallproxy', '10.0.0.3', '1081']; +const GROUPS = [ + { name: 'pac', settings: [HTTPS, ['-setautoproxyurl', pacUrl]] }, + { name: 'none', settings: [] }, + { name: 'http', settings: [HTTP] }, + { name: 'https', settings: [HTTPS] }, + { name: 'socks', settings: [SOCKS] }, + { name: 'http-socks', settings: [HTTP, SOCKS] }, + { name: 'https-socks', settings: [HTTPS, SOCKS] }, + { name: 'all', settings: [HTTP, HTTPS, SOCKS] }, + { name: 'exceptions', settings: [HTTP, HTTPS, ['-setproxybypassdomains', '*.local', '169.254/16', 'example.com:8443', + '10.0.0.0/8', 'ex?mple.com', 'https://www.example.com', 'a.example.com, b.example.com', 'fd00::/8']] }, + { name: 'subtract-implicit', settings: [HTTP, HTTPS, ['-setproxybypassdomains', '<-loopback>']] }, + { name: 'auto-discovery', settings: [HTTPS, ['-setproxyautodiscovery', 'on']] }, + // Only the HTTPS proxy is configured with a user. Some runners omit HTTPSUser in scutil output. + { name: 'authenticated', expect: 'auth', authenticatedProxy: 'PROXY 10.0.0.2:3129', + settings: [['-setsecurewebproxy', '10.0.0.2', '3129', 'on', 'ci-proxy-user', 'ci-proxy-pass'], HTTP] }, +]; + +function safeStorageItems() { + const script = path.join(scriptsDir, 'macos-system-proxy-keychain.swift'); + return new Set(JSON.parse(execFileSync('/usr/bin/swift', [script], { encoding: 'utf8', timeout: 60_000 }))); +} + +const report = []; +let mismatches = 0; +try { + for (const group of GROUPS) { + resetSettings(); + for (const service of services) for (const [flag, ...args] of group.settings) networksetup(flag, service, ...args); + // configd publishes the new dictionary asynchronously. + await new Promise(resolve => setTimeout(resolve, 2000)); + const sample = await readScutilProxyOutput(); + fs.writeFileSync(path.join(outDir, `scutil-${group.name}.txt`), sample); + const namesHttpsProxyUser = group.expect === 'auth' && sampleNamesHttpsProxyUser(sample); + if (group.expect === 'auth' && !namesHttpsProxyUser) { + console.log('authenticated: scutil did not publish a nonblank HTTPSUser on this runner. ' + + 'The refusal assertion was not run. Host and Electron routes are still compared.'); + } + // A new helper per group, started the production way (default launcher and assets, no test switch). + const helper = createChromiumProxyHelper({ profileDir: fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-proxy-compare-helper-')) }); + const session = createMacSystemProxySession(async () => sample, helper); + const needsHelper = await session.needsChromium(); + if (group.name === 'pac' && !needsHelper) throw new Error('no PAC in the runner system settings'); + const before = needsHelper ? safeStorageItems() : null; + const hostAnswers = new Map(); + try { + if (needsHelper) await helper.warmUp(); + for (const url of URLS) { + try { hostAnswers.set(url, await session.resolveProxy(url)); } + catch (error) { hostAnswers.set(url, `ERROR: ${error.message}`); } + } + } finally { + await helper.close(); + } + if (before) { + const additions = [...safeStorageItems()].filter(item => !before.has(item)).length; + report.push({ group: group.name, url: 'new Safe Storage items', chromium: '-', host: additions, ok: additions === 0 }); + if (additions) mismatches += 1; + } + const electron = await electronProxyResults(electronBinary, URLS); + for (const url of URLS) { + const host = hostAnswers.get(url); + const chromium = electron[url]; + // Check the PAC's verdict independently: two DIRECT answers could both have missed the PAC. + if (group.name.startsWith('pac') && url === 'https://api.example.test/' && chromium !== 'PROXY 10.9.9.9:8080') { + throw new Error(`PAC did not take effect for ${url}: Electron returned ${chromium}`); + } + const row = compareProxyResult(group, url, host, chromium, namesHttpsProxyUser); + if (!row.ok) mismatches += 1; + report.push(row); + } + } +} finally { + resetSettings(); + pacServer.close(); +} + +fs.writeFileSync(path.join(outDir, 'report.json'), `${JSON.stringify(report, null, 2)}\n`); +const table = formatReport(report); +fs.writeFileSync(path.join(outDir, 'report.md'), `${table}\n`); +if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `## macOS system proxy comparison\n\n${table}\n`); +console.log(table); +console.log(mismatches === 0 ? 'No mismatches in the checks that ran.' : `${mismatches} result(s) differ.`); +process.exitCode = mismatches === 0 ? 0 : 1; diff --git a/apps/host/scripts/macos-system-proxy-electron.cjs b/apps/host/scripts/macos-system-proxy-electron.cjs new file mode 100644 index 00000000000..c408474782f --- /dev/null +++ b/apps/host/scripts/macos-system-proxy-electron.cjs @@ -0,0 +1,19 @@ +// Run by macos-system-proxy-compare.mjs (macOS CI only) with the repository's Electron: prints, as one +// JSON line, Chromium's PAC result (session.defaultSession.resolveProxy) for each URL in the JSON array +// given as the last argument. The default session uses the system proxy settings, as the desktop's does +// (the desktop never calls setProxy). Reads settings only; changes nothing. +const { app, session } = require('electron'); + +if (process.env.CINDY_COMPARE_USER_DATA) app.setPath('userData', process.env.CINDY_COMPARE_USER_DATA); +app.dock?.hide(); + +app.whenReady().then(async () => { + const urls = JSON.parse(process.argv[process.argv.length - 1]); + const results = {}; + for (const url of urls) results[url] = await session.defaultSession.resolveProxy(url); + process.stdout.write(`${JSON.stringify(results)}\n`); + app.exit(0); +}).catch((error) => { + process.stderr.write(`${error && error.stack ? error.stack : String(error)}\n`); + app.exit(1); +}); diff --git a/apps/host/scripts/macos-system-proxy-keychain.swift b/apps/host/scripts/macos-system-proxy-keychain.swift new file mode 100644 index 00000000000..9c689e1cbd3 --- /dev/null +++ b/apps/host/scripts/macos-system-proxy-keychain.swift @@ -0,0 +1,32 @@ +// Compare item identities without reading passwords or writing account names to CI logs. +import Foundation +import Security + +let env = ProcessInfo.processInfo.environment +guard env["GITHUB_ACTIONS"] == "true", env["RUNNER_ENVIRONMENT"] == "github-hosted", + env["CINDY_SYSTEM_PROXY_COMPARE"] == "1" else { exit(2) } + +let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecReturnAttributes as String: true, + kSecReturnPersistentRef as String: true, + kSecMatchLimit as String: kSecMatchLimitAll, +] +var result: CFTypeRef? +let status = SecItemCopyMatching(query as CFDictionary, &result) +if status == errSecItemNotFound { + print("[]") + exit(0) +} +guard status == errSecSuccess, let rows = result as? [[String: Any]] else { + fatalError("Cannot enumerate keychain attributes (OSStatus \(status))") +} +let matches = rows.compactMap { row -> String? in + let names = [row[kSecAttrService as String], row[kSecAttrLabel as String]] + guard names.contains(where: { ($0 as? String)?.hasSuffix("Safe Storage") == true }) else { return nil } + guard let identity = row[kSecValuePersistentRef as String] as? Data else { + fatalError("Keychain query returned an item without its identity") + } + return identity.base64EncodedString() +} +print(String(decoding: try JSONEncoder().encode(matches.sorted()), as: UTF8.self)) diff --git a/apps/host/scripts/macos-system-proxy-reference.mjs b/apps/host/scripts/macos-system-proxy-reference.mjs new file mode 100644 index 00000000000..9899e9eaafb --- /dev/null +++ b/apps/host/scripts/macos-system-proxy-reference.mjs @@ -0,0 +1,22 @@ +// Shared Electron reference for the macOS and Windows CI comparisons. +import { execFile } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +const script = fileURLToPath(new URL('./macos-system-proxy-electron.cjs', import.meta.url)); + +export async function electronProxyResults(binary, urls) { + const userData = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-proxy-compare-electron-')); + try { + const env = { ...process.env, CINDY_COMPARE_USER_DATA: userData }; + delete env.ELECTRON_RUN_AS_NODE; + // This process serves the loopback PAC while Electron loads it. + const { stdout } = await promisify(execFile)(binary, [script, JSON.stringify(urls)], { env, timeout: 60_000 }); + return JSON.parse(stdout.trim().split('\n').at(-1)); + } finally { + fs.rmSync(userData, { recursive: true, force: true }); + } +} diff --git a/apps/host/scripts/pi-native.e2e.mjs b/apps/host/scripts/pi-native.e2e.mjs index ed44d86fce6..bf1ce29683b 100644 --- a/apps/host/scripts/pi-native.e2e.mjs +++ b/apps/host/scripts/pi-native.e2e.mjs @@ -307,6 +307,63 @@ try { } console.log('PASS Pi third-party route refusing the cache retention option: Pi retries without it in the turn and learns the route; no client error, no rebuild; the next message goes without it'); } + + // 4. Idle runtime release, through the queue as main.ts wires it (idle-release.ts): an ordinary Pi + // task idle for 30 minutes (a test clock, no real wait) releases its Pi process; the next message + // resumes the same native session, whose history reaches the provider. + { + const task = 'pi-idle-release'; + await new OwnerSessionStorage({ db: () => database }).create({ id: task, + title: 'Idle release fixture', agentKind: 'pi', model: 'fixture-pi-model', workDir: root }); + await database.drizzle.update(sessions).set({ providerId: 'cprov-pi' }).where(eq(sessions.id, task)); + const hub = createEventHub(); + const readSession = async id => (await database.drizzle.select().from(sessions).where(eq(sessions.id, id)).limit(1))[0]; + const clock = { monotonic: 0, wall: Date.now() }; + const queue = createInputQueue({ getMaker: () => graph.maker, hub, readSession, + getOwner: getCurrentDbClientSnapshot, + persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: event => hub.publish(event) }), + markStarted: async id => { markSessionTurnStarted(id); await drainSessionActiveTurnWrites(id); }, + markEnded: async (id, at) => { markSessionTurnEnded(id, at); await drainSessionActiveTurnWrites(id); }, + readClaudeIdleMinutes: () => 30, + idleReleaseClock: { monotonic: () => clock.monotonic, wall: () => clock.wall }, + }); + const seen = []; + const unsubscribe = hub.subscribe(event => { if (event.sessionId === task) seen.push(event); }); + const doneCount = () => seen.filter(event => event.event?.type === 'done').length; + const until = async (predicate, what) => { + const deadline = Date.now() + 60_000; + // real-wait: the Pi process answers on its own schedule. + while (!predicate()) { + if (Date.now() > deadline) throw new Error(`Timed out waiting for ${what}`); + await new Promise(resolve => setTimeout(resolve, 50)); + } + }; + try { + await queue.enqueue(task, { clientId: 'pi-idle-first', text: 'remember the word heron' }); + await until(() => doneCount() === 1, 'the first turn'); + const live = graph.maker.getSession(task); + assert.ok(live?.sdkSessionId, 'the first turn has a native session'); + const nativeId = live.sdkSessionId; + await queue.scanIdleRelease(); + assert.equal(graph.maker.getSession(task), live, 'not released before 30 idle minutes'); + clock.monotonic += 31 * 60_000; + clock.wall = Date.now() + 31 * 60_000; + await queue.scanIdleRelease(); + assert.equal(graph.maker.getSession(task), undefined, 'released after 30 idle minutes'); + const before = rejectsCacheRetention.requests.length; + await queue.enqueue(task, { clientId: 'pi-idle-second', text: 'now return synthetic complete' }); + await until(() => doneCount() === 2, 'the resumed turn'); + assert.equal(graph.maker.getSession(task)?.sdkSessionId, nativeId, 'the next message resumes the same native session'); + const resumed = rejectsCacheRetention.requests.slice(before).map(r => JSON.stringify(r.body)); + assert.ok(resumed.some(body => /now return synthetic complete/.test(body) && /remember the word heron/.test(body)), + 'the resumed request carries the first turn'); + } finally { + unsubscribe(); + await queue.dispose(); + await graph.maker.closeSession(task).catch(() => {}); + } + console.log('PASS Pi idle release through the production wiring: released after 30 idle minutes (test clock); the next message resumes the same native session with its history'); + } } catch (error) { process.exitCode = 1; throw error; diff --git a/apps/host/scripts/release-region.e2e.mjs b/apps/host/scripts/release-region.e2e.mjs new file mode 100644 index 00000000000..0e26352e0d1 --- /dev/null +++ b/apps/host/scripts/release-region.e2e.mjs @@ -0,0 +1,106 @@ +/** + * Packaged acceptance for the Host's edition: one release per region (region-and-editions.md §2.4). + * Separate from the unit suite: it needs one release of each region, built by scripts/build.mjs. + * + * CINDY_TEST_HOST_RELEASE_CN= CINDY_TEST_HOST_RELEASE_GLOBAL= \ + * node scripts/release-region.e2e.mjs (from apps/host) + * + * For each release, signed out, in a new empty profile and HOME (never a real profile): + * - release.json and `cindy-host status --json` give its build region; + * - the web client it serves is the renderer of that region, and boots with that region's voice input + * default language (zh-CN for cn, automatic for global), read by the packaged desktop module; + * - started with CINDY_HOST_REGION naming the other edition, it refuses with HOST_REGION_MISMATCH and + * publishes no endpoint. + * Takes about 10 s for both releases on an Apple Silicon Mac. + */ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { readHostEndpoint, requestHostStop } from '../src/control.mjs'; +import { readWebRegions } from '../src/release-region.mjs'; + +const RELEASES = { cn: process.env.CINDY_TEST_HOST_RELEASE_CN, global: process.env.CINDY_TEST_HOST_RELEASE_GLOBAL }; +for (const [region, dir] of Object.entries(RELEASES)) { + if (!dir) throw new Error(`Set CINDY_TEST_HOST_RELEASE_${region.toUpperCase()} to a ${region} release built by scripts/build.mjs`); +} +const VOICE_LANGUAGE = { cn: 'zh-CN', global: 'auto' }; +const other = region => (region === 'cn' ? 'global' : 'cn'); + +function releaseCommand(release, args) { + return [path.join(release, 'bin', process.platform === 'win32' ? 'node.exe' : 'node'), [path.join(release, 'bin', 'host.mjs'), ...args]]; +} + +function isolatedEnv(profile) { + const env = { ...process.env, CINDY_HOST_DATA_DIR: profile, CINDY_HOST_PORT: '0', + XDT_DEVICE_ID_OVERRIDE: 'cindy-release-region-isolated-test', HOME: path.join(profile, 'home') }; + env.USERPROFILE = env.HOME; + for (const key of ['CINDY_HOST_REGION', 'VITE_CINDY_AUTH_REGION', 'CINDY_HOST_OWNER', 'CINDY_HOST_OWNER_KEY', 'NODE_OPTIONS', 'NODE_PATH']) delete env[key]; + return env; +} + +async function run(release, args, env, timeoutMs = 20_000) { + const [command, argv] = releaseCommand(release, args); + const child = spawn(command, argv, { cwd: env.CINDY_HOST_DATA_DIR, env, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = '', stderr = ''; + child.stdout.on('data', chunk => { stdout += chunk; }); + child.stderr.on('data', chunk => { stderr += chunk; }); + const timer = setTimeout(() => child.kill(), timeoutMs); + const [code] = await once(child, 'exit'); + clearTimeout(timer); + return { code, stdout, stderr }; +} + +async function checkRelease(region, release) { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), `cindy-host-release-${region}-`)); + fs.mkdirSync(path.join(profile, 'home')); + const env = isolatedEnv(profile); + let serve; + try { + assert.equal(JSON.parse(fs.readFileSync(path.join(release, 'release.json'), 'utf8')).region, region, 'release.json region'); + assert.deepEqual(readWebRegions(path.join(release, 'resources', 'web')), [region], 'packaged renderer region'); + + const refused = await run(release, ['serve'], { ...env, CINDY_HOST_REGION: other(region) }); + assert.equal(refused.code, 1, `serve with CINDY_HOST_REGION=${other(region)} must fail: ${refused.stderr}`); + assert.match(refused.stderr, new RegExp(`HOST_REGION_MISMATCH: this Cindy Host release is the ${region} edition`)); + assert.equal(readHostEndpoint(profile), null, 'a refused Host publishes no endpoint'); + + const [command, argv] = releaseCommand(release, ['serve']); + serve = spawn(command, argv, { cwd: profile, env, stdio: ['ignore', 'pipe', 'pipe'] }); + let output = ''; + serve.stdout.on('data', chunk => { output += chunk; }); + serve.stderr.on('data', chunk => { output += chunk; }); + const deadline = Date.now() + 30_000; + while (!readHostEndpoint(profile)) { + if (serve.exitCode !== null || Date.now() > deadline) throw new Error(`${region} Host did not start:\n${output}`); + await delay(100); + } + const status = await run(release, ['status', '--json'], env); + assert.equal(status.code, 0, status.stderr); + assert.equal(JSON.parse(status.stdout).region, region, 'status --json region'); + + // The local API token stands in for a paired browser (server.mjs isWebAuthorized); unpaired, / is the connect page. + const token = fs.readFileSync(path.join(profile, 'host-api-token'), 'utf8').trim(); + const page = await fetch(readHostEndpoint(profile).baseUrl + '/', { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(10_000) }); + assert.equal(page.status, 200); + const boot = /window\.__cindyBoot=(\{.*?\});<\/script>/s.exec(await page.text()); + assert.ok(boot, 'the web client page carries its boot values'); + assert.equal(JSON.parse(boot[1]).voiceInput.settings.language, VOICE_LANGUAGE[region], 'voice input default language'); + console.log(`PASS ${region}: release.json, status and packaged renderer say ${region}; voice default ${VOICE_LANGUAGE[region]}; ` + + `CINDY_HOST_REGION=${other(region)} refused`); + } finally { + if (serve && serve.exitCode === null) { + await requestHostStop(profile).catch(() => undefined); + const stopped = once(serve, 'exit'); + const timer = setTimeout(() => serve.kill(), 15_000); + await stopped; + clearTimeout(timer); + } + fs.rmSync(profile, { recursive: true, force: true }); + } +} + +for (const [region, release] of Object.entries(RELEASES)) await checkRelease(region, path.resolve(release)); diff --git a/apps/host/scripts/windows-system-proxy-compare.mjs b/apps/host/scripts/windows-system-proxy-compare.mjs new file mode 100644 index 00000000000..46dce723c67 --- /dev/null +++ b/apps/host/scripts/windows-system-proxy-compare.mjs @@ -0,0 +1,117 @@ +// Windows system proxy comparison (release table row 28, 28c; .github/workflows/macos-system-proxy-compare.yml). +// +// THIS SCRIPT CHANGES THE MACHINE'S PROXY SETTINGS (the current user's Internet Settings in the registry). It runs +// only on a GitHub-hosted Windows runner, which is thrown away afterwards; it refuses to start anywhere else. Never +// run it on a development machine or on your own computer. +// +// For each group of settings it writes them, then compares, URL by URL, the Host's answer (its Chromium proxy +// helper, src/chromium-proxy.ts, started exactly as in production: no test switch) with Electron's +// session.defaultSession.resolveProxy (the repository's Electron, as the desktop asks it). Both are Chromium, so +// every group must agree; the manual group must also show a proxy, or the settings did not apply and the comparison +// would prove nothing. Auto-discovery (WPAD) is not set here: Windows keeps it in a binary connection blob. +// It restores the settings it found and writes a report. +// +// usage (on the runner, from apps/host): +// node --import tsx --import ./src/loaders/register-raw.mjs scripts/windows-system-proxy-compare.mjs +import { execFileSync, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import { createServer } from 'node:http'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { electronProxyResults } from './macos-system-proxy-reference.mjs'; + +import { createChromiumProxyHelper } from '../src/chromium-proxy.ts'; + +if (process.platform !== 'win32' || process.env.GITHUB_ACTIONS !== 'true' + || process.env.RUNNER_ENVIRONMENT !== 'github-hosted' || process.env.CINDY_SYSTEM_PROXY_COMPARE !== '1') { + console.error('Refusing to run: this script changes the proxy settings and runs only in the system proxy comparison ' + + 'workflow on a GitHub-hosted Windows runner.'); + process.exit(2); +} + +const outDir = path.resolve(process.argv[2] ?? 'system-proxy-compare'); +fs.mkdirSync(outDir, { recursive: true }); +const scriptsDir = path.dirname(fileURLToPath(import.meta.url)); +const electronBinary = createRequire(path.join(scriptsDir, '../../desktop/package.json'))('electron'); +const REG = path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'reg.exe'); +const KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'; +const VALUES = { ProxyEnable: 'REG_DWORD', ProxyServer: 'REG_SZ', ProxyOverride: 'REG_SZ', AutoConfigURL: 'REG_SZ' }; + +const URLS = [ + 'http://api.example.test/', 'https://api.example.test/', 'wss://api.example.test/', + 'https://example.com/', 'http://example.com/', 'https://www.example.com/', 'https://a.example.com/', + 'https://intranet/', 'https://localhost/', 'https://127.0.0.5/', 'https://10.1.2.3/', 'https://[::1]/', +]; + +function readValue(name) { + const result = spawnSync(REG, ['query', KEY, '/v', name], { encoding: 'utf8' }); + if (result.status !== 0) return null; + const line = result.stdout.split(/\r?\n/).find(row => row.trim().startsWith(name)); + return line ? line.trim().split(/\s{2,}/).slice(2).join(' ') : null; +} +function writeValue(name, value) { + if (value === null) spawnSync(REG, ['delete', KEY, '/v', name, '/f'], { stdio: 'ignore' }); + else execFileSync(REG, ['add', KEY, '/v', name, '/t', VALUES[name], '/d', String(value), '/f'], { stdio: 'ignore' }); +} +const original = Object.fromEntries(Object.keys(VALUES).map(name => [name, readValue(name)])); +const restore = () => { for (const [name, value] of Object.entries(original)) writeValue(name, value); }; + +const pacServer = createServer((_req, res) => { + res.writeHead(200, { 'content-type': 'application/x-ns-proxy-autoconfig' }); + res.end('function FindProxyForURL(url, host) { if (dnsDomainIs(host, ".example.com")) return "DIRECT"; return "PROXY 10.9.9.9:8080"; }\n'); +}); +await new Promise(resolve => pacServer.listen(0, '127.0.0.1', resolve)); +const pacUrl = `http://127.0.0.1:${pacServer.address().port}/proxy.pac`; + +const GROUPS = [ + { name: 'none', values: { ProxyEnable: 0, ProxyServer: null, ProxyOverride: null, AutoConfigURL: null } }, + { name: 'manual', mustProxy: 'https://example.com/', values: { ProxyEnable: 1, ProxyServer: '10.0.0.1:3128', ProxyOverride: null, AutoConfigURL: null } }, + { name: 'per-scheme', values: { ProxyEnable: 1, ProxyServer: 'http=10.0.0.1:3128;https=10.0.0.2:3129;socks=10.0.0.3:1081', ProxyOverride: null, AutoConfigURL: null } }, + { name: 'exceptions', values: { ProxyEnable: 1, ProxyServer: '10.0.0.1:3128', ProxyOverride: '*.example.com;10.*;', AutoConfigURL: null } }, + { name: 'pac', values: { ProxyEnable: 0, ProxyServer: null, ProxyOverride: null, AutoConfigURL: pacUrl } }, + { name: 'pac-and-manual', values: { ProxyEnable: 1, ProxyServer: '10.0.0.1:3128', ProxyOverride: null, AutoConfigURL: pacUrl } }, +]; + +const report = []; +let mismatches = 0; +try { + for (const group of GROUPS) { + for (const [name, value] of Object.entries(group.values)) writeValue(name, value); + const electron = await electronProxyResults(electronBinary, URLS); + const helper = createChromiumProxyHelper({ profileDir: fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-proxy-compare-helper-')) }); + try { + await helper.warmUp(); + for (const url of URLS) { + let host; + try { host = await helper.resolveProxy(url); } + catch (error) { host = `ERROR: ${error.message}`; } + const chromium = electron[url]; + // Check the PAC's verdict independently: two DIRECT answers could both have missed the PAC. + if (group.name.startsWith('pac') && url === 'https://api.example.test/' && chromium !== 'PROXY 10.9.9.9:8080') { + throw new Error(`PAC did not take effect for ${url}: Electron returned ${chromium}`); + } + const applied = !(group.mustProxy === url && !/PROXY/.test(String(chromium))); + const ok = host === chromium && applied; + if (!ok) mismatches += 1; + report.push({ group: group.name, url, chromium: applied ? chromium : `${chromium} (settings not applied)`, host, ok }); + } + } finally { + await helper.close(); + } + } +} finally { + restore(); + pacServer.close(); +} + +fs.writeFileSync(path.join(outDir, 'report.json'), `${JSON.stringify(report, null, 2)}\n`); +const table = ['| group | url | Chromium | Host | |', '|---|---|---|---|---|', + ...report.map(row => `| ${row.group} | ${row.url} | ${row.chromium} | ${row.host} | ${row.ok ? 'ok' : 'MISMATCH'} |`)].join('\n'); +fs.writeFileSync(path.join(outDir, 'report.md'), `${table}\n`); +if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `## Windows system proxy comparison\n\n${table}\n`); +console.log(table); +console.log(mismatches === 0 ? 'All results agree.' : `${mismatches} result(s) differ.`); +process.exitCode = mismatches === 0 ? 0 : 1; diff --git a/apps/host/src/agent/agent-deps-engines.ts b/apps/host/src/agent/agent-deps-engines.ts new file mode 100644 index 00000000000..5663d0f39b4 --- /dev/null +++ b/apps/host/src/agent/agent-deps-engines.ts @@ -0,0 +1,111 @@ +/** + * AgentDeps is one interface for the three engines. These bags write out, once, the optional ports + * that only another engine reads, so each Host engine bag in runtime.ts can be built with + * `explicitPorts` (explicit-ports.ts) without repeating them: a port the desktop adds later fails every + * engine bag until it is placed here or bound. + * + * Classified by reading maker-core (2026-11-17): a port belongs to the engines whose agent code + * (`agents/claude-code`, `agents/codex`, `agents/pi`) reads it from its deps; a port read in shared agent + * code (`base-agent.ts`) counts as read by all three and is not in any bag here. `toolLoopReviewer` is + * read by the Claude agent only (Codex and Pi take Maker's, MakerDeps.toolLoopReviewer). The agents keep + * the deps object as given and read its members with `?.` or `??`, so an explicit `undefined` is the same + * as an absent key. + */ +import type { AgentDeps } from '@cindy/maker-core'; + +type UnreadPorts = { [K in keyof AgentDeps]?: undefined }; + +/** Ports only the Codex agent reads. */ +export const PORTS_ONLY_CODEX_READS = { + armCodexHttpRecovery: undefined, + createCodexAuthTokenReader: undefined, + disableCodexPluginRuntime: undefined, + getCodexServerCompactionPreference: undefined, + getCodexSubagentIdentity: undefined, + getOutboundPathFact: undefined, + getRemoteCodexTransport: undefined, + isCodexAccountProvider: undefined, + isolateCodexAccountSessions: undefined, + onCodexLocalModelsListed: undefined, + prepareCodexExtraSpawnConfig: undefined, + prepareCodexHostToolCatalog: undefined, + prepareCodexLocalCredentialModeSwitch: undefined, + prepareCodexMcpToolCancellation: undefined, + prepareCodexResumeSession: undefined, + prepareCodexSkills: undefined, + recordCodexThreadLocation: undefined, + registerCodexChildThreadForParent: undefined, + registerCodexMcpThreadContext: undefined, + registerCodexSystemPromptForThread: undefined, + registerCodexTextOnlyPolicy: undefined, + registerLocalCodexAppServerProcess: undefined, + resolveCapabilityRouting: undefined, + resolveCodexContextWindowInfo: undefined, + resolveCodexLocalAuthPolicy: undefined, + resolveCodexSubagentRoutingSignature: undefined, + resolveCodexThreadContextWindow: undefined, + resolveCodexThreadStorage: undefined, + unregisterCodexMcpThreadContext: undefined, + withCodexMcpDiscoveryContext: undefined, +} as const satisfies UnreadPorts; + +/** Ports only the Pi agent reads. */ +export const PORTS_ONLY_PI_READS = { + derivePiProxySessionToken: undefined, + formatPiStartupCloudFileHint: undefined, + getLocalPiHttpsProxy: undefined, + getPiExtensionUiStrings: undefined, + getRemotePiAgentProxyEnv: undefined, + getRemotePiFileOps: undefined, + getRemotePiTransport: undefined, + mutatePiManagedPackage: undefined, + onPiManagedPackageMutationSettled: undefined, + preparePiExtraSpawnConfig: undefined, + registerPiProxySession: undefined, + remotePiSkipMcpBridge: undefined, + resolvePiAgentHome: undefined, + resolvePiGatewayModelApi: undefined, + resolvePiGatewayModelDescriptor: undefined, + resolvePiGatewayModelSpec: undefined, + resolvePiGlobalContextHome: undefined, + resolvePiManagedPackageResources: undefined, + resolvePiNativeCompatOverride: undefined, + resolvePiNativeCompatStorePath: undefined, + resolvePiNativePackagePaths: undefined, + resolvePiNativeProviders: undefined, + resolvePiProjectTrustInput: undefined, + resolvePiRuntimeModelDescriptor: undefined, + resolvePiRuntimeModels: undefined, + resolveRemotePiBinaryPath: undefined, + spawnPiSubagentRunner: undefined, +} as const satisfies UnreadPorts; + +/** Ports only the Claude agent reads. */ +export const PORTS_ONLY_CLAUDE_READS = { + claudeAllowedTools: undefined, + claudeHooks: undefined, + getClaudeSubagentTaskUsage: undefined, + registerClaudeSubagentTask: undefined, + remoteCcQueryFactory: undefined, + resolveCcDebugFile: undefined, + resolveClaudeSubagentModelAccess: undefined, + resolveLocalMcpDuplicateChoices: undefined, + resolveModelEfforts: undefined, + resolveModelMaxOutputTokens: undefined, + resolveRemoteClaudeRoute: undefined, + toolLoopReviewer: undefined, + trackCcDebugFile: undefined, +} as const satisfies UnreadPorts; + +/** Ports only the Claude and Pi agents read. */ +export const PORTS_ONLY_CLAUDE_AND_PI_READ = { + registerLocalAgentProcess: undefined, + toolLifecycleControl: undefined, + turnChangeCapture: undefined, +} as const satisfies UnreadPorts; + +/** Ports only the Claude and Codex agents read. */ +export const PORTS_ONLY_CLAUDE_AND_CODEX_READ = { + capabilityRouting: undefined, + resolveVerifiedContextWindow: undefined, +} as const satisfies UnreadPorts; diff --git a/apps/host/src/agent/agent-skills.ts b/apps/host/src/agent/agent-skills.ts new file mode 100644 index 00000000000..dfc483c25c4 --- /dev/null +++ b/apps/host/src/agent/agent-skills.ts @@ -0,0 +1,49 @@ +/** + * `/api/agent-skills`, the Host's `maker:list-agent-skills` (release table row 25, 25b; L1). + * + * As the desktop (maker-ipc/register.ts LIST_AGENT_SKILLS): refresh the shared global Skills first + * (Claude and Pi; Codex's own asset step is 25c), then list through `maker.listAgentSkills` with the + * request's disabled-Skill reader, so a Skill the user switched off is not offered. The Host used to + * call the engine's own scan, which skips that filter (L1, type A). + * + * While a desktop that opens this profile's database is running, the shared Skill roots belong to it: + * the refresh is skipped and the list shows what is already there (reviewer decision, 2026-11-17). + */ +import path from 'node:path'; + +import type { AgentKind, Maker } from '@cindy/maker-core'; + +import { builtInSkillDescriptorsAsync } from '../../../desktop/src/main/maker-host/built-in-skills.ts'; +import { readDisabledSkillPaths } from '../../../desktop/src/main/skillhub/activationPreferences.ts'; +import { getAppDataDir, getUserDataDir } from '../../../desktop/src/main/userDataPath.ts'; + +export interface HostAgentSkillListPorts { + maker(): Pick | null; + hasAgent(kind: AgentKind): boolean; + readStoredWorkDir(sessionId: string): Promise<{ found: boolean; workDir?: string | null }>; + /** The input queue's desktop hold; true while a desktop uses this profile. */ + isProfileHeld(): boolean; + ensureSharedGlobalSkills(): Promise; +} + +export function createHostAgentSkillList(ports: HostAgentSkillListPorts) { + return async (input: { agentKind?: string; workingDir?: string; sessionId?: string; forceReload?: boolean }) => { + const rawKind = String(input.agentKind ?? ''); + const kind: AgentKind = rawKind === 'codex' ? 'codex' : rawKind === 'pi' ? 'pi' : 'claude-code'; + const maker = ports.maker(); + if (!maker || !ports.hasAgent(kind)) return { success: false, error: `Agent '${kind}' is not registered` }; + const stored = input.sessionId ? await ports.readStoredWorkDir(input.sessionId) : null; + if (input.sessionId && !stored?.found) throw new Error('session not found'); + const workingDir = stored?.workDir || input.workingDir || undefined; + if (workingDir && !path.isAbsolute(workingDir)) throw new Error('workingDir must be absolute'); + if (kind !== 'codex' && !ports.isProfileHeld()) await ports.ensureSharedGlobalSkills(); + // The desktop's readActivation: the verified built-in descriptors, then the disabled paths. + const readDisabled = async () => readDisabledSkillPaths(await builtInSkillDescriptorsAsync(getUserDataDir(), getAppDataDir())); + const result = await maker.listAgentSkills(kind, { + ...(workingDir ? { workingDir } : {}), + ...(input.sessionId ? { sessionId: input.sessionId } : {}), + ...(kind === 'pi' && input.forceReload === true && !ports.isProfileHeld() ? { forceReload: true } : {}), + }, readDisabled); + return { success: true, skills: result.skills ?? [] }; + }; +} diff --git a/apps/host/src/agent/auto-resume.ts b/apps/host/src/agent/auto-resume.ts new file mode 100644 index 00000000000..88c1bd98698 --- /dev/null +++ b/apps/host/src/agent/auto-resume.ts @@ -0,0 +1,209 @@ +import type { Session } from '@cindy/maker-core'; +import type { AgentInputCoordinator } from '../../../desktop/src/main/maker-ipc/agent-input-coordinator.ts'; +import { createAutoResumeRuntime, type AutoResumeRuntimePorts } from '../../../desktop/src/main/maker-ipc/autoResumeRuntime.ts'; +import { + createInterruptedTurnAutoResumeHooks, + type InterruptedTurnAutoResumeHookPorts, +} from '../../../desktop/src/main/maker-ipc/interruptedTurnAutoResumeHooks.ts'; +import { + createUserMessageDurableWrite, + type UserMessageDurableWritePorts, +} from '../../../desktop/src/main/maker-ipc/userMessageDurableWrite.ts'; +import type { RuntimeFallbackResult } from '../../../desktop/src/main/maker-ipc/botCandidateRecovery.ts'; +import type { SuppressedTurnError } from '../../../desktop/src/main/maker-ipc/autoResumeBookkeeping.ts'; +import { readInterruptedTurnAutoResumeSettingsFrom } from '../../../desktop/src/main/maker-host/interruptedTurnAutoResumeSettingsCore.ts'; +import { readSilentStopAutoResumeSettingsFrom } from '../../../desktop/src/main/maker-host/silentStopAutoResumeSettingsCore.ts'; +import { createSessionRuntimeFallbackSettingsFile } from '../../../desktop/src/main/maker-host/sessionRuntimeFallbackSettingsCore.ts'; +import { explicitPorts } from './explicit-ports.ts'; +import type { HostProductTurn } from './product-turn.ts'; + +type CreateDbMessage = UserMessageDurableWritePorts['createDbMessage']; + +/** What the auto-resume runtime writes through for one task: the Host's event persistence of that task. */ +export interface AutoResumeHistory { + onTurnErrorEvent(sessionId: string, data: SuppressedTurnError, agentMeta: null): unknown; + markAutoResumeOutcome(sessionId: string, clientId: string | undefined, outcome: 'succeeded' | 'failed'): Promise; + saveTurnStartedAtForDeferred(sessionId: string): void; + getLastAssistantTranscriptUuid(sessionId: string): string | undefined; + getSessionDbAgentKind(sessionId: string): ReturnType; + enqueueDurableWrite: UserMessageDurableWritePorts['enqueueDurableWrite']; +} + +type AutoResumeLog = InterruptedTurnAutoResumeHookPorts['log']; + +export interface HostAutoResumePorts { + /** The profile the kill switches are read from, on every decision (as the desktop reads them). */ + userDataDir(): string; + /** The task's input coordinator; it is assembled after this runtime, so it is read when used. */ + coordinator(): AgentInputCoordinator; + /** The task's event persistence (turn-executor.mjs historyFor); read when used. */ + history(sessionId: string): AutoResumeHistory; + /** The task's live runtime, if any. */ + getSession(sessionId: string): Session | null | undefined; + /** Writes a user row (the Host's message store). */ + createDbMessage: CreateDbMessage; + /** The product-turn failure gate and finalizer of this runtime (product-turn.ts); read when used. */ + productTurn?(): HostProductTurn | null; + /** + * The automatic route change an auto-resume tries first (sessionRuntimeFallback.ts). Without it the + * resume stays on the task's route, as the desktop does when there is no other route. + */ + maybeApplySessionRuntimeFallback?: InterruptedTurnAutoResumeHookPorts['maybeApplySessionRuntimeFallback']; + /** The rebuild leases the route change marks on the runtime it switched (sessionRuntimeFallback.ts). */ + pendingSessionRuntimeFallbackRebuilds?: InterruptedTurnAutoResumeHookPorts['pendingSessionRuntimeFallbackRebuilds']; + /** + * A takeover ended without a resumed turn to answer its input: the held error row was written, or + * the takeover was dropped (Host-only; input-queue.mjs ends that input's /api/chat stream). + */ + onTakeoverReleased?(sessionId: string): void; + /** + * Coexistence plan A (input-queue.mjs holdForDesktop): a desktop that opens this profile's database + * is running. A resume that comes due then answers as superseded: the interrupted turn ends with its + * error in its history, as when the person takes over, and no continuation is queued (a queued one + * would be written to the queue snapshot the desktop is using). + */ + isProfileHeld(): boolean; + log: AutoResumeLog; +} + +/** The route stays as it is: what the desktop's fallback answers when it has nothing to change. */ +const UNCHANGED_ROUTE: RuntimeFallbackResult = { session: null, outcome: 'unchanged' }; + +/** + * The desktop's auto-resume for the Node Host: the process-wide runtime (autoResumeRuntime.ts), the + * input coordinator's interrupted-turn hooks (interruptedTurnAutoResumeHooks.ts) and the user-row + * write that charges the budgets (userMessageDurableWrite.ts), with register.ts's side effects bound + * to the Host's. Every optional port is written out; the ones left empty say why. + * + * The Host's scheduled input has a single source, the queue snapshot restored from the shared + * database at startup, and no runner to resume or settle it (release table B1). The five scheduler + * ports are therefore bound empty: beginSchedulerAutoResume, pendingSchedulerAutoResumeRunBySession, + * notifySchedulerAutoResumeFailed, the bookkeeping's onAutoResumeFailed and + * finishScheduledUsageLimitWait. The Host refuses provider-group, Teammate and Orca tasks at + * admission, so their held errors and terminals are never stashed. + */ +export function createHostAutoResume(ports: HostAutoResumePorts) { + const fallbackSettings = createSessionRuntimeFallbackSettingsFile(() => ports.userDataDir()); + const runtime = createAutoResumeRuntime(explicitPorts({ + isSilentStopAutoResumeEnabled: () => readSilentStopAutoResumeSettingsFrom(ports.userDataDir()).enabled, + // As register.ts: the route-change setting also turns the interrupted-turn resume on. + isInterruptedTurnAutoResumeEnabled: () => + readInterruptedTurnAutoResumeSettingsFrom(ports.userDataDir()).enabled || fallbackSettings.read().enabled, + guardLog: { debug: ports.log.debug, warn: ports.log.warn }, + bookkeeping: explicitPorts({ + // As register.ts (agentMeta null): the held error row, written once the takeover gives up. + persistSuppressedError: (sessionId, detail) => { + ports.history(sessionId).onTurnErrorEvent(sessionId, detail, null); + ports.onTakeoverReleased?.(sessionId); + }, + // As register.ts: once the held error row is written (persistSuppressedError, just before this, + // exactly once), the deferred product-turn failure is settled (settleDeferredProductTurnFailure): + // the held activity of the turn that failed is committed if that turn is still the current one + // (product-turn.ts). The desktop also shows the error in its Agent Island, which the Host has not. + surfaceSuppressedError: (sessionId) => { ports.productTurn?.()?.settleDeferred(sessionId); }, + // Orca and Teammate tasks are refused at Host admission: nothing is held for them. + finalizeOrcaSuppressedTerminal: undefined, + finalizeBotGroupSuppressedTerminal: undefined, + markOutcome: (sessionId, clientId, outcome) => { void ports.history(sessionId).markAutoResumeOutcome(sessionId, clientId, outcome); }, + abandonTakeover: (sessionId, message, attemptToken) => { + ports.coordinator().abandonAutoResume(sessionId, message, attemptToken); + ports.onTakeoverReleased?.(sessionId); + }, + // Scheduler (see above): no run is waiting on this attempt. + onAutoResumeFailed: undefined, + log: (message, fields) => ports.log.debug(message, fields), + }), + restoreAutoResumeRecovery: (sessionId, clientId, attemptToken) => + ports.coordinator().restoreAutoResumeRecovery(sessionId, clientId, attemptToken) === true, + // Scheduler (see above): no scheduled quota wait exists. + finishScheduledUsageLimitWait: () => {}, + // Provider-group tasks are refused at admission: no continuation is held. + settleProviderGroupContinuation: () => {}, + })); + const { interruptedTurnAutoResumeGuard, silentStopAutoResumeGuard, autoResumeBookkeeping, autoResumeAttemptToken } = runtime; + const pendingSessionRuntimeFallbackRebuilds = ports.pendingSessionRuntimeFallbackRebuilds ?? new WeakMap(); + const hooks = createInterruptedTurnAutoResumeHooks(explicitPorts>({ + inputCoordinator: { + isExecutionPaused: sessionId => ports.coordinator().isExecutionPaused(sessionId), + // As the desktop (register.ts): a retry of a proven-stopped startup admission runs only while its + // attempt is still the coordinator's current one. + isAutoResumeAttemptCurrent: (sessionId, attemptToken) => ports.coordinator().isAutoResumeAttemptCurrent(sessionId, attemptToken), + autoRetryLastError: (sessionId, attemptToken) => ports.isProfileHeld() + ? Promise.resolve('superseded' as const) + : ports.coordinator().autoRetryLastError(sessionId, attemptToken), + }, + interruptedTurnAutoResumeGuard, + settlePausedResumeIntoHistory: true, + autoResumeBookkeeping, + // Teammate tasks are refused at admission: no input carries a Teammate route to fall back from. + botFallbackInputs: { has: () => false }, + // Configured model groups are bound at dispatch in the desktop only. + modelGroupInputs: undefined, + resumeQuotaWait: undefined, + // The Host has no Orca worker dispatch or scheduled remote teammate quota waits. + workerInputs: undefined, + scheduledQuotaInputs: undefined, + saveTurnStartedAtForDeferred: sessionId => ports.history(sessionId).saveTurnStartedAtForDeferred(sessionId), + // Scheduler (see above). + beginSchedulerAutoResume: () => {}, + getStableSessionForTurnBoundary: sessionId => ports.getSession(sessionId) ?? null, + // The lease a continuation-only resume keeps on its runtime (register.ts keeps it across an + // unexpected close). The Host does not tear the resume down when a runtime closes, so nothing reads it. + pendingContinuationOnlyAutoResumeRebuilds: new WeakMap(), + maybeApplySessionRuntimeFallback: ports.maybeApplySessionRuntimeFallback ?? (async () => UNCHANGED_ROUTE), + pendingSessionRuntimeFallbackRebuilds, + // Provider-group tasks are refused at admission (see above). + providerGroupHeldErrors: { stash: () => {} }, + providerGroupHeldTerminals: { stash: () => {} }, + // Scheduler (see above). + pendingSchedulerAutoResumeRunBySession: { get: () => undefined }, + notifySchedulerAutoResumeFailed: () => {}, + autoResumeAttemptToken, + log: ports.log, + })); + /** + * The user-row write of a turn (register.ts createUserMessageDurably): it charges the budgets for a + * person's message and registers an auto-resume's pending outcome, and writes the row through the + * task's durable writes, behind its reply rows. + */ + const createUserMessage: CreateDbMessage = (sessionId, message, opts) => { + const history = ports.history(sessionId); + return createUserMessageDurableWrite(explicitPorts({ + autoResumeBookkeeping, silentStopAutoResumeGuard, interruptedTurnAutoResumeGuard, + // The usage-limit resume arrives with the third batch; until then a person's message has no + // usage-limit wait to restart. + usageLimitAutoResume: { noteUserAction: () => {} }, + // Provider-group tasks are refused at admission (see above). + getProviderGroupService: () => null, + // Behind the task's reply rows, as on the desktop, and with the desktop's failure handling: the + // desktop's write FIFO never pauses (it is not given onPersistenceError), so a failed user row goes + // back to the caller, which keeps the input as an error with its retry text, and is not written + // later. The Host's FIFO pauses and replays a failed write on resume; through it, a user row that + // failed would be written after its input was dropped or replaced (release table, section 2). + enqueueDurableWrite: (label, write) => history.enqueueDurableWrite(label, scope => Promise.resolve() + .then(() => write(scope)).then(value => ({ value }), (error: unknown) => ({ error }))) + .then(result => { if ('error' in result) throw result.error; return result.value; }), + getLastAssistantTranscriptUuid: id => history.getLastAssistantTranscriptUuid(id), + getSessionDbAgentKind: id => history.getSessionDbAgentKind(id), + createDbMessage: ports.createDbMessage, + }))(sessionId, message, opts); + }; + return { + ...runtime, + ...hooks, + createUserMessage, + /** + * An explicit stop withdraws both automatic resumes and their backoff, and the deferred product-turn + * failures of the task (register.ts resetAutomaticRecoveryForExplicitStop). The desktop also clears + * its MCP setup bridge, which the Host does not have. + */ + resetForExplicitStop(sessionId: string) { + silentStopAutoResumeGuard.noteSessionReset(sessionId); + interruptedTurnAutoResumeGuard.noteSessionReset(sessionId); + autoResumeBookkeeping.teardown(sessionId); + ports.productTurn?.()?.stopped(sessionId); + }, + }; +} + +export type HostAutoResume = ReturnType; diff --git a/apps/host/src/agent/auto-review.ts b/apps/host/src/agent/auto-review.ts index 6a2e77fcf93..b1a54ce680b 100644 --- a/apps/host/src/agent/auto-review.ts +++ b/apps/host/src/agent/auto-review.ts @@ -1,4 +1,8 @@ import { createAuxiliaryUsageRecorder } from '../../../desktop/src/main/usage/auxiliaryUsage.js'; +import { createMemoryReviewOneShotCore } from '../../../desktop/src/main/maker-host/memory-review-one-shot-core.js'; +import { createOneShotRouteGuard } from '../../../desktop/src/main/maker-host/oneShotRouteGuardCore.js'; +import { verdictForModelRouteWithProviders } from '../../../desktop/src/main/maker-host/model-route-guard-catalog.js'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; import type { AutoReviewDelegate, Maker } from '@cindy/maker-core'; import { createOneShotCandidates, DEDICATED_AUTO_REVIEW_CANDIDATES } from '../../../desktop/src/main/utility-model/oneShotCandidatesCore.js'; import { AUTO_REVIEW_ROUTER_GUARD_TIMEOUT_MS, createAutoReviewModelRouter } from '../../../desktop/src/main/maker-host/autoReviewModelRouterCore.js'; @@ -80,6 +84,38 @@ export function createHostAutoReview(options: { const toolLoopReviewer = createToolLoopReviewer({ requestText: (prompt, opts) => oneShot.requestUtilityText(options.getMaker(), prompt, { ...opts, source: 'tool-loop-review' }), }); + const memoryReview = (profileHold: () => string | null) => { + const assertNotHeld = () => { + const held = profileHold(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + }; + const listRouteGuardProviders = () => config.publicViews(Boolean(options.gateway?.credential)); + const isDisabled = createOneShotRouteGuard({ + listRouteGuardProviders, + verdictForModelRoute: (...args) => verdictForModelRouteWithProviders(listRouteGuardProviders, ...args), + }); + const review = createMemoryReviewOneShotCore({ + getMaker: options.getMaker, + requestText: (maker, prompt, opts) => oneShot.requestUtilityText(maker, prompt, { + ...opts, + beforeDispatch: async () => !profileHold(), + }), + }); + return { + isOneShotRouteDisabled: async (agent: Parameters[0]) => { + assertNotHeld(); + const disabled = await isDisabled(agent); + assertNotHeld(); + return disabled; + }, + reviewOneShot: async (...args: Parameters) => { + assertNotHeld(); + const result = await review(...args); + if (result === null) assertNotHeld(); + return result; + }, + }; + }; let contextResolver: AutoReviewDelegate['prepareRequest']; // As the desktop before its resolver is set: no review without the authorization context. reviewAutoPermissionAction.prepareRequest = async request => { @@ -87,7 +123,7 @@ export function createHostAutoReview(options: { return contextResolver(request); }; return { - reviewAutoPermissionAction, toolLoopReviewer, oneShot, chain, + reviewAutoPermissionAction, toolLoopReviewer, oneShot, chain, memoryReview, /** The desktop's setAutoReviewContextResolver. */ setContextResolver(resolver: AutoReviewDelegate['prepareRequest']) { contextResolver = resolver; }, }; diff --git a/apps/host/src/agent/codex-runtime.ts b/apps/host/src/agent/codex-runtime.ts index 4a193d8208d..faee5a74eab 100644 --- a/apps/host/src/agent/codex-runtime.ts +++ b/apps/host/src/agent/codex-runtime.ts @@ -1,6 +1,7 @@ import { createCodexLocalModelSink } from '../../../desktop/src/main/maker-host/codexLocalModelSink.js'; import { hostBlobStore, hostMediaIngest, hostMediaJournal } from '../media-store.js'; import { MAKER_PUSH } from '../../../desktop/src/main/maker-ipc/channels.js'; +import fs from 'node:fs'; import path from 'node:path'; import type { AgentDeps } from '@cindy/maker-core'; import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../../desktop/src/main/appSessionState.js'; @@ -29,6 +30,8 @@ import { createHostCodexCredentials } from './codex-credentials.js'; import { createHostCodexThreadStorage } from './codex-thread-storage.js'; import { invalidateHostCodexLogin } from './codex-invalidation.js'; import { createHostCodexSystemLogin, resolveHostSystemCodexAuthPath } from './codex-system-login.js'; +import { HOST_PROFILE_IN_USE_BY_DESKTOP } from './profile-coexistence.js'; +import { heldCredentialError } from './held-credentials.js'; import { createCodexAuthBoundary } from './codex-auth-boundary.js'; import { createCodexProxyInbound } from './codex-proxy-inbound.js'; import { createLogger } from '../../../desktop/src/main/logger.js'; @@ -56,12 +59,159 @@ export function createBridgeTokenReader(options: { check(): void; systemLogin: { reconcile(): Promise }; readAccessToken(providerId?: string): Promise | string | null; + /** Coexistence plan A: whether a Cindy desktop app running on its own uses this profile. */ + isProfileHeld?: () => boolean; + /** Logins upstream rejected while held (createHeldLoginRefusals). */ + refusals?: ReturnType; }) { return async (providerId?: string): Promise => { options.check(); - if (!providerId || providerId === 'openai') await options.systemLogin.reconcile(); + const nativeLogin = !providerId || providerId === 'openai'; + // While a desktop uses this profile, the reconciliation is skipped: it can relink and rewrite + // codex-home/auth.json, the login that desktop uses too (reviewer, 2026-11-17). + const held = options.isProfileHeld?.() === true; + if (nativeLogin && !held) await options.systemLogin.reconcile(); options.check(); - return options.readAccessToken(providerId); + const token = await options.readAccessToken(providerId); + // Released, this read forgets what was remembered while held. + if (nativeLogin && token) options.refusals?.assertUsable('openai', token); + // The bridge renews a token that expires within its margin and writes the result back to + // auth.json (anthropicResponsesBridgeHostCore.ts refreshIfNeeded). Two processes renewing one + // login rotate each other's refresh token out, so while held the request fails instead, saying why. + if (held && nativeLogin && token && expiresWithinBridgeMargin(token)) throw heldLoginExpired(); + return token; + }; +} + +/** The bridge's own renewal margin (anthropicResponsesBridgeHostCore.ts REFRESH_MARGIN_SEC); a guard + * test keeps the two equal. */ +export const BRIDGE_REFRESH_MARGIN_SEC = 120; +/** As the bridge's isExpired: a token whose `exp` cannot be read is not renewed early. */ +function expiresWithinBridgeMargin(token: string): boolean { + const part = token.split('.')[1]; + if (!part) return false; + try { + const exp = (JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf-8')) as { exp?: unknown }).exp; + return typeof exp === 'number' && Date.now() / 1000 >= exp - BRIDGE_REFRESH_MARGIN_SEC; + } catch { return false; } +} +const heldLoginExpired = () => heldCredentialError('the ChatGPT sign-in has expired, and it is not renewed'); + +/** + * Coexistence plan A (reviewer, 2026-11-17): a ChatGPT login the upstream rejected while a desktop + * uses this profile. Nothing is marked, unbound or removed (that login is the desktop's too); the + * rejection is remembered in this process, so later requests with the same token fail with the same + * reason instead of reaching the upstream again. Once the profile is released everything is + * forgotten: the next read reconciles, and a login that is really invalid takes the normal path. + */ +export function createHeldLoginRefusals(isProfileHeld: () => boolean) { + const rejected = new Map(); + return { + note(providerId: string, token: string | null, reason: string): void { + if (token) rejected.set(providerId, { token, reason }); + }, + /** The first read after the profile is released forgets every remembered rejection. */ + forgetIfReleased(): void { if (!isProfileHeld()) rejected.clear(); }, + /** Throws the remembered refusal for this token while held; forgets a replaced login. */ + assertUsable(providerId: string, token: string): void { + if (!isProfileHeld()) { rejected.clear(); return; } + const entry = rejected.get(providerId); + if (!entry) return; + if (entry.token !== token) { rejected.delete(providerId); return; } + throw new Error(`${HOST_PROFILE_IN_USE_BY_DESKTOP}: OpenAI rejected this ChatGPT sign-in (${entry.reason}). It is not marked ` + + 'invalid while a Cindy desktop app running on its own uses this data. Quit that app, then try again.'); + }, + }; +} + +/** + * The login ports the Host gives the shared subscription bridge (anthropicResponsesBridgeHostCore.ts), + * the default ChatGPT login and independently added Codex accounts alike. Released, they are the + * runtime's own reads and invalidations. While a desktop uses this profile (its codex-home and + * codex-accounts are that desktop's too): no reconciliation, no renewal of a token about to expire + * (the bridge renews only after reading the account home, :322–330), and an upstream rejection + * writes nothing (createHeldLoginRefusals). + */ +export function createHostBridgeLoginPorts(options: { + check(): void; + systemLogin: { reconcile(): Promise }; + native: Pick, 'readAccessToken' | 'captureDispatchProof'>; + accounts: Pick['codexAccounts'], 'codexAccountHome' | 'codexAccountState' | 'invalidateCodexAccount'>; + invalidateNative(reason: string): Promise; + isProfileHeld?: () => boolean; + /** The rejections remembered while held, shared with the engine's ports (createHostEngineLoginPorts). */ + refusals?: ReturnType; +}) { + const held = () => options.isProfileHeld?.() === true; + const refusals = options.refusals ?? createHeldLoginRefusals(held); + const accountToken = (home: string): string | null => { + try { + const token = JSON.parse(fs.readFileSync(path.join(home, 'auth.json'), 'utf8')).tokens?.access_token; + return typeof token === 'string' && token ? token : null; + } catch { return null; } + }; + return { + desktopCodexAuthAdapter: { + getAccessToken: createBridgeTokenReader({ check: options.check, systemLogin: options.systemLogin, + readAccessToken: providerId => options.native.readAccessToken(providerId), isProfileHeld: options.isProfileHeld, refusals }), + // The bridge has just matched the rejected token against getAccessToken above. + invalidate: async (reason: string) => { + if (held()) { refusals.note('openai', options.native.readAccessToken('openai'), reason); return; } + await options.invalidateNative(reason); + }, + captureOAuthDispatchProof: (accessToken: string, accountId: string | null, providerId?: string) => + options.native.captureDispatchProof(accessToken, accountId, providerId), + }, + codexAccountHome: (providerId: string) => { + const home = options.accounts.codexAccountHome(providerId); + refusals.forgetIfReleased(); + if (held()) { + const token = accountToken(home); + if (token) { + refusals.assertUsable(providerId, token); + if (expiresWithinBridgeMargin(token)) throw heldLoginExpired(); + } + } + return home; + }, + codexAccountState: (providerId: string) => options.accounts.codexAccountState(providerId), + invalidateCodexAccount: async (providerId: string, reason: string, failedAccessToken: string) => { + if (held()) { refusals.note(providerId, failedAccessToken, reason); return; } + await options.accounts.invalidateCodexAccount(providerId, reason, failedAccessToken); + }, + }; +} + +/** + * The login ports the Host gives the Codex engine (runtime.ts createCodexLocalCliAuth): its + * report that the server rejected the default login mid-turn (maker-core codex/index.ts + * onAuthInvalidated → auth.invalidate), and a check before a task spawns on that login. Released, + * the report is the runtime's invalidateNative. While a desktop uses this profile it writes nothing + * (no suppression or invalidation marker, no unbinding, no removed auth.json) and is remembered in + * the same refusals as the subscription bridge's: after either side saw a rejection, both the + * bridge's requests and a native spawn fail with that reason until the token changes or the profile + * is released. + */ +export function createHostEngineLoginPorts(options: { + native: Pick, 'readAccessToken'>; + accounts: Pick['codexAccounts'], 'isCodexAccountProvider'>; + invalidateNative(reason: string, context?: { providerId?: string; credentialGeneration?: string | null; credentialAttribution?: 'unproven' }): Promise; + isProfileHeld?: () => boolean; + refusals: ReturnType; +}) { + const held = () => options.isProfileHeld?.() === true; + return { + async invalidate(reason: string, context?: { providerId?: string; credentialGeneration?: string | null; credentialAttribution?: 'unproven' }): Promise { + if (!held()) { await options.invalidateNative(reason, context); return; } + // An independent account is never invalidated here (invalidateHostCodexLogin 'not-native'). + if (context?.providerId && context.providerId !== 'openai' && options.accounts.isCodexAccountProvider(context.providerId)) return; + options.refusals.note('openai', options.native.readAccessToken('openai'), reason); + }, + /** Before a task spawns on the default login: the remembered refusal, if any (forgotten once released). */ + assertNativeLoginUsable(): void { + const token = options.native.readAccessToken('openai'); + if (token) options.refusals.assertUsable('openai', token); + }, }; } @@ -73,6 +223,8 @@ export function createHostCodexRuntime(options: { availabilityPolicy: ReturnType; mcp: ReturnType; publish(channel: string, payload: unknown): void; + /** Coexistence plan A: whether a Cindy desktop app running on its own uses this profile. */ + isProfileHeld?: () => boolean; }) { const owner = activeOwnerScopeKey(); let closed = false; @@ -96,6 +248,7 @@ export function createHostCodexRuntime(options: { const systemLogin = createHostCodexSystemLogin({ codexHome: path.join(options.profileDir, 'codex-home'), systemAuthPath, loginActive: () => options.config.codexAccounts.isCodexAccountLoginActive('openai'), + isProfileHeld: options.isProfileHeld, // The desktop's onOAuthBindingClaimed: a claimed credential is an auth boundary for Pi. onBindingClaimed: () => { if (current()) options.mcp.invalidatePiEnvironment(); }, }); @@ -121,6 +274,8 @@ export function createHostCodexRuntime(options: { // (desktop: anthropic-responses-bridge-host.ts, pi-subscription-websocket.ts), with this // profile's credentials. Ports resolve at call time. const accounts = options.config.codexAccounts; + // One memory of the rejections seen while held, for the bridge and the engine alike. + const heldLogins = createHeldLoginRefusals(() => options.isProfileHeld?.() === true); const bridge = createAnthropicResponsesBridgeHost({ subscriptionRequestAllowsFast: (...args) => requestPolicy.subscriptionRequestAllowsFast(...args), isXaiSubscriptionProviderId: (...args) => isXaiSubscriptionProviderId(...args), @@ -130,15 +285,9 @@ export function createHostCodexRuntime(options: { peekGrokAccessToken: (...args) => options.config.grok.peekGrokAccessToken(...args), invalidateXaiBridgeAuth: (...args) => xai.invalidateXaiBridgeAuth(...args), chatgptAccountIdFromTokens: (...args) => chatgptAccountIdFromTokens(...args), - desktopCodexAuthAdapter: { - getAccessToken: createBridgeTokenReader({ check, systemLogin, readAccessToken: providerId => native.readAccessToken(providerId) }), - // The bridge has just matched the rejected token against getAccessToken above. - invalidate: reason => invalidateNative(reason), - captureOAuthDispatchProof: (accessToken, accountId, providerId) => native.captureDispatchProof(accessToken, accountId, providerId), - }, - codexAccountHome: (...args) => accounts.codexAccountHome(...args), - codexAccountState: (...args) => accounts.codexAccountState(...args), - invalidateCodexAccount: (...args) => accounts.invalidateCodexAccount(...args), + // The default login and independently added Codex accounts, with the coexistence hold. + ...createHostBridgeLoginPorts({ check, systemLogin, native, accounts, invalidateNative: reason => invalidateNative(reason), + isProfileHeld: options.isProfileHeld, refusals: heldLogins }), isOpenAiSubscriptionProviderId: (...args) => accounts.isOpenAiSubscriptionProviderId(...args), recordXaiRateLimitSnapshot: (...args) => usage.recordXaiRateLimitSnapshot(...args), }); @@ -173,6 +322,10 @@ export function createHostCodexRuntime(options: { disposeLocalHost: () => authBoundary.afterLogout(), onInvalidated: credentialScope => authBoundary.afterInvalidation(reason, credentialScope) }); }; + const engineLogins = () => { + const ports = createHostEngineLoginPorts({ native, accounts, invalidateNative, isProfileHeld: options.isProfileHeld, refusals: heldLogins }); + return { invalidateNative: ports.invalidate, assertNativeLoginUsable: ports.assertNativeLoginUsable }; + }; const readRoute = () => { check(); return { authInjection: proxy.getCodexProxyAuthInjectionState() ?? (native.hasLogin() ? 'oauth-bearer' : 'env-key') }; @@ -204,7 +357,8 @@ export function createHostCodexRuntime(options: { prepareRemote: async () => { throw new Error('SSH Codex transport is not configured in this Host'); }, }); const threadStorage = createHostCodexThreadStorage({ profileDir: options.profileDir, accounts, check }); - const deps: Partial = { + // Typed by its literal (checked against AgentDeps) so the Codex bag in runtime.ts sees exactly these ports. + const deps = { ...threadStorage.deps, prepareCodexExtraSpawnConfig: async (...args) => { check(); const value = inbound.withToken(await prepare(...args)); check(); return value; }, disableCodexPluginRuntime: true, @@ -247,7 +401,7 @@ export function createHostCodexRuntime(options: { getCodexSubagentIdentity: ({ childThreadId }) => proxy.getObservedCodexSubagentIdentity(childThreadId), armCodexHttpRecovery: proxy.armCodexHttpRecovery, registerCodexChildThreadForParent: ({ parentThreadId, childThreadId }) => { check(); proxy.registerChildThread(parentThreadId, childThreadId); }, - }; + } satisfies Partial; return { deps, proxy, native, readRoute, modelContext, /** This runtime's native Codex history, read only (context recovery's history classification). */ codexHistory: { @@ -256,7 +410,8 @@ export function createHostCodexRuntime(options: { }, /** Whether this runtime still belongs to the current owner (the agent graph's Codex token reader). */ isCurrent: current, fastPolicies: policies, fastRequestPolicy: requestPolicy, closeSession: proxy.unregister, - invalidateNative, authBoundary, systemAuthPath, systemLogin, + // The engine's ports (createHostEngineLoginPorts): its rejection report and the spawn check. + ...engineLogins(), authBoundary, systemAuthPath, systemLogin, /** What this runtime's Codex processes carry to its proxies (tests; never logged). */ inboundToken: () => inbound.token(), /** How this runtime retires the local Codex hosts (the agent graph's CodexAgent). */ diff --git a/apps/host/src/agent/codex-system-login.test.mjs b/apps/host/src/agent/codex-system-login.test.mjs index 64037d8b72c..f323aa1e535 100644 --- a/apps/host/src/agent/codex-system-login.test.mjs +++ b/apps/host/src/agent/codex-system-login.test.mjs @@ -40,8 +40,9 @@ import { createCodexLocalCliAuth } from './runtime.ts'; import { createHostCodexSystemLogin } from './codex-system-login.ts'; import { invalidateHostCodexLogin } from './codex-invalidation.ts'; import { createHostCodexCredentials } from './codex-credentials.ts'; -import { createBridgeTokenReader } from './codex-runtime.ts'; -import { bindNativeProviderAuth } from '../../../desktop/src/main/maker-host/nativeProviderAuthBinding.ts'; +import { createBridgeTokenReader, createHeldLoginRefusals, createHostBridgeLoginPorts, createHostEngineLoginPorts } from './codex-runtime.ts'; +import { createAnthropicResponsesBridgeHost } from '../../../desktop/src/main/maker-host/anthropicResponsesBridgeHostCore.ts'; +import { bindNativeProviderAuth, isNativeProviderAuthBound } from '../../../desktop/src/main/maker-host/nativeProviderAuthBinding.ts'; import { currentCodexCredentialGeneration } from '../../../desktop/src/main/maker-host/codexCredentialRead.ts'; import { lifoCleanup } from '../test-support/cleanup.mjs'; @@ -144,3 +145,523 @@ test('the subscription bridge reconciles before it reads the native token', { ti await read('codex-account-2'); assert.deepEqual(calls.splice(0), ['check', 'check', 'read:codex-account-2']); }); + +/* + * 测试价值 + * - 生产入口:createCodexLocalCliAuth 的 getState(/api/agents/auth-state 与 /api/agents/status 都不带参数调用它, + * maker.ts getAgentAuthState / getAgentStatus),对账用真实的 createHostCodexSystemLogin 和真实的 profile 文件。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。闸门关着时读 Codex 登录状态不对账:对账会改写 codex-home/auth.json + * 并把登录绑到账号,这两样都和占用 profile 的桌面共用;只按现有的 auth.json 和作废标记作答。 + * - 现有覆盖缺口:之前读状态一律对账,闸门不管读取路径。 + * - 最小失败输入:系统 Codex 已登录、profile 里还没有链接也没有绑定,闸门关着时读一次状态。 + * - tier:unit(临时目录里的真实文件;系统登录是临时目录下的路径,不读 HOME)。 + */ +test('while a desktop uses the profile, reading the Codex state does not reconcile, write or bind', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const { root, profileDir, codexHome } = isolatedProfile(t, 'held-owner'); + const systemAuth = path.join(root, 'fake-home', '.codex', 'auth.json'); + fs.mkdirSync(path.dirname(systemAuth), { recursive: true }); + fs.writeFileSync(systemAuth, authJson('system-token-held'), { mode: 0o600 }); + const real = createHostCodexSystemLogin({ codexHome, systemAuthPath: systemAuth, loginActive: () => false }); + let reconciles = 0; + const systemLogin = { ...real, reconcile: (...args) => { reconciles++; return real.reconcile(...args); } }; + let held = true; + const auth = createCodexLocalCliAuth(null, undefined, codexHome, { isCodexAccountLoginActive: () => false, isCodexAccountProvider: () => false }, + undefined, { systemLogin, isProfileHeld: () => held }); + // Every entry under the profile: kind, link target and bytes. + const snapshot = () => { + const out = {}; + const walk = dir => { for (const name of fs.readdirSync(dir).sort()) { + const file = path.join(dir, name); const stat = fs.lstatSync(file); const key = path.relative(profileDir, file); + if (stat.isSymbolicLink()) out[key] = `link:${fs.readlinkSync(file)}`; + else if (stat.isDirectory()) { out[key] = 'dir'; walk(file); } + else out[key] = fs.readFileSync(file).toString('base64'); + } }; + walk(profileDir); + return out; + }; + const before = snapshot(); + // auth-state, then status: both read the state without options. + await auth.getState(); + await auth.getState(); + assert.equal(reconciles, 0, 'no reconciliation while held'); + assert.deepEqual(snapshot(), before, 'nothing under the profile changed'); + assert.equal(isNativeProviderAuthBound('openai'), false, 'the login was not bound to the account'); + // Released, the same read reconciles: it links the system login and binds it, the writes skipped above. + held = false; + const state = await auth.getState(); + assert.ok(reconciles > 0); + assert.notDeepEqual(snapshot(), before); + assert.equal(isNativeProviderAuthBound('openai'), true); + assert.equal(state.authenticated, true); +}); + +/* + * 测试价值 + * - 生产入口:订阅桥(共用的 anthropicResponsesBridgeHostCore.ts)用 Host 给它的登录端口 + * (codex-runtime.ts 的 createHostBridgeLoginPorts,createHostCodexRuntime 原样装上)取 ChatGPT 令牌、读 + * codex-home/auth.json 或单独添加的 Codex 账号目录、必要时续期(getChatgptBridgeAuth,请求发出前就走这一步), + * 上游拒绝令牌时经 invalidateChatgptBridgeAuth 作废。对账用真实的 createHostCodexSystemLogin,凭据是临时 + * profile 里的真实文件。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。闸门关着时:桥读令牌不对账(对账会改写桌面也在用的 auth.json); + * 快过期的令牌不续期(两边各自续期会把对方的 refresh token 挤掉),请求带原因失败;上游拒绝时不作废(不删登录 + * 文件、不解绑、不写作废标记),只在本进程记住,之后的请求不再发上游、带同一原因失败;闸门放开后第一次读取照常 + * 对账,确实作废的登录走正常路径。单独添加的 Codex 账号的目录也在共用 profile 里,同样处理。 + * - 现有覆盖缺口:上面的“reconciles before it reads the native token”只测了放开时的顺序。 + * - 最小失败输入:闸门关着时取一次令牌(有效、已过期、快过期),上游拒绝一次再取一次。 + * - tier:unit(临时目录里的真实文件;续期请求是记录调用的桩,不联网)。 + */ +function bridgeFixture(t, ownerId) { + const { root, profileDir, codexHome } = isolatedProfile(t, ownerId); + const systemAuth = path.join(root, 'fake-home', '.codex', 'auth.json'); + fs.mkdirSync(path.dirname(systemAuth), { recursive: true }); + const accountHome = path.join(profileDir, 'codex-accounts', 'owner-hash', 'acct'); + fs.mkdirSync(accountHome, { recursive: true }); + const jwt = expSec => `h.${Buffer.from(JSON.stringify({ exp: expSec })).toString('base64url')}.s`; + const writeLogin = (home, token) => { + const body = JSON.stringify({ tokens: { access_token: token, refresh_token: 'refresh-fixture', account_id: 'workspace-a' } }); + fs.writeFileSync(path.join(home, 'auth.json'), body, { mode: 0o600 }); + // A different system login: a reconciliation would act on it. + fs.writeFileSync(systemAuth, authJson('system-token-other'), { mode: 0o600 }); + }; + bindNativeProviderAuth('openai', { instanceIsolated: true }); + const snapshot = () => { + const out = {}; + const walk = dir => { for (const name of fs.readdirSync(dir).sort()) { + const file = path.join(dir, name); const stat = fs.lstatSync(file); const key = path.relative(root, file); + if (stat.isSymbolicLink()) out[key] = `link:${fs.readlinkSync(file)}`; + else if (stat.isDirectory()) { out[key] = 'dir'; walk(file); } + else out[key] = fs.readFileSync(file).toString('base64'); + } }; + walk(root); + return out; + }; + let held = true; + const counts = { reconcile: 0, renew: 0, invalidateNative: [], invalidateAccount: [] }; + // The account service as the bridge and the credential reader see it: one added account, signed in. + const accounts = { isCodexAccountLoginActive: () => false, isCodexAccountProvider: id => id === 'acct', + codexAccountHome: id => (id === 'acct' ? accountHome : null), codexAccountState: () => ({ authenticated: true }), + invalidateCodexAccount: async (...args) => { counts.invalidateAccount.push(args); } }; + const credentials = createHostCodexCredentials(profileDir, accounts); + const real = createHostCodexSystemLogin({ codexHome, systemAuthPath: systemAuth, loginActive: () => false }); + const systemLogin = { ...real, reconcile: (...args) => { counts.reconcile++; return real.reconcile(...args); } }; + // The runtime's invalidateNative, recorded and real (codex-runtime.ts gives it the same input). + const invalidateNative = async (reason, context) => { + counts.invalidateNative.push(reason); + await invalidateHostCodexLogin({ codexHome, systemAuthPath: systemAuth, reason, ...context, isCodexAccountProvider: id => id === 'acct', + hostBound: context !== undefined, loginInProgress: () => false, isCurrent: () => true }); + }; + // One memory for the bridge and the engine, as createHostCodexRuntime builds them. + const refusals = createHeldLoginRefusals(() => held); + const ports = createHostBridgeLoginPorts({ check() {}, systemLogin, native: credentials, accounts, invalidateNative, + isProfileHeld: () => held, refusals }); + const engine = createHostEngineLoginPorts({ native: credentials, accounts, invalidateNative, isProfileHeld: () => held, refusals }); + // The Codex engine's auth adapter, with the ports runtime.ts createHostAgentGraph passes it. + const codexAuth = createCodexLocalCliAuth(null, undefined, codexHome, accounts, undefined, + { systemLogin, isProfileHeld: () => held, invalidate: engine.invalidate, assertNativeLoginUsable: engine.assertNativeLoginUsable }); + const bridge = createAnthropicResponsesBridgeHost({ + subscriptionRequestAllowsFast: () => false, isXaiSubscriptionProviderId: () => false, app: { getPath: () => profileDir }, + // The renewal request: answered with a failure, so a test run never writes a renewed login. + outboundFetch: async () => { counts.renew++; return new Response('{}', { status: 500 }); }, + getGrokAccessToken: async () => null, peekGrokAccessToken: () => null, invalidateXaiBridgeAuth: async () => false, + chatgptAccountIdFromTokens: tokens => tokens?.account_id ?? null, + ...ports, + isOpenAiSubscriptionProviderId: id => id === 'openai' || id === 'acct', recordXaiRateLimitSnapshot: () => {}, + }); + const now = () => Math.floor(Date.now() / 1000); + // A new login on disk is read by the next request, as after a login change (the bridge keeps a token up to 30 s). + const login = (dir, token) => { writeLogin(dir, token); bridge.clearChatgptBridgeCredentialCache(); }; + return { codexHome, accountHome, jwt, writeLogin: login, snapshot, bridge, codexAuth, counts, now, setHeld: value => { held = value; }, + // What the bridge does with an upstream 401 that names a revoked token. + reject: (providerId, token) => bridge.invalidateChatgptBridgeAuth({ status: 401, + body: '{"error":{"code":"token_revoked","message":"Your authentication token has been revoked."}}', failedAccessToken: token }, providerId) }; +} + +for (const [label, providerId, home] of [['the ChatGPT login', 'openai', 'codexHome'], ['an independently added Codex account', 'acct', 'accountHome']]) { + test(`while a desktop uses the profile, the subscription bridge neither reconciles nor renews ${label}`, { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = bridgeFixture(t, `bridge-held-${providerId}`); + // Held, a valid token: used as it is. + const valid = f.jwt(f.now() + 3600); + f.writeLogin(f[home], valid); + let before = f.snapshot(); + assert.equal((await f.bridge.getChatgptBridgeAuth(providerId)).accessToken, valid); + assert.deepEqual([f.counts.reconcile, f.counts.renew], [0, 0]); + assert.deepEqual(f.snapshot(), before, 'no file under the profile or the system login changed'); + // Held, an expired token, and one the bridge would renew early (within its 120 seconds): the + // request fails, saying why; nothing is renewed or written. + for (const exp of [f.now() - 60, f.now() + 60]) { + f.writeLogin(f[home], f.jwt(exp)); + before = f.snapshot(); + await assert.rejects(f.bridge.getChatgptBridgeAuth(providerId), + /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: the ChatGPT sign-in has expired, and it is not renewed while a Cindy desktop app/); + assert.deepEqual([f.counts.reconcile, f.counts.renew], [0, 0]); + assert.deepEqual(f.snapshot(), before); + } + // Released, the same read tries to renew the expiring token (and reconciles the default login). + f.setHeld(false); + await f.bridge.getChatgptBridgeAuth(providerId).catch(() => {}); + assert.equal(f.counts.renew, 1); + assert.equal(f.counts.reconcile > 0, providerId === 'openai'); + }); + + test(`while a desktop uses the profile, an upstream rejection of ${label} writes nothing and is not retried`, { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = bridgeFixture(t, `bridge-reject-${providerId}`); + const token = f.jwt(f.now() + 3600); + f.writeLogin(f[home], token); + assert.equal((await f.bridge.getChatgptBridgeAuth(providerId)).accessToken, token); + const before = f.snapshot(); + // Held: the rejection marks, unbinds and removes nothing. + await f.reject(providerId, token); + assert.deepEqual([f.counts.invalidateNative, f.counts.invalidateAccount], [[], []]); + assert.deepEqual(f.snapshot(), before); + // Later requests with that token fail before the upstream, with the same reason. + for (let i = 0; i < 2; i++) { + await assert.rejects(f.bridge.getChatgptBridgeAuth(providerId), + /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: OpenAI rejected this ChatGPT sign-in \(token_revoked\)/); + } + assert.deepEqual([f.counts.reconcile, f.counts.renew], [0, 0]); + assert.deepEqual(f.snapshot(), before); + // Released: the first read reconciles (the default login) and uses the login again; a + // rejection now takes the normal invalidation. + f.setHeld(false); + assert.equal((await f.bridge.getChatgptBridgeAuth(providerId)).accessToken, token); + assert.equal(f.counts.reconcile > 0, providerId === 'openai'); + // That read forgot the rejection: a later hold does not refuse the same login for it. + f.setHeld(true); + assert.equal((await f.bridge.getChatgptBridgeAuth(providerId)).accessToken, token); + f.setHeld(false); + await f.reject(providerId, token); + if (providerId === 'openai') assert.deepEqual(f.counts.invalidateNative, ['token_revoked']); + else assert.deepEqual(f.counts.invalidateAccount, [['acct', 'token_revoked', token]]); + }); +} + +/* + * 测试价值 + * - 生产入口:Codex 引擎的认证适配器(runtime.ts createCodexLocalCliAuth,带 createHostAgentGraph 传的 + * invalidate 与 assertNativeLoginUsable,来自 codex-runtime.ts createHostEngineLoginPorts):引擎在回合中途报 + * “服务端拒绝了登录”时调 auth.invalidate(maker-core codex/index.ts onAuthInvalidated,带 credentialAttribution + * 'unproven'),起本机 Codex 前调 getAuthEnv。作废是真实的 invalidateHostCodexLogin,凭据是临时 profile 里的真实文件。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。闸门关着时引擎报拒绝:写标记、解绑、删登录文件都不做,只记进程内的拒绝, + * 和订阅桥共用同一份记忆——引擎报过,桥的请求带同一原因失败;桥报过,起本机 Codex 也带同一原因失败; + * 闸门关着时起本机 Codex 也不对账。放开后同样的拒绝走正常作废。 + * - 现有覆盖缺口:桥那两条只测了桥自己报的拒绝。 + * - 最小失败输入:闸门关着时引擎报一次拒绝,再经桥取令牌;反过来桥报一次,再起本机 Codex。 + * - tier:unit(临时目录里的真实文件;续期请求是桩,不联网)。 + */ +test('while a desktop uses the profile, an engine-reported rejection writes nothing and the bridge and the engine share it', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = bridgeFixture(t, 'engine-reject'); + const token = f.jwt(f.now() + 3600); + f.writeLogin(f.codexHome, token); + const before = f.snapshot(); + // Held, the engine reports a rejection mid-turn: no marker, no unbinding, auth.json kept as it was. + await f.codexAuth.invalidate('token_revoked', { credentialAttribution: 'unproven' }); + assert.deepEqual(f.counts.invalidateNative, []); + assert.deepEqual(f.snapshot(), before); + assert.equal(isNativeProviderAuthBound('openai'), true); + // The bridge's next request fails before the upstream with that reason, and so does a native spawn. + const refusal = /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: OpenAI rejected this ChatGPT sign-in \(token_revoked\)/; + await assert.rejects(f.bridge.getChatgptBridgeAuth('openai'), refusal); + await assert.rejects(f.codexAuth.getAuthEnv({ credentialMode: 'oauth-bearer' }), refusal); + assert.deepEqual([f.counts.reconcile, f.counts.renew], [0, 0]); + assert.deepEqual(f.snapshot(), before); + // Released: the same report takes the real invalidation, which writes its marker. + f.setHeld(false); + await f.codexAuth.invalidate('token_revoked', { credentialAttribution: 'unproven' }); + assert.deepEqual(f.counts.invalidateNative, ['token_revoked']); + assert.notDeepEqual(f.snapshot(), before); +}); + +test('while a desktop uses the profile, a bridge-reported rejection also stops a native Codex spawn, which does not reconcile', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = bridgeFixture(t, 'bridge-then-engine'); + const token = f.jwt(f.now() + 3600); + f.writeLogin(f.codexHome, token); + // Held, a spawn on the login is allowed and does not reconcile. + assert.deepEqual(await f.codexAuth.getAuthEnv({ credentialMode: 'oauth-bearer' }), { CODEX_HOME: f.codexHome }); + assert.equal(f.counts.reconcile, 0); + await f.bridge.getChatgptBridgeAuth('openai'); + const before = f.snapshot(); + await f.reject('openai', token); + await assert.rejects(f.codexAuth.getAuthEnv({ credentialMode: 'oauth-bearer' }), + /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: OpenAI rejected this ChatGPT sign-in \(token_revoked\)/); + assert.deepEqual([f.counts.reconcile, f.counts.invalidateNative], [0, []]); + assert.deepEqual(f.snapshot(), before); + // Released: the spawn reconciles again and the remembered rejection is gone. + f.setHeld(false); + assert.deepEqual(await f.codexAuth.getAuthEnv({ credentialMode: 'oauth-bearer' }), { CODEX_HOME: f.codexHome }); + assert.ok(f.counts.reconcile > 0); +}); + +// ---- With a production Codex runtime (createHostCodexRuntime) and its provider configuration ---- +import fsp from 'node:fs/promises'; + +// §3.2 unit with isolated login files: getState already skips reconciliation when +// held at entry. The file read in a running reconciliation must also fence writes. +test('Codex reconciliation that loses profile access during the account read leaves the link and binding alone', async t => { + const { root, codexHome } = isolatedProfile(t, 'reconcile-race-owner'); + const systemAuth = path.join(root, 'system-auth.json'); + fs.writeFileSync(systemAuth, authJson('fixture-token')); + const readStarted = Promise.withResolvers(); + const continueRead = Promise.withResolvers(); + let held = false; + const read = fsp.readFile; + const mockedRead = t.mock.method(fsp, 'readFile', async (file, ...args) => { + if (file === systemAuth && !held) { + readStarted.resolve(); + await continueRead.promise; + } + return read(file, ...args); + }); + const systemLogin = createHostCodexSystemLogin({ + codexHome, systemAuthPath: systemAuth, loginActive: () => false, isProfileHeld: () => held, + }); + const auth = createCodexLocalCliAuth(null, undefined, codexHome, { + isCodexAccountLoginActive: () => false, isCodexAccountProvider: () => false, + }, undefined, { systemLogin, isProfileHeld: () => held }); + const state = auth.getState(); + await Promise.race([readStarted.promise, state]); + held = true; + continueRead.resolve(); + await state; + mockedRead.mock.restore(); + assert.deepEqual(fs.readdirSync(codexHome), []); + assert.equal(isNativeProviderAuthBound('openai'), false); +}); + +import { createHostProviderConfig } from './provider-config.ts'; +import { createHostModelAccess } from './model-access.ts'; +import { createHostCodexRuntime } from './codex-runtime.ts'; +import { createHostMcpRuntime } from './mcp-runtime.ts'; +import { createCredentialStore } from '../credentials/store.mjs'; +import { hostOutbound } from '../outbound.mjs'; +import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { createAvailabilityPolicy } from '../../../desktop/src/main/device-link/providerShareAvailabilityPolicyCore.ts'; +import { createXaiAuthInvalidationHost } from '../../../desktop/src/main/maker-host/xaiAuthInvalidationCore.ts'; +import { hostRuntimeLayout } from '../runtime-layout.mjs'; +import { openOwnerDatabase } from '../../../desktop/src/main/localDb/startupCore.ts'; +import { createDbClientForHandle } from '../../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; + +/** A production Codex runtime on a temporary profile and database, as codex-thread-routes.test.mjs builds it. */ +async function productionRuntime(t, ownerId) { + const root = await fsp.realpath(await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-host-held-runtime-'))); + t.after(() => fsp.rm(root, { recursive: true, force: true })); + const savedEnv = { ...process.env }; + t.after(() => { for (const key of Object.keys(process.env)) if (!(key in savedEnv)) delete process.env[key]; Object.assign(process.env, savedEnv); }); + process.env.HOME = process.env.USERPROFILE = path.join(root, 'home'); + const fixtureHome = process.env.HOME; + t.mock.method(os, 'homedir', () => fixtureHome); + await fsp.mkdir(fixtureHome); + for (const key of ['XDT_OFFICIAL_SHARED_PROFILE', 'OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_HOME', 'XDT_CODEX_API_KEY', 'ANTHROPIC_API_KEY', HOST_TEST_SYSTEM_CODEX_AUTH_ENV]) delete process.env[key]; + // Every outbound request (token renewals included) is recorded and answered with a failure. + const outbound = []; + t.mock.method(hostOutbound, 'outboundFetch', async url => { outbound.push(String(url)); return new Response('{}', { status: 500 }); }); + const profile = path.join(root, 'profile'); + await fsp.mkdir(path.join(profile, 'codex-home'), { recursive: true }); + configureHostOwner({ userDataDir: profile, ownerId }); + t.after(() => configureHostOwner({ userDataDir: profile, ownerId: null })); + configureAppDataDir(path.join(root, 'app-data')); + const layout = hostRuntimeLayout(); + const opened = await openOwnerDatabase({ userDataDir: profile, ownerId, isPackaged: false, + drizzleDir: layout.drizzleDir, sqliteVecExtPath: layout.sqliteVecPath }); + const database = createDbClientForHandle({ db: opened.db, drizzle: opened.drizzle, dispose: async () => opened.db.close() }); + setCurrentDbClient(database, ownerId); + t.after(async () => { clearCurrentDbClient(database); await database.dispose(); }); + const credentials = await createCredentialStore({ userDataDir: profile, platform: 'linux', keyPromise: Promise.resolve(Buffer.alloc(16, 5)) }); + let held = true; + let modelAccess; + const config = createHostProviderConfig({ profileDir: profile, ownerId, credentials, getCodexBinary: () => null, isProfileHeld: () => held, + gatewayConnected: () => Boolean(modelAccess?.gateway.credential), openExternal: async () => { throw new Error('Unexpected browser request'); } }); + t.after(() => config.close()); + modelAccess = createHostModelAccess({ ownerId, region: 'global', readKey: () => config.builtinStore.get('xd'), + writeKey: value => config.builtinStore.set('xd', value), request: async () => ({ endpoint: 'http://127.0.0.1:9', apiKey: 'synthetic-gateway-key' }), + onKeyChanged: () => {}, publish: () => {} }); + await modelAccess.start(); + t.after(() => modelAccess.close()); + const mcp = createHostMcpRuntime({ appServerIds: () => [], getRemoteMcpBridgeToken: config.remoteBridgeToken }); + t.after(() => mcp.close()); + const runtime = createHostCodexRuntime({ profileDir: profile, binaryPath: path.join(root, 'no-codex-binary'), config, modelAccess, mcp, + availabilityPolicy: createAvailabilityPolicy(async () => { throw new Error('Unexpected share mutation'); }), publish: () => {}, + isProfileHeld: () => held }); + t.after(() => runtime.close()); + const snapshot = () => { + const out = {}; + const walk = dir => { for (const name of fs.readdirSync(dir).sort()) { + const file = path.join(dir, name); const stat = fs.lstatSync(file); const key = path.relative(profile, file); + if (stat.isSymbolicLink()) out[key] = `link:${fs.readlinkSync(file)}`; + else if (stat.isDirectory()) { out[key] = 'dir'; walk(file); } + // The database and its journal change on their own; the logins do not live there. + else if (!/\.(db|sqlite)(-wal|-shm|-journal)?$/.test(name)) out[key] = fs.readFileSync(file).toString('base64'); + } }; + walk(profile); + return out; + }; + const jwt = expSec => `h.${Buffer.from(JSON.stringify({ exp: expSec })).toString('base64url')}.s`; + return { profile, config, runtime, snapshot, jwt, outbound, setHeld: value => { held = value; } }; +} + +/* + * 测试价值 + * - 生产入口:生产的 createHostCodexRuntime 实例:引擎的作废端口(它返回的 invalidateNative,createHostAgentGraph 交给 + * Codex 引擎)、起本机 Codex 前的检查(assertNativeLoginUsable)、订阅桥(runtime.subscriptions.bridge)。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。桥和引擎共用同一实例里的同一份“闸门关着时被拒过”的记忆:引擎报过, + * 桥的请求带同一原因失败;桥报过,起本机 Codex 带同一原因失败。这一条由生产的装配保证,fixture 里的手工装配钉不住。 + * - 现有覆盖缺口:上面几条用的是手工装配的端口。 + * - 最小失败输入:闸门关着时,引擎报一次拒绝再经桥取令牌;桥报一次再起本机 Codex。 + * - tier:unit(真实的临时库与 profile;所有对外请求是记录调用的桩)。 + */ +test('one production Codex runtime: the engine and the bridge see each other\'s rejection while held', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = await productionRuntime(t, 'held-runtime-owner'); + const token = f.jwt(Math.floor(Date.now() / 1000) + 3600); + const writeLogin = value => fs.writeFileSync(path.join(f.profile, 'codex-home', 'auth.json'), + JSON.stringify({ tokens: { access_token: value, refresh_token: 'refresh-fixture', account_id: 'workspace-a' } }), { mode: 0o600 }); + writeLogin(token); + bindNativeProviderAuth('openai', { instanceIsolated: true }); + const bridge = f.runtime.subscriptions.bridge; + const refusal = /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: OpenAI rejected this ChatGPT sign-in \(token_revoked\)/; + assert.equal((await bridge.getChatgptBridgeAuth('openai')).accessToken, token); + const before = f.snapshot(); + // The engine reports; the same runtime's bridge refuses the token. + await f.runtime.invalidateNative('token_revoked', { credentialAttribution: 'unproven' }); + bridge.clearChatgptBridgeCredentialCache(); + await assert.rejects(bridge.getChatgptBridgeAuth('openai'), refusal); + assert.throws(() => f.runtime.assertNativeLoginUsable(), refusal); + assert.deepEqual(f.snapshot(), before); + assert.equal(isNativeProviderAuthBound('openai'), true); + // Released, the memory is gone; held again with a new login, the bridge reports and the engine refuses. + f.setHeld(false); + f.runtime.assertNativeLoginUsable(); + f.setHeld(true); + const next = f.jwt(Math.floor(Date.now() / 1000) + 3600) + 'b'; + writeLogin(next); + bridge.clearChatgptBridgeCredentialCache(); + assert.equal((await bridge.getChatgptBridgeAuth('openai')).accessToken, next); + await bridge.invalidateChatgptBridgeAuth({ status: 401, + body: '{"error":{"code":"token_revoked","message":"Your authentication token has been revoked."}}', failedAccessToken: next }, 'openai'); + assert.throws(() => f.runtime.assertNativeLoginUsable(), refusal); + assert.equal(isNativeProviderAuthBound('openai'), true); + assert.deepEqual(f.outbound, [], 'nothing left this test'); +}); + +/* + * 测试价值 + * - 生产入口:生产的 createHostProviderConfig 里的 xAI 服务(config.grok,订阅桥、Codex 代理的 xAI 观察者、 + * 供应商 OAuth 令牌读取与自动审查都经它),上游拒绝经 createXaiAuthInvalidationHost(config.grok),与 codex-runtime.ts 同一装配。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。xAI 登录在共用 profile 的 safe-storage 里,桌面也读写;闸门关着时: + * 快过期的令牌不续期、带原因失败;上游拒绝时不续期、不登出、不解绑,只记进程内,之后同一令牌带原因失败;放开后照常。 + * - 现有覆盖缺口:之前闸门不管 xAI 的续期与登出。 + * - 最小失败输入:闸门关着时取一次快过期的令牌;上游拒绝一次再取一次。 + * - tier:unit(真实的临时库与 profile;续期请求是记录调用的桩,不联网)。 + */ +test('while a desktop uses the profile, the xAI login is neither renewed nor signed out', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = await productionRuntime(t, 'held-xai-owner'); + const grok = f.config.grok; + const writeLogin = (access, expiresAt) => { + assert.equal(f.config.builtinStore.set('xai', JSON.stringify({ access_token: access, refresh_token: 'xai-refresh-fixture', expires_at: expiresAt })), true); + grok.resetGrokOAuthMemoryCache(); + }; + bindNativeProviderAuth('xai', { instanceIsolated: true }); + // Held, a valid token: used as it is. + writeLogin('xai-token-valid', Date.now() + 3_600_000); + let before = f.snapshot(); + assert.equal(await grok.getGrokAccessToken(), 'xai-token-valid'); + // Held, a token about to expire (within the 120 seconds the service renews ahead): refused, not renewed. + writeLogin('xai-token-expiring', Date.now() + 60_000); + before = f.snapshot(); + await assert.rejects(grok.getGrokAccessToken(), + /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: the SuperGrok sign-in has expired, and it is not renewed while a Cindy desktop app/); + assert.deepEqual(f.outbound, []); + assert.deepEqual(f.snapshot(), before); + // Held, the upstream rejects a valid token: nothing renewed, signed out or unbound; the token is refused afterwards. + writeLogin('xai-token-rejected', Date.now() + 3_600_000); + before = f.snapshot(); + const xai = createXaiAuthInvalidationHost(grok); + await xai.invalidateXaiBridgeAuth({ status: 403, body: 'unauthenticated: bad-credentials', failedAccessToken: 'xai-token-rejected' }); + assert.deepEqual(f.outbound, []); + assert.deepEqual(f.snapshot(), before); + assert.equal(isNativeProviderAuthBound('xai'), true); + await assert.rejects(grok.getGrokAccessToken(), /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: xAI rejected this SuperGrok sign-in/); + // Released: the token is used again, and a rejection takes the service's forced renewal (one request). + f.setHeld(false); + assert.equal(await grok.getGrokAccessToken(), 'xai-token-rejected'); + await xai.invalidateXaiBridgeAuth({ status: 403, body: 'unauthenticated: bad-credentials', failedAccessToken: 'xai-token-rejected' }); + assert.equal(f.outbound.length, 1); +}); + +/* + * 测试价值 + * - 生产入口:生产的 createHostProviderConfig 里的自定义供应商 OAuth(config.oauth.readGenericOAuthAccessToken: + * setOAuthTokenReader 注册给各代理的路由读取与自动审查都经它),续期请求经 provider-config 传给它的 fetch。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。登录存在共用 profile 的 safe-storage 里;闸门关着时不续期(续期请求不发出, + * 不消耗 refresh token、不写回),还没过期的令牌照用,已过期的按现有路径报 provider_oauth_refresh_failed;放开后照常续期。 + * - 现有覆盖缺口:之前闸门不管自定义供应商 OAuth 的续期。 + * - 最小失败输入:闸门关着时读一次快过期的令牌、一次已过期的令牌。 + * - tier:unit(真实的临时库与 profile;对外请求是记录调用的桩)。 + */ +test('while a desktop uses the profile, a custom provider OAuth sign-in is not renewed', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = await productionRuntime(t, 'held-oauth-owner'); + const descriptor = { tokenUrl: 'https://oauth.example.test/token', clientId: 'fixture-client' }; + const writeLogin = (id, expiresAt) => assert.equal(f.config.recipeSecretIo.write(id, + JSON.stringify({ access_token: `${id}-access`, refresh_token: `${id}-refresh`, expires_at: expiresAt })), true); + // Held, about to expire (within the 120 seconds it renews ahead): the current token is used, nothing renewed. + writeLogin('cprov-expiring', Date.now() + 60_000); + let before = f.snapshot(); + assert.equal(await f.config.oauth.readGenericOAuthAccessToken('cprov-expiring', descriptor), 'cprov-expiring-access'); + assert.deepEqual(f.outbound, []); + assert.deepEqual(f.snapshot(), before); + // Held, expired: the existing refusal, still nothing sent or written. + writeLogin('cprov-expired', Date.now() - 1_000); + before = f.snapshot(); + await assert.rejects(f.config.oauth.readGenericOAuthAccessToken('cprov-expired', descriptor), /provider_oauth_refresh_failed/); + assert.deepEqual(f.outbound, []); + assert.deepEqual(f.snapshot(), before); + // Released: the renewal goes out (answered with a failure here, so nothing is written). + f.setHeld(false); + writeLogin('cprov-released', Date.now() + 60_000); + await f.config.oauth.readGenericOAuthAccessToken('cprov-released', descriptor); + assert.deepEqual(f.outbound, ['https://oauth.example.test/token']); +}); + +/* + * 测试价值 + * - 生产入口:生产的 createHostProviderConfig 的 recipeSecretIo(main.ts 交给浏览器运行时,browser.ts 的 recipeSecrets + * 以 browserRecipeSecretId 的 id 读写它),配方本身是 opencli-vendor 里真实的小宇宙与 Spotify 代码,在 withRecipeHost 里运行。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。续期会轮换 refresh token 的配方(名单只在 held-credentials.ts 一处:小宇宙), + * 闸门关着时读密钥直接带原因失败,挡在它自己发续期请求之前;Spotify 不轮换,照常;放开后两个都照常。 + * - 现有覆盖缺口:之前闸门不管浏览器配方的密钥。 + * - 最小失败输入:闸门关着时,小宇宙的令牌已到续期时间,发一次请求。 + * - tier:unit(真实的临时库与 profile;配方的 fetch 是记录调用的桩,不联网)。 + */ +test('while a desktop uses the profile, the Xiaoyuzhou recipe reads no secret and sends nothing; Spotify is unaffected', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const f = await productionRuntime(t, 'held-recipe-owner'); + const { withRecipeHost, readSecretJSON } = await import('../../../../packages/opencli-vendor/cindy/host.ts'); + const { requestXiaoyuzhouJson } = await import('../../../../packages/opencli-vendor/clis/xiaoyuzhou/auth.js'); + const io = f.config.recipeSecretIo; + // As browser.ts recipeSecrets: the recipe key under its store id. + const secrets = { read: key => io.readStrict(`browser-recipe-${key}`), write: (key, value) => io.write(`browser-recipe-${key}`, value) }; + // A token due for renewal, so the recipe's first request would be its renewal. + assert.equal(io.write('browser-recipe-xiaoyuzhou', JSON.stringify({ access_token: 'xyz-access', refresh_token: 'xyz-refresh', expires_at: Date.now() - 1_000 })), true); + assert.equal(io.write('browser-recipe-spotify', JSON.stringify({ access_token: 'sp-access', refresh_token: 'sp-refresh', expires_at: Date.now() + 3_600_000 })), true); + const sent = []; + const fetchImpl = async url => { sent.push(String(url)); return new Response(JSON.stringify({ success: false }), { status: 500 }); }; + const before = f.snapshot(); + await assert.rejects(withRecipeHost(secrets, () => requestXiaoyuzhouJson('/v1/profile', {}, fetchImpl)), + /^Error: HOST_PROFILE_IN_USE_BY_DESKTOP: this browser recipe sign-in, whose renewal replaces its refresh token, is not used while a Cindy desktop app/); + assert.deepEqual(sent, [], 'no renewal and no request left'); + assert.deepEqual(f.snapshot(), before); + assert.equal((await withRecipeHost(secrets, async () => readSecretJSON('spotify'))).access_token, 'sp-access'); + // Released: the Xiaoyuzhou recipe reads its secret and starts with its renewal; Spotify as before. + f.setHeld(false); + await assert.rejects(withRecipeHost(secrets, () => requestXiaoyuzhouJson('/v1/profile', {}, fetchImpl))); + assert.equal(sent.length, 1); + assert.match(sent[0], /xiaoyuzhou/i); + assert.equal((await withRecipeHost(secrets, async () => readSecretJSON('spotify'))).access_token, 'sp-access'); +}); diff --git a/apps/host/src/agent/codex-system-login.ts b/apps/host/src/agent/codex-system-login.ts index 9805fa11d28..60659b36912 100644 --- a/apps/host/src/agent/codex-system-login.ts +++ b/apps/host/src/agent/codex-system-login.ts @@ -109,6 +109,8 @@ export function createHostCodexSystemLogin(options: { systemAuthPath: string | null; /** A native login of this connection is in progress or being cancelled. */ loginActive(): boolean; + /** A non-client desktop owns the shared files until the Host releases its hold. */ + isProfileHeld?(): boolean; /** The desktop's onOAuthBindingClaimed. */ onBindingClaimed?: () => unknown; }) { @@ -122,7 +124,7 @@ export function createHostCodexSystemLogin(options: { let sharedAuthLinkUnavailable = false; /** runReconcileWithSystemCodex, steps 2 to 9 (auth-adapters.ts 1172–1353). */ - async function run(systemAuth: string): Promise { + async function run(systemAuth: string, profileAllowsWrite: () => boolean): Promise { // Every pass judges again: only this pass failing to link counts as unreachable. sharedAuthLinkUnavailable = false; // Step 2: an explicit disconnect or an invalidation still covering the system login. @@ -133,7 +135,10 @@ export function createHostCodexSystemLogin(options: { if (codexAuthPathsShareEntry(systemAuth, myAuth)) return; // Step 5: a healthy hardlink is marked shared and replaced by a file symlink below. const topology = await inspectCodexAuthLink(systemAuth, myAuth); - if (topology.healthy && topology.linkType === 'hardlink') markNativeProviderAuthSharedSystemCredential('openai'); + if (topology.healthy && topology.linkType === 'hardlink') { + if (!profileAllowsWrite()) return; + markNativeProviderAuthSharedSystemCredential('openai'); + } if (topology.healthy && topology.linkType === 'symlink') return; // Step 6: a login made explicitly in Cindy stays the instance's own. const hasLocalEntry = topology.linkType !== 'missing'; @@ -152,6 +157,7 @@ export function createHostCodexSystemLogin(options: { if (!sysAccount && topology.linkType !== 'hardlink') return; const myAccount = hasLocalEntry ? await readCodexAccountId(myAuth) : null; if (legacyExplicitOwner && myAccount && myAccount !== sysAccount) { + if (!profileAllowsWrite()) return; const migrated = migrateLegacyExplicitNativeProviderAuthToInstanceIsolated('openai', legacyExplicitOwner); log.info('keeping account-distinct legacy explicit Codex auth', { provenanceMigrated: migrated, ownerMatchesActive: legacyExplicitOwner === getActiveAppSession().dataOwnerId }); @@ -159,7 +165,8 @@ export function createHostCodexSystemLogin(options: { } // Step 8: Windows keeps a standalone file (no Release snapshot on the Host). if (process.platform === 'win32' && topology.linkType === 'file') { - if (legacyExplicitOwner) migrateLegacyExplicitNativeProviderAuthToInstanceIsolated('openai', legacyExplicitOwner); + if (legacyExplicitOwner && profileAllowsWrite()) + migrateLegacyExplicitNativeProviderAuthToInstanceIsolated('openai', legacyExplicitOwner); return; } if (hasLocalEntry) { @@ -167,8 +174,9 @@ export function createHostCodexSystemLogin(options: { { linkType: topology.linkType, accountMatch: myAccount ? myAccount === sysAccount : 'unknown', dryRunCandidate: true }); } // Step 9: the reads above crossed awaits; a login may have started since. - if (options.loginActive()) return; + if (options.loginActive() || !profileAllowsWrite()) return; await fsp.mkdir(options.codexHome, { recursive: true }).catch(() => undefined); + if (!profileAllowsWrite()) return; const { kind, error, linkType } = await relinkSharedCodexAuth(systemAuth, myAuth); if (kind === 'linked') log.info('codex auth.json linked with shared OpenAI login', { linkType }); else if (kind === 'link-unsupported') { @@ -181,7 +189,7 @@ export function createHostCodexSystemLogin(options: { /** claimDetectedCodexOAuthBinding (auth-adapters.ts 1061–1135), step 10. */ function claim(systemAuth: string, sessionAtStart: { generation: number; dataOwnerId: string | null }): void { - if (options.loginActive()) return; + if (options.loginActive() || options.isProfileHeld?.()) return; const session = getActiveAppSession(); if (isAppSessionBoundaryPending()) return; if (session.generation !== sessionAtStart.generation || session.dataOwnerId !== sessionAtStart.dataOwnerId) return; @@ -221,11 +229,19 @@ export function createHostCodexSystemLogin(options: { reconcile(opts?: { allowCurrentLogin?: boolean }): Promise { const systemAuth = options.systemAuthPath; if (!systemAuth) return Promise.resolve(); + if (options.isProfileHeld?.()) return Promise.resolve(); if (!opts?.allowCurrentLogin && options.loginActive()) return Promise.resolve(); if (pending) return pending; const sessionAtStart = getActiveAppSession(); - const current = run(systemAuth) - .then(() => claim(systemAuth, sessionAtStart)) + // As on desktop, the filesystem link is independent of which account gets the binding. + // An observed profile hold ends this pass; only a later pass can resume writing. + let sawProfileHold = false; + const profileAllowsWrite = () => { + sawProfileHold ||= options.isProfileHeld?.() === true; + return !sawProfileHold; + }; + const current = run(systemAuth, profileAllowsWrite) + .then(() => { if (profileAllowsWrite()) claim(systemAuth, sessionAtStart); }) .finally(() => { if (pending === current) pending = null; }); pending = current; return current; diff --git a/apps/host/src/agent/context-recovery-assembly.ts b/apps/host/src/agent/context-recovery-assembly.ts index 4e74ee67e32..90feea59654 100644 --- a/apps/host/src/agent/context-recovery-assembly.ts +++ b/apps/host/src/agent/context-recovery-assembly.ts @@ -36,6 +36,7 @@ import { findLatestContextRebuildMeta, findLatestUserMessageForRebuild } from '. import { listMessagesForAgentHandoff } from '../../../desktop/src/main/localDb/agentHandoffHistory.ts'; import { dbToMakerAgentKind } from '../../../desktop/src/shared/agentKindConversion.ts'; import { DEFAULT_MODEL_COMPACTION_PCT } from '../../../desktop/src/shared/modelContextLimit.ts'; +import { explicitPorts } from './explicit-ports.ts'; type Log = ContextOverflowRolloverDeps['log']; @@ -54,8 +55,10 @@ export interface HostRecoveryPorts { readSessionWritableDirsFromDb: ReplayContextRecoveryPorts['readSessionWritableDirsFromDb']; resolveVerifiedWindow?: ContextOverflowRolloverDeps['resolveVerifiedWindow']; resolveHandoffWindow?: ContextOverflowRolloverDeps['resolveHandoffWindow']; - /** Present only while oversized Codex history recovery is open (classifyCodexHistory). */ - codexHistory?: Pick; + /** A cold Pi runtime resumed only to read its window and usage (runtime-selection.ts, the desktop's binding). */ + rehydrateColdPiRuntimeForWindowVerification?: ContextOverflowRolloverDeps['rehydrateColdPiRuntimeForWindowVerification']; + /** The native thread locator and classifier used before sending to a task with a saved history error. */ + codexHistory: Pick; /** Present only while Pi's unsupported request option recovery is open. */ piCompat?: { read: NonNullable; @@ -77,6 +80,8 @@ export interface HostRecoveryPorts { export interface HostRecoveryRuntimePorts { /** The replay turn (turn-executor.mjs replay); the recovery holds the task's send lock. */ replay: ReplayContextRecoveryPorts['sendToAgentAcceptedUnlocked']; + /** Checks the database owner bound to this queue runtime when the turn started. */ + assertCurrent(): void; drainHistories(): Promise; resetWireNotes(sessionId: string): void; readAutoReviewHistory: ReplayContextRecoveryPorts['readAutoReviewHistory']; @@ -98,32 +103,47 @@ export function createHostContextRecoveryRollover(host: HostRecoveryPorts, runti const readSession = (sessionId: string) => readContextRecoverySessionWithPorts({ getDbClient, sessions, botSessionLinks, botProfiles, eq: (left, right) => eq(left, right), }, sessionId); - const callbacks: RecoveryCallbackPorts = { + const callbacks: RecoveryCallbackPorts = explicitPorts({ getCoordinator: () => runtime.coordinator, resetWireNotes: id => runtime.resetWireNotes(id), - }; - return createContextOverflowRollover({ + }); + return createContextOverflowRollover(explicitPorts[0]>({ // Plugin-owned and headless plugin setup turns: the Host refuses both inputs today. hasExternalRecoveryOwner: () => false, + // Ports the Host leaves unbound, each written out (explicit-ports.ts): + // - a teammate's own sessions widen the recalled history; the Host refuses teammate tasks, so a + // recovery reads only the current conversation, as the desktop does for an ordinary task. + listCompanionSessionIds: undefined, + // - a subscription account change that needs a native session handoff: the Host has no + // subscription account handoff before a send yet (release table, row 30), so none is reported. + needsNativeSessionHandoff: undefined, + // A cold Pi runtime resumed only to read its context for a smaller window: the same binding the + // model change uses (register.ts binds one function into both, as here). + rehydrateColdPiRuntimeForWindowVerification: host.rehydrateColdPiRuntimeForWindowVerification, getSessionRow: readSession, - ...(host.codexHistory ? { - classifyCodexHistory: (threadId: string) => classifyCodexHistoryWithPorts({ - captureDataOwnerBroadcastScope, getCurrentDbClientSnapshot, isDataOwnerBroadcastScopeCurrent, - ...host.codexHistory!, - }, threadId), - } : {}), + classifyCodexHistory: (threadId: string) => classifyCodexHistoryWithPorts({ + captureDataOwnerBroadcastScope, getCurrentDbClientSnapshot, isDataOwnerBroadcastScopeCurrent, + ...host.codexHistory, + }, threadId), getAutoCompactThresholdPct: () => DEFAULT_MODEL_COMPACTION_PCT, - ...(host.resolveVerifiedWindow ? { resolveVerifiedWindow: host.resolveVerifiedWindow } : {}), - ...(host.resolveHandoffWindow ? { resolveHandoffWindow: host.resolveHandoffWindow } : {}), + resolveVerifiedWindow: host.resolveVerifiedWindow, + resolveHandoffWindow: host.resolveHandoffWindow, listMessages: sessionId => listMessagesForAgentHandoff(sessionId, 400) as ReturnType, listReplayMessages: sessionId => listMessagesForAgentHandoff(sessionId, null, undefined, 'replay'), findLatestUser: sessionId => findLatestUserMessageForRebuild(sessionId) as ReturnType>, findLatestRebuildMeta: findLatestContextRebuildMeta, getLiveSession: sessionId => host.getMaker().getSession(sessionId), - closeSession: sessionId => host.getMaker().closeSession(sessionId, 'runtime-refresh'), + closeSession: sessionId => { + runtime.assertCurrent(); + return host.getMaker().closeSession(sessionId, 'runtime-refresh'); + }, drainPersistQueue: () => runtime.drainHistories(), commitRebuild: (sessionId, handoff, meta, signal) => commitContextRecoveryWithPorts({ - captureDataOwnerBroadcastScope, getCurrentDbClientSnapshot, isDataOwnerBroadcastScopeCurrent, + captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent, + getCurrentDbClientSnapshot: () => { + runtime.assertCurrent(); + return getCurrentDbClientSnapshot(); + }, sessions, eq: (left, right) => eq(left, right), commitContextRebuild: (id, text, rebuildMeta) => commitContextRebuildWithPorts({ now: () => Date.now(), createId: () => createId(), tx: (name, args) => getDbClient().tx(name, args), @@ -133,18 +153,18 @@ export function createHostContextRecoveryRollover(host: HostRecoveryPorts, runti createId: () => createId(), log: host.log, }, sessionId, handoff, meta, signal), - setPendingHandoff: (sessionId, handoff, expectedGeneration) => - host.pendingHandoff.set(sessionId, handoff, expectedGeneration), + setPendingHandoff: (sessionId, handoff, expectedGeneration) => { + runtime.assertCurrent(); + return host.pendingHandoff.set(sessionId, handoff, expectedGeneration); + }, readPendingHandoffGeneration: sessionId => host.pendingHandoff.readGeneration(sessionId), onRebuilt: sessionId => { contextRecoveryRebuilt(callbacks, sessionId); runtime.noteRebuilt(sessionId); }, getRecoveryAbortSignal: sessionId => contextRecoveryAbortSignal(callbacks, sessionId), - ...(host.piCompat ? { - readPiNativeCompatOverride: host.piCompat.read, - recordPiNativeCompatOverride: host.piCompat.record, - } : {}), + readPiNativeCompatOverride: host.piCompat?.read, + recordPiNativeCompatOverride: host.piCompat?.record, replayUserMessage: (sessionId, content, agentFacingWireContent, recovery) => replayContextRecoveryWithPorts({ getDbClient, sessions, eq: (left, right) => eq(left, right), buildCreateOptsWithStderr: host.buildCreateOptsWithStderr, @@ -173,5 +193,5 @@ export function createHostContextRecoveryRollover(host: HostRecoveryPorts, runti withSessionLock: withSendToSessionLock, withCloseSuppressed: withRehydrateCloseSuppressed, log: host.log, - }); + })); } diff --git a/apps/host/src/agent/context-recovery-wiring.ts b/apps/host/src/agent/context-recovery-wiring.ts index 7a1a8864121..cb7f1994779 100644 --- a/apps/host/src/agent/context-recovery-wiring.ts +++ b/apps/host/src/agent/context-recovery-wiring.ts @@ -10,7 +10,7 @@ type AgentGraph = Pick, 'maker' | 'conte * The input queue's context recovery (createInputQueue's isContextRecoveryOpen and * createContextRecoveryRollover), as main.ts wires it: a kind opens only when it is in `openKinds`, * after its real-engine test (release table); a closed kind takes the normal error path, unclaimed. - * The Codex history and Pi ports reach the rollover only once their kind is open. + * A saved Codex history error is classified before a send even when terminal claims are closed. */ export function createHostContextRecoveryWiring(deps: { openKinds: ReadonlySet; @@ -20,6 +20,8 @@ export function createHostContextRecoveryWiring(deps: { publish: HostRecoveryPorts['publish']; pendingHandoff: HostRecoveryPorts['pendingHandoff']; log: HostRecoveryPorts['log'] & { warn(message: string): void }; + /** The runtime selection's cold Pi window check, read at call time (it is created after the queue). */ + rehydrateColdPiRuntimeForWindowVerification?: HostRecoveryPorts['rehydrateColdPiRuntimeForWindowVerification']; }) { const { openKinds } = deps; const graph = () => { @@ -48,11 +50,11 @@ export function createHostContextRecoveryWiring(deps: { deps.getGraph()?.contextRecovery.resolveVerifiedWindow(agentKind, modelId, providerId) ?? null, resolveHandoffWindow: (sessionId, route) => deps.getGraph()?.contextRecovery.resolveHandoffWindow(sessionId, route) ?? null, - ...(openKinds.has('oversized-history') ? { codexHistory: { - readCodexThreadStorageReadOnly: (threadId: string) => codexHistory().readCodexThreadStorageReadOnly(threadId), + codexHistory: { + readCodexThreadStorageReadOnly: async (threadId: string) => codexHistory().readCodexThreadStorageReadOnly(threadId), classifyCodexHistoryOversized: (threadId: string, located?: { rolloutPath?: string }) => codexHistory().classifyCodexHistoryOversized(threadId, located), - } } : {}), + }, ...(openKinds.has('unsupported-request-option') ? { piCompat: { read: (providerId: string, modelId: string, routeKey?: string) => deps.getGraph()?.contextRecovery.piCompat.read(providerId, modelId, routeKey), @@ -61,6 +63,7 @@ export function createHostContextRecoveryWiring(deps: { } } : {}), pendingHandoff: deps.pendingHandoff, log: deps.log, + rehydrateColdPiRuntimeForWindowVerification: deps.rehydrateColdPiRuntimeForWindowVerification, }, runtime), }; } diff --git a/apps/host/src/agent/context-recovery.ts b/apps/host/src/agent/context-recovery.ts index 7928be0f726..6353a2a4c39 100644 --- a/apps/host/src/agent/context-recovery.ts +++ b/apps/host/src/agent/context-recovery.ts @@ -14,6 +14,7 @@ import { type OverflowClaimResult, } from '../../../desktop/src/main/maker-ipc/contextOverflowRollover.ts'; import { isTerminalTurnErrorEvent } from '../../../desktop/src/main/maker-ipc/sessionTurnActivityTracker.ts'; +import { explicitPorts } from './explicit-ports.ts'; /** * How long a Host shutdown waits, in total, for the context recoveries still in flight to end @@ -59,6 +60,10 @@ export interface RecoveryTerminal { /** The Host is stopping: as the desktop's planned upgrade close, recovery does not claim. */ isStopping: boolean; isGatewayProxyTokenRecovery: boolean; + /** Holds the turn's product failure for this recovery (product-turn.ts defer of its owner). */ + deferProductTurn?: () => void; + /** The recovery's final failure: the turn's product failure goes through the finalizer. */ + notifyProductTurn?: () => void; } export type HostContextRecovery = ReturnType; @@ -98,6 +103,11 @@ export function createHostContextRecovery(deps: { */ isRecoverable?(data: unknown): boolean; publish(sessionId: string, event: AgentEvent, fields: Record): void; + /** + * Whether the input coordinator has taken this terminal error over for an automatic resume, read + * as the desktop's delivery reads it (sessionErrorSuppression.ts, sessionEventDelivery.ts). + */ + isErrorSuppressed?(sessionId: string, event: AgentEvent): boolean; log: { warn(message: string, fields?: Record): void }; }) { const held = new Map(); @@ -108,7 +118,7 @@ export function createHostContextRecovery(deps: { }; function ports(history: RecoveryHistory, rollover: () => Rollover | null): ContextRecoveryTerminalPorts { - return { + return explicitPorts({ getRollover: rollover, getSuppressedBroadcasts: () => held as unknown as ReturnType, isTerminalTurnErrorEvent: event => isTerminalTurnErrorEvent(event), @@ -128,7 +138,7 @@ export function createHostContextRecovery(deps: { handleAgentIslandEventAfterBroadcast: () => {}, eventChannel: () => 'agent-event', log: deps.log, - }; + }); } function input(terminal: RecoveryTerminal) { @@ -142,7 +152,7 @@ export function createHostContextRecovery(deps: { isPlannedUpgradeClose: terminal.isStopping, isRemoteAuthRetry: false, isGatewayProxyTokenRecovery: terminal.isGatewayProxyTokenRecovery, - autoResumeSuppressesPersist: false, + autoResumeSuppressesPersist: deps.isErrorSuppressed?.(terminal.session.id, terminal.event) === true, // A held terminal reserves no row id, as on the desktop (sessionEventDelivery.ts). persistId: undefined, }; @@ -161,8 +171,14 @@ export function createHostContextRecovery(deps: { if (holds && deps.isRecoverable && !deps.isRecoverable(event.data)) return 'idle'; if (holds) held.set(session.id, { sessionId: session.id, event, fields: terminal.fields }); const result = claimContextRecoveryTerminal(ports(terminal.history, deps.getRollover), input(terminal)); - // The Host has no product-turn follow-up to defer (release table). - deferContextRecoveryTerminal(ports(terminal.history, deps.getRollover), input(terminal), result, () => {}); + // As the desktop: the terminal a recovery claims holds its product failure until the recovery ends. + // The shared rule also holds a gateway key recovery and a planned close, whose rows the desktop + // writes later; the Host writes them at once and has no later exit for them, so only a claim + // ('claimed', 'in-flight') holds here. A terminal an automatic resume holds is deferred by the + // executor (turn-executor.mjs settleProductTurn), with the same owner. + deferContextRecoveryTerminal(ports(terminal.history, deps.getRollover), input(terminal), result, () => { + if (result === 'claimed' || result === 'in-flight') terminal.deferProductTurn?.(); + }); if (holds && result === 'idle' && held.get(session.id)?.event === event) held.delete(session.id); return result; }, @@ -189,7 +205,8 @@ export function createHostContextRecovery(deps: { return recovery; }, }; - settleContextRecoveryTerminal(ports(terminal.history, () => waiting), input(terminal), result, () => {}); + // The recovery's final failure settles the held product failure, as the desktop's notify does. + settleContextRecoveryTerminal(ports(terminal.history, () => waiting), input(terminal), result, () => terminal.notifyProductTurn?.()); }, /** @@ -206,6 +223,11 @@ export function createHostContextRecovery(deps: { * terminal of its own client id). Only while that recovery runs: it ends, fails, throws, is * rebuilt or is drained at shutdown, and the entry goes. A replay outside a recovery gets none. */ + /** Whether a recovery of this task is running (its replay belongs to the turn that overflowed). */ + isRecovering(sessionId: string): boolean { + return recovering.has(sessionId); + }, + replayClientId(sessionId: string): string | undefined { const clientId = recovering.get(sessionId)?.terminal.fields.inputClientId; return typeof clientId === 'string' ? clientId : undefined; diff --git a/apps/host/src/agent/context-usage.ts b/apps/host/src/agent/context-usage.ts new file mode 100644 index 00000000000..e9fdfe8a12d --- /dev/null +++ b/apps/host/src/agent/context-usage.ts @@ -0,0 +1,28 @@ +import { recordSessionContextSnapshotWith } from '../../../desktop/src/main/localDb/sessionContextSnapshotPersistence.ts'; +import * as broadcastTap from '../../../desktop/src/main/device-link/broadcast-tap.js'; +import { createLogger } from '../../../desktop/src/main/logger.ts'; +import { explicitPorts } from './explicit-ports.ts'; + +/** + * A task's context usage (tokens used, window) written back to its row, as the desktop's + * recordSessionContextSnapshot (sessionSpendBroadcaster.ts) writes it: the same shared writer with the + * same rules. The model-window gate reads these columns for a task without a live runtime + * (resolveModelSwitchContextTokens); without them the row stayed at its default 0, taken as known + * usage. + * + * Ports bound here: the data owner scope capture and check, as sessionSpendBroadcaster.ts binds them + * (the same broadcast tap); the logger. The broadcast of the written usage is not done on the Host + * yet (release table, context usage write-back: the write is done, the broadcast is the third + * batch), so that port does nothing. + */ +const ports = explicitPorts[0]>({ + captureOwnerScope: () => broadcastTap.captureDataOwnerBroadcastScope?.() ?? null, + isOwnerScopeCurrent: (scope: ReturnType | null) => + scope === null || broadcastTap.isDataOwnerBroadcastScopeCurrent?.(scope) !== false, + broadcastContext: () => {}, + log: createLogger('host-context-usage'), +}); + +export function recordHostContextSnapshot(sessionId: string, contextTokens: number, contextWindow: number): Promise { + return recordSessionContextSnapshotWith(ports, sessionId, contextTokens, contextWindow); +} diff --git a/apps/host/src/agent/coordinator-deps.ts b/apps/host/src/agent/coordinator-deps.ts new file mode 100644 index 00000000000..4e884e4ef91 --- /dev/null +++ b/apps/host/src/agent/coordinator-deps.ts @@ -0,0 +1,310 @@ +import type { AgentInputCoordinator, AgentInputCoordinatorDeps } from '../../../desktop/src/main/maker-ipc/agent-input-coordinator.ts'; +import type { AgentInputQueuedMessage } from '../../../desktop/src/shared/agentInputQueue.ts'; +import { hydrateQueuedAgentReferences } from '../../../desktop/src/main/maker-ipc/agentInputReferences.ts'; +import { runSchedulerQueuedPreparation } from '../../../desktop/src/main/maker-ipc/schedulerQueuedPreparation.ts'; +import type { createQueuedAcceptedCallbacks } from '../../../desktop/src/main/maker-ipc/queuedAcceptedCallbacks.ts'; +import type { QueuedAttachmentOwnershipRegistry } from '../../../desktop/src/main/maker-ipc/queuedAttachmentOwnership.ts'; +import { prepareQueuedPromptSnapshot, type createSchedulerQueueBridge, type SchedulerQueuedPromptObserver } from '../../../desktop/src/main/maker-ipc/schedulerQueueBridge.ts'; +import { settleTaskActionInput } from '../../../desktop/src/main/maker-ipc/taskActionAuthorization.ts'; +import type { HostAutoResume } from './auto-resume.ts'; +import { explicitPorts } from './explicit-ports.ts'; + +type Deps = AgentInputCoordinatorDeps; +type LiveSession = { + agentKind?: string; + isTurnRunning?(): boolean; + getTurnGeneration?(): number | null; + getObservedCurrentTurnTerminal?(): ReturnType>; +}; + +/** The input queue's deps (input-queue.mjs createInputQueue) the coordinator's ports read. */ +export interface HostCoordinatorQueueDeps { + getTaskRuntimePlugins?(): Pick | null; + getMaker(): { getSession(sessionId: string): LiveSession | undefined } | null | undefined; + readSession(sessionId: string): Promise<{ sdkSessionId?: string | null }>; + persistMessage?: Deps['createUserMessage']; + touchUserSend?: Deps['touchUserSend']; + interactions?: { pending(sessionId: string): unknown[] | undefined } | null; + hasAssistantProgressAfter?: Deps['hasAssistantProgressAfter']; + getRecoveryContextSnapshot?: Deps['getRecoveryContextSnapshot']; + hasPendingCredentialSwitch?: Deps['hasPendingCredentialSwitch']; + rewindPersistedUserMessageAfterClear?: Deps['rewindPersistedUserMessageAfterClear']; + loadQueueSnapshot?: Deps['loadQueueSnapshot']; + loadClearBoundary?: Deps['loadClearBoundary']; + getPersistedClientIds?: Deps['getPersistedClientIds']; + resolveSessionReferences?: Deps['resolveSessionReferences']; + supersedeRetriedUserTurn?: Deps['supersedeRetriedUserTurn']; + /** + * The task's activity time when a person's turn is dispatched or steered (register.ts + * touchSessionActivityInDb); main.ts gives the Host's write (session-activity.ts, release table 甲 10). + */ + touchSessionActivity?: (sessionId: string, atMs?: number) => Promise; +} + +/** The turn executor (turn-executor.mjs) as the coordinator's ports read it. */ +export interface HostCoordinatorExecutor { + send: Deps['sendToAgent']; + steer: Deps['steerToAgent']; + abort(sessionId: string): Promise; + isRunning(sessionId: string): boolean; + isSettling(sessionId: string): boolean; + reconcileIdle: NonNullable; + beforeDispatchUserTurn( + ...args: [...Parameters>, + (snapshots: Parameters[0]) => Promise] + ): ReturnType>; + onUndispatchedUserTurn: NonNullable; + persistTerminalSendError(sessionId: string, message: string, inputClientId?: string): void; + /** The task's event persistence (historyFor), for the reply anchor of a user row. */ + autoResumeHistory(sessionId: string): { getLastAssistantTranscriptUuid(sessionId: string): string | undefined }; + onPersistedSendRejected(sessionId: string, message: string): void; +} + +/** One owner runtime of the input queue (input-queue.mjs createRuntime), as the ports read it. */ +export interface HostCoordinatorContext { + deps: HostCoordinatorQueueDeps; + executor: HostCoordinatorExecutor; + /** The coordinator these ports are handed to; read when a port runs. */ + coordinator(): AgentInputCoordinator; + /** The scheduler bridge, assembled after the coordinator; read when a port runs. */ + scheduleBridge(): Pick, 'onPersistedSendRejected' | 'recoverySourceClientId'>; + assertCurrent(): void; + /** Starts an abort and remembers it, so a stop can wait for it (input-queue.mjs stop). */ + noteAborting(sessionId: string, aborting: Promise): void; + publish: Deps['emitProjection']; + persist: NonNullable; + flushed: NonNullable; + /** Runs once the coordinator's next snapshot is durable (input-queue.mjs afterSnapshot). */ + afterSnapshot(sessionId: string, action: () => unknown): void; + attachmentOwnership: QueuedAttachmentOwnershipRegistry; + acceptedCallbacks: ReturnType; + schedulePreparations: Parameters[1]; + scheduleDiscardWatchers: Map; + /** The auto-resume runtime and hooks of this owner runtime (auto-resume.ts). */ + autoResume: HostAutoResume; + /** This owner runtime's context recovery, if assembled; read when a port runs. */ + rollover(): { cancelRecovery(sessionId: string): void } | null | undefined; +} + +const makerKind = (kind: string | undefined) => kind === 'cc' ? 'claude-code' : kind; + +/** + * The input coordinator's ports on the Node Host, with every optional port written out + * (explicit-ports.ts): bound to the Host's, or left out with the reason the Host does not bind it. + * register.ts binds the desktop's. + */ +export function hostCoordinatorDeps(ctx: HostCoordinatorContext): AgentInputCoordinatorDeps { + const { deps, executor } = ctx; + /** + * An exact retry owner that never crossed vendor dispatch (register.ts + * finalizeUndispatchedClaimedRetry): a failure surfaces the held error, a cancellation writes it + * quietly. The desktop also closes the Agent Island lifecycle, which the Host does not have. + */ + const finalizeUndispatchedClaimedRetry = (id: string, item: AgentInputQueuedMessage, disposition: 'cancelled' | 'failed') => + disposition === 'failed' + ? ctx.autoResume.autoResumeBookkeeping.surfaceSuppressedErrorForRetry(id, item.clientId) + : ctx.autoResume.autoResumeBookkeeping.flushSuppressedErrorForRetry(id, item.clientId); + return explicitPorts({ + sendToAgent: async (id, message, createOpts, sendOpts) => { + const clientId = sendOpts.persistUserMessage?.clientId; + try { + await runSchedulerQueuedPreparation(clientId, ctx.schedulePreparations, + () => { ctx.scheduleDiscardWatchers.delete(clientId as string); ctx.acceptedCallbacks.discard(clientId as string); }); + ctx.assertCurrent(); + const result = await executor.send(id, message, createOpts, sendOpts); + await ctx.acceptedCallbacks.settle(id, sendOpts, result); + return result; + } catch (error) { + await ctx.acceptedCallbacks.rollback(id, clientId); + throw error; + } + }, + steerToAgent: executor.steer, + abortSession: id => { + // As register.ts: an explicit stop withdraws both automatic resumes and their backoff first. + ctx.autoResume.resetForExplicitStop(id); + const promise = executor.abort(id); + ctx.noteAborting(id, promise); + return promise; + }, + isTurnRunning: id => executor.isRunning(id), + // While a turn's rows settle after its terminal, the Host still counts it as running (isTurnRunning) + // and the Session is already idle; the coordinator, which gets the terminal on arrival, would read + // that as a stale boundary and start polling it. The probe answers 'unavailable' (fail-closed) in that + // window; it never reports the Host's own record as a running Session. + isLiveTurnRunning: id => executor.isSettling(id) ? undefined : deps.getMaker()?.getSession(id)?.isTurnRunning?.(), + isLiveSessionPresent: id => !!deps.getMaker()?.getSession(id), + getTurnGeneration: id => deps.getMaker()?.getSession(id)?.getTurnGeneration?.() ?? null, + getTurnSessionIdentity: id => (deps.getMaker()?.getSession(id) as object | undefined) ?? null, + getObservedCurrentTurnTerminal: id => deps.getMaker()?.getSession(id)?.getObservedCurrentTurnTerminal?.(), + reconcileTurnIdle: executor.reconcileIdle, + getAgentKind: id => (makerKind(deps.getMaker()?.getSession(id)?.agentKind) ?? null) as ReturnType, + getSdkSessionId: async id => (await deps.readSession(id)).sdkSessionId || undefined, + hasAssistantProgressAfter: deps.hasAssistantProgressAfter, + getRecoveryContextSnapshot: deps.getRecoveryContextSnapshot, + hasPendingInteraction: id => (deps.interactions?.pending(id)?.length ?? 0) > 0, + hasPendingCredentialSwitch: deps.hasPendingCredentialSwitch, + rewindPersistedUserMessageAfterClear: deps.rewindPersistedUserMessageAfterClear, + // As register.ts (createUserMessageDurably): budgets charged for a person's message, an + // auto-resume's outcome registered, the row written behind the task's reply rows. + createUserMessage: ctx.autoResume.createUserMessage, + touchUserSend: deps.touchUserSend ?? (async () => {}) as unknown as Deps['touchUserSend'], + emitProjection: ctx.publish, + persistQueueSnapshot: ctx.persist, + awaitQueuePersistence: ctx.flushed, + loadQueueSnapshot: deps.loadQueueSnapshot, + loadClearBoundary: deps.loadClearBoundary, + getPersistedClientIds: deps.getPersistedClientIds, + onUserMessagePersisting: (id, item) => ctx.attachmentOwnership.markPersistenceStarted(id, item.clientId), + onUserMessagePersisted: (id, item) => { void ctx.attachmentOwnership.settleDurable(id, item.clientId); }, + onUserMessagePersistenceFailed: (id, item, options) => { + ctx.afterSnapshot(id, () => ctx.attachmentOwnership.markPersistenceFailed(id, item.clientId, options)); + }, + // Desktop register.ts (AgentInputCoordinator hooks): after the user row is durable + // and before vendor dispatch, open the turn change record, then the Git baseline. + beforeDispatchUserTurn: (id, item, signal) => { + ctx.autoResume.autoResumeBookkeeping.markReplacementDispatching(id, item.clientId); + return executor.beforeDispatchUserTurn(id, item, signal, + snapshots => prepareQueuedPromptSnapshot(snapshots, ctx.scheduleDiscardWatchers, id, item, signal)); + }, + onRetryUndispatchedUserTurn: (id, item) => executor.onUndispatchedUserTurn(id, item, 'cancelled'), + // A durable turn that never reached the vendor: drop the record, then the baseline. + // Then, as register.ts, the auto-resume that item carried hands its error back (exactly once). + onUndispatchedUserTurn: (id, item, disposition) => { + executor.onUndispatchedUserTurn(id, item, disposition); + ctx.autoResume.autoResumeBookkeeping.rollbackReplacementPreview(id, item.clientId); + const autoResume = item.autoResume === true; + if (autoResume) ctx.autoResume.settleUndispatchedInterruptedAutoResume(id, item); + finalizeUndispatchedClaimedRetry(id, item, disposition); + if (!autoResume) ctx.autoResume.settleUndispatchedInterruptedAutoResume(id, item); + }, + // Session references in the composer (register.ts resolveSessionReferences, with the Host's + // device identity; reading another device's task needs Device Link, which the Host lacks). + resolveSessionReferences: deps.resolveSessionReferences, + refreshAgentReferencesBeforeDispatch: async (item: AgentInputQueuedMessage) => { + const refreshed = await hydrateQueuedAgentReferences(item, { + isSessionTurnRunning: target => deps.getMaker()?.getSession(target)?.isTurnRunning?.() ?? false, + }); + Object.assign(item, refreshed); + if (refreshed.agentReferences === undefined) delete item.agentReferences; + }, + supersedeRetriedUserTurn: deps.supersedeRetriedUserTurn, + // The coordinator has just kept this input as the task's recovery point (active-turn) when it + // stores the error row; that input stopped here, so its receipt follows the row (turn-executor). + persistTerminalSendError: (id, message, attemptToken) => { + // An automatic recovery already owns this input (main 3792724192): its error is held once, in + // that attempt, and written when the attempt gives up. + if (attemptToken !== undefined) { + ctx.autoResume.autoResumeBookkeeping.stashSuppressedError(id, { message }, attemptToken); + return; + } + const recovery = ctx.coordinator().getProjection(id).recovery; + executor.persistTerminalSendError(id, message, recovery?.kind === 'active-turn' ? recovery.item?.clientId : undefined); + }, + // As register.ts: the scheduler bridge first (a scheduled prompt's persisted failure), then the + // Pi prompt timeout's runtime close (turn-executor). + onPersistedSendRejected: (id, message, item, recovering) => { + ctx.scheduleBridge().onPersistedSendRejected(id, message, item, recovering); + executor.onPersistedSendRejected(id, message); + }, + onAcceptedQueuedMessage: async (id, item) => { + ctx.schedulePreparations.delete(item.clientId); + ctx.scheduleDiscardWatchers.delete(item.clientId); + await ctx.acceptedCallbacks.run(id, item, ctx.scheduleBridge().recoverySourceClientId(id, item)); + }, + onDiscardedQueuedMessage: (id, item) => { + // As register.ts: settle a task-action input that will not run. + void settleTaskActionInput(item).catch(() => undefined); + ctx.afterSnapshot(id, () => ctx.attachmentOwnership.discardClient(id, item.clientId)); + ctx.acceptedCallbacks.discard(item.clientId); + ctx.schedulePreparations.delete(item.clientId); + const discarded = ctx.scheduleDiscardWatchers.get(item.clientId); + ctx.scheduleDiscardWatchers.delete(item.clientId); + // As register.ts: an auto-resume item settles before a claimed retry releases its error. + const autoResume = item.autoResume === true; + if (autoResume) ctx.autoResume.settleUndispatchedInterruptedAutoResume(id, item); + finalizeUndispatchedClaimedRetry(id, item, 'cancelled'); + if (!autoResume) ctx.autoResume.settleUndispatchedInterruptedAutoResume(id, item); + discarded?.onDiscarded(); + }, + + // ── Interrupted-turn auto-resume (auto-resume.ts), as register.ts binds it ─────────────────── + isResumableTurnErrorCandidate: ctx.autoResume.canRecoverTurn, + claimExternalAutomaticRecovery: id => + ctx.autoResume.interruptedTurnAutoResumeGuard.claimExternalAutomaticRecovery(id).action === 'allow', + onResumableTurnErrorDiscarded: ctx.autoResume.onResumableTurnErrorDiscarded, + onResumableTurnError: ctx.autoResume.onResumableTurnError, + onUnconfirmedAutoResumeTurn: ctx.autoResume.onUnconfirmedAutoResumeTurn, + // The desktop also settles Teammate group, plugin-task and welcome receipts and the Agent Island + // here; the Host has none of them. + onRejectedUserTurn: ctx.autoResume.onRejectedUserTurn, + onDispatchedUserTurn: (id, item, preVendorDispatchAt) => { + if (!item.autoResume) void deps.touchSessionActivity?.(id, preVendorDispatchAt); + void settleTaskActionInput(item).catch(() => undefined); + const attemptToken = ctx.autoResume.autoResumeAttemptToken(item); + // The vendor accepted the resume: the held error is dropped, unless a newer attempt owns it. + if (attemptToken !== null) ctx.autoResume.autoResumeBookkeeping.discardSuppressedError(id, attemptToken); + }, + onSteerAccepted: (id, item) => { + if (!item.autoResume) void deps.touchSessionActivity?.(id); + void settleTaskActionInput(item).catch(() => undefined); + // The desktop also releases the Orca accepted callback; Orca tasks are refused at Host admission. + }, + onUiRetry: (id, clientId, source, attemptToken) => { + const bookkeeping = ctx.autoResume.autoResumeBookkeeping; + bookkeeping.claimSuppressedErrorForRetry(id, clientId, source); + if (source === 'auto' && attemptToken !== undefined) bookkeeping.bindSuppressedErrorToClient(id, attemptToken, clientId); + if (source === 'manual') { + ctx.rollover()?.cancelRecovery(id); + // The click itself is the person's intervention: a fresh budget, before any await. + ctx.autoResume.silentStopAutoResumeGuard.noteUserSend(id); + ctx.autoResume.interruptedTurnAutoResumeGuard.noteUserSend(id); + } + // The desktop also retires a scheduled waiter, notes the provider group and publishes the hook + // continuation signal; the Host has no scheduler runner, provider groups or hook channels. + }, + // A new message takes the task over: a context recovery in flight and an unclaimed held error give way. + onUserEnqueue: id => { + ctx.rollover()?.cancelRecovery(id); + ctx.autoResume.autoResumeBookkeeping.supersedeUnclaimedErrorForUserIntervention(id); + }, + // An automatic input moves the task on too, without charging the person's budgets. + onAutomaticEnqueue: id => { + ctx.rollover()?.cancelRecovery(id); + ctx.autoResume.autoResumeBookkeeping.supersedeUnclaimedErrorForUserIntervention(id); + }, + getLastAssistantTranscriptUuid: id => executor.autoResumeHistory(id).getLastAssistantTranscriptUuid(id), + + screenUserMessage: deps.getTaskRuntimePlugins + ? (id, text, item) => deps.getTaskRuntimePlugins!()?.screenUserMessage?.(id, text, item) ?? Promise.resolve({ action: 'allow' }) + : undefined, + onUserMessageBlocked: (...args) => deps.getTaskRuntimePlugins?.()?.onUserMessageBlocked?.(...args), + onUserMessageRewritten: (...args) => deps.getTaskRuntimePlugins?.()?.onUserMessageRewritten?.(...args), + + // ── Not bound on the Host, and why ───────────────────────────────────────────────────────── + // Orca tasks are refused at Host admission: no saved report is restored, so none is revalidated. + canRestoreOrcaReport: undefined, + // The usage-limit resume arrives with the third batch (release table). + onUsageLimitedTurnError: undefined, + isScheduledQuotaInput: undefined, + onUserAction: undefined, + // Provider-group tasks are refused at Host admission. + providerGroupSwitchCandidate: undefined, + // The desktop's Orca assignment-history gate; Orca tasks are refused at Host admission. + onUserMessageQueryable: undefined, + // Orca queue notes; Orca tasks are refused at Host admission. + describeQueueBehindDispatch: undefined, + // Agent Island (a desktop window surface): the Host has none. + onQueueEmptied: undefined, + previewQueuedUserTurn: undefined, + // Dismissing an input handoff and the runtime's asynchronous questions on the owner's next + // message: the Host's questions arrive after checkpoint 4 (askUserQuestionAsync, release table). + onOwnerMessage: undefined, + // The desktop's message persistence learns the conversation clear boundary here, so a background + // turn started before a /clear writes no rows after it (backgroundTurnPredatesSessionClear). The + // desktop calls clearSession only from its /clear entry (maker:input:clear-session). The Host has no + // /clear entry yet: it calls clearSession only when a task is deleted or a draft discarded, and + // closes the task's persistence right after. Bound with the Host's /clear entry (release table). + noteSessionClearBoundary: undefined, + }); +} diff --git a/apps/host/src/agent/create-runtime-session.ts b/apps/host/src/agent/create-runtime-session.ts new file mode 100644 index 00000000000..633f9405565 --- /dev/null +++ b/apps/host/src/agent/create-runtime-session.ts @@ -0,0 +1,54 @@ +/** + * The Device Link create entry of a task with its runtime (the desktop's maker:create-session; main.ts + * passes it to createHostDeviceLink). Moved verbatim out of main.ts so its steps run under test; it + * adds the runtime start admission (register.ts bootstrapSession's admitLocalRoute) before the task row + * is written. + * + * Ports: the server's task creation (main.ts serverDeps.createSession), the owner runtime's agent graph + * (null until it is ready), the send path's provider group refusal and the runtime selection's start + * admission (runtime-selection.ts). + */ +import type { Maker } from '@cindy/maker-core'; +import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../../desktop/src/main/appSessionState.js'; +import { ensureDialogueWorkspaceDir } from '../../../desktop/src/main/localDb/dialogueWorkspace.js'; +import type { LocalRouteAdmissionOpts } from '../../../desktop/src/main/maker-ipc/localRouteAdmission.ts'; +import { readHostCreateSessionOpts } from '../create-session-request.js'; + +export interface HostRuntimeSessionCreatePorts { + serverDeps: { createSession(input: Record): Promise<{ id: string }> }; + getAgentGraph(): { maker: Pick } | null; + /** The send path's provider group refusal (send-preflight.ts createHostProviderExecutionCheck). */ + assertProviderExecutionSupported(id: string, providerId?: string | null): void; + admitLocalRoute(opts: LocalRouteAdmissionOpts): Promise; +} + +export async function createHostRuntimeSession(ports: HostRuntimeSessionCreatePorts, input: unknown) { + const { serverDeps, getAgentGraph, assertProviderExecutionSupported, admitLocalRoute } = ports; + const scope = activeOwnerScopeKey(); + const opts = readHostCreateSessionOpts(input, ensureDialogueWorkspaceDir); + // These routes need separate execution services; never reinterpret a remote + // task or Orca worker as an ordinary local task. + if (opts.remoteHostId || opts.agentDeviceId || opts.orcaRole) + throw new Error('[NOT_SUPPORTED] This execution route is not assembled in the Host yet'); + // As the send path (turn-executor.mjs readExecutionSession): a provider group task is refused before + // its row or runtime exists; this entry did not refuse it before. + assertProviderExecutionSupported(opts.id ?? '', opts.providerId); + // As the desktop's create entry starts its runtime (register.ts bootstrapSession): the start admission + // before the task row is written, so a refused start leaves no row and a rerouted provider is the + // one the row is created with. + await admitLocalRoute(opts); + if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending()) throw new Error('Host account changed'); + const row = await serverDeps.createSession({ + id: opts.id, agentKind: opts.agentKind, workingDir: opts.workingDir, + workspaceKind: opts.workspaceKind, model: opts.model, + permissionMode: opts.permissionMode, effort: opts.effort, providerId: opts.providerId, + fastMode: opts.fastMode, planModeEnabled: opts.planMode, + extraDirs: opts.extraDirs, writableDirs: opts.writableDirs, + }); + const agentGraph = getAgentGraph(); + if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending() || !agentGraph) throw new Error('Host account changed'); + const session = await agentGraph.maker.createSession({ ...opts, id: row.id }); + if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending()) throw new Error('Host account changed'); + return { sessionId: session.id, agentKind: session.agentKind, workDir: session.workDir, + capabilities: session.capabilities, usedProjectContext: false }; +} diff --git a/apps/host/src/agent/engine-deps.test.mjs b/apps/host/src/agent/engine-deps.test.mjs index 7df41252e25..2db09dc9b3b 100644 --- a/apps/host/src/agent/engine-deps.test.mjs +++ b/apps/host/src/agent/engine-deps.test.mjs @@ -11,6 +11,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import fs from 'node:fs'; +import { once } from 'node:events'; +import { createServer, request } from 'node:http'; import os from 'node:os'; import path from 'node:path'; @@ -20,9 +22,14 @@ import { createHostAgentGraph } from './runtime.ts'; import { getDesktopClaudeReadOnlyAllowedTools } from '../../../desktop/src/main/maker-host/mcp-tool-approval-policy.ts'; import { claudeSubagentUsageBridge } from '../../../desktop/src/main/maker-host/claude-subagent-usage-bridge.ts'; import { CodexCredentialModeSwitchBusyError } from '../../../desktop/src/main/maker-host/codex-credential-switch.ts'; +import { writeCodexServerCompaction } from '../../../desktop/src/main/maker-host/compaction-settings-store.ts'; import { readPiGlobalContext } from '../../../../packages/maker-core/src/agents/pi/global-context.ts'; import { createMainI18n } from '../../../desktop/src/main/i18n.ts'; import { lifoCleanup } from '../test-support/cleanup.mjs'; +import { createHostHarnessBinaries, resolveHarnessBinaryPath } from './harness-binary.ts'; +import { AGENT_BINARY_LAYOUT } from '../../../desktop/src/main/agent-binaries/binaryStatus.ts'; +import { closeCliProxyBridge } from '../../../desktop/src/main/maker-host/cli-proxy-bridge.ts'; +import { useHostChromiumProxySession } from '../outbound-proxy.ts'; // node:test has no default timeout; an explicit bound turns a hang into a failure. const TEST_TIMEOUT_MS = 120_000; @@ -75,6 +82,49 @@ test('Claude gets the desktop read-only allowed tools', { timeout: TEST_TIMEOUT_ assert.ok(graph.agent.deps.claudeAllowedTools.length > 0); }); +// Rule: the desktop Pi spawn port in pi-host.ts yields to explicit proxy env, otherwise the +// shared CONNECT bridge resolves each target through the host runtime's own system proxy session. +// Gap: the shared bridge tests do not exercise the port on the real Host graph. Minimal input: +// Pi's empty spawn env and one CONNECT to a synthetic host. Tier: unit with a loopback proxy. +test('Host Pi preserves explicit proxy settings and uses Host system routing for HTTPS tunnels', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const graph = buildGraph(t, 'engine-deps-pi-proxy'); + const proxyKeys = Object.keys(process.env).filter(key => /^(?:https?|all|no)_proxy$/i.test(key)); + const savedProxyEnv = Object.fromEntries(proxyKeys.map(key => [key, process.env[key]])); + for (const key of proxyKeys) delete process.env[key]; + t.after(() => Object.assign(process.env, savedProxyEnv)); + const authorities = []; + const upstream = createServer().on('connect', (req, socket) => { + authorities.push(req.url); + socket.end('HTTP/1.1 200 Connection Established\r\n\r\n'); + }); + upstream.listen(0, '127.0.0.1'); + t.after(() => new Promise(resolve => upstream.close(resolve))); + await once(upstream, 'listening'); + const targets = []; + useHostChromiumProxySession({ resolveProxy: async url => { + targets.push(url); + return `PROXY 127.0.0.1:${upstream.address().port}`; + } }); + t.after(() => useHostChromiumProxySession(null)); + t.after(closeCliProxyBridge); + + const getProxy = graph.pi.deps.getLocalPiHttpsProxy; + assert.equal(await getProxy({ HTTPS_PROXY: 'http://proxy.example.test:8080' }), undefined); + assert.equal(await getProxy({ all_proxy: 'socks5://proxy.example.test:1080' }), undefined); + const bridge = new URL(await getProxy({})); + assert.equal(bridge.hostname, '127.0.0.1'); + const connect = request(bridge, { method: 'CONNECT', path: 'pi-host-routing.example.test:443', + signal: AbortSignal.timeout(2000) }); + const connected = once(connect, 'connect'); + connect.end(); + const [response, socket] = await connected; + socket.destroy(); + assert.equal(response.statusCode, 200); + assert.deepEqual(targets, ['https://pi-host-routing.example.test/']); + assert.deepEqual(authorities, ['pi-host-routing.example.test:443']); +}); + test('Claude subagent usage goes through the process-wide bridge the loopback proxy fills', { timeout: TEST_TIMEOUT_MS }, t => { t = lifoCleanup(t); const graph = buildGraph(t, 'engine-deps-usage'); @@ -130,6 +180,20 @@ test('a Codex credential-mode switch is refused while a session is busy, by its }); +// The desktop passes the user's Codex server-compaction choice at every Codex start; the Host passed +// nothing, so a choice made in the window was ignored by Host tasks. +test('Codex reads the user\'s server-compaction choice from the owner file the desktop writes', { timeout: TEST_TIMEOUT_MS }, t => { + t = lifoCleanup(t); + const graph = buildGraph(t, 'engine-deps-codex-compaction'); + const read = graph.codex.deps.getCodexServerCompactionPreference; + assert.equal(read(), null, 'no choice keeps the native policy'); + t.after(() => writeCodexServerCompaction(null)); + writeCodexServerCompaction(false); + assert.equal(read(), false); + writeCodexServerCompaction(true); + assert.equal(read(), true); +}); + test('Claude gets the MCP duplicate choices main.ts builds from the plugin gateway reads', { timeout: TEST_TIMEOUT_MS }, t => { t = lifoCleanup(t); const resolveLocalMcpDuplicateChoices = async () => ({ skipHostServers: [], denyNativeServers: [] }); @@ -244,3 +308,99 @@ test('Pi gets the desktop startup hint and extension dialog strings in the syste const values = [strings.confirm, strings.cancel, strings.mutationFailed, ...Object.values(strings.mutationFailure), ...Object.values(strings.mutationSuccess)]; for (const value of values) assert.ok(value.trim() && !value.startsWith('settings.piPackages.'), value); }); + +// The engine binary each harness starts with (harness-binary.ts), chosen with the desktop's rules +// (agent-binaries/index.ts prepare, localOnly). Gap: the Host took the first `.verified` install in +// readdirSync order and ignored Pi's selected.json. Fake engines are scripts that print a version. +const binarySkip = process.platform === 'win32' && 'the fake engines are shell scripts'; +const PI_A = '0.70.0-11111111-1111-1111-1111-111111111111'; +const PI_B = '0.72.0-22222222-2222-2222-2222-222222222222'; +function binaryProfile(t) { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-harness-binary-')); + t.after(() => fs.rmSync(profile, { recursive: true, force: true })); + return profile; +} +// An install `///` whose binary prints `version`; verified unless told not. +function installEngine(profile, kind, directory, version, { verified = true } = {}) { + const layout = AGENT_BINARY_LAYOUT[kind]; + const binary = path.join(profile, layout.installSubdir, directory, layout.binaryName); + fs.mkdirSync(path.dirname(binary), { recursive: true }); + fs.writeFileSync(binary, `#!/bin/sh\necho ${version}\n`, { mode: 0o755 }); + if (verified) fs.writeFileSync(path.join(profile, layout.installSubdir, directory, '.verified'), ''); + return binary; +} +const selectPi = (profile, value) => fs.writeFileSync(path.join(profile, 'pi', 'selected.json'), + typeof value === 'string' ? value : JSON.stringify(value)); +const piSelection = directory => ({ schema: 1, source: 'official', version: directory.split('-')[0], directory }); + +// Rule (index.ts prepare; pi-kernel-selection.ts "A saved downgrade wins over every higher leftover +// install"): a valid selection of the lower version is used, ahead of the higher install and of the +// bundled binary. +test('Pi starts with its selected version, ahead of a higher install and the bundled binary', { timeout: TEST_TIMEOUT_MS, skip: binarySkip }, async t => { + const profile = binaryProfile(t); + const lower = installEngine(profile, 'pi', PI_A, '0.70.0'); + installEngine(profile, 'pi', PI_B, '0.72.0'); + const bundled = installEngine(profile, 'pi', 'bundled', '0.73.0'); + selectPi(profile, piSelection(PI_A)); + assert.deepEqual(await resolveHarnessBinaryPath('pi', { userDataDir: profile, bundledCandidates: [bundled] }), + { binaryPath: lower }); +}); + +// Rule (index.ts prepare: "Do not resurrect a higher leftover version after an explicit downgrade"): a +// malformed selection, or one naming an install without `.verified`, leaves Pi unavailable. +test('Pi is unavailable with an unusable selection and does not take a higher install', { timeout: TEST_TIMEOUT_MS, skip: binarySkip }, async t => { + const unusable = { binaryPath: null, error: 'pi_selection_invalid' }; + const malformed = binaryProfile(t); + installEngine(malformed, 'pi', PI_B, '0.72.0'); + selectPi(malformed, '{"schema":1,'); + assert.deepEqual(await resolveHarnessBinaryPath('pi', { userDataDir: malformed, bundledCandidates: [] }), unusable); + const unverified = binaryProfile(t); + installEngine(unverified, 'pi', PI_A, '0.70.0', { verified: false }); + installEngine(unverified, 'pi', PI_B, '0.72.0'); + selectPi(unverified, piSelection(PI_A)); + assert.deepEqual(await resolveHarnessBinaryPath('pi', { userDataDir: unverified, bundledCandidates: [] }), unusable); +}); + +// Rule (factory.ts findUsableLocalBinary through findPreferredLocalBinary): with no selection, the +// install whose binary reports the highest version, whatever the directory names or their order. +test('with no selection, Pi takes the install that reports the highest version', { timeout: TEST_TIMEOUT_MS, skip: binarySkip }, async t => { + for (const order of [['a-9.9.9', 'b-0.0.1'], ['b-0.0.1', 'a-9.9.9']]) { + const profile = binaryProfile(t); + const reported = { 'a-9.9.9': '0.70.0', 'b-0.0.1': '0.72.0' }; // names disagree with the versions + const binaries = Object.fromEntries(order.map(directory => [directory, installEngine(profile, 'pi', directory, reported[directory])])); + assert.deepEqual(await resolveHarnessBinaryPath('pi', { userDataDir: profile, bundledCandidates: [] }), + { binaryPath: binaries['b-0.0.1'] }, `created in the order ${order.join(', ')}`); + } +}); + +// Rule (index.ts: every engine prepares with preserveLocalVersion): Claude Code and Codex take the same +// highest reported version; their bundled binary comes first. +test('Claude Code and Codex take the install that reports the highest version, after the bundled binary', { timeout: TEST_TIMEOUT_MS, skip: binarySkip }, async t => { + for (const kind of ['claude-code', 'codex']) { + const profile = binaryProfile(t); + installEngine(profile, kind, 'a-9.9.9', '1.0.0'); + const highest = installEngine(profile, kind, 'b-0.0.1', '2.0.0'); + assert.deepEqual(await resolveHarnessBinaryPath(kind, { userDataDir: profile, bundledCandidates: [] }), { binaryPath: highest }, kind); + const bundled = installEngine(profile, kind, 'bundled', '0.1.0', { verified: false }); + assert.deepEqual(await resolveHarnessBinaryPath(kind, { userDataDir: profile, bundledCandidates: [bundled] }), { binaryPath: bundled }, kind); + } +}); + +// Rule (desktop prepare: an invalid selection leaves Pi unavailable): the harness status the Host reports +// (main.ts probe and boot values) is the engine choice it starts with. Gap: the status kept its own scan, +// which takes the first `.verified` install, so Pi showed ready with an invalid selection and a higher +// install left. Minimal failing input: status() still scanning after resolve(). tier: unit (fake engines). +test('once the engines are chosen, an invalid Pi selection is not reported ready', { timeout: TEST_TIMEOUT_MS, skip: binarySkip }, async t => { + const profile = binaryProfile(t); + installEngine(profile, 'pi', PI_B, '0.72.0'); + selectPi(profile, '{"schema":1,'); + const claude = installEngine(profile, 'claude-code', 'a', '2.0.0'); + const unavailable = []; + const binaries = createHostHarnessBinaries({ userDataDir: () => profile, harnessRoot: () => path.join(profile, 'no-bundled'), + onUnavailable: (kind, error) => unavailable.push([kind, error]) }); + // Before an owner runtime chooses, the synchronous scan answers (and sees the leftover Pi install). + assert.deepEqual(binaries.status(), { 'claude-code': true, codex: false, pi: true }); + assert.deepEqual(await binaries.resolve(), { 'claude-code': claude, codex: null, pi: null }); + assert.deepEqual(binaries.status(), { 'claude-code': true, codex: false, pi: false }); + assert.deepEqual(unavailable, [['pi', 'pi_selection_invalid']]); +}); diff --git a/apps/host/src/agent/event-persistence.ts b/apps/host/src/agent/event-persistence.ts index bb44b2f04d5..72850614397 100644 --- a/apps/host/src/agent/event-persistence.ts +++ b/apps/host/src/agent/event-persistence.ts @@ -24,6 +24,10 @@ import { findVisibleToolUseMessageByAliasesRow, } from "../../../desktop/src/main/localDb/messageMutations.js"; import { createLogger } from "../../../desktop/src/main/logger.js"; +import { + reconcileCorrectedMessagePrRefs, + reconcileUpdatedMessagePrRefs, +} from "../../../desktop/src/main/localDb/messagePrRefs.js"; import { hostChatAttachments, materializeHostToolMedia, @@ -96,9 +100,10 @@ export function createHostEventPersistence(deps: { (!deps.getOwner || deps.getOwner() === owner) && finalSnapshot?.isCurrent() !== false; if (!isCurrent()) return null; + let originalRow: typeof messages.$inferSelect | undefined; if (finalSnapshot) { const [original] = await client.drizzle - .select({ id: messages.id }) + .select() .from(messages) .where( and( @@ -110,6 +115,7 @@ export function createHostEventPersistence(deps: { ) .limit(1); if (!original || !isCurrent()) return null; + originalRow = original; } const row = await writeMessageContentRow( client, @@ -118,7 +124,31 @@ export function createHostEventPersistence(deps: { content, answer, ); - if (!row) return null; + // The desktop updateMessageContent (localDb/ipc/messages.ts): a correction of a final answer settles + // the original row's derived state (reconcileAssistantDerivedState) even when the row is gone on + // readback: the images of the original content no live message uses any more leave the task, then + // its PR references are recomputed. + const settleOriginal = async (original: typeof messages.$inferSelect) => { + for (const hash of hostChatAttachments.collectCindyMediaHashes(original.content)) { + try { + await removeSessionAttachmentRefIfUnreferencedByLiveMessage( + { sessionId, hash }, + client.drizzle, + ); + } catch (error) { + log.warn("assistant correction media reference reconciliation failed", { + sessionId, + clientId, + error: error instanceof Error ? error.message : String(error), + }); + } + } + await reconcileCorrectedMessagePrRefs(original, client, isCurrent); + }; + if (!row) { + if (originalRow) await settleOriginal(originalRow); + return null; + } await hostChatAttachments.commitMessageMediaRefs( { sessionId, role: row.role, content: row.content }, client.drizzle, @@ -134,19 +164,23 @@ export function createHostEventPersistence(deps: { }, }); } + if (originalRow) await settleOriginal(originalRow); + else if (row.role === "user" || row.role === "assistant") + await reconcileUpdatedMessagePrRefs(client, sessionId, row.id, isCurrent); return message; }, async discardPersistedAssistantMessage(sessionId, clientId, current) { const owner = deps.getOwner?.(); const client = owner?.client ?? getDbClient(); + const stillCurrent = () => + current() && + deps.isCurrent() && + (!deps.getOwner || deps.getOwner() === owner); const row = await rollbackAssistantMessageRow( client, sessionId, clientId, - () => - current() && - deps.isCurrent() && - (!deps.getOwner || deps.getOwner() === owner), + stillCurrent, ); if (!row) return false; // The deletion has committed. Derived cleanup is best-effort, just as on @@ -160,6 +194,8 @@ export function createHostEventPersistence(deps: { client.drizzle, ); } + // The desktop reconcileAssistantDerivedState: settle this row's PR record, then recompute. + await reconcileCorrectedMessagePrRefs(row, client, stillCurrent); const latest = await latestVisiblePreviewRow(sessionId, client); if (deps.isCurrent() && (!deps.getOwner || deps.getOwner() === owner)) { publish({ diff --git a/apps/host/src/agent/explicit-ports.ts b/apps/host/src/agent/explicit-ports.ts new file mode 100644 index 00000000000..c8a4483a376 --- /dev/null +++ b/apps/host/src/agent/explicit-ports.ts @@ -0,0 +1,30 @@ +/** + * Port bags the Host hands to the desktop's shared factories, with every optional port written out. + * + * A shared factory can gain an optional port that the desktop binds and the Host does not; for many + * of them "not bound" means "allowed" (main e322628568: canRecreateDirectory of the working + * directory recovery). The type checker says nothing, so the Host falls behind silently. + * `explicitPorts()` takes a bag where each optional member of T must be present: bound for real, + * or `undefined` with a comment saying why the Host need not bind it. A new optional port on the + * desktop side then fails the Host's typecheck at every binding until someone decides. Required + * members keep their own type (they do not start accepting `undefined`). + */ + +type OptionalKeys = { [K in keyof T]-?: {} extends Pick ? K : never }[keyof T]; +type RequiredKeys = Exclude>; + +/** + * T with its optional members made required (still allowing `undefined` for those only). Mapped over + * key unions, not `keyof T`, so the optional modifier is not carried over (a homomorphic `-?` would + * also strip `undefined` from those members). + */ +export type Explicit = { [K in RequiredKeys]: T[K] } & { [K in OptionalKeys]: T[K] | undefined }; + +/** + * A port bag for T in which every optional port is written out; returned as T. `undefined` is + * stripped from T first: a factory parameter with a default value has `X | undefined` as its type + * (`Parameters<…>[0]`), and `keyof (X | undefined)` is empty, which would let any bag through. + */ +export function explicitPorts(ports: Explicit>): NonNullable { + return ports as NonNullable; +} diff --git a/apps/host/src/agent/generated-images.ts b/apps/host/src/agent/generated-images.ts new file mode 100644 index 00000000000..4e5f1e8ea4e --- /dev/null +++ b/apps/host/src/agent/generated-images.ts @@ -0,0 +1,113 @@ +import type { AgentEvent } from '@cindy/maker-core'; +import { createGeneratedImageStorage } from '../../../desktop/src/main/cindy-media/generatedImageStorageCore.js'; +import { + createGeneratedImageDelivery, + type GeneratedImageDeliveryPlatform, +} from '../../../desktop/src/main/cindy-media/generatedImageDelivery.js'; +import { setGeneratedImageRecovery } from '../../../desktop/src/main/cindy-media/generatedImageRecovery.js'; +import { readGeneratedImageFile } from '../../../desktop/src/main/cindy-media/generatedImageBytes.js'; +import { uiText } from '../../../desktop/src/main/uiText.js'; +import { createLogger } from '../../../desktop/src/main/logger.js'; +import { getCurrentDbClientSnapshot } from '../../../desktop/src/main/localDb/client/current.js'; +import type { Message } from '../../../desktop/src/renderer/lib/ccAgent.types.js'; +import { isDataOwnerBroadcastScopeCurrent } from '../../../desktop/src/main/device-link/broadcast-tap.js'; +import type { DataOwnerBroadcastScope } from '../../../desktop/src/main/device-link/broadcastTapCore.js'; +import { hostBlobStore, hostChatAttachments, hostMediaIngest, hostMediaJournal } from '../media-store.js'; + +/** The desktop's generated-image storage (generatedImageStorageCore.ts) over the Host's media store. */ +export const hostGeneratedImageStorage = createGeneratedImageStorage({ + captureMediaRefCompensationScope: () => hostMediaJournal.captureMediaRefCompensationScope(), + parseBlobUrl: url => hostBlobStore.parseBlobUrl(url), + resolveSafe: url => hostBlobStore.resolveSafe(url), + extForMime: mimeType => hostBlobStore.extForMime(mimeType), + blobUrl: (hash, ext) => hostBlobStore.blobUrl(hash, ext), + ingestMedia: (params, db) => hostMediaIngest.ingestMedia(params, db), +}); + +/** + * A Codex generated image, as the desktop delivers it (register.ts, generatedImageDelivery.ts): the + * bytes go into the media store, the image becomes the imagegen tool rows of the task's history with + * its media reference, and clients get those rows and events with the stored address, never the bytes. + * The rows go through the Host's message writer; the copy is the main i18n the Host binds (ui-text.ts). + */ +export function createHostGeneratedImages(deps: { + createMessage: GeneratedImageDeliveryPlatform['createMessage']; + publish: (event: unknown) => void; + isProfileHeld: () => boolean; + registerProfileRelease: (resumeRecovery: () => Promise) => void; +}) { + const log = createLogger('generated-images'); + const delivery = createGeneratedImageDelivery({ + captureGeneratedImageStorage: () => hostGeneratedImageStorage.captureGeneratedImageStorage(), + releaseGeneratedImageUpstream: (storage, record, invoke) => + hostGeneratedImageStorage.releaseGeneratedImageUpstream(storage, record, invoke), + createMessage: (sessionId, body, opts) => deps.createMessage(sessionId, body, opts), + // The desktop's broadcastMessageRow: the committed row reaches clients as a created message, only + // while the owner it was captured under is still current. + broadcastMessageRow: (sessionId: string, message: Message, ownerScope?: DataOwnerBroadcastScope | null) => { + if (ownerScope && !isDataOwnerBroadcastScopeCurrent(ownerScope)) return; + deps.publish({ type: 'message_created', sessionId, messageId: message.id, message }); + }, + commitChatImageUrls: (params, db) => hostChatAttachments.commitChatImageUrls(params, db), + // The catalog always has both keys (chat.imageDelivery.stored / failed). + t: key => uiText(key, key), + // The Host has no Device Link: an image whose source is another computer is not reachable, the + // answer the desktop gets when that computer is not connected (REMOTE_SOURCE_REQUIRED). The shared + // task ports are left out, as the Host refuses shared tasks at admission. + invoke: async () => ({ ok: false }), + publish: (sessionId, event, persistId, resolvedContent) => + deps.publish({ ...event, sessionId, event, persistId, resolvedContent }), + // As the desktop's readSource, without its SSH file service and its legacy xdt-image cache: a + // managed address, then the file the image names on this machine. + readSource: async (_sessionId, image, session) => { + if (image.pathOrigin === 'remote-agent') throw new Error('REMOTE_SOURCE_REQUIRED'); + if (session.remoteHostId) throw new Error('REMOTE_SOURCE_REQUIRED'); + const managed = image.url?.startsWith('cindy-media://') ? hostBlobStore.resolveSafe(image.url) : undefined; + if (managed) { + try { return await readGeneratedImageFile(managed.absPath); } + catch (error) { if (!image.path) throw error; } + } + const source = image.path; + if (!source) throw new Error('MEDIA_SOURCE_MISSING'); + return readGeneratedImageFile(source); + }, + }); + let deferred: { clientEpoch: number; sessions: Set } | undefined; + async function recoverFromHistory(sessionId: string) { + if (!deps.isProfileHeld()) return delivery.recover(sessionId); + const owner = getCurrentDbClientSnapshot(); + if (!owner) return; + if (deferred?.clientEpoch !== owner.clientEpoch) { + deferred = { clientEpoch: owner.clientEpoch, sessions: new Set() }; + } + deferred.sessions.add(sessionId); + } + // History reads and task deletion can start writes to the image store. Resume work deferred by a + // hold only for the same open owner database. A new hold can defer the remaining work again. + async function onProfileReleased() { + const pending = deferred; + deferred = undefined; + if (!pending) return; + for (const sessionId of pending.sessions) { + if (getCurrentDbClientSnapshot()?.clientEpoch !== pending.clientEpoch) return; + await recoverFromHistory(sessionId).catch(() => undefined); + } + } + setGeneratedImageRecovery(recoverFromHistory, () => delivery.reconcile()); + deps.registerProfileRelease(onProfileReleased); + + /** register.ts deliverCodexGeneratedImage: the tool events published for the image, `[]` when none. */ + function deliverCodexGeneratedImage(sessionId: string, event: AgentEvent): Promise { + const warn = () => log.warn('Codex generated image delivery could not be persisted', { sessionId }); + try { + const run = delivery.start(sessionId, event); + if (!run) return Promise.resolve([]); + run.completion.catch(warn); + return run.published; + } catch { + warn(); + return Promise.resolve([]); + } + } + return { delivery, deliverCodexGeneratedImage }; +} diff --git a/apps/host/src/agent/git-snapshot.test.mjs b/apps/host/src/agent/git-snapshot.test.mjs index ffe8cdab72f..22d89e56c82 100644 --- a/apps/host/src/agent/git-snapshot.test.mjs +++ b/apps/host/src/agent/git-snapshot.test.mjs @@ -18,6 +18,7 @@ import test from 'node:test'; import { createHostGitSnapshot } from './git-snapshot.ts'; import { configureHostOwner } from './claude-auth.mjs'; import { listShadowSavepoints } from '../../../desktop/src/main/git-snapshot/gitSnapshotService.ts'; +import { enqueueGitRepoWrite } from '../../../desktop/src/main/git-snapshot/gitRepoWriteQueue.ts'; import { lifoCleanup } from '../test-support/cleanup.mjs'; // node:test has no default timeout. These tests start subprocesses or use real temporary @@ -44,32 +45,78 @@ function setup(t, ownerId) { configureHostOwner({ userDataDir: profile, ownerId }); const repo = fixtureRepo(t); const meta = { workDir: repo, agentKind: 'claude-code' }; + const warnings = []; const snapshot = createHostGitSnapshot({ getSessionMeta: async () => meta }, - { getLatestUserMessage: async () => ({ clientId: 'user-1', text: 'change a.txt' }) }); - return { repo, snapshot }; + { + getLatestUserMessage: async () => ({ clientId: 'user-1', text: 'change a.txt' }), + logger: { debug() {}, info() {}, warn: (message, fields) => warnings.push({ message, ...fields }) }, + }); + return { repo, snapshot, warnings }; } +const loggedDeadline = (warnings, id) => + warnings.some(warning => warning.sessionId === id && warning.error === 'Snapshot operation deadline exceeded'); + test('a Host turn keeps the desktop savepoint chain in the task repository without a model call', { timeout: TEST_TIMEOUT_MS }, async t => { t = lifoCleanup(t); - const { repo, snapshot } = setup(t, 'snapshot-owner'); + const { repo, snapshot, warnings } = setup(t, 'snapshot-owner'); const head = git(repo, 'rev-parse', 'HEAD'); await snapshot.onTurnStart('task-1'); fs.writeFileSync(path.join(repo, 'a.txt'), 'two\n'); + warnings.length = 0; await snapshot.onTurnEnd('task-1'); assert.equal(git(repo, 'for-each-ref', '--format=%(refname)', 'refs/cindy/savepoints/'), 'refs/cindy/savepoints/task-1'); const { entries } = await listShadowSavepoints(repo, 'task-1'); - assert.equal(entries.length, 2, 'turn-start baseline and after-edit savepoint'); // Newest first. The after-edit label is the labeler's deterministic fallback: // the Host reports the label one-shot unavailable, so no model request is made. - assert.deepEqual(entries.map(entry => entry.label), ['改动 a.txt', '本轮开始时的工作区基线']); + const labels = entries.map(entry => entry.label); + if (labels.length === 1 && loggedDeadline(warnings, 'task-1')) { + assert.deepEqual(labels, ['本轮开始时的工作区基线']); + t.diagnostic('The turn-end Git operation reached its deadline before publishing the edit'); + } else { + assert.deepEqual(labels, ['改动 a.txt', '本轮开始时的工作区基线']); + } // The user's branch, index and working tree are not touched. assert.equal(git(repo, 'rev-parse', 'HEAD'), head); assert.equal(git(repo, 'status', '--porcelain'), 'M a.txt'); assert.equal(fs.readFileSync(path.join(repo, 'a.txt'), 'utf8'), 'two\n'); }); +// A queued repository write can consume the same turn-end budget on Windows +// and Desktop. Drive its deadline while the queue is held, then drain it to +// verify that the cancelled operation cannot publish a late savepoint. +test('a queued Git write can expire without failing the Host turn or publishing a late savepoint', { timeout: TEST_TIMEOUT_MS }, async t => { + t = lifoCleanup(t); + const id = 'queued-edit'; + const { repo, snapshot, warnings } = setup(t, 'snapshot-owner-queued'); + await snapshot.onTurnStart(id); + fs.writeFileSync(path.join(repo, 'a.txt'), 'queued edit\n'); + const held = Promise.withResolvers(); + const release = Promise.withResolvers(); + const writer = enqueueGitRepoWrite(repo, () => { held.resolve(); return release.promise; }); + await held.promise; + warnings.length = 0; + t.mock.timers.enable({ apis: ['setTimeout'] }); + try { + const end = snapshot.onTurnEnd(id); + // The turn's cached repo resolution and queue registration run as microtasks. + await new Promise(resolve => setImmediate(resolve)); + t.mock.timers.runAll(); + await end; + assert.ok(loggedDeadline(warnings, id), 'the completed turn records the Git deadline'); + } finally { + t.mock.timers.reset(); + release.resolve(); + await writer; + await enqueueGitRepoWrite(repo, async () => {}); + } + const { entries } = await listShadowSavepoints(repo, id); + assert.deepEqual(entries.map(entry => entry.label), ['本轮开始时的工作区基线']); + assert.equal(fs.readFileSync(path.join(repo, 'a.txt'), 'utf8'), 'queued edit\n'); +}); + test('a Host turn that is not dispatched leaves no after-edit savepoint', { timeout: TEST_TIMEOUT_MS }, async t => { t = lifoCleanup(t); const { repo, snapshot } = setup(t, 'snapshot-owner-abort'); diff --git a/apps/host/src/agent/harness-binary.ts b/apps/host/src/agent/harness-binary.ts new file mode 100644 index 00000000000..82679bbcd29 --- /dev/null +++ b/apps/host/src/agent/harness-binary.ts @@ -0,0 +1,118 @@ +/** + * The engine binary the Host starts, chosen with the desktop's rules (agent-binaries/index.ts prepare + * with localOnly, factory.ts findUsableLocalBinary): + * 1. Pi's explicit selection (`/pi/selected.json`): a valid selection wins over every other + * binary; an invalid one leaves Pi unavailable (`pi_selection_invalid`) and never falls back to a + * higher leftover install. + * 2. The Host's bundled or dev checkout binary. + * 3. The profile install whose binary reports the highest version (not the first directory listed). + * Read once when an owner runtime starts (main.ts); nothing here installs, updates or deletes. The + * harness status the Host reports (probe and boot values) is then that choice, not a separate scan. + */ +import fs from 'node:fs'; +import path from 'node:path'; + +import { AGENT_BINARY_LAYOUT, readCachedBinaryStatus, type AgentBinaryKind } from '../../../desktop/src/main/agent-binaries/binaryStatus.js'; +import { probeBinaryVersion } from '../../../desktop/src/main/agent-binaries/binary-version-probe.js'; +import { findPreferredLocalBinary } from '../../../desktop/src/main/agent-binaries/local-version-selection.js'; +import { resolveSelectedPiBinary } from '../../../desktop/src/main/agent-binaries/pi-kernel-selection.js'; + +export interface HarnessBinary { + binaryPath: string | null; + /** As the desktop's prepare reports it: Pi has a selection that cannot be used. */ + error?: 'pi_selection_invalid'; +} + +function isExecutableFile(candidate: string): boolean { + try { + fs.accessSync(candidate, fs.constants.X_OK); + return true; + } catch { + return false; + } +} + +export async function resolveHarnessBinaryPath( + kind: AgentBinaryKind, + options: { userDataDir: string; bundledCandidates: readonly string[] }, +): Promise { + const layout = AGENT_BINARY_LAYOUT[kind]; + const installRoot = path.join(options.userDataDir, layout.installSubdir); + if (kind === 'pi') { + try { + // The desktop's hasSelection + selectedBinary: null only when there is no selection. + const selected = await resolveSelectedPiBinary(installRoot, probeBinaryVersion); + if (selected) return { binaryPath: selected }; + } catch { + // Do not resurrect a higher leftover version after an explicit downgrade. + return { binaryPath: null, error: 'pi_selection_invalid' }; + } + } + const bundled = options.bundledCandidates.find(isExecutableFile); + if (bundled) return { binaryPath: bundled }; + const local = await findPreferredLocalBinary(() => installRoot, layout.binaryName, undefined, probeBinaryVersion); + return { binaryPath: local?.binaryPath ?? null }; +} + +/** The engines the Host runs, in the order the desktop's dev lookup uses. */ +export const HOST_HARNESS_KINDS = ['claude-code', 'codex', 'pi'] as const; +const platformKey = `${process.platform}-${process.arch}`; + +/** The Host's bundled or dev checkout binary of an engine. */ +function bundledHarnessBinary(kind: AgentBinaryKind, harnessRoot: string): string { + const layout = kind === 'claude-code' + ? { dir: 'claude-code-bin', file: AGENT_BINARY_LAYOUT['claude-code'].binaryName } + : kind === 'codex' + ? { dir: 'codex-package-bin', file: AGENT_BINARY_LAYOUT.codex.binaryName } + : { dir: 'pi-bin', file: AGENT_BINARY_LAYOUT.pi.binaryName }; + return path.join(harnessRoot, layout.dir, platformKey, layout.file); +} + +export interface HostHarnessBinaries { + /** Choose every engine binary (resolveHarnessBinaryPath); status() reports this choice from then on. */ + resolve(): Promise>; + /** + * Whether each engine can start. Once resolve() has run, an engine is ready only when its chosen + * binary is still executable: an invalid Pi selection is not ready even with a higher install left. + * Before that (no owner runtime yet), the synchronous scan of binaryStatus.ts. + */ + status(): Record; +} + +export function createHostHarnessBinaries(ports: { + userDataDir: () => string; + harnessRoot: () => string; + onUnavailable: (kind: AgentBinaryKind, error: 'pi_selection_invalid') => void; +}): HostHarnessBinaries { + let chosen: Record | null = null; + return { + async resolve() { + const entries = await Promise.all(HOST_HARNESS_KINDS.map(async (kind) => { + const resolved = await resolveHarnessBinaryPath(kind, { + userDataDir: ports.userDataDir(), + bundledCandidates: [bundledHarnessBinary(kind, ports.harnessRoot())], + }); + if (resolved.error) ports.onUnavailable(kind, resolved.error); + return [kind, resolved.binaryPath] as const; + })); + chosen = Object.fromEntries(entries) as Record; + return chosen; + }, + status() { + const current = chosen; + return Object.fromEntries(HOST_HARNESS_KINDS.map((kind) => { + if (current) { + const binary = current[kind]; + return [kind, binary !== null && isExecutableFile(binary)]; + } + const status = readCachedBinaryStatus({ + kind, + isPackaged: false, + userDataDir: ports.userDataDir(), + devCandidates: [bundledHarnessBinary(kind, ports.harnessRoot())].map((candidate) => path.resolve(candidate)), + }); + return [kind, status.binaryReady]; + })) as Record; + }, + }; +} diff --git a/apps/host/src/agent/held-credentials.ts b/apps/host/src/agent/held-credentials.ts new file mode 100644 index 00000000000..1ab5c5e953e --- /dev/null +++ b/apps/host/src/agent/held-credentials.ts @@ -0,0 +1,59 @@ +/** + * Coexistence plan A (reviewer, 2026-11-17): while a Cindy desktop app running on its own uses this + * profile, the Host writes no credential the desktop shares. The Cindy account session renewal is + * the one exception (the Host would sign itself out otherwise; release table, coexistence row). + * + * One place for the decision and the words, for the credentials whose renewal goes out through a + * fetch the Host passes (custom provider OAuth, plugin OAuth): while held that request is answered + * here, before it reaches the network, so no refresh token is spent or rotated, and the owner of the + * fetch sees an ordinary refused renewal (it writes nothing and marks nothing expired). Credentials + * with their own Host wrapper (Codex: codex-runtime.ts, xAI: xai-held-login.ts) use the same words. + */ +import { HOST_PROFILE_IN_USE_BY_DESKTOP } from './profile-coexistence.js'; + +/** `HOST_PROFILE_IN_USE_BY_DESKTOP: while a Cindy desktop app … Quit that app, then try again.` */ +export function heldCredentialMessage(what: string): string { + return `${HOST_PROFILE_IN_USE_BY_DESKTOP}: ${what} while a Cindy desktop app running on its own uses this data ` + + '(both would renew the same sign-in). Quit that app, then try again.'; +} + +/** The refusal a held credential request gets, as an Error. */ +export function heldCredentialError(what: string): Error { + return new Error(heldCredentialMessage(what)); +} + +/** + * A fetch that, while held, answers 503 with an OAuth error body naming the reason instead of + * sending the request. Released, it is the fetch it wraps. + */ +export function holdCredentialFetch Promise>(fetchImpl: F, isProfileHeld: () => boolean, what: string): F { + return (async (input: unknown, init?: unknown) => { + if (!isProfileHeld()) return fetchImpl(input, init); + return new Response(JSON.stringify({ error: HOST_PROFILE_IN_USE_BY_DESKTOP, error_description: heldCredentialMessage(what) }), + { status: 503, headers: { 'content-type': 'application/json' } }); + }) as F; +} + +/** + * Browser recipe credentials that cannot be read while held. The rule for a recipe: list it when its + * renewal rotates the refresh token. Such a recipe sends its own renewal and only then writes the + * result back, so holding the write alone would leave the server rotated and the stored token dead + * for both processes; refusing the read stops it before its first request. Recipes that keep their + * refresh token may renew while held (they write back only a new access token, which does not harm + * the desktop). + * - Xiaoyuzhou: renews with x-jike-refresh-token and saves the new pair (opencli-vendor + * clis/xiaoyuzhou/auth.js 120–145), also after a 401 (188–192). Listed. + * - Spotify: keeps `data.refresh_token || refreshToken` (clis/spotify/spotify.js 33–64). Not listed. + * The ids are the store ids browser.ts browserRecipeSecretId gives them. + */ +export const RECIPE_SECRETS_UNREADABLE_WHILE_HELD: readonly string[] = Object.freeze(['browser-recipe-xiaoyuzhou']); + +/** The recipe secret store with RECIPE_SECRETS_UNREADABLE_WHILE_HELD refused while held. */ +export function holdRecipeSecrets( + io: T, isProfileHeld: () => boolean): T { + const refuse = (id: string) => { + if (isProfileHeld() && RECIPE_SECRETS_UNREADABLE_WHILE_HELD.includes(id)) + throw heldCredentialError('this browser recipe sign-in, whose renewal replaces its refresh token, is not used'); + }; + return { ...io, read: (id: string) => { refuse(id); return io.read(id); }, readStrict: (id: string) => { refuse(id); return io.readStrict(id); } }; +} diff --git a/apps/host/src/agent/history.ts b/apps/host/src/agent/history.ts index cffb3590a7e..8bb374d23dc 100644 --- a/apps/host/src/agent/history.ts +++ b/apps/host/src/agent/history.ts @@ -1,17 +1,20 @@ /** - * Windowed history reader for cindy-host. + * History reads for cindy-host. * - * Reuses createHistoryViewReader from desktop localDb/ipc/historyViewReader - * so the web client gets the exact same pagination, work grouping, - * and lazy details as desktop. + * The history view and work details are the desktop's reader (createHostHistoryReader below binds + * its ports). readMessagesList and readMessagesAroundClientId are the Host's own reads for + * `/api/messages/list`, `/api/sessions/messages` and the around-a-message read. */ import { and, asc, desc, eq, gt, isNull, lt, or, sql, type SQL } from 'drizzle-orm'; -import { createHistoryViewReader } from '../../../desktop/src/main/localDb/ipc/historyViewReader.js'; +import { createLocalHistoryViewReader, type LocalHistoryViewReaderPorts } from '../../../desktop/src/main/localDb/ipc/localHistoryViewReader.js'; +import { isDeviceLinkInvoke } from '../../../desktop/src/main/device-link/invoke-context.js'; import { messageToCamel } from '../../../desktop/src/main/localDb/mapper.js'; import { messages as messageTable, sessions as sessionTable } from '../../../desktop/src/main/localDb/schema.js'; import { getDbClient } from '../../../desktop/src/main/localDb/client/current.js'; import type { Message } from '../../../desktop/src/renderer/lib/ccAgent.types.js'; +import { explicitPorts } from './explicit-ports.js'; +import { recoverGeneratedImagesForHistory } from '../../../desktop/src/main/cindy-media/generatedImageRecovery.js'; const messageRowid = sql`"messages"."rowid"`; @@ -29,6 +32,10 @@ export async function readMessagesList(sessionId: string, opts: HistoryListOptio const limit = Math.max(1, Math.min(opts.limit ?? 200, 2000)); const before = opts.before?.trim() || null; const after = opts.after?.trim() || null; + // As the desktop's messages list (localHistoryViewReader.ts createReadMessagesList): its first page + // starts the task's generated-image recovery without waiting (agent/generated-images.ts binds it). + // The history view reads outlines, which do not. + if (!before && !after) void recoverGeneratedImagesForHistory(sessionId).catch(() => undefined); // Session clearedAt boundary const [session] = await db @@ -110,48 +117,40 @@ export async function readMessagesList(sessionId: string, opts: HistoryListOptio })); } -export function createHostHistoryReader(isSessionRunning: (sessionId: string) => boolean = () => false) { - return createHistoryViewReader({ - list: async (sessionId, opts) => { - return readMessagesList(sessionId, { - limit: opts.limit, - before: opts.before, - after: opts.after, - }); - }, - anchor: async (sessionId, id) => { - const dbClient = getDbClient(); - if (!dbClient) throw new Error('DbClient not ready'); - const db = dbClient.drizzle; - - const [row] = await db - .select({ - id: messageTable.id, - clientId: messageTable.clientId, - sessionId: messageTable.sessionId, - role: messageTable.role, - content: messageTable.content, - toolUseId: messageTable.toolUseId, - agentMeta: messageTable.agentMeta, - agentKind: messageTable.agentKind, - createdAt: messageTable.createdAt, - rewindAt: messageTable.rewindAt, - rowid: messageRowid, - }) - .from(messageTable) - .where(and(eq(messageTable.sessionId, sessionId), eq(messageTable.id, id), isNull(messageTable.rewindAt))) - .limit(1); +export interface HostHistoryReaderPorts { + /** The task's turn has not settled yet (the input queue's isTurnRunning, the executor's isRunning). */ + running(sessionId: string): boolean; + /** Rows of the task's turn not in the database yet (the input queue's liveHistory). */ + live(sessionId: string): Message[]; +} - if (!row) throw new Error(`Message not found: ${id}`); - return { - ...messageToCamel(row), - rowid: row.rowid, - }; - }, - running: isSessionRunning, - live: () => [], - revision: async () => '1', - }); +/** + * The history view and work details (`/api/messages/history-view`, `/api/messages/work-details`): + * the desktop's reader itself (localHistoryViewReader.ts createLocalHistoryViewReader), with list, + * outline, hydrate, validate, revision and anchor as the desktop wrote them. The Host binds only the + * process ports, every one written out below. + */ +export function createHostHistoryReader(ports: HostHistoryReaderPorts) { + return createLocalHistoryViewReader(explicitPorts({ + // The desktop binds isSessionTurnPendingCompletion (registerAll.ts, register.ts): running until the + // turn's rows have settled. The executor's isRunning is that boundary on the Host (turn-executor.mjs: + // a turn counts as running until its reply rows settle). + running: (sessionId) => ports.running(sessionId), + live: (sessionId) => ports.live(sessionId), + // Device Link reaches these routes on the Host as well: the shared inbound dispatch runs a peer's + // invoke inside its device-link context and device-link.ts calls the service in process + // (HOST_CONTRACT_CHANNELS, local-db:messages:view). The value is the same as the desktop's and only + // keeps a peer's in-flight page apart from a local one (historyViewReader.ts shareScope). + isDeviceLinkCaller: () => isDeviceLinkInvoke(), + // The desktop imports a task's external history (Codex rollout, Claude transcript) before an + // unpaged read (runMessagesListImportSideEffects). It needs the desktop's agent registries and + // is not on the Host: the Host's own list (readMessagesList above) does not import either. + importBeforeList: undefined, + // Local task images on durable assistant rows (restoreTaskImageRows): taskImageDelivery.ts loads + // Electron through the desktop media ingest and ref journal, so it cannot load on the Host yet; + // rows are returned as read (release table section 5, Host history reader ④, 甲类次要). + restoreTaskImages: undefined, + })); } export async function readMessagesAroundClientId( diff --git a/apps/host/src/agent/host-tools.ts b/apps/host/src/agent/host-tools.ts index 0b32441d414..48e2169d1cd 100644 --- a/apps/host/src/agent/host-tools.ts +++ b/apps/host/src/agent/host-tools.ts @@ -24,13 +24,20 @@ import type { HostStorageService } from '../../../desktop/src/main/cindy-brain/s import { createStorageToolExecutor } from '../../../desktop/src/main/cindy-brain/storageToolAccess.js'; import { HostServiceCatalog, createHostServiceToolExecutor } from '../../../desktop/src/main/cindy-brain/hostServiceCatalog.js'; import { ownerScopedPath } from '../../../desktop/src/main/dataOwnerPath.js'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; +import { HELP_KNOWLEDGE } from '../../../desktop/src/main/maker-ipc/helpKnowledge.generated.js'; import type { createHostConfirmations } from '../host-confirmations.js'; +import { parseTypedError } from '../typed-error.mjs'; +import { HOST_PROFILE_IN_USE_BY_DESKTOP } from './profile-coexistence.js'; + +const PROJECT_WRITE_TOOLS = new Set(['create_project', 'update_project_info', 'rename_project', 'remove_project']); interface Options { profileDir: string; ownerId: string; owner(): DataOwnerPushStamp; current(): boolean; + profileHold?(): string | null; deviceId?(): string; onProjectsChanged?(catalogChanged: boolean): void; getGhost(id: string): InstalledGhost | null; @@ -59,16 +66,31 @@ export function createHostToolService(options: Options) { }) : async () => ({ ok: false, errorCode: 'HOST_NOT_READY', message: 'Task input authority is unavailable.' }), }); const authorizeCall: ToolCallAuthorizer = async call => { + const projectWrite = call.server === 'cindy_helper' && PROJECT_WRITE_TOOLS.has(call.tool); + const projectHold = () => projectWrite ? options.profileHold?.() : null; + let held = projectHold(); + if (held) return { ok: false, errorCode: 'PRECONDITION_FAILED', message: held }; + const database = getCurrentDbClientSnapshot(); const decision = await authorizeTaskCall(call); if (!decision.ok) return decision; + // Task authorization can wait for a confirmation while the desktop takes the profile. + held = projectHold(); + if (held) return { ok: false, errorCode: 'PRECONDITION_FAILED', message: held }; const assertCurrent = () => { if (!current() || !database || database !== getCurrentDbClientSnapshot()) throw new Error('OWNER_SCOPE_CHANGED'); }; try { assertCurrent(); } catch { return { ok: false, errorCode: 'OWNER_SCOPE_CHANGED', message: 'Host account changed.' }; } return { ok: true, run: operation => { - const run = async () => { assertCurrent(); const result = await operation(); assertCurrent(); return result; }; + const run = async () => { + assertCurrent(); + const occupied = projectHold(); + if (occupied) throwIpcError('PRECONDITION_FAILED', occupied); + const result = await operation(); + assertCurrent(); + return result; + }; return decision.run ? decision.run(run) : run(); } }; }; @@ -101,7 +123,14 @@ export function createHostToolService(options: Options) { return result; }, updateProjectInfo: async (input, authorization) => { - const result = await updateProjectInfo(input, authorization); + const result = await updateProjectInfo(input, authorization && { + ...authorization, + assertCurrent() { + authorization.assertCurrent?.(); + const held = options.profileHold?.(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + }, + }); if (current()) options.onProjectsChanged?.(false); return result; }, @@ -117,12 +146,24 @@ export function createHostToolService(options: Options) { }, }, }); + const updateProjectTool = projectTools.projectManagement!.updateInfo!; + projectTools.projectManagement!.updateInfo = async request => { + try { + return await updateProjectTool(request); + } catch (error) { + const refusal = parseTypedError(error); + if (refusal?.code !== 'PRECONDITION_FAILED' || !refusal.message.startsWith(HOST_PROFILE_IN_USE_BY_DESKTOP)) throw error; + return { ok: false, errorCode: refusal.code, message: refusal.message }; + } + }; // Node plugin installation and connection lifecycles are not connected yet. // Agent providers remain unchanged; plugins fail before setup. const supportsPluginServer = (server: string) => server !== 'cindy_computer'; const providers = createLiziMcpProviders({ xdtHelper: { authorizeCall, ...projectTools, hostServices: createHostServiceToolExecutor(services, { pluginCall: getPluginHostToolCaller, getGhost: options.getGhost, supportsPluginServer }), + // The product help the desktop gives get_capabilities({ scope: 'help' }) (mcp-providers.ts productHelpDocs). + productHelpDocs: HELP_KNOWLEDGE, resolveSurface: async ({ sessionId }) => { const db = current() ? tryGetDbClient() : null; return db ? resolveHelperSurface(db, sessionId) : 'restricted'; @@ -140,6 +181,15 @@ export function createHostToolService(options: Options) { services.replace(providers); return { providers, terminal, services, + /** + * Whether a task's history reads may cover every task: the cindy_helper history decision + * (historyToolCallbacks.ts resolveSessionScope, through the same authorizer), which the desktop's + * session_search shares (mcp-providers.ts botReadsAccountHistory). + */ + async readsAccountHistory(sessionId: string | undefined): Promise { + if (!sessionId && getPluginHostToolCaller()) return true; + return (await authorizeCall({ sessionId, server: 'cindy_helper', tool: 'history', args: {} })).ok; + }, request(id: string, payload: unknown, pageCurrent: () => boolean) { return handlePluginHostToolRequest(id, payload, () => current() && pageCurrent(), { owner: options.owner, getGhost: options.getGhost, diff --git a/apps/host/src/agent/idle-release.test.mjs b/apps/host/src/agent/idle-release.test.mjs new file mode 100644 index 00000000000..3fb737be783 --- /dev/null +++ b/apps/host/src/agent/idle-release.test.mjs @@ -0,0 +1,212 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { configureHostOwner } from './claude-auth.mjs'; +import { hostRuntimeLayout } from '../runtime-layout.mjs'; +import { openOwnerDatabase } from '../../../desktop/src/main/localDb/startupCore.ts'; +import { createDbClientForHandle } from '../../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { OwnerSessionStorage } from '../../../desktop/src/main/localDb/sessionStorageAdapter.ts'; +import { AgentInputCoordinator } from '../../../desktop/src/main/maker-ipc/agent-input-coordinator.ts'; +import { withSendToSessionLock } from '../../../desktop/src/main/maker-ipc/sendToSessionLock.ts'; +import { + noteClaudeSessionTurnState, recordClaudeApiActivity, resetClaudeBackgroundActivityForTests, +} from '../../../desktop/src/main/maker-host/claude-session-background-activity.ts'; +import { createHostIdleRelease } from './idle-release.ts'; + +const MINUTE = 60_000; + +// Ordinary tasks in this owner's real (migrated) database: the desktop's ordinary-task SQL and the Pi +// candidate queries run against the schema the Host opens, not a hand-made table. +async function fixture(t) { + const sharedProfile = process.env.XDT_OFFICIAL_SHARED_PROFILE; + delete process.env.XDT_OFFICIAL_SHARED_PROFILE; + t.after(() => { if (sharedProfile !== undefined) process.env.XDT_OFFICIAL_SHARED_PROFILE = sharedProfile; }); + const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-idle-release-')); + const profile = path.join(root, 'profile'); + mkdirSync(profile, { recursive: true }); + configureHostOwner({ userDataDir: profile, ownerId: 'owner-idle-release' }); + configureAppDataDir(path.join(root, 'app-data')); + const layout = hostRuntimeLayout(); + const opened = await openOwnerDatabase({ userDataDir: profile, ownerId: 'owner-idle-release', + isPackaged: false, drizzleDir: layout.drizzleDir, sqliteVecExtPath: layout.sqliteVecPath }); + const database = createDbClientForHandle({ db: opened.db, drizzle: opened.drizzle, dispose: async () => opened.db.close() }); + setCurrentDbClient(database, 'owner-idle-release'); + const storage = new OwnerSessionStorage({ db: () => database }); + const clock = { monotonic: 0, wall: Date.parse('2026-11-15T00:00:00Z') }; + const live = new Map(); + const closes = []; + const maker = { + listActiveSessions: () => [...live.values()], + getSession: id => live.get(id), + async closeSessionIfCurrent(session, reason, options) { + closes.push({ id: session.id, reason, options }); + if (live.get(session.id) !== session) return 'not-current'; + if (options?.onlyIfIdle && !(await session.closeIfIdle())) return 'busy'; + live.delete(session.id); + return 'closed'; + }, + }; + const queued = new Map(); + const coordinator = new AgentInputCoordinator({ + sendToAgent: async () => 'accepted', steerToAgent: async () => {}, abortSession: async () => {}, + isTurnRunning: () => false, getTurnGeneration: () => 0, hasPendingInteraction: () => false, + getAgentKind: () => 'claude-code', getSdkSessionId: async () => undefined, + hasAssistantProgressAfter: async () => false, createUserMessage: async () => undefined, + touchUserSend: async () => {}, emitProjection: () => {}, persistQueueSnapshot: async () => {}, + loadQueueSnapshot: async id => queued.get(id) ?? [], getPersistedClientIds: async () => new Set(), + }); + const running = new Set(); + const interactions = new Set(); + let claudeMinutes = 30; + const release = createHostIdleRelease({ + coordinator, getMaker: () => maker, + isTurnPendingCompletion: id => running.has(id), + hasPendingInteraction: id => interactions.has(id), + readClaudeMinutes: () => claudeMinutes, + clock: { monotonic: () => clock.monotonic, wall: () => clock.wall }, + }); + t.after(async () => { + release.stop(); + resetClaudeBackgroundActivityForTests(); + clearCurrentDbClient(); await database.dispose(); + configureHostOwner({ userDataDir: profile, ownerId: null }); + rmSync(root, { recursive: true, force: true }); + }); + /** A task row and its live runtime, idle since now. */ + async function task(id, agentKind) { + const dbKind = agentKind === 'claude-code' ? 'cc' : agentKind; + await storage.create({ id, title: id, agentKind, model: 'model', workDir: root }); + opened.db.prepare('UPDATE sessions SET sdk_session_id = ?, updated_at = ?, last_turn_ended_at = ?, user_send_at = ? WHERE id = ?') + .run(`native-${id}`, clock.wall, clock.wall, clock.wall, id); + assert.equal(opened.db.prepare('SELECT agent_kind FROM sessions WHERE id = ?').get(id).agent_kind, dbKind); + let generation = 0; + const listeners = new Set(); + const session = { + id, agentKind, remoteHostId: null, agentDeviceId: null, sdkSessionId: `native-${id}`, + tasks: [], turnRunning: false, + getStatus: () => 'active', getTurnGeneration: () => generation, + isTurnRunning: () => session.turnRunning, listBackgroundTasks: () => session.tasks, + countPendingWakeContinuations: () => 0, manageAsyncUserQuestions: () => ({ questions: [] }), + onEvent(listener) { listeners.add(listener); return () => listeners.delete(listener); }, + closeIfIdle: async () => true, close: async () => {}, hasLiveBackgroundWork: async () => false, + /** A send started a new turn on this runtime. */ + startTurn() { generation += 1; for (const listener of listeners) listener({ type: 'status', data: { isRunning: true } }); }, + }; + live.set(id, session); + return session; + } + /** Moves both clocks forward, as idle time passes. */ + function pass(ms) { clock.monotonic += ms; clock.wall += ms; } + const released = () => closes.filter(close => !live.has(close.id)).map(close => close.id).sort(); + return { db: opened.db, task, pass, release, closes, released, queued, running, interactions, live, + setClaudeMinutes(minutes) { claudeMinutes = minutes; } }; +} + +test('idle release: ordinary Claude, Codex and Pi tasks release their runtimes after 30 idle minutes, idle-only and resumable', async t => { + const f = await fixture(t); + await f.task('claude', 'claude-code'); + await f.task('codex', 'codex'); + await f.task('pi', 'pi'); + await f.release.scanNow(); + f.pass(29 * MINUTE); + await f.release.scanNow(); + assert.deepEqual(f.released(), [], 'not before 30 minutes'); + f.pass(2 * MINUTE); + await f.release.scanNow(); + assert.deepEqual(f.released(), ['claude', 'codex', 'pi']); + for (const close of f.closes) { + assert.equal(close.reason, 'runtime-refresh', 'a transient close: task resources and native identity stay'); + assert.deepEqual(close.options, { onlyIfIdle: true }); + } +}); + +test('idle release: the Claude override in the profile root shortens Claude only', async t => { + const f = await fixture(t); + f.setClaudeMinutes(5); + await f.task('claude', 'claude-code'); + await f.task('codex', 'codex'); + await f.release.scanNow(); + f.pass(6 * MINUTE); + await f.release.scanNow(); + assert.deepEqual(f.released(), ['claude']); +}); + +test('idle release: queued input, a settling turn, a pending interaction, a background task or Claude background activity keep the runtime', async t => { + t.mock.timers.enable({ apis: ['Date'], now: Date.parse('2026-11-15T00:00:00Z') }); + const f = await fixture(t); + const queued = await f.task('queued', 'claude-code'); + f.queued.set('queued', [{ clientId: 'next', text: 'next', persistedContent: 'next', model: 'model', effort: 'medium', + permissionMode: 'default', workingDir: '/repo', + chatMessage: { clientId: 'next', role: 'user', content: 'next', isStreaming: false, createdAt: '2026-11-15T00:00:00.000Z' }, + createOpts: { agentKind: 'claude-code', workingDir: '/repo', model: 'model', effort: 'medium', permissionMode: 'default' } }]); + await f.task('settling', 'codex'); + f.running.add('settling'); + // The desktop's Claude and Codex watchers read pending interactions; its Pi watcher does not + // (a Pi turn waiting on one is still running), and neither does the Host's. + await f.task('asking', 'codex'); + f.interactions.add('asking'); + const background = await f.task('background', 'codex'); + background.tasks = [{ taskId: 'build' }]; + // Claude's sub-agent still calls the model after the turn ended (the proxy records it). + await f.task('subagent', 'claude-code'); + noteClaudeSessionTurnState('subagent', true); + noteClaudeSessionTurnState('subagent', false); + t.mock.timers.tick(5_000); + recordClaudeApiActivity('native-subagent', 'subagent'); + await f.release.scanNow(); + f.pass(31 * MINUTE); + await f.release.scanNow(); + assert.deepEqual(f.released(), [], 'every runtime is kept'); + assert.ok(queued, 'the queued task has a live runtime'); +}); + +test('idle release: a release waits for the task\'s send lock and leaves a runtime whose send started meanwhile', async t => { + const f = await fixture(t); + const session = await f.task('sending', 'claude-code'); + await f.release.scanNow(); + f.pass(31 * MINUTE); + let releaseLock; + const held = new Promise(resolve => { releaseLock = resolve; }); + const sending = withSendToSessionLock('sending', async () => { await held; session.startTurn(); }); + const scanning = f.release.scanNow(); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(f.closes, [], 'the release waits for the send that holds the lock'); + releaseLock(); + await sending; + await scanning; + assert.deepEqual(f.released(), [], 'the send started a new turn: the runtime stays'); +}); + +// Tasks outside the ordinary scope keep their own lifecycle on the Host as on the desktop, also when +// the profile carries them from the desktop: hidden, remote-host, other-computer, Orca and goal tasks +// keep their Claude and Codex runtimes; hidden, remote-host, other-computer and Orca Pi tasks keep theirs. +test('idle release: hidden, remote, other-computer, Orca and goal tasks keep their runtimes', async t => { + const f = await fixture(t); + const scoped = { + hidden: "UPDATE sessions SET hidden_at = 1 WHERE id = ?", + remote: "UPDATE sessions SET remote_host_id = 'ssh-host' WHERE id = ?", + device: "UPDATE sessions SET agent_device_id = 'other-computer' WHERE id = ?", + orca: "UPDATE sessions SET orca_role = 'worker' WHERE id = ?", + goal: "INSERT INTO session_goals (session_id, objective, status, agent_kind, started_at, updated_at) VALUES (?, 'ship it', 'active', 'cc', 0, 0)", + }; + const kept = []; + for (const [scope, sql] of Object.entries(scoped)) { + for (const agentKind of ['claude-code', 'codex', 'pi']) { + if (agentKind === 'pi' && scope === 'goal') continue; + const id = `${scope}-${agentKind}`; + await f.task(id, agentKind); + f.db.prepare(sql).run(id); + kept.push(id); + } + } + await f.task('ordinary', 'claude-code'); + await f.release.scanNow(); + f.pass(31 * MINUTE); + await f.release.scanNow(); + assert.deepEqual(f.released(), ['ordinary'], 'only the ordinary task releases its runtime'); + for (const id of kept) assert.ok(f.live.has(id), `${id} keeps its runtime`); +}); diff --git a/apps/host/src/agent/idle-release.ts b/apps/host/src/agent/idle-release.ts new file mode 100644 index 00000000000..17190bd4e18 --- /dev/null +++ b/apps/host/src/agent/idle-release.ts @@ -0,0 +1,120 @@ +import type { Maker } from '@cindy/maker-core'; +import { + createClaudeIdleReleaseWatcher, + createIdleReleaseRuntimeClose, + createOrdinaryIdleReleaseTaskCheck, + DEFAULT_CODEX_IDLE_RELEASE_MINUTES, + ORDINARY_CLAUDE_TASK_SQL, + ORDINARY_CODEX_TASK_SQL, +} from '../../../desktop/src/main/maker-ipc/claudeIdleReleaseWatcher.ts'; +import { + createPiIdleReleaseCandidateQueries, + createPiIdleReleaseClose, + createPiIdleReleaseWatcher, + DEFAULT_PI_IDLE_RELEASE_MINUTES, +} from '../../../desktop/src/main/maker-ipc/piIdleReleaseWatcher.ts'; +import { + hasIdleReleaseQueuedWork, + hasPendingIdleReleaseInput, + hasScheduledIdleReleaseAutoResume, + type IdleReleaseInputCoordinator, +} from '../../../desktop/src/main/maker-ipc/idleReleaseInputGates.ts'; +import { getClaudeSessionBackgroundActivity } from '../../../desktop/src/main/maker-host/claude-session-background-activity.ts'; +import { withSendToSessionLock } from '../../../desktop/src/main/maker-ipc/sendToSessionLock.ts'; +import { withRehydrateCloseSuppressed } from '../../../desktop/src/main/maker-host/rehydrateCloseSuppression.ts'; +import { getDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { createLogger } from '../../../desktop/src/main/logger.ts'; + +const log = createLogger('host-idle-release'); + +/** + * The desktop's idle-runtime release (register.ts: the Claude, Codex and Pi watchers) for one + * owner's input runtime: ordinary local tasks idle for 30 minutes (Claude: the + * claude-idle-release.json override in the profile root) release their runtime, and the next send + * resumes the native session. Same watchers, same gates and the same send lock as the desktop. + * + * The desktop's facts arrive as ports: whether the turn is still settling (the desktop's + * isSessionTurnPendingCompletion; the Host executor's running turn), whether an Agent interaction + * is pending, and whether a credential switch waits for the task's turn to end. + */ +export function createHostIdleRelease(deps: { + coordinator: IdleReleaseInputCoordinator; + getMaker(): Maker | null | undefined; + isTurnPendingCompletion(sessionId: string): boolean; + hasPendingInteraction(sessionId: string): boolean; + hasPendingCredentialSwitch?(sessionId: string): boolean; + readClaudeMinutes(): number; + /** Tests only: the clocks the watchers read (the desktop's performance.now and Date.now). */ + clock?: { monotonic(): number; wall(): number }; +}) { + const { coordinator } = deps; + const monotonic = deps.clock ? () => deps.clock!.monotonic() : () => performance.now(); + const wall = deps.clock ? () => deps.clock!.wall() : Date.now; + const maker = () => { + const current = deps.getMaker(); + if (!current) throw new Error('agent runtime is not ready'); + return current; + }; + const makerPorts = { + closeSessionIfCurrent: ((...args) => maker().closeSessionIfCurrent(...args)) as Maker['closeSessionIfCurrent'], + }; + const listSessions = () => deps.getMaker()?.listActiveSessions() ?? []; + const getSession = (id: string) => deps.getMaker()?.getSession(id); + const hasPendingInput = (id: string) => hasPendingIdleReleaseInput(coordinator, id); + const pendingCredentialSwitch = (id: string) => deps.hasPendingCredentialSwitch?.(id) === true; + const close = createIdleReleaseRuntimeClose(makerPorts, withRehydrateCloseSuppressed); + + const claude = createClaudeIdleReleaseWatcher({ + listSessions, getSession, + readMinutes: deps.readClaudeMinutes, + isOrdinaryTask: createOrdinaryIdleReleaseTaskCheck(getDbClient, ORDINARY_CLAUDE_TASK_SQL), + hasPendingInput, + isHostBusy: (id) => deps.isTurnPendingCompletion(id) + || deps.hasPendingInteraction(id) + || Boolean(getClaudeSessionBackgroundActivity(id)) + || hasIdleReleaseQueuedWork(coordinator, id) + || pendingCredentialSwitch(id), + withLock: withSendToSessionLock, + close, + now: monotonic, + released: (sessionId, idleMs) => log.info('claudeIdleWatcher: released idle runtime', { sessionId, idleMs }), + warn: (message) => log.warn(message), + }); + const codex = createClaudeIdleReleaseWatcher({ + agentKind: 'codex', + listSessions, getSession, + readMinutes: () => DEFAULT_CODEX_IDLE_RELEASE_MINUTES, + isOrdinaryTask: createOrdinaryIdleReleaseTaskCheck(getDbClient, ORDINARY_CODEX_TASK_SQL), + hasPendingInput, + isHostBusy: (id) => deps.isTurnPendingCompletion(id) + || deps.hasPendingInteraction(id) + || hasIdleReleaseQueuedWork(coordinator, id) + || pendingCredentialSwitch(id), + withLock: withSendToSessionLock, + close, + now: monotonic, + released: (sessionId, idleMs) => log.info('codexIdleWatcher: released idle runtime', { sessionId, idleMs }), + warn: (message) => log.warn(message), + }); + const pi = createPiIdleReleaseWatcher({ + closeSession: createPiIdleReleaseClose(makerPorts, withRehydrateCloseSuppressed), + readIdleReleaseMinutes: () => DEFAULT_PI_IDLE_RELEASE_MINUTES, + ...createPiIdleReleaseCandidateQueries(getDbClient), + getSession: (sessionId) => getSession(sessionId) ?? null, + withSessionLock: withSendToSessionLock, + hasPendingInput, + hasScheduledAutoResume: (sessionId) => hasScheduledIdleReleaseAutoResume(coordinator, sessionId), + now: wall, + timer: { setInterval, clearInterval }, + log, + }); + + return { + /** Starts the three watchers once this owner's agent runtime is ready. */ + start() { pi.start(); claude.start(); codex.start(); }, + /** Stops them before the owner's runtime is disposed (shutdown, sign-out, account switch). */ + stop() { claude.stop(); codex.stop(); pi.stop(); }, + /** One scan of each watcher, for tests. */ + async scanNow() { await claude.scanNow(); await codex.scanNow(); await pi.scanNow(); }, + }; +} diff --git a/apps/host/src/agent/input-queue.mjs b/apps/host/src/agent/input-queue.mjs index 30debaee132..2e0daaf9291 100644 --- a/apps/host/src/agent/input-queue.mjs +++ b/apps/host/src/agent/input-queue.mjs @@ -2,17 +2,26 @@ import { AgentInputCoordinator } from '../../../desktop/src/main/maker-ipc/agent import { isDeviceLinkInvoke, isMobileControllerInvoke, readDeviceLinkInvokeSourceDevice } from '../../../desktop/src/main/device-link/invoke-context.ts'; import { stampTrustedDeviceLinkQueuedOrigin, stampTrustedDesktopQueuedOrigin } from '../../../desktop/src/main/maker-ipc/queuedInputOrigin.ts'; import { createTurnExecutor } from './turn-executor.mjs'; +import { hostCoordinatorDeps } from './coordinator-deps.ts'; +import { createHostAutoResume } from './auto-resume.ts'; +import { createHostProductTurn } from './product-turn.ts'; +import { getUserDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { createHostIdleRelease } from './idle-release.ts'; import { createAppMessageSender } from '../../../desktop/src/main/mcp-apps/messageSender.ts'; import { MCP_APP_MESSAGE_GUARD } from '../../../desktop/src/main/mcp-apps/message.ts'; import { randomUUID } from 'node:crypto'; -import { createSchedulerQueueBridge, prepareQueuedPromptSnapshot } from '../../../desktop/src/main/maker-ipc/schedulerQueueBridge.ts'; +import { createSchedulerQueueBridge } from '../../../desktop/src/main/maker-ipc/schedulerQueueBridge.ts'; import { createQueuedAcceptedCallbacks } from '../../../desktop/src/main/maker-ipc/queuedAcceptedCallbacks.ts'; -import { runSchedulerQueuedPreparation } from '../../../desktop/src/main/maker-ipc/schedulerQueuedPreparation.ts'; import { readTaskActionInput } from '../../../desktop/src/main/maker-ipc/taskActionInput.ts'; import { QueuedAttachmentOwnershipRegistry } from '../../../desktop/src/main/maker-ipc/queuedAttachmentOwnership.ts'; import { createLogger } from '../../../desktop/src/main/logger.ts'; +import { isSessionErrorSuppressed } from '../../../desktop/src/main/maker-ipc/sessionErrorSuppression.ts'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.ts'; +import { createIpcError } from '../../../desktop/src/shared/ipc-errors.ts'; +const settlementLog = createLogger('host-turn-settlement'); const attachmentLog = createLogger('host-attachments'); +const log = createLogger('host-auto-resume'); /** Create options for every start from a stored task row (send, restore, resume). */ export function storedSessionOptions(stored) { @@ -24,6 +33,20 @@ export function storedSessionOptions(stored) { } const makerKind = kind => kind === 'cc' ? 'claude-code' : kind; + +/** The interaction lock a profile hold puts on every task (coexistence plan A, profile-coexistence.ts). */ +export const PROFILE_HOLD_LOCK = 'profile-coexistence'; + +/** + * Hold one task while a desktop that opens this profile's database runs: nothing queued starts + * (any interaction lock stops the coordinator's dispatch) and the execution pause stops the + * automatic continuations that read it (interrupted-turn auto-resume when the error arrives and + * when its wait ends; a saved usage-limit recovery). Both survive Stop. + */ +export function holdTaskForProfile(coordinator, id) { + coordinator.setInteractionLock(id, PROFILE_HOLD_LOCK, true, { preserveOnStop: true }); + coordinator.setExecutionPaused(id, true); +} const errorText = error => error instanceof Error ? error.message : String(error); /** Only composition fields cross the browser trust boundary. Host receipts, @@ -32,8 +55,9 @@ function composeInput(item, stored) { if (!item || typeof item.clientId !== 'string' || !item.clientId.trim()) throw new Error('clientId is required'); const text = typeof item.text === 'string' ? item.text : item.content; if (typeof text !== 'string' || !text.trim()) throw new Error('message text is required'); - // Picker changes already persist through /sessions/update. Input fields are - // snapshots for presentation, not another authority over task settings. + // Picker changes already persist through their own entries (set-model, set-effort, + // set-permission-mode and the like). Input fields are snapshots for presentation, + // not another authority over task settings. const agentKind = makerKind(stored.agentKind); if (!['claude-code', 'codex', 'pi'].includes(agentKind)) throw new Error('invalid agent kind'); const model = stored.model || ''; @@ -83,9 +107,16 @@ function composeInput(item, stored) { /** Node assembly of the desktop input transaction. There is one queue state * machine for both launchers; this module owns only IO and runtime lifetime. */ export function createInputQueue(deps) { + // Coexistence plan A: null, or the refusal a new send gets while a desktop uses this profile. + let profileHold = null; + let ownerStopping = false; let runtime = createRuntime(); function createRuntime() { + // A blocked route probe must hit Maker's native metadata fence even if its + // adapter is still starting. This signal never aborts an admitted turn. + const routeStartup = new AbortController(); + if (profileHold) routeStartup.abort(createIpcError('PRECONDITION_FAILED', profileHold.message)); const states = new Map(); const schedulePreparations = new Map(); const scheduleDiscardWatchers = new Map(); @@ -126,6 +157,35 @@ export function createInputQueue(deps) { }); return { item: materialized.item, ownerId }; } + async function settleAndWake(id, terminal = false) { + if (closing) return; + // The rebuilt queue has not served a send yet. Bind its history writer to + // the current owner before delivering a cancellation from the old hold. + assertCurrent(); + let settled = false; + try { + settled = (await deps.onSessionSettled?.(id)) !== false; + } finally { + if ((terminal || settled) && !closing && !profileHold && isCurrent()) { + try { deps.afterTurnSettled?.(id); } + finally { coordinator.onExternalTurnSettled(id); } + } + } + } + function retryTurnSettlement(id, terminal = false) { + void settleAndWake(id, terminal).catch(error => settlementLog.warn('turn settlement failed', { id, error: errorText(error) })); + } + /** A new send while the profile is held: refused, typed, before anything is written. */ + function refuseWhileHeld() { + if (profileHold) throwIpcError('PRECONDITION_FAILED', profileHold.message); + } + function holdIfHeld(id) { + if (profileHold) holdTaskForProfile(coordinator, id); + } + /** The execution pause this module lifts after a write stays while the profile is held. */ + function unpause(id) { + if (!profileHold) coordinator.setExecutionPaused(id, false); + } function stateFor(id) { if (!states.has(id)) states.set(id, { commands: Promise.resolve(), writing: Promise.resolve(), admission: 0, closed: false, snapshot: [], persistenceError: null }); @@ -159,14 +219,77 @@ export function createInputQueue(deps) { // Context recovery (context-recovery-assembly.ts): one rollover per runtime, so its memory of // continued inputs lasts as long as this owner's runtime; a new owner's runtime gets a new one. let rollover = null; - const applyPendingAgentSwitchAtDispatch = (id, signal, nextInputChars, assertPreparationCurrent) => deps.applyPendingAgentSwitch?.(id, { - signal, nextInputChars, assertPreparationCurrent, - prepareModelWindowSwitch: (taskId, target) => rollover?.prepareModelWindowSwitch(taskId, target) ?? 'unknown-context', + // The desktop's product-turn failure gate, finalizer and task list activity (product-turn.ts), one per + // owner runtime: the executor ends a turn's activity (held while a resume or recovery owns it), the + // auto-resume and the context recovery settle a held one when they give up. + const productTurn = createHostProductTurn({ getBoundSession: id => executor.boundSession(id), + touchActivity: deps.touchSessionActivity, log }); + // The desktop's auto-resume (auto-resume.ts), one per owner runtime with its coordinator. + const autoResume = createHostAutoResume({ + productTurn: () => productTurn, + userDataDir: deps.userDataDir ?? getUserDataDir, + coordinator: () => coordinator, + history: id => executor.autoResumeHistory(id), + getSession: id => deps.getMaker()?.getSession(id), + createDbMessage: (id, input, options) => deps.persistMessage?.(id, input, options), + onTakeoverReleased: id => releaseResumeOrigin(id), + maybeApplySessionRuntimeFallback: deps.maybeApplySessionRuntimeFallback, + pendingSessionRuntimeFallbackRebuilds: deps.pendingSessionRuntimeFallbackRebuilds, + isProfileHeld: () => profileHold !== null, + log, }); + // The input whose stream an automatic resume continues, per task (Host-only: /api/chat follows + // the resume's turns, which carry their own client ids). Set when the coordinator takes a terminal + // error over; the resume's turns carry it; it ends with the first receipt of an abandoned resume. + const resumeOrigins = new Map(); + // A resume that gives up writes the held error row (once) or drops the takeover: the input it + // continued stopped there, so its stream gets the interrupted receipt once that row is stored. + function releaseResumeOrigin(id) { + const origin = resumeOrigins.get(id); + if (origin === undefined) return; + resumeOrigins.delete(id); + const history = executor.autoResumeHistory(id); + void history.drain().then(() => { + if (history.hasFailedWrites() || !isCurrent()) return; + deps.hub?.publish({ type: 'input_receipt', sessionId: id, inputClientId: origin, clientId: origin, status: 'interrupted' }); + }); + } const executor = createTurnExecutor({ ...deps, storedSessionOptions, + // The owner this runtime's turns started under (assertCurrent): usage is written to that account only. + runtimeOwner: () => owner ?? null, + getAutoResume: () => autoResume, + productTurn, + // A terminal ends its activity held while the coordinator's automatic resume owns it (sessionEventTerminal.ts). + isAutoResumeHeld: id => coordinator.isAutoResumePending(id) || coordinator.isAutoResumeDeferred(id), + // The desktop's silent-stop continuation (silent-stop.ts) reads the queue and rebinds the coordinator's + // turn to the continuation's generation (silentStopTurnEnd.ts); while the profile is held it sends none. + silentStopCoordinator: { + hasPendingQueuedWork: id => coordinator.hasPendingQueuedWork(id), + noteHostTurnContinuation: (id, generation) => coordinator.noteHostTurnContinuation(id, generation), + noteHostTurnContinuationFailed: (id, generation) => coordinator.noteHostTurnContinuationFailed(id, generation), + }, + isProfileHeld: () => profileHold !== null, + resumeOriginOf: id => resumeOrigins.get(id), + resumeAnswered: (id, origin) => { if (resumeOrigins.get(id) === origin) resumeOrigins.delete(id); }, + autoResumePendingOf: (id, origin) => { + const pending = coordinator.getProjection(id).autoResumePending; + if (!pending) { resumeOrigins.delete(id); return undefined; } + resumeOrigins.set(id, origin); + return pending; + }, + // The terminal error an automatic resume holds (sessionEventTerminal.ts): kept in its attempt, + // with the coordinator's attempt and deferred owner, and written once if the resume gives up. + holdSuppressedError: (id, data) => autoResume.autoResumeBookkeeping.stashSuppressedError(id, data, + coordinator.getAutoResumeAttemptToken(id), coordinator.getAutoResumeDeferredOwner(id)), assertCurrent, isCurrent, + prepareUnhealthySession: deps.createContextRecoveryRollover ? async id => { + assertCurrent(); + const rebuilt = await rollover.prepareUnhealthySession(id); + // A healthy result also crosses an await before the transaction reads the live session. + assertCurrent(); + return rebuilt; + } : undefined, getRecoveryRollover: deps.createContextRecoveryRollover ? () => rollover : deps.getRecoveryRollover, - applyPendingAgentSwitch: applyPendingAgentSwitchAtDispatch, prepareUserMessage: attachments?.prepareUserMessage, isClearBoundaryCurrent: (id, boundary, generation) => coordinator.getClearBoundaryMs(id) === boundary && (generation === undefined || coordinator.isGenerationCurrent(id, generation)), @@ -175,82 +298,36 @@ export function createInputQueue(deps) { isStoppingRuntime: () => closing, persistMessage: deps.persistMessage ?? (async () => {}), onPersistenceError: persistenceFailed, - onTerminal: (id, type, error, meta, direct) => { - if (direct) coordinator.wakeSession(id, 'host-turn-settled'); + // When a terminal arrives (turn-executor.mjs handTerminalToCoordinator), as on the desktop. + handTerminal: (id, type, error, signals, meta) => coordinator.onTurnEvent(id, type, error, signals, meta), + isSessionErrorSuppressed: (id, event) => isSessionErrorSuppressed(coordinator, id, event), + // Once the turn's rows settle: the coordinator already has the terminal when it arrived as an + // event, so it is only woken; a turn that ended without one (a stop that only went idle, a + // closed or replaced runtime, a silent-stop done) hands it here, once. + onTerminal: (id, type, error, meta, direct, handedOver) => { + if (direct || handedOver) coordinator.wakeSession(id, 'host-turn-settled'); else coordinator.onTurnEvent(id, type, error, undefined, meta); - deps.onSessionSettled?.(id); + retryTurnSettlement(id, true); }, }); - const coordinator = new AgentInputCoordinator({ - sendToAgent: async (id, message, createOpts, sendOpts) => { - const clientId = sendOpts.persistUserMessage?.clientId; - try { - await runSchedulerQueuedPreparation(clientId, schedulePreparations, - () => { scheduleDiscardWatchers.delete(clientId); acceptedCallbacks.discard(clientId); }); - assertCurrent(); - const result = await executor.send(id, message, createOpts, sendOpts); - await acceptedCallbacks.settle(id, sendOpts, result); - return result; - } catch (error) { - await acceptedCallbacks.rollback(id, clientId); - throw error; - } - }, - steerToAgent: executor.steer, - abortSession: id => { - const promise = executor.abort(id); - stateFor(id).aborting = promise; - return promise; - }, - isTurnRunning: executor.isRunning, - isLiveTurnRunning: id => deps.getMaker()?.getSession(id)?.isTurnRunning?.(), - isLiveSessionPresent: id => !!deps.getMaker()?.getSession(id), - getTurnGeneration: id => deps.getMaker()?.getSession(id)?.getTurnGeneration?.() ?? null, - getTurnSessionIdentity: id => deps.getMaker()?.getSession(id) ?? null, - getObservedCurrentTurnTerminal: id => deps.getMaker()?.getSession(id)?.getObservedCurrentTurnTerminal?.(), - reconcileTurnIdle: executor.reconcileIdle, - getAgentKind: id => makerKind(deps.getMaker()?.getSession(id)?.agentKind) ?? null, - getSdkSessionId: async id => (await deps.readSession(id)).sdkSessionId || undefined, - hasAssistantProgressAfter: deps.hasAssistantProgressAfter, - getRecoveryContextSnapshot: deps.getRecoveryContextSnapshot, + // The coordinator's ports (coordinator-deps.ts, every optional port written out). + const coordinator = new AgentInputCoordinator(hostCoordinatorDeps({ + deps, executor, coordinator: () => coordinator, scheduleBridge: () => scheduleBridge, assertCurrent, + noteAborting: (id, aborting) => { stateFor(id).aborting = aborting; }, + publish, persist, flushed, afterSnapshot, attachmentOwnership, acceptedCallbacks, + schedulePreparations, scheduleDiscardWatchers, autoResume, rollover: () => rollover, + })); + // The desktop's idle-runtime release (idle-release.ts), one set of watchers per owner runtime. + const idleRelease = deps.readClaudeIdleMinutes ? createHostIdleRelease({ + coordinator, + getMaker: () => { try { return deps.getMaker(); } catch { return null; } }, + isTurnPendingCompletion: executor.isRunning, hasPendingInteraction: id => (deps.interactions?.pending(id)?.length ?? 0) > 0, - hasPendingCredentialSwitch: deps.hasPendingCredentialSwitch, - rewindPersistedUserMessageAfterClear: deps.rewindPersistedUserMessageAfterClear, - createUserMessage: (id, input, options) => deps.persistMessage?.(id, input, options), - touchUserSend: deps.touchUserSend ?? (async () => {}), - emitProjection: publish, - persistQueueSnapshot: persist, - awaitQueuePersistence: flushed, - loadQueueSnapshot: deps.loadQueueSnapshot, - loadClearBoundary: deps.loadClearBoundary, - getPersistedClientIds: deps.getPersistedClientIds, - onUserMessagePersisting: (id, item) => attachmentOwnership.markPersistenceStarted(id, item.clientId), - onUserMessagePersisted: (id, item) => { void attachmentOwnership.settleDurable(id, item.clientId); }, - onUserMessagePersistenceFailed: (id, item, options) => { - afterSnapshot(id, () => attachmentOwnership.markPersistenceFailed(id, item.clientId, options)); - }, - // Desktop register.ts (AgentInputCoordinator hooks): after the user row is durable - // and before vendor dispatch, open the turn change record, then the Git baseline. - beforeDispatchUserTurn: (id, item, signal) => executor.beforeDispatchUserTurn(id, item, signal, - snapshot => prepareQueuedPromptSnapshot(snapshot, scheduleDiscardWatchers, id, item, signal)), - // A durable turn that never reached the vendor: drop the record, then the baseline. - onUndispatchedUserTurn: executor.onUndispatchedUserTurn, - onPersistedSendRejected: (id, message, item, recovering) => - scheduleBridge.onPersistedSendRejected(id, message, item, recovering), - onAcceptedQueuedMessage: async (id, item) => { - schedulePreparations.delete(item.clientId); - scheduleDiscardWatchers.delete(item.clientId); - await acceptedCallbacks.run(id, item, scheduleBridge.recoverySourceClientId(id, item)); - }, - onDiscardedQueuedMessage: (id, item) => { - afterSnapshot(id, () => attachmentOwnership.discardClient(id, item.clientId)); - acceptedCallbacks.discard(item.clientId); - schedulePreparations.delete(item.clientId); - const discarded = scheduleDiscardWatchers.get(item.clientId); - scheduleDiscardWatchers.delete(item.clientId); - discarded?.onDiscarded(); - }, - }); + // As register.ts: a credential switch waiting for this task's turn keeps its runtime. + hasPendingCredentialSwitch: id => deps.hasPendingCredentialSwitchEntry?.(id) === true, + readClaudeMinutes: deps.readClaudeIdleMinutes, + ...(deps.idleReleaseClock ? { clock: deps.idleReleaseClock } : {}), + }) : null; const scheduleBridge = createSchedulerQueueBridge({ coordinator, isSessionBusy: id => coordinator.shouldQueueNewTurn(id) || @@ -290,7 +367,7 @@ export function createInputQueue(deps) { acceptedCallbacks.discard(req.clientId); throw error; } finally { - if (!stateFor(id).persistenceError) coordinator.setExecutionPaused(id, false); + if (!stateFor(id).persistenceError) unpause(id); } }, }); @@ -302,6 +379,7 @@ export function createInputQueue(deps) { assertCurrent(); await coordinator.ensureQueueRestored(id); assertCurrent(); + holdIfHeld(id); if (state.admission !== admission) throw new Error('input cancelled before acceptance'); return fn(state, admission); }); @@ -310,10 +388,12 @@ export function createInputQueue(deps) { } async function mutate(id, fn) { return command(id, async state => { + // Editing, removing or moving a queued input writes the queue the desktop may be using. + refuseWhileHeld(); coordinator.setExecutionPaused(id, true); const result = fn(); await flushed(id); - if (!state.persistenceError) coordinator.setExecutionPaused(id, false); + if (!state.persistenceError) unpause(id); return project(result); }); } @@ -321,6 +401,7 @@ export function createInputQueue(deps) { const state = stateFor(id); state.admission += 1; await coordinator.ensureQueueRestored(id); + holdIfHeld(id); // Abort is urgent. A pending steer/send command may itself need this // cancellation to settle, so never serialize Stop behind that promise. coordinator.stop(id, options); @@ -331,6 +412,7 @@ export function createInputQueue(deps) { } if (deps.createContextRecoveryRollover) { rollover = deps.createContextRecoveryRollover({ + assertCurrent, replay: (...args) => executor.replay(...args), drainHistories: () => executor.drainHistories(), resetWireNotes: id => executor.resetWireNotes(id), @@ -361,6 +443,7 @@ export function createInputQueue(deps) { assertCurrent(); return scheduleBridge.hasPendingInput(id); }, enqueuePrompt: req => command(req.sessionId, async (_state, admission) => { + refuseWhileHeld(); // The bridge reads metadata and the stored row before enqueue. Keep // the original command generation across every one of those reads. scheduleAdmissions.set(req.sessionId, admission); @@ -374,27 +457,52 @@ export function createInputQueue(deps) { getLastUserActionAt: id => states.get(id)?.lastUserActionAt ?? null, }), isTurnRunning: executor.isRunning, + /** Closes a task's idle runtime with the executor letting go of it first (turn-executor.mjs). */ + closeRuntime: id => { assertCurrent(); return executor.closeRuntime(id); }, + /** This runtime's context recovery rollover (null when recovery is not assembled). */ + contextRecoveryRollover: () => rollover, + /** The engine of a task as its message persistence knows it. */ + sessionDbAgentKind: id => executor.sessionDbAgentKind(id), + recordRuntimeControlError: (id, data) => executor.recordRuntimeControlError(id, data), + /** Forgets a task's working-directory recovery at its archive or delete (turn-executor.mjs). */ + discardWorkingDirectoryRecovery: id => executor.discardWorkingDirectoryRecovery(id), + /** Rows of a task's turn not in the database yet (turn-executor.mjs liveHistory). */ + liveHistory: id => executor.liveHistory(id), + /** Starting a task's runtime outside a turn, as a send starts it (turn-executor.mjs startPorts). */ + startPorts: () => executor.startPorts, + cancelUsageLimitWait: id => coordinator.cancelUsageLimitWait(id), + refreshQueuedRoute: (id, route) => coordinator.refreshQueuedRoute(id, route), /** A context recovery's replay was accepted (the recovery factory's onRebuilt). */ noteContextRecoveryRebuilt: id => executor.noteRecoveryRebuilt(id), wakeSession: (id, reason) => coordinator.wakeSession(id, reason), + profileRouteStartupSignal: () => routeStartup.signal, capturePiSkillPreparation(id) { + refuseWhileHeld(); + assertCurrent(); const state = stateFor(id); const admission = state.admission; return () => { + refuseWhileHeld(); assertCurrent(); if (closing || state.closed || state.admission !== admission) throw new Error('input cancelled before acceptance'); }; }, preparePiSkillRuntime: (id, dir, options = {}) => command(id, async (state, admission) => { const check = () => { + refuseWhileHeld(); options.assertPreparationCurrent?.(); assertCurrent(); if (state.closed || state.admission !== admission) throw new Error('input cancelled before acceptance'); }; check(); if (options.applyPendingOwnerSelection) { - // This explicitly selected Skill send is already under the task's route lock. - await applyPendingAgentSwitchAtDispatch(id, undefined, options.nextInputChars, check); + // A bad task must be rejected before the pending selection can write. + await executor.assertPiSkillPreparationReady(id, dir, check, true); + await deps.applyPendingAgentSwitch?.(id, { + nextInputChars: options.nextInputChars, + expectedPiModel: options.expectedPiModel, + assertPreparationCurrent: check, + }); check(); } await executor.preparePiSkillRuntime(id, dir, check); @@ -410,8 +518,14 @@ export function createInputQueue(deps) { getProjection: id => command(id, () => api.projection(id)), inputStatus: (id, clientId) => command(id, async () => { const projection = api.projection(id); - if (executor.isInputRunning(id, clientId)) return 'running'; - if (projection.recovery?.clientId === clientId) return 'interrupted'; + // Before the recovery point below: during context recovery the claimed input is the recovery + // point too, but it is still being answered. + if (executor.isInputRunning(id, clientId) || executor.isInputRecovering(id, clientId)) return 'running'; + // An automatic resume continues this input (waiting for its backoff, or its resumed turn running). + if (resumeOrigins.get(id) === clientId) return 'running'; + // A recovery point names its input as clientId (before dispatch) or as item (a stored turn + // whose dispatch failed): either way the input stopped there. + if ((projection.recovery?.clientId ?? projection.recovery?.item?.clientId) === clientId) return 'interrupted'; if (projection.pendingQueue.some(item => item.clientId === clientId)) return 'queued'; const known = await deps.getPersistedClientIds?.(id, [clientId]); assertCurrent(); @@ -426,6 +540,7 @@ export function createInputQueue(deps) { } const known = await deps.getPersistedClientIds?.(id, [item?.clientId]); if (known?.has(item?.clientId)) return api.projection(id); + refuseWhileHeld(); const prepared = await prepareAttachments(id, composeInput(item, await deps.readSession(id)), admission); let accepted = false; try { @@ -436,7 +551,7 @@ export function createInputQueue(deps) { if (prepared.ownerId) attachmentOwnership.activateCurrentOwner(id, item.clientId, prepared.ownerId); await flushed(id); await attachmentOwnership.markDurable(id, item.clientId, prepared.ownerId ?? undefined); - if (!state.persistenceError) coordinator.setExecutionPaused(id, false); + if (!state.persistenceError) unpause(id); return api.projection(id); } finally { if (!accepted && prepared.ownerId) await attachmentOwnership.discardSpecific(id, item.clientId, prepared.ownerId); @@ -447,6 +562,7 @@ export function createInputQueue(deps) { async resume(id) { if (stateFor(id).closed) return api.projection(id); return command(id, async (state, admission) => { + refuseWhileHeld(); await state.aborting?.catch(error => { if (executor.isRunning(id)) throw error; }); await executor.retryPersistence(id); if (state.persistenceError) await persist(id, state.snapshot); @@ -454,14 +570,15 @@ export function createInputQueue(deps) { if (state.admission !== admission) throw new Error('input cancelled before acceptance'); state.persistenceError = null; coordinator.resume(id); - coordinator.setExecutionPaused(id, false); + unpause(id); return api.projection(id); }); }, - retryLastError: id => command(id, () => coordinator.retryLastError(id)), + retryLastError: id => command(id, () => { refuseWhileHeld(); return coordinator.retryLastError(id); }), clearError: id => command(id, () => coordinator.clearError(id)), steer(id, item) { return command(id, async (state, admission) => { + refuseWhileHeld(); const prepared = await prepareAttachments(id, composeInput(item, await deps.readSession(id)), admission); const previous = prepared.ownerId ? attachmentOwnership.activateCurrentOwner(id, item.clientId, prepared.ownerId) : null; @@ -485,6 +602,7 @@ export function createInputQueue(deps) { updateText: (id, clientId, text) => mutate(id, () => coordinator.updateText(id, clientId, text)), updateContent(id, clientId, item) { return command(id, async (state, admission) => { + refuseWhileHeld(); const old = coordinator.getProjection(id).pendingQueue.find(row => row.clientId === clientId); if (!old) return api.projection(id); const composed = composeInput({ ...old, ...item, clientId, @@ -504,7 +622,7 @@ export function createInputQueue(deps) { } await flushed(id); await attachmentOwnership.markDurable(id, clientId); - if (!state.persistenceError) coordinator.setExecutionPaused(id, false); + if (!state.persistenceError) unpause(id); return api.projection(id); } finally { if (!accepted && prepared.ownerId) await attachmentOwnership.discardSpecific(id, clientId, prepared.ownerId); @@ -529,8 +647,36 @@ export function createInputQueue(deps) { await attachments?.closeSession(id); await flushed(id); }, + /** Starts releasing idle runtimes once this owner's agent runtime is ready (main.ts). */ + startIdleRelease: () => { if (!closing) idleRelease?.start(); }, + /** Hold every task this runtime knows (the profile hold started; later tasks are held as they are read). */ + holdKnownTasks() { + routeStartup.abort(createIpcError('PRECONDITION_FAILED', profileHold.message)); + for (const id of states.keys()) holdTaskForProfile(coordinator, id); + deps.holdTurnSettlements?.(states.keys()); + }, + /** + * Whether a turn of this runtime is still running, a context recovery included (its replay is + * part of the turn that overflowed): the hold is not released before they end. + */ + hasRunningTurns: () => [...states.keys()].some(id => executor.isRunning(id) || executor.isRecovering(id)), + /** One scan of every idle-release watcher, for tests. */ + scanIdleRelease: async () => { await idleRelease?.scanNow(); }, + /** + * The owner boundary began (agent/owner-boundary.ts): the runtime is stopping before dispose() + * runs. No new input is accepted, and a turn that ends from now on is an interruption (the + * executor writes no turn end for it). Cancel only prospective route starts here. + */ + beginStop() { + closing = true; + routeStartup.abort(createIpcError('PRECONDITION_FAILED', 'Host account changed; runtime selection was not changed')); + }, + settleAndWake, retryTurnSettlement, + canSettleTurnControls: () => !ownerStopping && !closing && profileHold === null, async dispose() { closing = true; + // No runtime is released while this owner's runtime drains and stops. + idleRelease?.stop(); // Recoveries in flight end as failures and write their error rows first (bounded), // before their tasks are stopped; a stop would read as the user's and drop the error. await executor.drainRecoveriesForShutdown(); @@ -563,6 +709,70 @@ export function createInputQueue(deps) { return api; } const api = Object.fromEntries(Object.keys(runtime).map(name => [name, (...args) => runtime[name](...args)])); - api.dispose = async () => { try { await runtime.dispose(); } finally { runtime = createRuntime(); } }; + // The owner's runtime ends: a hold belonged to it (the next owner's start scans the profile again). + api.beginStop = () => { ownerStopping = true; runtime.beginStop(); }; + api.dispose = async () => { + api.beginStop(); + try { + if (releasing) await releasing; + await runtime.dispose(); + } finally { + deps.disposeTurnSettlements?.(); + profileHold = null; + runtime = createRuntime(); + ownerStopping = false; + } + }; + /** + * Coexistence plan A: a desktop that opens this profile's database is running. New sends are + * refused with `[PRECONDITION_FAILED] `; nothing queued starts and no automatic + * continuation runs (holdTaskForProfile). A running turn finishes, and a context recovery's replay + * belongs to it. Repeating it only updates the message. + */ + let profileHoldGeneration = 0; + api.holdForDesktop = message => { + const first = profileHold === null; + profileHold = { message }; + if (first) { + profileHoldGeneration++; + runtime.holdKnownTasks(); + } + }; + api.isHeldForDesktop = () => profileHold !== null; + api.profileHoldGeneration = () => profileHoldGeneration; + /** + * The desktop is gone: open again only once no turn runs (false: still held, ask again later). The + * desktop may have answered or removed queued inputs meanwhile, so this runtime's queues are not + * trusted: the runtime is rebuilt (dispose writes no queue whose items did not change) and every + * task restores its queue from the database when next read, before the hold is lifted. + */ + let releasing = null; + async function release() { + if (ownerStopping || runtime.hasRunningTurns()) return false; + // The hold ends between the two runtimes: no read of the new one is held by mistake. When the + // old one cannot be disposed, the new one stays held and the next clean scan tries again. + const released = profileHold; + let disposed = false; + try { await runtime.dispose(); disposed = true; } + // A desktop that came back meanwhile replaced the hold: that one stays. + finally { + if (disposed && !ownerStopping && profileHold === released) profileHold = null; + runtime = createRuntime(); + if (ownerStopping) runtime.beginStop(); + } + if (profileHold === null) { + runtime.startIdleRelease(); + for (const id of deps.deferredTurnSettlements?.() ?? []) { + try { await runtime.settleAndWake(id); } + catch (error) { settlementLog.warn('task settlement failed after profile release', { id, error: errorText(error) }); } + } + } + return profileHold === null; + } + api.releaseDesktopHold = () => { + if (profileHold === null) return Promise.resolve(true); + if (!releasing) releasing = release().finally(() => { releasing = null; }); + return releasing; + }; return api; } diff --git a/apps/host/src/agent/input-queue.test.mjs b/apps/host/src/agent/input-queue.test.mjs index 88956966365..ba81f059aab 100644 --- a/apps/host/src/agent/input-queue.test.mjs +++ b/apps/host/src/agent/input-queue.test.mjs @@ -1,7 +1,7 @@ import { runDeviceLinkInvokeContext } from '../../../desktop/src/main/device-link/invoke-context.ts'; -import { test } from 'node:test'; +import { test, after } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'node:fs'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, readdirSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import Database from 'better-sqlite3'; @@ -15,27 +15,75 @@ import { createImageCacheStore } from '../../../desktop/src/main/imageCacheStore import { createHostAttachments } from '../attachments.ts'; import { setCurrentDbClient, clearCurrentDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; import { saveAgentInputQueueSnapshot, loadAgentInputQueueSnapshot, getPersistedInputClientIds } from '../../../desktop/src/main/localDb/agentInputQueueSnapshots.ts'; -import { markSessionTurnStartedDurable, markSessionTurnEnded, drainSessionActiveTurnWrites } from '../../../desktop/src/main/localDb/sessionActiveTurn.ts'; - -import { createInputQueue } from './input-queue.mjs'; +import { markSessionTurnStartedDurable, markSessionTurnEnded, drainSessionActiveTurnWrites, listInterruptedPendingRows, + _setBootAtMsForTests } from '../../../desktop/src/main/localDb/sessionActiveTurn.ts'; +import { getSessionInterruptionBootAt } from '../../../desktop/src/main/localDb/sessionInterruptionBoot.ts'; +import { createOwnerBoundaryStop, runOwnerBoundary } from './owner-boundary.ts'; +import { logoutHostSession } from '../auth/logout.mjs'; +import { serializeAuthSessionRecord } from '@cindy/auth-client'; +import { AUTH_SESSION_KEY } from '../../../desktop/src/main/authCredentialKeys.ts'; + +import { createHostHistoryReader, readMessagesList } from './history.ts'; +import { createInputQueue, holdTaskForProfile, PROFILE_HOLD_LOCK } from './input-queue.mjs'; +import { USAGE_LIMIT_RESET_AUTO_RESUME_REASON } from '../../../desktop/src/shared/agentInputQueue.ts'; +import { AgentInputCoordinator } from '../../../desktop/src/main/maker-ipc/agent-input-coordinator.ts'; import { createTurnExecutor } from './turn-executor.mjs'; +import { CredentialModeSwitchBusyError } from '../../../desktop/src/main/maker-host/credentialSwitchError.ts'; +import { SILENT_STOP_DECISION_DELAY_MS } from '../../../desktop/src/main/maker-ipc/silentStopAutoResume.ts'; +import { SILENT_STOP_AUTO_RESUME_SETTINGS_FILE } from '../../../desktop/src/main/maker-host/silentStopAutoResumeSettingsCore.ts'; import { lockSessionRoute } from './session-route-lock.mjs'; import { CONTEXT_OVERFLOW_REASON } from '../../../../packages/maker-core/src/agents/shared/context-overflow-error.ts'; import { RECOVERY_SHUTDOWN_WAIT_MS, contextRecoveryKind, createHostContextRecovery } from './context-recovery.ts'; +import { createHostCodexThreadStorage } from './codex-thread-storage.ts'; +import { createHostContextRecoveryWiring } from './context-recovery-wiring.ts'; +import { CODEX_HISTORY_OVERSIZED_REASON, CODEX_LIVE_TAIL_OVERSIZED_BYTES } from '@cindy/maker-core'; import { createHostContextRecoveryRollover } from './context-recovery-assembly.ts'; import { createHostAgentHandoffPending } from './handoff-pending.ts'; +import { markCodexPlanInterrupted, writeCodexPlanUpdate } from '../../../desktop/src/main/localDb/codexPlanState.ts'; +import { buildPlanReconcileNote } from '../../../desktop/src/main/maker-ipc/planReconcile.ts'; +import { buildGoalInactiveNote } from '../../../desktop/src/main/goal-host/inactiveNote.ts'; import { createSessionStderrOptions } from '../../../desktop/src/main/maker-ipc/sessionRequest.ts'; import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { getActiveAppSession } from '../../../desktop/src/main/appSessionState.ts'; import { configureHostOwner } from './claude-auth.mjs'; import { hostRuntimeLayout } from '../runtime-layout.mjs'; import { openOwnerDatabase } from '../../../desktop/src/main/localDb/startupCore.ts'; import { createDbClientForHandle } from '../../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; import { getCurrentDbClientSnapshot } from '../../../desktop/src/main/localDb/client/current.ts'; import { OwnerSessionStorage } from '../../../desktop/src/main/localDb/sessionStorageAdapter.ts'; -import { createHostMessageStore } from '../message-store.ts'; +import { createHostRuntimeSession } from './create-runtime-session.ts'; +import { createHostProviderExecutionCheck } from './send-preflight.ts'; +import { bindHostSessionRuntimeHooks, createHostRuntimeSelection, hostRuntimeSelectionQueueHooks, HOST_RUNTIME_SELECTION_QUEUE_MEMBERS, HOST_RUNTIME_START_PORTS } from './runtime-selection.ts'; +import { Session } from '../../../../packages/maker-core/src/session.ts'; +import { acceptSessionRuntimeMutation, getSessionRuntimeControlSnapshot } from '../../../desktop/src/main/maker-ipc/sessionRuntimeControl.ts'; +import { readHostSession } from '../session-reads.ts'; +import { createHostSessionUpdate } from './session-update.ts'; +import { createHostTaskRestore } from './task-restore.ts'; +import { createHostRuntimePluginSettings, createHostTaskRuntimePlugins } from './task-runtime-plugins.ts'; +import { createRuntimePluginHost } from '../../../desktop/src/main/cindy-brain/runtimePluginHostCore.ts'; +import { writeRuntimePluginSettings } from '../../../desktop/src/main/maker-host/runtime-plugin-settings.ts'; +import { installedGhostStoragePart } from '../../../desktop/src/shared/pluginIdentity.ts'; +import { forgetSessionLastLiveUsage } from '../../../desktop/src/main/maker-ipc/sessionLastLiveUsage.ts'; +import { withCrossProcessLock } from '../../../desktop/src/main/device-link/crossProcessLock.ts'; +import { ownerScopedPath } from '../../../desktop/src/main/ownerContext.ts'; +import { getDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { appliedContextWindowBudgets, pendingSessionContextWindowBudgetReconciles } from '../../../desktop/src/main/maker-ipc/sessionContextWindowBudgetState.js'; +import { readSessionContextWindowBudget } from '../../../desktop/src/main/maker-host/session-context-budget-store.js'; +import { getUserDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { getSessionProvider, setSessionProvider } from '../../../desktop/src/main/maker-host/session-provider-store.ts'; +import { watchCredentialGrantRevocation } from '../../../desktop/src/main/remote-agent/executor/credentialGrants.ts'; +import { withSessionPermissionChange } from '../../../desktop/src/main/maker-ipc/sessionPermissionChange.ts'; +import { createUserInputEnqueue } from './user-input.ts'; +import { getThinkingEnabledFromMemory } from '../../../desktop/src/main/maker-host/newMakerDefaultsCache.ts'; +import { createHostMessageStore, createHostMessageRecovery } from '../message-store.ts'; +import { resolveSessionReferencesWithPorts } from '../../../desktop/src/main/maker-ipc/sessionReferenceResolverCore.ts'; import { listErrorTailPendingRows } from '../../../desktop/src/main/localDb/sessionActiveTurn.ts'; -import { withSendToSessionLock } from '../../../desktop/src/main/maker-ipc/sendToSessionLock.ts'; +import { sendToSessionLocks, withSendToSessionLock } from '../../../desktop/src/main/maker-ipc/sendToSessionLock.ts'; +import { AgentStartupStoppedError, Maker } from '@cindy/maker-core'; +import { createHostSessionMovePorts } from './session-move.ts'; import { createEventHub } from '../events.mjs'; +import { createHostService } from '../service.mjs'; +import { estimateHandoffTokens } from '../../../desktop/src/main/maker-ipc/agentHandoff.ts'; import { createChatHandler } from '../chat.mjs'; import { EventEmitter } from 'node:events'; import { Readable } from 'node:stream'; @@ -51,6 +99,16 @@ import { AUTO_REVIEW_USER_INTENT, AUTO_REVIEW_SOURCE_CONTENT, ASYNC_QUESTION_ANS import { lifoCleanup } from '../test-support/cleanup.mjs'; import { GIT_SETTLEMENT_SEQUENCES } from '../../../desktop/src/main/maker-ipc/__tests__/gitBaselineSettlementSequences.ts'; import { GitSnapshotCoordinator } from '../../../desktop/src/main/git-snapshot/gitSnapshotCoordinator.ts'; +import { createHash } from 'node:crypto'; +import { createHostGeneratedImages } from './generated-images.ts'; +import { hostBlobStore } from '../media-store.ts'; +import { bindHostUiText } from '../ui-text.ts'; +import { configureUiText } from '../../../desktop/src/main/uiText.ts'; +import { createInteractionBroker } from './interactions.mjs'; +import { consumeClaudeOpusPlanMismatch, createClaudeGatewayErrorObserver } from '../../../desktop/src/main/maker-host/claude-gateway-error-observer.ts'; +import { recordClaudeRequestRoute } from '../../../desktop/src/main/maker-host/claude-session-route-registry.ts'; +import { CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON } from '../../../desktop/src/shared/claudeGatewayError.ts'; +import { reconcileGeneratedImageRecovery, recoverGeneratedImagesForHistory } from '../../../desktop/src/main/cindy-media/generatedImageRecovery.ts'; function assertOwnerChangedDisposal(disposal) { return assert.rejects(disposal, error => @@ -59,16 +117,53 @@ function assertOwnerChangedDisposal(disposal) { } /** Minimal Maker stand-in: one live session per id, driven by the test. */ +// The Host always runs with a profile: the working-directory check reads the profile's conversation +// recovery directories (working-directory.ts). Tests that open their own profile reconfigure it. +// A test that opens its own profile signs its owner out afterwards; the next fixture signs this one in. +const unitProfile = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-input-queue-')); +const signInUnitOwner = () => configureHostOwner({ userDataDir: unitProfile, ownerId: 'input-queue-unit' }); +signInUnitOwner(); +// The send reads the task's rows (plan, goal, the turn's model) as on the desktop, where a database +// is always open, so a sending fixture without its own database uses this empty one (a fixture +// profile: the development guard against migrating the official shared profile is lifted to open it). +const unitDatabase = await (async () => { + const sharedProfile = process.env.XDT_OFFICIAL_SHARED_PROFILE; + delete process.env.XDT_OFFICIAL_SHARED_PROFILE; + try { + const layout = hostRuntimeLayout(); + configureAppDataDir(path.join(unitProfile, 'app-data')); + const opened = await openOwnerDatabase({ userDataDir: unitProfile, ownerId: 'input-queue-unit', + isPackaged: false, drizzleDir: layout.drizzleDir, sqliteVecExtPath: layout.sqliteVecPath }); + return createDbClientForHandle({ db: opened.db, drizzle: opened.drizzle, dispose: async () => opened.db.close() }); + } finally { + if (sharedProfile !== undefined) process.env.XDT_OFFICIAL_SHARED_PROFILE = sharedProfile; + } +})(); +after(async () => { + await unitDatabase.dispose(); + rmSync(unitProfile, { recursive: true, force: true }); +}); +function ensureUnitOwner() { + if (!getActiveAppSession().dataOwnerId) signInUnitOwner(); + if (!getCurrentDbClientSnapshot()) setCurrentDbClient(unitDatabase, 'input-queue-unit'); +} +ensureUnitOwner(); + function createFakeMaker() { const sessions = new Map(); + // Told of every message a runtime of this fake receives (the enqueue helper waits on it). + const sendListeners = new Set(); return { sessions, + onSent(listener) { sendListeners.add(listener); return () => sendListeners.delete(listener); }, getSession(id) { return sessions.get(id) ?? null; }, async getSessionMeta(id) { return { id, agentKind: 'claude-code', model: 'stored-model', workDir: '/tmp' }; }, + // As Maker (maker.ts listActiveSessions): the live runtimes; the shared agent switch reads it. + listActiveSessions() { return [...sessions.values()]; }, async closeSession(id) { sessions.delete(id); }, async closeSessionIfCurrent(session) { if (sessions.get(session.id) === session) sessions.delete(session.id); @@ -89,6 +184,7 @@ function createFakeMaker() { isTurnRunning() { return session.running; }, getTurnGeneration() { return session.generation; }, options: opts, + get model() { return session.options.model; }, sent: [], sendOptions: [], steerOptions: [], @@ -116,12 +212,20 @@ function createFakeMaker() { session.running = true; session.sent.push(typeof text === 'string' ? text : text.content); session.sendOptions.push(opts); + for (const listener of [...sendListeners]) listener(session.id); return { accepted: true }; }, async abort() { session.aborted += 1; session.running = false; + session.continuationClaim = null; }, + // As the maker-core Session (session.ts): the Host's claim on a generation for a silent-stop + // continuation (released by its settle or a stop), and the continuation's send. + continuationClaim: null, + claimHostTurnContinuation(generation) { if (generation === session.generation) session.continuationClaim = generation; }, + settleHostTurnContinuation(generation) { if (session.continuationClaim === generation) session.continuationClaim = null; }, + sendHostTurnContinuation(text, opts) { return session.send(text, opts); }, async steer(text, options = {}) { await options.beforeProviderStart?.(); session.steerMessages.push(text); @@ -136,12 +240,15 @@ function createFakeMaker() { } function createHarness(overrides = {}) { + ensureUnitOwner(); const maker = createFakeMaker(); const events = []; const persisted = []; + // Every event the queue publishes reaches the hub a test passes (or `events`) and these listeners. + const hubListeners = new Set(); + const hub = overrides.hub ?? { publish: (event) => events.push(event) }; const queue = createInputQueue({ getMaker: () => maker, - hub: { publish: (event) => events.push(event) }, // Unit fixture: all bound working directories exist; filesystem-specific // regressions below override this port with the directory state they need. statDirectory: async () => ({ isDirectory: () => true }), @@ -160,9 +267,13 @@ function createHarness(overrides = {}) { }, readAuthorizationHistory: async id => persisted.filter(row => row.sessionId === id), sent: () => {}, + // Fixture does not test admission (夹具不测准入): the runtime start admission lets every start through. + admitLocalRoute: async () => {}, ...overrides, + hub: { publish(event) { hub.publish(event); for (const listener of [...hubListeners]) listener(event); } }, }); - return { maker, events, persisted, queue }; + const onHubEvent = listener => { hubListeners.add(listener); return () => hubListeners.delete(listener); }; + return { maker, events, persisted, queue, onHubEvent }; } // Unit: preparation of a cold remote Pi task must use the stored route and never create a user turn. @@ -259,6 +370,30 @@ test('Stop prevents Pi skill preparation from booting after an in-flight lookup' } finally { await h.queue.dispose(); } }); +// Unit regression for #11352: a prewarm admitted by Device Link must not open a +// runtime once a desktop owns the profile, even if the stored task was already located. +test('profile hold that starts during Pi skill preparation prevents runtime startup', async () => { + const dir = os.tmpdir(); + let started, resume; + const reading = new Promise(resolve => { started = resolve; }); + const pause = new Promise(resolve => { resume = resolve; }); + const h = createHarness({ readSession: async id => { + started(); + await pause; + return { id, agentKind: 'pi', model: 'stored-model', status: 'active', workingDir: dir }; + } }); + try { + const preparation = h.queue.preparePiSkillRuntime('s', dir); + const denied = assert.rejects(preparation, { code: 'PRECONDITION_FAILED', message: '[PRECONDITION_FAILED] profile is held' }); + await reading; + h.queue.holdForDesktop('profile is held'); + resume(); + await denied; + assert.equal(h.maker.getSession('s'), null); + assert.deepEqual(h.persisted, []); + } finally { await h.queue.dispose(); } +}); + const waitFor = async (check) => { for (let attempt = 0; attempt < 200; attempt += 1) { if (check()) return; @@ -327,6 +462,7 @@ test('stopping a direct Host turn drains its pending start marker', async () => let release; const gate = new Promise(resolve => { release = resolve; }); session.abort = async () => { order.push('aborted'); }; + ensureUnitOwner(); const executor = createTurnExecutor({ getMaker: () => maker, assertCurrent() {}, isCurrent: () => true, isStoppingRuntime: () => false, hub: { publish() {} }, persistMessage: async () => {}, onPersistenceError: error => { throw error; }, onTerminal() {}, @@ -501,9 +637,11 @@ test('persisted scheduler snapshot failure reaches its run with the original err onAccepted() { assert.fail('snapshot failed before acceptance'); }, })); await waitFor(() => failure); + // Snapshot deadlines return their cause to the scheduler for its existing backoff. assert.deepEqual(failure, { error: message, recovering: false }); assert.equal(h.persisted.some(row => row.clientId === result.clientId), true); assert.equal(bridge.isPromptTracked('scheduled-task', result.clientId), false); + assert.equal(h.queue.projection('scheduled-task').autoResumePending, undefined); assert.equal(h.maker.getSession('scheduled-task').sent.length, 0); }); @@ -591,13 +729,53 @@ test('stopping a task cancels the real file-confirmation bridge before awaiting await h.queue.dispose(); }); -// Durable enqueue acknowledges acceptance, not vendor startup. Observe the -// actual send boundary before asserting agent side effects. +// Durable enqueue acknowledges acceptance, not vendor startup. Observe the actual send boundary before +// asserting agent side effects: this waits for the event that ends the send's start, not for a number of +// polls. A message reaches the engine only after the send's working-directory check, whose filesystem +// probes (workdir-probe-host, bounded by their own 5 s deadline) take as long as the machine needs, so a +// poll budget (waitFor) ran out under load while the send was still on its way. The events: +// - the fake engine received a message for the task (createFakeMaker onSent): resolves; +// - the queue settled the input without one (its projection carries an error, or a recovery point names +// the input): fails at once, with the projection; +// - neither within ENQUEUE_EVENT_LIMIT_MS (real time; past the probes' own deadline): fails, naming the +// event that did not come, with the projection. +const ENQUEUE_EVENT_LIMIT_MS = 30_000; +// The real timer, taken before any test mocks setTimeout: ticking a mocked clock must not fire this limit. +const setRealTimeout = globalThis.setTimeout; +const clearRealTimeout = globalThis.clearTimeout; async function enqueue(h, id, item) { - await h.queue.enqueue(id, item); - await waitFor(() => h.maker.getSession(id)?.sent.length > 0).catch(error => { - throw new Error(`${error.message}: ${JSON.stringify(h.queue.projection(id))}`); + return enqueueUntilSent(h, id, item, 1); +} +/** enqueue, then wait (as above) until the task's runtime has received `count` messages in all. */ +async function enqueueUntilSent(h, id, item, count) { + const reached = () => (h.maker.getSession(id)?.sent.length ?? 0) >= count; + const settledWithout = projection => Boolean(projection?.error) + || (projection?.recovery?.clientId ?? projection?.recovery?.item?.clientId) === item?.clientId; + let offSent = () => {}; + let offHub = () => {}; + let limit; + const started = new Promise((resolve, reject) => { + const fail = what => reject(new Error(`${what}: ${JSON.stringify(h.queue.projection(id))}`)); + offSent = h.maker.onSent(sessionId => { if (sessionId === id && reached()) resolve(); }); + offHub = h.onHubEvent(event => { + if (event.type === 'input_projection' && event.sessionId === id && !reached() && settledWithout(event.projection)) { + fail(`the input ${item?.clientId} settled without reaching the engine`); + } + }); + // real-wait: a guard against hanging, never the expected wait: it fires only when neither event comes (a failure); normally the send's event resolves first and the timer is cleared. A real timer because tests mock setTimeout and tick past 30 s. + limit = setRealTimeout(() => fail(`message ${count} did not reach the engine for ${id} and the input did not settle within ${ENQUEUE_EVENT_LIMIT_MS} ms`), ENQUEUE_EVENT_LIMIT_MS); }); + // Awaited only while the send is still on its way; a rejection before that is reported below instead. + started.catch(() => {}); + try { + await h.queue.enqueue(id, item); + if (!reached()) { + if (settledWithout(h.queue.projection(id))) throw new Error(`the input ${item?.clientId} settled without reaching the engine: ${JSON.stringify(h.queue.projection(id))}`); + await started; + } + } finally { + offSent(); offHub(); clearRealTimeout(limit); + } return h.queue.projection(id); } @@ -627,7 +805,7 @@ for (const cold of [false, true]) for (const queuedPlan of [false, true]) { await enqueue(h, 'settings', { clientId: 'first', text: 'one' }); const first = h.maker.getSession('settings'); await h.queue.enqueue('settings', { clientId: 'second', text: 'two', model: 'model-a', permissionMode: 'bypassPermissions' }); - // This represents the existing /sessions/update picker endpoint, not input metadata. + // This represents a picker change through its own entry, not input metadata. Object.assign(settings, { model: 'model-b', providerId: 'provider-b', permissionMode: 'ask', effort: 'high', fastMode: false, planModeEnabled: !queuedPlan }); await applyLiveSessionSettings(first, { planModeEnabled: settings.planModeEnabled }, settings); @@ -732,7 +910,8 @@ for (const writeFails of [false, true]) { test('production startup marker failure prevents dispatch and leaves input recoverable', async t => { t = lifoCleanup(t); const sqlite = new Database(':memory:'); - sqlite.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, active_turn_started_at INTEGER); + // The runtime start writes the task's provider (as the desktop's bootstrapSession): the column it writes. + sqlite.exec(`CREATE TABLE sessions(id TEXT PRIMARY KEY, active_turn_started_at INTEGER, provider_id TEXT); INSERT INTO sessions(id) VALUES ('marker-failure'); CREATE TRIGGER reject_start BEFORE UPDATE OF active_turn_started_at ON sessions BEGIN SELECT RAISE(ABORT, 'startup marker storage unavailable'); END;`); @@ -848,6 +1027,32 @@ test('persists thinking and tool work with the shared message identities', async await h.queue.dispose(); }); +// Release table section 6, Host history reader ③ and ④: the Host's history view was told a task is +// running only while it was a provisional (unsent) task, and had no in-flight rows, so the latest +// page of a running turn was projected as settled and showed nothing of the turn yet. The desktop +// binds isSessionTurnPendingCompletion and getSessionThinkingSnapshots; main.ts binds this queue's +// isTurnRunning (the executor's isRunning) and liveHistory. Minimal failing input: a running turn with +// one thinking block still streaming. Tier: unit, the real queue and executor, real owner database. +test('the history view of a running turn shows its in-flight rows as running', async () => { + const h = createHarness(); + // The task's row, as every Host task has one: the reader checks the clear line against it. + await unitDatabase.exec(`INSERT OR IGNORE INTO sessions(id,source,status,created_at,updated_at) + VALUES ('history-running','desktop','active',1,1)`); + const reader = createHostHistoryReader({ running: id => h.queue.isTurnRunning(id), live: id => h.queue.liveHistory(id) }); + await enqueue(h, 'history-running', { clientId: 'input', text: 'check a file' }); + const session = h.maker.getSession('history-running'); + session.emit({ type: 'thinking', data: { stage: 'delta', blockId: 'thought', text: 'inspecting' } }); + const running = await reader.page('history-running', undefined, true); + assert.deepEqual(running.items.map(item => item.type === 'work' && [item.summary.firstMessageId, item.summary.isStreaming]), + [['history-live:thought', true]]); + + session.emit({ type: 'thinking', data: { stage: 'final', blockId: 'thought', text: 'inspecting', durationMs: 5 } }); + session.emit({ type: 'done' }); + await waitFor(() => !h.queue.isTurnRunning('history-running')); + assert.deepEqual(h.queue.liveHistory('history-running'), []); + await h.queue.dispose(); +}); + // Host event exits: what the hub carries to the event stream (and its replay), /api/chat and the // device link is the desktop's renderer-boundary projection (rendererEventRedaction.ts), never the // raw agent event. Fixture credentials only; no network. @@ -1515,15 +1720,127 @@ test('failed abort retains the active turn and does not start a second message', assert.deepEqual(session.sent, ['long']); }); -// A provider may acknowledge abort before it is idle, without a later done. -// Reconciliation must release that boundary only after the partial reply saves. +// Checkpoint 4a. Rule: as on the desktop (sessionEventPreparation.ts), the input coordinator gets a turn's +// terminal when it arrives, and each terminal once; the Host only wakes it after the rows settle. A turn +// that ends with no terminal event (a stop that only goes idle) is handed once by finish; the done that +// follows a failed turn goes to the coordinator only (not published, no row). Tier: unit, Host queue +// with the shared coordinator. +test('each terminal reaches the coordinator once: a done, a stop that only goes idle, a failed turn and its done', async t => { + const handed = t.mock.method(AgentInputCoordinator.prototype, 'onTurnEvent'); + const kinds = id => handed.mock.calls.filter(call => call.arguments[0] === id).map(call => call.arguments[1]); + const h = createHarness(); + + await enqueue(h, 'once-done', { clientId: 'a', text: 'work' }); + h.maker.sessions.get('once-done').emit({ type: 'done' }); + await waitFor(() => !h.queue.projection('once-done').turnInProgress); + assert.deepEqual(kinds('once-done'), ['done']); + + await enqueue(h, 'once-stop', { clientId: 'a', text: 'work' }); + await h.queue.stop('once-stop'); + await waitFor(() => !h.queue.projection('once-stop').turnInProgress); + assert.deepEqual(kinds('once-stop'), ['done']); + + await enqueue(h, 'once-failed', { clientId: 'a', text: 'work' }); + const failed = h.maker.sessions.get('once-failed'); + failed.emit({ type: 'error', data: { message: 'upstream failed' } }); + await waitFor(() => !h.queue.projection('once-failed').turnInProgress); + const published = h.events.length; + const rows = h.persisted.length; + failed.emit({ type: 'done' }); + await waitFor(() => kinds('once-failed').length === 2); + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(kinds('once-failed'), ['error', 'done']); + assert.equal(h.events.slice(published).some(event => event.type === 'done'), false, 'the paired done is not published'); + assert.equal(h.persisted.length, rows, 'the paired done writes no row'); + await h.queue.dispose(); +}); + +// Checkpoint 4a. Rule: the coordinator now gets a terminal on arrival, while the Host still counts the +// turn as running until its rows settle and the Session is already idle; that pair must not read as a +// stale boundary. (1) The next input waits for the reply rows however long they take, past the +// coordinator's stale-boundary confirmation (250 ms). (2) Once the rows settle nothing keeps re-checking +// the boundary: the Host's live-turn probe answers "unavailable" while the rows settle, so no +// stale-boundary retry starts; before it, a failed stop left the queue retrying every 250 ms forever. +// Tier: unit, Host queue with the shared coordinator, mocked clock. +const settle = async (rounds = 50) => { for (let i = 0; i < rounds; i += 1) await new Promise(resolve => setImmediate(resolve)); }; +/** + * settle until check() holds, for tests whose setTimeout is mocked (waitFor polls with it). A fixed number + * of event-loop rounds is not enough for work outside the loop: a send's working-directory check stats the + * profile through the libuv thread pool (dialogueRecoveryWorkspace.ts), which a loaded machine finishes + * after any number of rounds. Returns as soon as check() holds; fails after 10 s of real time. + */ +const settleUntil = async (check, what) => { + const deadline = performance.now() + 10_000; + while (!check()) { + if (performance.now() > deadline) throw new Error(`condition not reached: ${what}`); + await new Promise(resolve => setImmediate(resolve)); + } +}; + +test('the next input is not dispatched before the reply rows settle, even past the stale-boundary confirmation', async t => { + let releaseWrite; + const write = new Promise(resolve => { releaseWrite = resolve; }); + const h = createHarness({ persistMessage: async (_id, row) => { if (row.role === 'assistant') await write; } }); + await enqueue(h, 'held-write', { clientId: 'a', text: 'first' }); + const session = h.maker.sessions.get('held-write'); + await h.queue.enqueue('held-write', { clientId: 'b', text: 'second' }); + t.mock.timers.enable({ apis: ['setTimeout'] }); + session.emit({ type: 'text', data: { text: 'the reply', isFinal: true } }); + session.emit({ type: 'done' }); + for (let i = 0; i < 8; i += 1) { await settle(); t.mock.timers.tick(250); } + await settle(); + assert.deepEqual(h.queue.projection('held-write').pendingQueue.map(item => item.clientId), ['b'], + 'the coordinator keeps the next input queued'); + assert.equal(h.queue.projection('held-write').turnInProgress, true); + assert.deepEqual(session.sent, ['first'], 'the next input waits for the reply row'); + assert.equal(h.maker.sessions.size, 1, 'no other runtime is started'); + releaseWrite(); + for (let i = 0; i < 20 && session.sent.length < 2; i += 1) { await settle(); t.mock.timers.tick(250); } + await settleUntil(() => session.sent.length >= 2, 'the next input reached the engine'); + assert.deepEqual(session.sent, ['first', 'second']); + t.mock.timers.reset(); + await h.queue.dispose(); +}); + +test('once the rows settle no stale-boundary retry is left running, even with input held by a failed stop', async t => { + const retries = t.mock.method(AgentInputCoordinator.prototype, 'scheduleSessionRunningRetry'); + const retriesFor = id => retries.mock.calls.filter(call => call.arguments[0] === id).length; + const h = createHarness(); + await enqueue(h, 'no-poll', { clientId: 'a', text: 'long' }); + const session = h.maker.sessions.get('no-poll'); + session.abort = async () => { throw new Error('abort failed'); }; + await h.queue.enqueue('no-poll', { clientId: 'b', text: 'later' }); + await assert.rejects(h.queue.stop('no-poll'), /abort failed/); + t.mock.timers.enable({ apis: ['setTimeout'] }); + session.emit({ type: 'text', data: { text: 'finished after failed abort', isFinal: true } }); + session.emit({ type: 'done' }); + await settleUntil(() => !h.queue.projection('no-poll').turnInProgress, 'the reply rows settled'); + assert.equal(h.queue.projection('no-poll').turnInProgress, false); + const settled = retriesFor('no-poll'); + for (let i = 0; i < 8; i += 1) { t.mock.timers.tick(250); await settle(); } + assert.equal(retriesFor('no-poll'), settled, 'nothing re-checks the boundary after the rows settle'); + assert.deepEqual(session.sent, ['long']); + t.mock.timers.reset(); + // No dispose: its stop would meet the same failing abort (as in the failed abort test above). +}); + +// Host stop/resume with the shared coordinator (unit): a provider can acknowledge abort +// before going idle, without a later done. Hold a partial reply write to verify the receipt +// and the queued send both wait for it. In CI the working-directory probe on the next send +// outlasted a fixed number of loop turns, even though that send eventually reached the engine. test('late provider idle after stop saves the partial reply before draining', async t => { + let writing = false; let releaseWrite; const write = new Promise(resolve => { releaseWrite = resolve; }); - const h = createHarness({ readSession: async id => ({ id, agentKind: 'codex', model: 'm', workingDir: '/tmp' }), + const h = createHarness({ + readSession: async id => ({ id, agentKind: 'codex', model: 'm', workingDir: '/tmp' }), persistMessage: async (_id, row) => { - if (row.role === 'assistant') await write; - } }); + if (row.role === 'assistant') { + writing = true; + await write; + } + }, + }); await enqueue(h, 'late-stop', { clientId: 'a', text: 'first' }); const session = h.maker.getSession('late-stop'); let running = true; @@ -1537,13 +1854,15 @@ test('late provider idle after stop saves the partial reply before draining', as assert.deepEqual(session.sent, ['first']); running = false; t.mock.timers.tick(250); - await new Promise(resolve => setImmediate(resolve)); - assert.deepEqual(session.sent, ['first']); - assert.equal(h.events.some(event => event.type === 'input_receipt'), false, 'do not settle before the reply write finishes'); - releaseWrite(); - await new Promise(resolve => setImmediate(resolve)); - t.mock.timers.tick(250); - await new Promise(resolve => setImmediate(resolve)); + try { + await settleUntil(() => writing, 'the partial reply reached persistence'); + await settle(); + assert.deepEqual(session.sent, ['first']); + assert.equal(h.events.some(event => event.type === 'input_receipt'), false, 'do not settle before the reply write finishes'); + } finally { + releaseWrite(); + } + await settleUntil(() => session.sent.length >= 2, 'the next input reached the engine'); assert.deepEqual(session.sent, ['first', 'second']); assert.deepEqual(h.events.filter(event => event.type === 'input_receipt'), [{ type: 'input_receipt', sessionId: 'late-stop', inputClientId: 'a', clientId: 'a', status: 'interrupted', @@ -1567,6 +1886,9 @@ test('failed reply persistence pauses the queue and resume saves without rerunni assert.equal(h.queue.projection('task-save').error, 'disk full'); assert.equal(h.queue.projection('task-save').queuePaused, true); assert.deepEqual(session.sent, ['first']); + // While reply writes are paused the next input is not dispatched, so its user row is never queued + // behind the paused writes (the send transaction writes it only after dispatch starts). + assert.equal(saved.some(row => row.role === 'user' && row.clientId === 'b'), false); failWrite = false; await h.queue.resume('task-save'); assert.equal(saved.filter(row => row.role === 'assistant').length, 1); @@ -1738,8 +2060,11 @@ test('concurrent enqueue reserves the turn before asynchronous preparation', asy test('an admission read failure rejects input before acknowledging acceptance', async () => { const maker = createFakeMaker(); let fail = true; + ensureUnitOwner(); const queue = createInputQueue({ getMaker: () => maker, hub: { publish() {} }, sent() {}, readSession: async () => { if (fail) throw new Error('storage unavailable'); return { agentKind: 'claude-code' }; }, + // Fixture does not test admission (夹具不测准入): the runtime start admission lets every start through. + admitLocalRoute: async () => {}, }); await assert.rejects(queue.enqueue('s', { clientId: 'a', text: 'A' }), /storage unavailable/); assert.equal(queue.projection('s').turnInProgress, false); @@ -1754,8 +2079,11 @@ test('stop during admission prevents a late model startup', async () => { const maker = createFakeMaker(); let release; const gate = new Promise(resolve => { release = resolve; }); + ensureUnitOwner(); const queue = createInputQueue({ getMaker: () => maker, hub: { publish() {} }, sent() {}, readSession: async () => { await gate; return { agentKind: 'cc', workingDir: '/tmp' }; }, + // Fixture does not test admission (夹具不测准入): the runtime start admission lets every start through. + admitLocalRoute: async () => {}, }); const enqueue = queue.enqueue('s', { clientId: 'a', text: 'first' }); const stopped = queue.stop('s'); @@ -1802,11 +2130,13 @@ test('restart restores a paused durable queue and deduplicates accepted input', let sqlite; const reopen = () => { sqlite = new Database(path.join(root, 'queue.sqlite')); + // The runtime start writes the task's provider (as the desktop's bootstrapSession): the column it writes. sqlite.exec(`CREATE TABLE IF NOT EXISTS messages(client_id TEXT, session_id TEXT, PRIMARY KEY(session_id, client_id)); CREATE TABLE IF NOT EXISTS agent_input_queue_snapshots(session_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER NOT NULL); - CREATE TABLE IF NOT EXISTS sessions(id TEXT PRIMARY KEY, active_turn_started_at INTEGER, last_turn_ended_at INTEGER); + CREATE TABLE IF NOT EXISTS sessions(id TEXT PRIMARY KEY, active_turn_started_at INTEGER, last_turn_ended_at INTEGER, + provider_id TEXT); INSERT OR IGNORE INTO sessions(id) VALUES ('durable')`); setCurrentDbClient({ drizzle: drizzle(sqlite) }, 'isolated-test'); }; @@ -2111,6 +2441,31 @@ test('a queued user turn opens its change record and Git baseline between the us await h.queue.dispose(); }); +/** + * 回合 diff 不发给客户端(甲 7 事件清点) + * - Bug:Host 把引擎的 `turn_diff`(本轮工作区的累计 unified diff,可达数 MB)原样发给每个客户端, + * 也交给历史记录;桌面只交给改动记录。Host 的客户端(web shim、/api/chat 的调用方、e2e)没有读它的。 + * - 规则依据:桌面 sessionEventPreparation.ts 在 broadcast 之前 `if (event.type === 'turn_diff') return;`。 + * - 最小失败输入:回合中一条 turn_diff。 + * - tier:unit(假引擎,真实的输入队列与回合执行,不调模型)。 + */ +test('a turn diff stays with the change record: it is not sent to clients or saved as history, as on the desktop', async t => { + t = lifoCleanup(t); + const h = createHarness(); + await enqueue(h, 'task-diff', { clientId: 'u-diff', text: 'edit' }); + const session = h.maker.getSession('task-diff'); + const rowsBefore = h.persisted.length; + session.emit({ type: 'turn_diff', source: 'codex', data: { diff: 'diff --git a/a.txt b/a.txt\n' } }); + session.emit({ type: 'text', data: { text: 'edited', isFinal: true } }); + session.emit({ type: 'done', data: {} }); + await waitFor(() => !h.queue.projection('task-diff').turnInProgress); + const published = h.events.filter(event => event.sessionId === 'task-diff').map(event => event.type); + assert.equal(published.includes('turn_diff'), false); + assert.ok(published.includes('text'), 'the events around it are still delivered'); + assert.deepEqual(h.persisted.slice(rowsBefore).map(row => row.role), ['assistant']); + await h.queue.dispose(); +}); + /** * Git 基线按回合结算(评审二,m1-rc4) * - Bug:已派发的回合以终止性 error 结束时不撤回基线;停止后 Host 先收尾、done 迟到时什么都不做。 @@ -2276,6 +2631,7 @@ test('a failed turn in one task leaves the next turn of another task in the same }); async function changeRecordFixture(t) { + ensureUnitOwner(); const { configureUserDataDir } = await import('../../../desktop/src/main/userDataPath.ts'); const store = await import('../../../desktop/src/main/turn-change-set/store.ts'); const { turnChangeSetSessionDirectory } = await import('../../../desktop/src/main/turn-change-set/storagePaths.ts'); @@ -2300,7 +2656,7 @@ async function changeRecordFixture(t) { const file = path.join(turnChangeSetSessionDirectory(profile, id), 'index.json'); return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')).entries : []; }; - return { calls, gitSnapshot, readSession, capture, entries, workDir, store }; + return { calls, gitSnapshot, readSession, capture, entries, workDir, store, profile }; } // The Host finalize is the desktop rule from sessionEventPreparation.ts, written in @@ -2309,7 +2665,7 @@ for (const [label, terminal, state] of [ ['a completed native turn', { type: 'done', data: { raw: { id: 'turn-1', status: 'completed' } } }, 'complete'], ['a native turn that did not complete', { type: 'done', data: { raw: { id: 'turn-2', status: 'interrupted' } } }, 'partial'], ['a terminal error', { type: 'error', data: { message: 'provider failed', isTerminal: true } }, 'partial'], - ['a silent-stop done', { type: 'done', data: { silentStop: true } }, 'complete'], + ['a silent-stop done that does not continue', { type: 'done', data: { silentStop: true } }, 'complete'], ]) { test(`the change record of ${label} is stored as ${state}`, async t => { t = lifoCleanup(t); @@ -2319,8 +2675,20 @@ for (const [label, terminal, state] of [ await enqueue(h, id, { clientId: `u-${label.length}`, text: 'edit a.txt' }); await f.capture(id); writeFileSync(path.join(f.workDir, 'a.txt'), 'two\n'); + // A silent stop is decided later; with the continuation switched off it settles as a done then. + const silentStop = terminal.data?.silentStop === true; + if (silentStop) { + writeFileSync(path.join(f.profile, SILENT_STOP_AUTO_RESUME_SETTINGS_FILE), JSON.stringify({ enabled: false })); + t.mock.timers.enable({ apis: ['setTimeout'] }); + } h.maker.getSession(id).emit(terminal); - await waitFor(() => !h.queue.projection(id).turnInProgress); + if (silentStop) { + t.mock.timers.tick(SILENT_STOP_DECISION_DELAY_MS); + await settleUntil(() => !h.queue.projection(id).turnInProgress, 'the silent stop settled'); + t.mock.timers.reset(); + } else { + await waitFor(() => !h.queue.projection(id).turnInProgress); + } assert.deepEqual((await f.entries(id)).map(entry => [entry.anchorClientId, entry.state]), [[`u-${label.length}`, state]]); // A done carrying native turn data also stores the Codex plan through the DB, // which this queue fixture does not open; that write is outside this check. @@ -2731,7 +3099,9 @@ async function recoveryDatabase(t) { const createTask = id => new OwnerSessionStorage({ db: () => database }).create({ id, title: 'Recovery fixture', agentKind: 'claude-code', model: 'stored-model', workDir: root }); const errorRows = id => opened.db.prepare("SELECT client_id FROM messages WHERE session_id = ? AND role = 'error'").all(id); - return { root, db: opened.db, createTask, errorRows, persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: () => {} }) }; + // As main.ts deleteSession removes the task row (OwnerSessionStorage.delete). + const deleteTask = id => new OwnerSessionStorage({ db: () => database }).delete(id); + return { root, db: opened.db, createTask, deleteTask, errorRows, persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: () => {} }) }; } test('context recovery: at the shutdown limit the Host writes the running recovery\'s error row once; after restart the task is an unhandled error and takes new input', { timeout: 30_000 }, async t => { @@ -2830,7 +3200,7 @@ test('context recovery: two tasks recovering at shutdown share one wait limit', const quiet = { info() {}, warn() {}, error() {} }; // One Host runtime over a profile database: the input queue, its recovery rollover and the Host's // pending handoff registry (handoff-pending.ts), as main.ts assembles them. -function assembledRuntime(t, db, overrides = {}) { +function assembledRuntime(t, db, overrides = {}, recoveryHost = {}) { const runtimes = []; let h; const handoffs = createHostAgentHandoffPending({ getOwner: getCurrentDbClientSnapshot, @@ -2846,7 +3216,8 @@ function assembledRuntime(t, db, overrides = {}) { return createHostContextRecoveryRollover({ getMaker: () => h.maker, persistMessage: db.persistMessage, publish: event => h.events.push(event), buildCreateOptsWithStderr: createSessionStderrOptions(quiet), readSessionExtraDirsFromDb: async () => [], readSessionWritableDirsFromDb: async () => [], - pendingHandoff: handoffs, log: quiet }, runtime); + codexHistory: { readCodexThreadStorageReadOnly: async () => undefined, classifyCodexHistoryOversized: async () => 'unknown' }, + pendingHandoff: handoffs, log: quiet, ...recoveryHost }, runtime); }, ...overrides, }); @@ -2870,6 +3241,1121 @@ async function assembledRecovery(t, overrides = {}) { return { db, h, handoffs, runtimes, overflow, rows, marker }; } +// Context usage write-back (checkpoint 3). Rule: as on the desktop (sessionEventSnapshots.ts → +// recordSessionContextSnapshot), a turn's end with its token count writes the task row's context +// tokens and window, so a task without a live runtime is judged on its real usage by the model-window +// gate (resolveModelSwitchContextTokens). Gap: the Host never wrote these columns; the row stayed at +// its default 0, and the gate took 0 as known usage. Tier: unit, real database, Host event path. +test('context usage: a turn\'s end writes the task\'s context tokens and window to its row', { timeout: 30_000 }, async t => { + const db = await recoveryDatabase(t); + const { h } = assembledRuntime(t, db); + await db.createTask('usage-write'); + await h.queue.enqueue('usage-write', { clientId: 'usage-input', text: 'work' }); + await waitFor(() => h.maker.sessions.get('usage-write')?.sent.length === 1); + const session = h.maker.sessions.get('usage-write'); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + session.emit({ type: 'status', data: { isRunning: false, status: 'Done', contextTokens: 95_000.7, contextWindow: 200_000 }, ...stamp }); + session.emit({ type: 'done', data: {}, ...stamp }); + const row = () => db.db.prepare('SELECT context_tokens, context_window, context_window_runtime FROM sessions WHERE id = ?').get('usage-write'); + await waitFor(() => row().context_tokens !== 0); + assert.deepEqual(row(), { context_tokens: 95_000, context_window: 200_000, context_window_runtime: 200_000 }); +}); + +// Rule: as on the desktop, a Done status that arrives after its turn has ended for the Host (the +// executor's terminal branch, where only the Git baseline still listens) still writes the usage it +// carries. Gap: that branch returned before any write. +test('context usage: a Done status arriving after the turn ended still writes the task\'s usage', { timeout: 30_000 }, async t => { + const db = await recoveryDatabase(t); + const { h } = assembledRuntime(t, db); + await db.createTask('usage-late'); + await h.queue.enqueue('usage-late', { clientId: 'usage-late-input', text: 'work' }); + await waitFor(() => h.maker.sessions.get('usage-late')?.sent.length === 1); + const session = h.maker.sessions.get('usage-late'); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + session.emit({ type: 'done', data: {}, ...stamp }); + await waitFor(() => h.events.some(event => event.type === 'done' && event.sessionId === 'usage-late')); + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + const row = () => db.db.prepare('SELECT context_tokens, context_window FROM sessions WHERE id = ?').get('usage-late'); + assert.deepEqual(row(), { context_tokens: 0, context_window: 0 }, 'nothing written before the late status'); + session.emit({ type: 'status', data: { isRunning: false, status: 'Done', contextTokens: 42_000, contextWindow: 128_000 }, ...stamp }); + await waitFor(() => row().context_tokens !== 0); + assert.deepEqual(row(), { context_tokens: 42_000, context_window: 128_000 }); +}); + +// A model picked in the client lands at the next send (checkpoint 3): runtime-selection.ts wired as +// main.ts wires it (the send transaction's applyPendingAgentSwitch, the owner runtime's rollover). +const SWITCH_WINDOWS = { big: 200_000, small: 100_000, 'big-alternate': 300_000, 'xai/big': 200_000 }; +const switchModel = id => ({ id, efforts: [], defaultEffort: null, supportsFastMode: false }); +const switchViews = agent => [{ id: 'prov-a', connected: true, agents: [agent], source: 'user', + routing: { [agent]: {} }, models: { [agent]: ['big', 'small'].map(switchModel) } }]; +async function modelChangeRuntime(t, { agent = 'claude-code', queue = {} } = {}) { + // The queue's owner is the account's database (as main.ts): close the queue before the database. + t = lifoCleanup(t); + const SWITCH_VIEWS = switchViews(agent); + const db = await recoveryDatabase(t); + const row = id => db.db.prepare('SELECT * FROM sessions WHERE id = ?').get(id); + let selection; + // Each send's landing hook call (the send transaction's applyPendingAgentSwitch), by task. + const landings = []; + const views = { current: SWITCH_VIEWS }; + // Each task's stored window budget, as the budget reconcile reads it. + const budgets = new Map(); + const queueHooks = hostRuntimeSelectionQueueHooks(() => selection, { isSessionRestarting: () => false }); + const { h, handoffs } = assembledRuntime(t, db, { + readSession: async id => { + const stored = row(id); + // As the Host reads a task for a run: its stored engine (main.ts readSessionForRun). + return { id, status: stored.status, agentKind: stored.agent_kind === 'cc' ? 'claude-code' : stored.agent_kind, model: stored.model, workingDir: db.root, + providerId: stored.provider_id, permissionMode: 'ask', planModeEnabled: false, sdkSessionId: stored.sdk_session_id, + source: stored.source, remoteHostId: stored.remote_host_id, agentDeviceId: stored.agent_device_id, orcaRole: stored.orca_role }; + }, + // The runtime selection's queue hooks, as main.ts passes them (runtime-selection.ts), each send's + // landing recorded by task. + ...queueHooks, + applyPendingAgentSwitch: (id, options) => { landings.push(id); return queueHooks.applyPendingAgentSwitch(id, options); }, + // As main.ts: the queue's owner is the current account's database. + getOwner: getCurrentDbClientSnapshot, + ...queue, + }, { + // As main.ts: the context rollover uses the runtime selection's cold Pi window check. + rehydrateColdPiRuntimeForWindowVerification: id => selection.rehydrateColdPiRuntimeForWindowVerification(id), + }); + // As Maker: a task's meta is its stored row (maker.ts getSessionMeta reads the session storage). + h.maker.getSessionMeta = id => new OwnerSessionStorage({ db: () => getCurrentDbClientSnapshot().client }).get(id); + selection = createHostRuntimeSelection({ + getMaker: () => h.maker, + getMakerIfReady: () => h.maker, + publish: event => h.events.push(event), + createDbMessage: db.persistMessage, + pendingHandoff: handoffs, + listProviderViews: async () => { await views.beforeList?.(); return views.current; }, + resolveConfiguredContextWindow: (_catalog, _agentKind, _providerId, modelId) => SWITCH_WINDOWS[modelId] ?? null, + readStoredSessionContextWindowBudget: async id => budgets.has(id) ? budgets.get(id) : readSessionContextWindowBudget(id), + contextWindowBudgetChangesEffectiveWindow: ({ previous, next }) => previous !== next, + codexProxyAuthInjectionState: () => null, + inputQueue: h.queue, + log: { debug() {}, info() {}, warn() {}, error() {} }, + }); + const createTask = id => new OwnerSessionStorage({ db: () => getCurrentDbClientSnapshot().client }).create({ + id, title: 'Model change fixture', agentKind: agent, model: 'big', providerId: 'prov-a', workDir: db.root }); + // One turn on the task's runtime that ends with this usage, then the runtime is released. + const runTurn = async (id, clientId, usage) => { + await h.queue.enqueue(id, { clientId, text: `work ${clientId}` }); + await waitFor(() => h.maker.sessions.get(id)?.sent.length >= 1); + const session = h.maker.sessions.get(id); + // Maker writes the runtime's native session id to the task row when it creates the runtime + // (maker.ts, createSession's metadata write); this fake Maker does not, so the fixture does. + db.db.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run(`native-${clientId}`, id); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + if (usage) session.emit({ type: 'status', data: { isRunning: false, status: 'Done', ...usage }, ...stamp }); + session.emit({ type: 'done', data: {}, ...stamp }); + await waitFor(() => h.queue.projection(id).active === null || h.queue.projection(id).active === undefined); + return session; + }; + const rebuilds = id => db.db.prepare("SELECT content FROM messages WHERE session_id = ? AND role = 'context_rebuild'").all(id) + .map(entry => JSON.parse(entry.content)); + const userRows = id => db.db.prepare("SELECT content FROM messages WHERE session_id = ? AND role = 'user'").all(id); + // The provider stops offering a model (it is no longer in its list); restore puts the list back. + const withdraw = modelId => { views.current = SWITCH_VIEWS.map(view => ({ ...view, + models: { [agent]: view.models[agent].filter(entry => entry.id !== modelId) } })); }; + const restoreModels = () => { views.current = SWITCH_VIEWS; }; + // The provider lists a model under a new id whose unified key is the saved one (uniqueRenamedSessionModelId). + const rename = (from, to) => { views.current = SWITCH_VIEWS.map(view => ({ ...view, + models: { [agent]: view.models[agent].map(entry => (entry.id === from ? switchModel(to) : entry)) } })); }; + const invoke = createHostService({ setSessionModel: (...args) => selection.setModel(...args) }); + const selectFromPhone = (id, model, providerId) => runDeviceLinkInvokeContext({ + controllerDeviceId: 'owner-phone', controllerPlatform: 'ios', channel: 'maker:set-model', + }, () => invoke('/api/sessions/set-model', { sessionId: id, model, providerId })); + return { db, h, handoffs, selection, row, createTask, runTurn, rebuilds, userRows, withdraw, restoreModels, rename, landings, views, budgets, selectFromPhone }; +} + +// #11352, DB tier. The phone's trusted selection origin must survive until the next +// send or Pi prewarm. An unverified window may neither move the row nor dispatch. +test('owner dispatch rebuilds Claude and hot Pi on the host-verified window and keeps an unverifiable Pi route', async t => { + for (const [agent, target, finalWindow, rebuild] of [ + ['claude-code', 'small', undefined, true], + ['pi', 'big-alternate', 100_000, true], + ['pi', 'small', 0, false], + ['claude-code', 'display-only', undefined, false], + ]) { + await t.test(`${agent} to ${target} (native window ${finalWindow})`, async t => { + const r = await modelChangeRuntime(t, { agent }); + const id = 'owner-window'; + const handoffs = []; + const setHandoff = r.handoffs.set; + r.handoffs.set = (sessionId, handoff, generation) => { + handoffs.push(handoff); + setHandoff(sessionId, handoff, generation); + }; + if (!r.views.current[0].models[agent].some(model => model.id === target)) r.views.current[0].models[agent].push(switchModel(target)); + await r.createTask(id); + const initial = await r.runTurn(id, 'owner-initial', { contextTokens: 95_000, contextWindow: 200_000 }); + let liveWindow = 200_000; + initial.getUsageSnapshot = () => ({ contextTokens: 95_000, contextWindow: liveWindow }); + if (agent === 'pi') { + initial.previewModelSwitch = async () => ({ action: 'hot', windowVerified: false }); + const setModel = initial.setModel.bind(initial); + initial.setModel = async (...args) => { await setModel(...args); liveWindow = finalWindow; }; + } + await r.db.persistMessage(id, { role: 'assistant', clientId: 'window-history', + content: 'Prior output '.repeat(9_000) }); + assert.equal((await r.selectFromPhone(id, target)).body.pendingUntilSend, true); + const intent = r.selection.pendingSwitches.get(id); + assert.equal(intent.deviceLinkModelSelectionOrigin, 'owner'); + const next = 'next '.repeat(9_000); + await r.h.queue.enqueue(id, { clientId: 'owner-next', text: next }); + await waitFor(() => r.h.queue.projection(id).error + || r.h.maker.getSession(id)?.sent.some(text => typeof text === 'string' && text.endsWith(next))); + const saved = r.row(id); + if (rebuild) { + assert.equal(saved.model, target); + assert.equal(saved.sdk_session_id, null); + assert.equal(saved.context_tokens, 0); + assert.deepEqual(r.rebuilds(id).map(marker => marker.handoffCoverage), ['condensed']); + assert.notEqual(r.h.maker.getSession(id), initial); + assert.equal(handoffs.length, 1); + const [handoff] = handoffs; + assert.match(handoff, /owner-initial/); + assert.ok(r.h.maker.getSession(id).sent[0].includes(handoff)); + assert.ok(handoff.length > 16_000, 'use the verified window instead of the unknown-window text limit'); + assert.ok(estimateHandoffTokens(handoff) <= 20_000, 'leave room for the next input'); + } else { + assert.equal(saved.model, 'big'); + assert.equal(saved.sdk_session_id, 'native-owner-initial'); + assert.equal(saved.context_tokens, 95_000); + assert.deepEqual(r.rebuilds(id), []); + assert.deepEqual(handoffs, []); + assert.match(JSON.stringify(r.h.queue.projection(id).error), /window/i); + assert.equal(initial.sent.length, 1); + } + }); + } +}); + +test('remote Pi skill preparation refuses an owner route with an unverified window', async t => { + const r = await modelChangeRuntime(t, { agent: 'pi' }); + const id = 'owner-prewarm-window'; + await r.createTask(id); + const runtime = await r.runTurn(id, 'pi-prewarm-native', { contextTokens: 95_000, contextWindow: 200_000 }); + runtime.getUsageSnapshot = () => ({ contextTokens: 95_000, contextWindow: 200_000 }); + runtime.previewModelSwitch = async () => ({ action: 'hot', windowVerified: false }); + r.views.current[0].models.pi.push(switchModel('display-only')); + assert.equal((await r.selectFromPhone(id, 'display-only')).body.pendingUntilSend, true); + await assert.rejects(r.h.queue.preparePiSkillRuntime(id, r.db.root, { + applyPendingOwnerSelection: true, expectedPiModel: 'display-only', + }), { code: 'PRECONDITION_FAILED' }); + assert.equal(r.row(id).model, 'big'); + assert.equal(r.row(id).sdk_session_id, 'native-pi-prewarm-native'); + assert.equal(runtime.model, 'big'); + assert.equal(runtime.sent.length, 1); + assert.deepEqual(r.rebuilds(id), []); +}); + +// #11352, DB tier. With a pending Pi pick, reject before applying the intent +// even when the stored task or the live runtime cannot be used for the prewarm. +test('remote Pi skill preparation refuses ineligible tasks before applying the pick', async t => { + for (const condition of ['review', 'workdir', 'remote host', 'agent device', 'Orca', 'busy', 'wrong model', 'wrong harness']) { + await t.test(condition, async t => { + const r = await modelChangeRuntime(t, { agent: 'pi' }); + const id = 'prewarm-admission'; + await r.createTask(id); + await r.selectFromPhone(id, 'small'); + const assignments = { + review: ["source = ?", 'review'], + 'remote host': ["remote_host_id = ?", 'remote'], + 'agent device': ["agent_device_id = ?", 'device'], + Orca: ["orca_role = ?", 'lead'], + }; + if (assignments[condition]) { + const [assignment, value] = assignments[condition]; + r.db.db.prepare(`UPDATE sessions SET ${assignment} WHERE id = ?`).run(value, id); + } + if (condition === 'wrong harness') r.selection.pendingSwitches.set(id, { targetAgentKind: 'claude-code', model: 'small' }); + if (condition === 'busy') { + const live = await r.h.maker.createSession({ id, agentKind: 'pi', model: 'big', workingDir: r.db.root }); + live.running = true; + } + const snapshot = r.row(id); + await assert.rejects(r.h.queue.preparePiSkillRuntime(id, condition === 'workdir' ? '/different/project' : r.db.root, { + applyPendingOwnerSelection: true, expectedPiModel: condition === 'wrong model' ? 'big' : 'small', + }), { code: 'PRECONDITION_FAILED' }); + assert.equal(r.row(id).model, snapshot.model); + assert.equal(r.row(id).provider_id, snapshot.provider_id); + assert.equal(r.row(id).sdk_session_id, snapshot.sdk_session_id); + assert.equal(r.selection.projectIntent(id)?.model, 'small'); + }); + } +}); + +// #11352, DB tier. A locally staged Harness choice remains valid when the owner +// subsequently requests Pi preparation from another device. +test('remote Pi skill preparation lands a locally staged Pi switch and retires the old engine', async t => { + const r = await modelChangeRuntime(t); + const id = 'local-pi-switch'; + r.views.current = [{ ...switchViews('claude-code')[0], agents: ['claude-code', 'pi'], + routing: { 'claude-code': {}, pi: {} }, models: { 'claude-code': [switchModel('big')], pi: [switchModel('small')] } }]; + await r.createTask(id); + const original = await r.runTurn(id, 'legacy-prewarm-native'); + const switchResult = await r.selection.switchAgent({ sessionId: id, targetAgentKind: 'pi', model: 'small', providerId: 'prov-a' }); + assert.equal(switchResult.deferred, true); + assert.equal(r.selection.pendingSwitches.get(id).deviceLinkModelSelectionOrigin, undefined); + await r.h.queue.preparePiSkillRuntime(id, r.db.root, { + applyPendingOwnerSelection: true, expectedPiModel: 'small', + }); + assert.equal(r.row(id).model, 'small'); + assert.equal(r.row(id).agent_kind, 'pi'); + assert.equal(r.row(id).sdk_session_id, null); + assert.notEqual(r.h.maker.getSession(id), original); + assert.equal(r.h.maker.getSession(id).agentKind, 'pi'); + assert.deepEqual(r.h.maker.getSession(id).sent, []); + assert.equal(r.selection.projectIntent(id), null); +}); + +// #11352, DB tier. A regular send can be waiting for a cold Pi runtime when +// desktop occupation is detected. SQLite triggers catch writes of unchanged values too. +test('a desktop hold during cold Pi window verification refuses the send before route or history writes', async t => { + const r = await modelChangeRuntime(t, { agent: 'pi' }); + const id = 'cold-pi-hold'; + await r.createTask(id); + r.views.current.push({ ...switchViews('pi')[0], id: 'prov-b' }); + await r.runTurn(id, 'before-hold', { contextTokens: 95_000, contextWindow: 200_000 }); + await r.h.maker.closeSession(id); + await r.selectFromPhone(id, 'small', 'prov-b'); + const before = r.row(id); + r.db.db.exec(`CREATE TABLE route_writes(fields TEXT); + CREATE TRIGGER record_route_update AFTER UPDATE OF model, provider_id, sdk_session_id ON sessions + WHEN NEW.id = 'cold-pi-hold' BEGIN INSERT INTO route_writes VALUES ('update'); END;`); + let started, release; + const entered = new Promise(resolve => { started = resolve; }); + const paused = new Promise(resolve => { release = resolve; }); + const create = r.h.maker.createSession.bind(r.h.maker); + r.h.maker.createSession = async (opts, signal) => { + started(); + await paused; + // Match Maker's storage fence after the adapter returns a changed native id. + signal?.throwIfAborted(); + r.db.db.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run('late-native-id', id); + const live = await create(opts); + live.getUsageSnapshot = () => ({ contextTokens: 95_000, contextWindow: 200_000 }); + live.previewModelSwitch = async () => ({ action: 'hot', windowVerified: true }); + return live; + }; + await r.h.queue.enqueue(id, { clientId: 'during-hold', text: 'next' }); + await entered; + r.h.queue.holdForDesktop('fixture desktop holds the profile'); + release(); + await waitFor(() => r.h.queue.projection(id).error || r.h.maker.getSession(id)?.sent.length); + assert.deepEqual(r.db.db.prepare('SELECT * FROM route_writes').all(), []); + const after = r.row(id); + assert.deepEqual([after.model, after.provider_id, after.sdk_session_id], [before.model, before.provider_id, before.sdk_session_id]); + assert.deepEqual(r.rebuilds(id), []); + assert.equal(r.selection.projectIntent(id)?.model, 'small'); + assert.match(JSON.stringify(r.h.queue.projection(id).error), /fixture desktop holds the profile/); + assert.equal(r.h.maker.getSession(id), null); +}); + +// Rule (the desktop's send-time landing, sessionRuntimeSelectionApply.ts: a user's pick applied on send +// has confirmedTargetPressure, so prepareModelWindowSwitch rebuilds without asking): a task with real +// usage at danger for the picked smaller window rebuilds its context when the pick lands, even after +// its runtime was released. Gap: the Host never wrote the usage, so a released task was judged on its +// default 0 and the smaller window landed with no rebuild. +test('model change at send: a released task with usage at danger rebuilds before the smaller window lands', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('danger'); + const first = await r.runTurn('danger', 'danger-1', { contextTokens: 95_000, contextWindow: 200_000 }); + // The turn's end writes its usage without anyone waiting on it (as on the desktop); let that work + // run, without waiting on the row itself, so that a missing write fails at the landing below. + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + await r.h.maker.closeSession('danger'); // idle release + const picked = await r.selection.setModel('danger', 'small', undefined, undefined, undefined); + assert.equal(picked.pendingUntilSend, true); + assert.equal(r.row('danger').model, 'big', 'the pick waits for the send'); + await r.h.queue.enqueue('danger', { clientId: 'danger-2', text: 'next' }); + await waitFor(() => { const next = r.h.maker.sessions.get('danger'); return next && next !== first && next.sent.length === 1; }); + assert.equal(r.row('danger').model, 'small'); + const rebuilt = r.rebuilds('danger'); + assert.equal(rebuilt.length, 1, 'the context was rebuilt for the smaller window'); + assert.equal(rebuilt[0].reason, 'model-window-switch'); + const next = r.h.maker.sessions.get('danger'); + assert.equal(next.options.model, 'small'); + assert.equal(next.options.resumeSessionId, undefined, 'the new runtime does not resume the rebuilt context'); +}); + +// Control: the same pick on a task whose usage is truly 0 lands with no rebuild. +test('model change at send: a task with no usage takes the smaller window with no rebuild', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('empty'); + await r.selection.setModel('empty', 'small', undefined, undefined, undefined); + await r.h.queue.enqueue('empty', { clientId: 'empty-1', text: 'first' }); + await waitFor(() => r.h.maker.sessions.get('empty')?.sent.length === 1); + assert.equal(r.row('empty').model, 'small'); + assert.equal(r.rebuilds('empty').length, 0); + assert.equal(r.h.maker.sessions.get('empty').options.model, 'small'); +}); + +// Rule (the desktop's send-time landing, makerSendTransaction.ts applyPendingAgentSwitch before the user +// row; sessionAgentSwitchHandler.ts applyPendingAgentSwitchIfIdle: a same-engine failure throws and keeps +// the intent): the send fails before it is accepted. No user row is written, the queue keeps the input as +// its head with the typed error (recovery 'queue-head'), its receipt reads 'interrupted', and the pick +// stays pending. Gap: the Host applied a pick at once and had no landing to fail. +const sameEngineLandingFailure = async (r, id) => { + await r.createTask(id); + await r.selection.setModel(id, 'small', undefined, undefined, undefined); + r.withdraw('small'); // the picked model is no longer offered when the send lands it + await r.h.queue.enqueue(id, { clientId: `${id}-1`, text: 'first' }); + await waitFor(() => r.h.queue.projection(id).error); + const projection = r.h.queue.projection(id); + assert.match(projection.error, /^\[[A-Z_]+\] /, 'the typed error, as the desktop shows it'); + assert.deepEqual(projection.recovery, { kind: 'queue-head', clientId: `${id}-1` }); + assert.deepEqual(projection.pendingQueue.map(item => item.clientId), [`${id}-1`], 'the input stays at the head'); + assert.equal(await r.h.queue.inputStatus(id, `${id}-1`), 'interrupted'); + assert.equal(r.userRows(id).length, 0, 'no user row before the pick lands'); + assert.equal(r.row(id).model, 'big'); + assert.equal(r.selection.projectIntent(id)?.model, 'small', 'the pick stays pending'); + assert.equal(r.h.maker.sessions.get(id)?.sent.length ?? 0, 0, 'nothing reached a runtime'); + return projection; +}; + +test('model change at send: a same-engine landing failure keeps the input at the queue head and the pick pending; switching back and retrying sends it', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await sameEngineLandingFailure(r, 'land-back'); + // Exit: pick the task's current model again (an intent for the current route), then retry. + await r.selection.setModel('land-back', 'big', undefined, undefined, undefined); + await r.h.queue.retryLastError('land-back'); + await waitFor(() => r.h.maker.sessions.get('land-back')?.sent.length === 1); + assert.equal(r.row('land-back').model, 'big'); + assert.equal(r.h.maker.sessions.get('land-back').options.model, 'big'); + assert.equal(r.userRows('land-back').length, 1, 'the input is written once, when it is sent'); + assert.equal(r.h.queue.projection('land-back').error ?? null, null); + assert.equal(r.selection.projectIntent('land-back') ?? null, null, 'the landed intent is spent'); +}); + +test('model change at send: a same-engine landing failure is left by discarding the input; the pick stays for the next send', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await sameEngineLandingFailure(r, 'land-drop'); + // Exit: discard the input that was never accepted. + await r.h.queue.remove('land-drop', 'land-drop-1'); + const projection = r.h.queue.projection('land-drop'); + assert.deepEqual(projection.pendingQueue, []); + assert.equal(projection.error ?? null, null); + assert.equal(projection.recovery ?? null, null); + assert.equal(r.userRows('land-drop').length, 0); + assert.equal(r.selection.projectIntent('land-drop')?.model, 'small', 'discarding the input does not cancel the pick'); + // The next send lands the pick once the model is offered again. + r.restoreModels(); + await r.h.queue.enqueue('land-drop', { clientId: 'land-drop-2', text: 'second' }); + await waitFor(() => r.h.maker.sessions.get('land-drop')?.sent.length === 1); + assert.equal(r.row('land-drop').model, 'small'); + assert.equal(r.userRows('land-drop').length, 1); +}); + +// Rule (the desktop's recovery replay goes through the same send transaction, makerSendTransaction.ts +// applyPendingAgentSwitch; contextOverflowRollover.ts keeps the task in flight for the whole recovery, +// so a landing that had to prepare the window would get 'in-flight'): a pick made during a turn that +// overflows lands at the recovery's replay. The overflow rebuild has already reset the task (no native +// session, no context used), so the landing needs no window preparation and the pick lands on the +// replay with no second rebuild and no error. The hook runs once per send (the first send, then the +// replay); the pick lands once. Gap: the Host landed a pick only on enqueue, so a replay kept the old +// model. +test('model change at send: a pick made during a turn that overflows lands on the recovery replay, with one rebuild', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('combo'); + await r.h.queue.enqueue('combo', { clientId: 'combo-1', text: 'long task' }); + await waitFor(() => r.h.maker.sessions.get('combo')?.sent.length === 1); + const first = r.h.maker.sessions.get('combo'); + // As Maker writes it for the runtime, and the usage at danger for the smaller window. + r.db.db.prepare('UPDATE sessions SET sdk_session_id = ?, context_tokens = ? WHERE id = ?').run('native-combo', 95_000, 'combo'); + const stamp = { sessionTurnGeneration: first.generation, sessionInstanceId: first.instanceId }; + first.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + const picked = await r.selection.setModel('combo', 'small', undefined, undefined, undefined); + assert.equal(picked.pendingUntilSend, true, 'a pick during a turn waits for the next send'); + first.emit({ type: 'error', data: OVERFLOW, ...stamp }); + await waitFor(() => { const next = r.h.maker.sessions.get('combo'); return next && next !== first && next.sent.length === 1; }); + const replayed = r.h.maker.sessions.get('combo'); + assert.equal(replayed.options.model, 'small', 'the replay runs on the picked model'); + assert.match(replayed.sent[0], /long task$/, 'the user\'s message is replayed once, after the rebuild summary'); + assert.equal(r.row('combo').model, 'small'); + assert.equal(r.row('combo').context_tokens, 0, 'the overflow rebuild reset the usage before the landing'); + assert.deepEqual(r.rebuilds('combo').map(marker => marker.reason), ['context-overflow'], 'one rebuild, no second one for the window'); + assert.equal(r.selection.projectIntent('combo') ?? null, null, 'the pick is spent'); + assert.deepEqual(r.landings.filter(id => id === 'combo'), ['combo', 'combo'], 'the hook runs for the first send and the replay'); + const projection = r.h.queue.projection('combo'); + assert.equal(projection.error ?? null, null); + assert.equal(projection.recovery ?? null, null); + assert.equal(await r.h.queue.inputStatus('combo', 'combo-1'), 'running', 'a reconnecting client sees the input running'); + assert.equal(r.userRows('combo').length, 1, 'the replay writes no second user row'); + assert.equal(r.db.db.prepare("SELECT COUNT(*) AS n FROM messages WHERE session_id = 'combo' AND role = 'error'").get().n, 0); +}); + +// Rule (the desktop's send transaction binding, register.ts: after the landing, a send that is not +// scheduled recovers a renamed model, recoverRenamedSessionModelOnSend): when the provider now lists the +// task's model under a new id with the same unified key, the send moves the task to that id before the +// runtime starts. A pick waiting for this send lands first, and then there is nothing to rename. Gap: +// the Host sent the saved id, which the provider no longer lists. +test('model change at send: a model the provider renamed moves to its new id before the runtime starts', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('renamed'); + r.rename('big', 'xai/big'); + await r.h.queue.enqueue('renamed', { clientId: 'renamed-1', text: 'first' }); + await waitFor(() => r.h.maker.sessions.get('renamed')?.sent.length === 1); + assert.equal(r.row('renamed').model, 'xai/big', 'the task row takes the new id'); + assert.equal(r.h.maker.sessions.get('renamed').options.model, 'xai/big', 'the runtime starts on the new id'); + assert.equal(r.userRows('renamed').length, 1); + assert.equal(r.h.queue.projection('renamed').error ?? null, null); +}); + +test('model change at send: a pick waiting for the send lands before the rename, which then has nothing to do', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('renamed-pick'); + await r.selection.setModel('renamed-pick', 'small', undefined, undefined, undefined); + r.rename('big', 'xai/big'); + await r.h.queue.enqueue('renamed-pick', { clientId: 'renamed-pick-1', text: 'first' }); + await waitFor(() => r.h.maker.sessions.get('renamed-pick')?.sent.length === 1); + assert.equal(r.row('renamed-pick').model, 'small', 'the pick landed; the saved model was not renamed'); + assert.equal(r.h.maker.sessions.get('renamed-pick').options.model, 'small'); + assert.equal(r.selection.projectIntent('renamed-pick') ?? null, null); +}); + +// Rule (the desktop's cold Pi window check, register.ts createColdPiRehydrationForWindowVerification +// bound into handleSetModel): a Pi task whose runtime was released has no live window to check a +// smaller pick against, so the landing resumes its native session first, reads the live window and +// usage, and then decides; at danger it rebuilds before the smaller window lands. Gap: the Host threw +// a plain error there ("not wired on the Host yet"), which the shared code takes as a failed resume and +// lets through (classifyColdPiRehydrationOutcome 'degraded'): the smaller model resumed the old native +// session at 95k of a 100k window, with no rebuild and no error. +test('model change at send: a released Pi task resumes to check its window, then rebuilds for the smaller one', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t, { agent: 'pi' }); + await r.createTask('cold-pi'); + const started = []; + const create = r.h.maker.createSession.bind(r.h.maker); + r.h.maker.createSession = async opts => { + started.push({ model: opts.model, resumeSessionId: opts.resumeSessionId }); + const session = await create(opts); + // A Pi runtime reports its usage and previews a switch (session.ts getUsageSnapshot, + // previewModelSwitch); this one has used 95k of its 200k window. + session.getUsageSnapshot = () => ({ tokenUsage: 0, contextTokens: 95_000, contextWindow: 200_000, costUsd: 0 }); + session.previewModelSwitch = async model => ({ action: 'hot', targetContextWindow: SWITCH_WINDOWS[model] ?? null, windowVerified: true }); + return session; + }; + await r.runTurn('cold-pi', 'cold-pi-1', { contextTokens: 95_000, contextWindow: 200_000 }); + await r.h.maker.closeSession('cold-pi'); // idle release + await r.selection.setModel('cold-pi', 'small', undefined, undefined, undefined); + await r.h.queue.enqueue('cold-pi', { clientId: 'cold-pi-2', text: 'next' }); + await waitFor(() => r.h.maker.sessions.get('cold-pi')?.sent.length === 1 || r.h.queue.projection('cold-pi').error); + assert.equal(r.h.queue.projection('cold-pi').error ?? null, null); + assert.deepEqual(started, [ + { model: 'big', resumeSessionId: undefined }, + { model: 'big', resumeSessionId: 'native-cold-pi-1' }, // the window check resumes the released runtime + { model: 'small', resumeSessionId: undefined }, // the rebuilt context starts fresh + ]); + assert.deepEqual(r.rebuilds('cold-pi').map(marker => marker.reason), ['model-window-switch']); + assert.equal(r.row('cold-pi').model, 'small'); + assert.equal(r.h.maker.sessions.get('cold-pi').options.model, 'small'); + assert.equal(r.selection.projectIntent('cold-pi') ?? null, null); +}); + +// Rule (register.ts binds the same cold Pi window check into the context rollover and the model +// change): when the rollover is asked about a smaller window for a Pi task whose runtime is released +// (the model change's own resume failed, or idle release came in between), it resumes the runtime to +// read its window and usage instead of answering 'unknown-context'. Gap: the Host left the rollover's +// port unbound (explicit ports pass, 2026-11-17). +test('model change at send: the context rollover resumes a released Pi task to read its window', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t, { agent: 'pi' }); + await r.createTask('cold-pi-rollover'); + const started = []; + const create = r.h.maker.createSession.bind(r.h.maker); + r.h.maker.createSession = async opts => { + started.push({ model: opts.model, resumeSessionId: opts.resumeSessionId }); + const session = await create(opts); + session.getUsageSnapshot = () => ({ tokenUsage: 0, contextTokens: 10_000, contextWindow: 200_000, costUsd: 0 }); + return session; + }; + await r.runTurn('cold-pi-rollover', 'cold-pi-rollover-1', { contextTokens: 10_000, contextWindow: 200_000 }); + await r.h.maker.closeSession('cold-pi-rollover'); // idle release + const answer = await r.h.queue.contextRecoveryRollover().prepareModelWindowSwitch('cold-pi-rollover', { + contextWindow: SWITCH_WINDOWS.small, recheckTargetPressure: true }); + assert.notEqual(answer, 'unknown-context'); + assert.deepEqual(started.at(-1), { model: 'big', resumeSessionId: 'native-cold-pi-rollover-1' }, + 'the released runtime is resumed to read its window'); +}); + +// Rule (sessionAgentSwitchHandler.ts applyPendingAgentSwitchIfIdle: a user's engine pick that fails +// to land does not stop the send; only a same-engine pick, an Agent's pick or a change of computer +// throws): the send goes on with the task's current engine, and the pick stays for the next send, +// which lands it once its route is usable. Gap: the Host landed an engine pick on enqueue, outside +// the send, and had no landing at the send to fail. +test('model change at send: an engine pick that cannot land lets the send go on, and lands on a later send', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('cross'); + const picked = await r.selection.switchAgent({ sessionId: 'cross', targetAgentKind: 'codex', model: 'gpt-x', providerId: 'prov-a' }); + assert.equal(picked.deferred, true, 'an engine pick waits for the send'); + const views = r.views.current; + // The picked route is unusable when the send lands the pick: its copy is disabled. The task's current + // route stays usable, so the runtime start's admission (register.ts admitLocalRoute) lets the send go on. + r.views.current = views.map(view => ({ ...view, agents: [...view.agents, 'codex'], + models: { ...view.models, codex: [{ ...switchModel('gpt-x'), disabled: true }] } })); + await r.h.queue.enqueue('cross', { clientId: 'cross-1', text: 'first' }); + await waitFor(() => r.h.maker.sessions.get('cross')?.sent.length === 1); + const first = r.h.maker.sessions.get('cross'); + assert.equal(first.agentKind, 'claude-code', 'the send goes on with the current engine'); + assert.equal(first.options.model, 'big'); + assert.equal(r.row('cross').agent_kind, 'cc'); + assert.equal(r.h.queue.projection('cross').error ?? null, null, 'no error for the send'); + assert.equal(r.selection.projectIntent('cross')?.targetAgentKind, 'codex', 'the pick stays for the next send'); + first.emit({ type: 'done', data: {}, sessionTurnGeneration: first.generation, sessionInstanceId: first.instanceId }); + await waitFor(() => !r.h.queue.projection('cross').active); + r.views.current = views; + await r.h.queue.enqueue('cross', { clientId: 'cross-2', text: 'second' }); + await waitFor(() => { const next = r.h.maker.sessions.get('cross'); return next && next !== first && next.sent.length === 1; }); + const next = r.h.maker.sessions.get('cross'); + assert.equal(next.agentKind, 'codex', 'the next send lands the engine pick'); + assert.equal(next.options.model, 'gpt-x'); + assert.equal(r.row('cross').agent_kind, 'codex'); + assert.equal(r.selection.projectIntent('cross') ?? null, null); + assert.equal(r.userRows('cross').length, 2); +}); + +// The runtime start admission (register.ts bootstrapSession's admitLocalRoute, shared as +// localRouteAdmission.ts). Gap: the Host started a task's runtime with no admission, so a task could run +// on a model or source the user disabled. Provider lists: a copy of a model disabled on a source, and the +// native default (xd) disabled with an enabled copy on another source. +const withDisabledCopy = (views, agent, providerId, modelId) => views.map(view => (view.id !== providerId ? view : { + ...view, models: { ...view.models, [agent]: view.models[agent].map(entry => (entry.id === modelId ? { ...entry, disabled: true } : entry)) }, +})); +const nativeDefaultDisabledViews = agent => [ + ...withDisabledCopy(switchViews(agent).map(view => ({ ...view, id: 'xd' })), agent, 'xd', 'big'), + ...switchViews(agent), +]; +const createTaskOn = (id, providerId) => new OwnerSessionStorage({ db: () => getCurrentDbClientSnapshot().client }).create({ + id, title: 'Route admission fixture', agentKind: 'claude-code', model: 'big', providerId, workDir: process.cwd() }); + +// Rule (admitLocalRoute: a start that is not a verified resume takes the route verdict; a disabled copy +// on the task's explicit source is refused with INVALID_PARAMS): the send is refused before any runtime +// starts, and the input stays at the queue head. +test('route admission: a send to a task whose model copy is disabled starts no runtime', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('disabled'); + r.views.current = withDisabledCopy(r.views.current, 'claude-code', 'prov-a', 'big'); + await r.h.queue.enqueue('disabled', { clientId: 'disabled-1', text: 'first' }); + await waitFor(() => r.h.queue.projection('disabled').error); + assert.match(r.h.queue.projection('disabled').error, /\[INVALID_PARAMS\] provider "prov-a" is disabled for model "big"/); + assert.equal(r.h.maker.sessions.get('disabled'), undefined, 'no runtime started'); + assert.deepEqual(r.h.queue.projection('disabled').pendingQueue.map(item => item.clientId), ['disabled-1']); +}); + +// Rule (admitLocalRoute: a verified resume, the request's route equal to the task's stored route, is not +// refused; a running task is not cut off by a later disable): a released task resumes its native session. +test('route admission: a verified resume of the stored route starts although its copy was disabled later', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('resume'); + const first = await r.runTurn('resume', 'resume-1'); // its native session: native-resume-1 + await r.h.maker.closeSession('resume'); // idle release + r.views.current = withDisabledCopy(r.views.current, 'claude-code', 'prov-a', 'big'); + await r.h.queue.enqueue('resume', { clientId: 'resume-2', text: 'next' }); + await waitFor(() => { const next = r.h.maker.sessions.get('resume'); return next && next !== first && next.sent.length === 1; }); + const next = r.h.maker.sessions.get('resume'); + assert.equal(next.options.resumeSessionId, 'native-resume-1'); + assert.equal(next.options.providerId, 'prov-a'); + assert.equal(r.h.queue.projection('resume').error ?? null, null); +}); + +// Rule (admitLocalRoute: an implicit source whose native default copy is disabled is rerouted to the +// enabled copy before the start; register.ts persistAndHydrateSessionProvider writes the start's provider +// to the task row): the runtime starts on the enabled copy (the provider frozen at the start), the task row +// takes it, a later send to the live runtime keeps it, and a later resume starts on it. +test('route admission: a disabled native default is rerouted before the start, saved, and kept', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + r.views.current = nativeDefaultDisabledViews('claude-code'); + await createTaskOn('reroute', null); + const first = await r.runTurn('reroute', 'reroute-1'); + assert.equal(first.options.providerId, 'prov-a', 'the runtime starts on the enabled copy'); + assert.equal(getSessionProvider('reroute'), 'prov-a', 'the provider frozen at the start'); + assert.equal(r.row('reroute').provider_id, 'prov-a', 'the task row takes the start provider'); + // The next send to the live runtime: the stored route equals the runtime's, so nothing moves it back. + await r.h.queue.enqueue('reroute', { clientId: 'reroute-2', text: 'again' }); + await waitFor(() => first.sent.length === 2); + assert.equal(first.options.providerId, 'prov-a', 'the live runtime keeps the enabled copy'); + first.emit({ type: 'done', data: {}, sessionTurnGeneration: first.generation, sessionInstanceId: first.instanceId }); + await waitFor(() => !r.h.queue.projection('reroute').active); + await r.h.maker.closeSession('reroute'); // idle release + await r.h.queue.enqueue('reroute', { clientId: 'reroute-3', text: 'later' }); + await waitFor(() => { const next = r.h.maker.sessions.get('reroute'); return next && next !== first && next.sent.length === 1; }); + const next = r.h.maker.sessions.get('reroute'); + assert.equal(next.options.resumeSessionId, 'native-reroute-1'); + assert.equal(next.options.providerId, 'prov-a', 'the resume starts on the enabled copy'); +}); + +// Rule (register.ts 18359: a plugin page's task restore starts through bootstrapSession, so its admission +// and the provider write apply): restoring a task that never ran, whose model copy is disabled, is refused +// and starts nothing; restoring one on a disabled native default starts on the enabled copy and saves it. +test('route admission: a plugin page restore is refused on a disabled copy, or started and saved on the rerouted copy', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('restore'); + r.views.current = withDisabledCopy(r.views.current, 'claude-code', 'prov-a', 'big'); + await assert.rejects(r.h.queue.restoreSession('restore', async () => {}), + /\[INVALID_PARAMS\] provider "prov-a" is disabled for model "big"/); + assert.equal(r.h.maker.sessions.get('restore'), undefined); + r.views.current = nativeDefaultDisabledViews('claude-code'); + await createTaskOn('restore-reroute', null); + const restored = await r.h.queue.restoreSession('restore-reroute', async () => {}); + assert.equal(restored.options.providerId, 'prov-a'); + assert.equal(r.row('restore-reroute').provider_id, 'prov-a'); +}); + +// Rule (the desktop's maker:create-session starts the runtime through bootstrapSession, whose admission +// runs before the task row is inserted): a Device Link create on a disabled copy writes no task row and +// starts nothing; a create on a disabled native default writes the row with the enabled copy. +// The Device Link create entry's ports as main.ts binds them: the runtime selection's admission and the +// send path's provider group refusal over the given group store; the row and the runtime are recorded. +const deviceLinkCreate = (r, groups = {}) => { + const rows = []; + const started = []; + const ports = { + serverDeps: { createSession: async input => { rows.push(input); await createTaskOn('created', input.providerId ?? null); return { id: 'created' }; } }, + getAgentGraph: () => ({ maker: { createSession: async opts => { started.push(opts); return r.h.maker.createSession(opts); } } }), + assertProviderExecutionSupported: createHostProviderExecutionCheck({ + hostProviderBindings: { readProviderGroupBinding: () => null }, + hostProviderGroups: { readProviderGroup: providerId => groups[providerId] ?? null }, + }), + admitLocalRoute: opts => r.selection.admitLocalRoute(opts), + }; + const input = providerId => ({ agentKind: 'claude-code', model: 'big', workingDir: process.cwd(), providerId }); + return { ports, rows, started, input }; +}; + +test('route admission: a Device Link create is refused before its row, or created on the rerouted copy', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const { ports, rows, started, input } = deviceLinkCreate(r); + r.views.current = withDisabledCopy(r.views.current, 'claude-code', 'prov-a', 'big'); + await assert.rejects(createHostRuntimeSession(ports, input('prov-a')), /\[INVALID_PARAMS\] provider "prov-a" is disabled for model "big"/); + assert.equal(rows.length, 0, 'no task row'); + assert.equal(started.length, 0, 'no runtime'); + r.views.current = nativeDefaultDisabledViews('claude-code'); + await createHostRuntimeSession(ports, input(null)); + assert.equal(rows[0].providerId, 'prov-a', 'the row is created with the enabled copy'); + assert.equal(r.row('created').provider_id, 'prov-a'); + assert.equal(started[0].providerId, 'prov-a'); +}); + +// Rule (send-preflight.ts createHostProviderExecutionCheck: the Host has no provider group assignment, so +// the send path refuses a provider group task with UNSUPPORTED_CAPABILITY): a Device Link create of a +// provider group task is refused the same way, before any task row or runtime. Gap: this entry (main.ts) +// did not refuse provider group tasks. +test('Device Link create: a provider group task is refused with no task row and no runtime', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const { ports, rows, started, input } = deviceLinkCreate(r, { 'group-1': { id: 'group-1' } }); + await assert.rejects(createHostRuntimeSession(ports, input('group-1')), + { message: '[UNSUPPORTED_CAPABILITY] Host does not yet support provider groups' }); + assert.equal(rows.length, 0, 'no task row'); + assert.equal(started.length, 0, 'no runtime'); +}); + +// Rule (sessionAgentSwitchHandler.ts: a switch back to an engine whose native session is parked starts +// that engine at once to see whether the resume holds, through agentSwitchDeps.bootstrapSwitchedSession; +// the handoff then carries only what happened while it was away): switching back resumes the parked +// native session. Gap: the Host's bootstrapSwitchedSession threw, which the switch takes as a failed +// resume and falls back from: the engine started fresh with a full handoff, and the parked session was +// silently dropped. +test('model change at send: switching back to an engine resumes its parked native session', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('park'); + const started = []; + const create = r.h.maker.createSession.bind(r.h.maker); + r.h.maker.createSession = async opts => { started.push({ agentKind: opts.agentKind, resumeSessionId: opts.resumeSessionId }); return create(opts); }; + const claude = await r.runTurn('park', 'park-1'); // its native session: native-park-1 + await r.selection.switchAgent({ sessionId: 'park', targetAgentKind: 'codex', model: 'gpt-x', providerId: 'prov-a' }); + await r.h.queue.enqueue('park', { clientId: 'park-2', text: 'on codex' }); + await waitFor(() => { const next = r.h.maker.sessions.get('park'); return next && next !== claude && next.sent.length === 1; }); + const codex = r.h.maker.sessions.get('park'); + r.db.db.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run('native-codex', 'park'); + codex.emit({ type: 'done', data: {}, sessionTurnGeneration: codex.generation, sessionInstanceId: codex.instanceId }); + await waitFor(() => !r.h.queue.projection('park').active); + await r.selection.switchAgent({ sessionId: 'park', targetAgentKind: 'claude-code', model: 'big', providerId: 'prov-a' }); + await r.h.queue.enqueue('park', { clientId: 'park-3', text: 'back' }); + await waitFor(() => { const next = r.h.maker.sessions.get('park'); return next && next !== codex && next.sent.length === 1; }); + assert.deepEqual(started, [ + { agentKind: 'claude-code', resumeSessionId: undefined }, + { agentKind: 'codex', resumeSessionId: undefined }, + { agentKind: 'claude-code', resumeSessionId: 'native-park-1' }, // the parked native session resumes + ]); + const boundaries = r.db.db.prepare("SELECT content FROM messages WHERE session_id = 'park' AND role = 'agent_switch'").all() + .map(entry => JSON.parse(entry.content)); + assert.deepEqual(boundaries.map(entry => [entry.fromAgentKind, entry.toAgentKind, entry.resumed === true]), + [['cc', 'codex', false], ['codex', 'cc', true]]); + const back = r.h.maker.sessions.get('park'); + assert.match(back.sent[0], /switching back to you/, 'the handoff carries only what happened while it was away'); + assert.match(back.sent[0], /back$/, 'followed by the user\'s message'); + assert.equal(r.h.queue.projection('park').error ?? null, null); +}); + +// Rule (register.ts rememberThinkingIntent): an engine switch that commits with a thinking choice puts +// it in the preference mirror the next runtime start reads (start-options.ts +// getThinkingEnabledFromMemory) and sends it to the clients' memory (DRAFT_PREF_APPLY). Gap: the Host +// left the port out, so the choice was dropped once the switch committed. +test('model change at send: an engine switch keeps its thinking choice for the next runtime start', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('think'); + await r.selection.switchAgent({ sessionId: 'think', targetAgentKind: 'codex', model: 'gpt-think', providerId: 'prov-a', thinking: false }); + await r.h.queue.enqueue('think', { clientId: 'think-1', text: 'first' }); + await waitFor(() => r.h.maker.sessions.get('think')?.agentKind === 'codex'); + assert.equal(getThinkingEnabledFromMemory('codex', 'prov-a', 'gpt-think'), false); + const pushed = r.h.events.filter(event => event.type === 'plugin_push' && event.channel === 'maker:draft-pref:apply'); + assert.deepEqual(pushed.map(event => event.payload), + [{ agent: 'codex', providerId: 'prov-a', modelId: 'gpt-think', active: false, thinking: false }]); +}); + +// Rule (the desktop's settlePendingCredentialSwitch, wired to a turn's end in register.ts; main.ts wires +// onSessionSettled to runtimeSelection.onTurnSettled): a credential switch registered while the task's +// turn runs waits for that turn, then lands at its end: the runtime is closed so the next send starts on +// the new route, the task's route store takes the new source, and the clients hear it applied. Gap: no +// Host test reached the turn end with a pending switch, so a broken onTurnSettled left every switch +// pending (the client keeps showing "switches after this turn"). The Host's own entries do not register +// yet (release table, B2); this registers through the shared registerPendingCredentialSwitchWith. +// The second case: the landing's route write resolves the task's effort against the target model, and a +// model without effort levels resolves none (fixed on the desktop in 7f86f08f2c: the write failed on +// sessions.effort NOT NULL, so the switch never landed). The column keeps its value, as on the desktop. +for (const efforts of [['low', 'high'], []]) { +test(`model change at send: a credential switch registered during a turn lands when the turn ends (target effort levels: ${efforts.length ? efforts.join(', ') : 'none'})`, { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + // As Maker: the runtimes it holds (maker.ts listActiveSessions). + r.h.maker.listActiveSessions = () => [...r.h.maker.sessions.values()]; + // A second connected provider offering the same models: the switch's target source. + const withEfforts = view => ({ ...view, models: { 'claude-code': view.models['claude-code'] + .map(entry => ({ ...entry, efforts, defaultEffort: efforts.at(-1) ?? null })) } }); + r.views.current = [...r.views.current, ...switchViews('claude-code').map(view => ({ ...view, id: 'prov-b' }))] + .map(withEfforts); + await r.createTask('settle'); + r.db.db.prepare('UPDATE sessions SET effort = ? WHERE id = ?').run('high', 'settle'); + await r.h.queue.enqueue('settle', { clientId: 'settle-1', text: 'work' }); + await waitFor(() => r.h.maker.sessions.get('settle')?.sent.length === 1); + const session = r.h.maker.sessions.get('settle'); + await r.selection.registerPendingCredentialSwitch('settle', { model: 'small', providerId: 'prov-b' }); + assert.equal(r.selection.hasPendingCredentialSwitch('settle'), true); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + assert.equal(r.selection.hasPendingCredentialSwitch('settle'), true, 'the switch waits while the turn runs'); + assert.equal(r.h.maker.sessions.get('settle'), session); + session.emit({ type: 'done', data: {}, ...stamp }); + await waitFor(() => !r.selection.hasPendingCredentialSwitch('settle')); + assert.equal(r.h.maker.sessions.get('settle'), undefined, 'the runtime is closed for the next send'); + assert.equal(getSessionProvider('settle'), 'prov-b'); + const applied = r.h.events.filter(event => event.type === 'plugin_push' && event.channel === 'maker:session-credential-switch-applied'); + assert.deepEqual(applied.map(event => event.payload), [{ sessionId: 'settle', model: 'small', providerId: 'prov-b' }]); + assert.deepEqual({ ...r.db.db.prepare('SELECT model, effort, provider_id AS providerId FROM sessions WHERE id = ?').get('settle') }, + { model: 'small', effort: 'high', providerId: 'prov-b' }); +}); +} + +// Rule (the desktop's send transaction, register.ts createMakerSendTransaction's applyPendingAgentSwitch: +// after the landing and the renamed-model recovery, replayPendingSessionContextWindowBudgetUnderLock): a +// window budget rebuild still owed for the task's live runtime is applied at the send, before the message +// goes out, so the message runs on a runtime rebuilt for the budget. Gap: the Host's send hook had no +// replay, so a budget saved during a turn never reached the runtime (release table, A3). +test('model change at send: a window budget rebuild still owed is applied before the message goes out', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + r.h.maker.listActiveSessions = () => [...r.h.maker.sessions.values()]; + t.after(() => { appliedContextWindowBudgets.delete('budget-replay'); pendingSessionContextWindowBudgetReconciles.delete('budget-replay'); }); + await r.createTask('budget-replay'); + await r.h.queue.enqueue('budget-replay', { clientId: 'budget-1', text: 'first' }); + await waitFor(() => r.h.maker.sessions.get('budget-replay')?.sent.length === 1); + const first = r.h.maker.sessions.get('budget-replay'); + first.emit({ type: 'done', data: {}, sessionTurnGeneration: first.generation, sessionInstanceId: first.instanceId }); + await waitFor(() => !r.h.queue.projection('budget-replay').turnInProgress); + // A budget saved during the turn left its rebuild owed (the reconcile's deferred branch). + r.budgets.set('budget-replay', 100_000); + pendingSessionContextWindowBudgetReconciles.add('budget-replay'); + + await r.h.queue.enqueue('budget-replay', { clientId: 'budget-2', text: 'second' }); + await waitFor(() => r.h.maker.sessions.get('budget-replay')?.sent.includes('second')); + assert.notEqual(r.h.maker.sessions.get('budget-replay'), first, 'the message runs on a rebuilt runtime'); + assert.equal(first.sent.includes('second'), false); + assert.equal(appliedContextWindowBudgets.get('budget-replay'), 100_000); + assert.equal(pendingSessionContextWindowBudgetReconciles.has('budget-replay'), false); +}); + +// Rule (the desktop's cleanupClosedSessionRuntime): a closed runtime's budget bookkeeping goes with it, +// after the pending switch's own close handling, so a replacement starts from the stored budget. Gap: the +// Host's close handling (runtime-selection.ts onSessionClosed, subscribed to Maker's session:closed) did +// not touch the budget tables. +test('model change at send: closing a task\'s runtime clears its window budget bookkeeping', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + // As Maker: session:closed for each runtime it closes (maker.ts); this fake Maker has no events. + const listeners = new Set(); + r.h.maker.on = listener => { listeners.add(listener); return () => listeners.delete(listener); }; + const off = r.selection.attachMaker(r.h.maker); + t.after(() => { off(); appliedContextWindowBudgets.delete('budget-close'); pendingSessionContextWindowBudgetReconciles.delete('budget-close'); }); + await r.createTask('budget-close'); + await r.h.queue.enqueue('budget-close', { clientId: 'close-1', text: 'work' }); + await waitFor(() => r.h.maker.sessions.get('budget-close')?.sent.length === 1); + const session = r.h.maker.sessions.get('budget-close'); + session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + await waitFor(() => !r.h.queue.projection('budget-close').turnInProgress); + appliedContextWindowBudgets.set('budget-close', 100_000); + pendingSessionContextWindowBudgetReconciles.add('budget-close'); + await r.h.maker.closeSession('budget-close'); + // The closed runtime's last usage (the fake runtime reports none). + for (const listener of listeners) listener({ type: 'session:closed', sessionId: 'budget-close', session: { getUsageSnapshot: () => undefined } }); + assert.equal(appliedContextWindowBudgets.has('budget-close'), false); + assert.equal(pendingSessionContextWindowBudgetReconciles.has('budget-close'), false); +}); + +// --- Permission mode and Plan mode (A7): the desktop's commit, run by the Host's set-permission-mode and +// set-plan-mode entries (runtime-selection.ts over sessionPermissionSettings.ts) on a migrated database. +// Gap for each: the Host's old /sessions/update path only switched the runtime and wrote the column. +const flushTurns = async () => { for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); }; +const sessionPatches = (r, id) => r.h.events.filter(event => event.type === 'session_changed' && event.sessionId === id) + .map(event => event.patch); +const permissionRow = (r, id) => r.db.db.prepare('SELECT permission_mode AS mode, plan_mode_enabled AS plan FROM sessions WHERE id = ?').get(id); +// A task with a live runtime (one turn run and ended). +async function liveTask(r, id) { + await r.createTask(id); + return r.runTurn(id, `${id}-1`); +} +// Holds a task's permission queue (sessionPermissionChange.ts) from now until release() is called; work +// queued for the task after this waits behind it. +function holdPermissionQueue(id) { + let release; + let started; + const ready = new Promise(resolve => { started = resolve; }); + const held = withSessionPermissionChange(id, () => new Promise(resolve => { release = resolve; started(); })); + return { held, release: async () => { await ready; release(); return held; } }; +} + +// Rule: the desktop's commitSessionPermissionMode: the live runtime switches, the task row is written +// through bots.persistSessionPermission, and the clients get the patch. +test('permission mode: a change applies to the live runtime, the task row and the clients', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const live = await liveTask(r, 'perm-apply'); + assert.equal(await r.selection.setPermissionMode('perm-apply', 'auto'), true); + assert.equal(live.options.permissionMode, 'auto'); + assert.equal(permissionRow(r, 'perm-apply').mode, 'auto'); + assert.deepEqual(sessionPatches(r, 'perm-apply').at(-1), { permissionMode: 'auto' }); +}); + +// Rule: the desktop's SET_PERMISSION_MODE checks its arguments before the commit (isSessionPermissionMode). +// Gap: the desktop's guard test injects a check that always passes, so no test refused an invalid mode. +test('permission mode: an invalid mode is refused with INVALID_PARAMS and nothing changes', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const live = await liveTask(r, 'perm-invalid'); + const before = live.options.permissionMode; + const patchesBefore = sessionPatches(r, 'perm-invalid').length; + // Refused before the runtime is touched (the database transaction would refuse it too, after the + // runtime had switched and been rolled back). + const runtimeSwitches = []; + const switchRuntime = live.setPermissionMode; + live.setPermissionMode = async mode => { runtimeSwitches.push(mode); return switchRuntime(mode); }; + await assert.rejects(r.selection.setPermissionMode('perm-invalid', 'everything'), err => err.code === 'INVALID_PARAMS'); + await assert.rejects(r.selection.setPermissionMode(42, 'auto'), err => err.code === 'INVALID_PARAMS'); + assert.deepEqual(runtimeSwitches, [], 'the runtime never switched'); + assert.equal(live.options.permissionMode, before); + assert.equal(permissionRow(r, 'perm-invalid').mode, 'ask'); + assert.equal(sessionPatches(r, 'perm-invalid').length, patchesBefore, 'no patch reached the clients'); +}); + +// Rule: the desktop's commit rolls the runtime back when the write fails, inside the same queue turn, and +// reports the failure; a task with no row is NOT_FOUND; a review task's settings are fixed. +test('permission mode: a failed write rolls the runtime back; a missing task is NOT_FOUND; a review task is refused', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const live = await liveTask(r, 'perm-fail'); + r.db.db.exec(`CREATE TRIGGER perm_fail BEFORE UPDATE OF permission_mode ON sessions WHEN NEW.id = 'perm-fail' + BEGIN SELECT RAISE(ABORT, 'permission write failed'); END;`); + await assert.rejects(r.selection.setPermissionMode('perm-fail', 'bypassPermissions'), /permission write failed/); + assert.equal(live.options.permissionMode, 'ask', 'the runtime is back on the stored mode'); + assert.equal(permissionRow(r, 'perm-fail').mode, 'ask'); + await assert.rejects(r.selection.setPermissionMode('perm-missing', 'auto'), err => err.code === 'NOT_FOUND'); + await r.createTask('perm-review'); + r.db.db.prepare("UPDATE sessions SET source = 'review' WHERE id = ?").run('perm-review'); + await assert.rejects(r.selection.setPermissionMode('perm-review', 'auto'), err => err.code === 'UNSUPPORTED_CAPABILITY'); + assert.equal(permissionRow(r, 'perm-review').mode, 'ask'); +}); + +// Rule: a real permission or Plan change drops the task's shared provider "always allow" grants and +// revokes their live observers (credentialGrants.ts forgetCredentialGrants). On the Host the observers are +// task actions' rewind authorizations (taskActionHost.ts, loaded by host-tools.ts). Gap: no Host test +// reached this revocation. +test('permission and Plan mode: a real change revokes the task\'s grant observers; the same value does not', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await liveTask(r, 'perm-grants'); + let revoked = 0; + const unwatch = watchCredentialGrantRevocation('perm-grants', () => { revoked += 1; }); + t.after(unwatch); + await r.selection.setPermissionMode('perm-grants', 'ask'); + assert.equal(revoked, 0, 'the same permission mode keeps the grants'); + await r.selection.setPermissionMode('perm-grants', 'auto'); + assert.equal(revoked, 1); + await r.selection.setPlanMode('perm-grants', false); + assert.equal(revoked, 1, 'the same Plan mode keeps the grants'); + await r.selection.setPlanMode('perm-grants', true); + assert.equal(revoked, 2); +}); + +// Rule: changes of one task are ordered behind its permission queue: a later change starts after the +// earlier one has finished (sessionPermissionChange.ts), so the last choice is what stays. +test('permission mode: two changes of a task run one after the other and the later one stays', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const live = await liveTask(r, 'perm-order'); + const switchRuntime = live.setPermissionMode; + const calls = []; + let releaseFirst; + const firstHeld = new Promise(resolve => { releaseFirst = resolve; }); + live.setPermissionMode = async mode => { calls.push(mode); if (calls.length === 1) await firstHeld; return switchRuntime(mode); }; + const first = r.selection.setPermissionMode('perm-order', 'auto'); + const second = r.selection.setPermissionMode('perm-order', 'bypassPermissions'); + await waitFor(() => calls.length === 1); + await flushTurns(); + assert.deepEqual(calls, ['auto'], 'the second change waits for the first'); + releaseFirst(); + await Promise.all([first, second]); + assert.deepEqual(calls, ['auto', 'bypassPermissions']); + assert.equal(live.options.permissionMode, 'bypassPermissions'); + assert.equal(permissionRow(r, 'perm-order').mode, 'bypassPermissions'); +}); + +// Rule (the desktop's maker:send and INPUT_ENQUEUE): a client's new input waits for the task's permission +// changes in flight before anything takes the send lock, and is refused if the account changed meanwhile. +// Gap: the Host's input entries did not wait, so an input could start a turn before a tightening landed. +test('new input waits for a permission change in flight, and is refused if the account changed', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const enqueue = createUserInputEnqueue({ getOwner: getCurrentDbClientSnapshot, enqueue: (id, input) => r.h.queue.enqueue(id, input) }); + await r.createTask('input-wait'); + const change = holdPermissionQueue('input-wait'); + const entered = enqueue('input-wait', { clientId: 'input-wait-1', text: 'after the change' }); + await flushTurns(); + assert.equal(r.h.maker.sessions.get('input-wait'), undefined, 'nothing started while the change runs'); + await change.release(); + await entered; + await waitFor(() => r.h.maker.sessions.get('input-wait')?.sent.length === 1); + // The account changes while an input waits: it is refused and never queued. + await r.createTask('input-owner'); + let owner = getCurrentDbClientSnapshot(); + const ownerEnqueue = createUserInputEnqueue({ getOwner: () => owner, enqueue: (id, input) => r.h.queue.enqueue(id, input) }); + const ownerChange = holdPermissionQueue('input-owner'); + const refused = ownerEnqueue('input-owner', { clientId: 'input-owner-1', text: 'stale' }).then(() => null, err => err); + await flushTurns(); + owner = { another: 'owner' }; + await ownerChange.release(); + assert.equal((await refused)?.code, 'PRECONDITION_FAILED'); + assert.equal(r.h.maker.sessions.get('input-owner'), undefined); +}); + +// Rule (the desktop: "Only fresh user IPC waits ... Internal continuations and turn cleanup must remain +// able to finish"): the queue's next input and a context recovery's replay do not wait for the permission +// queue. Reverse guard: a later change must not make them wait too. +test('the queue\'s next input and a recovery replay do not wait for the permission queue', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + await r.createTask('drain'); + await r.h.queue.enqueue('drain', { clientId: 'drain-1', text: 'first' }); + await waitFor(() => r.h.maker.sessions.get('drain')?.sent.length === 1); + await r.h.queue.enqueue('drain', { clientId: 'drain-2', text: 'second' }); + const session = r.h.maker.sessions.get('drain'); + const change = holdPermissionQueue('drain'); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + session.emit({ type: 'done', data: {}, ...stamp }); + // The queue sends its next input at the turn's end while the permission queue is still held. + await waitFor(() => [...r.h.maker.sessions.values()].some(entry => entry.sent.includes('second'))); + await change.release(); +}); +test('a context recovery replay does not wait for the permission queue', { timeout: 30_000 }, async t => { + const r = await assembledRecovery(t); + const change = holdPermissionQueue('replay-held'); + const first = await r.overflow('replay-held'); + await waitFor(() => { const next = r.h.maker.sessions.get('replay-held'); return next && next !== first && next.sent.length === 1; }); + await change.release(); +}); + +// Rule: the desktop's SET_PLAN_MODE commit, and its save of a Plan mode the runtime changed itself +// (emitWiredSessionEvent: behind the task's permission queue, only while the owner, the binding and the +// runtime's value still hold; the clients learn it from the session patch, not from the raw event). +// Gap: the Host did not save a runtime's own Plan change, so a task that left Plan mode was back in it at +// its next runtime start. +test('Plan mode: a change applies; a runtime\'s own exit is saved, but not for a stale value, a replaced runtime or another account', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const live = await liveTask(r, 'plan'); + live.getPlanMode = () => live.options.planMode ?? false; + await r.selection.setPlanMode('plan', true); + assert.equal(live.options.planMode, true); + assert.equal(permissionRow(r, 'plan').plan, 1); + assert.deepEqual(sessionPatches(r, 'plan').at(-1), { planModeEnabled: true }); + // The runtime leaves Plan mode itself (a plan approved): saved. + live.options.planMode = false; + live.emit({ type: 'plan_mode_changed', data: { enabled: false } }); + await withSessionPermissionChange('plan', async () => {}); + assert.equal(permissionRow(r, 'plan').plan, 0); + assert.deepEqual(sessionPatches(r, 'plan').at(-1), { planModeEnabled: false }); + assert.equal(r.h.events.some(event => event.event?.type === 'plan_mode_changed' || event.type === 'plan_mode_changed'), false, + 'not delivered as a turn event'); + // A stale value: the runtime is back in Plan mode by the time the save runs. + await r.selection.setPlanMode('plan', true); + let held = holdPermissionQueue('plan'); + live.options.planMode = false; + live.emit({ type: 'plan_mode_changed', data: { enabled: false } }); + live.options.planMode = true; + await held.release(); + await withSessionPermissionChange('plan', async () => {}); + assert.equal(permissionRow(r, 'plan').plan, 1); + // A replaced runtime: the event of the runtime the task no longer has is not saved. + held = holdPermissionQueue('plan'); + live.options.planMode = false; + live.emit({ type: 'plan_mode_changed', data: { enabled: false } }); + await r.h.maker.closeSession('plan'); + await r.h.queue.enqueue('plan', { clientId: 'plan-2', text: 'next' }); + await waitFor(() => { const next = r.h.maker.sessions.get('plan'); return next && next !== live && next.sent.length === 1; }); + await held.release(); + await withSessionPermissionChange('plan', async () => {}); + assert.equal(permissionRow(r, 'plan').plan, 1); + // A runtime wired under another account (the account changed since): the Host's binding with an owner + // that is no longer the current one, as the executor hands it over. + const next = r.h.maker.sessions.get('plan'); + next.getPlanMode = () => next.options.planMode ?? false; + next.options.planMode = false; + r.selection.persistAgentPlanModeChange({ ownerDb: { client: {}, userId: 'another-owner', clientEpoch: -1 }, + sessionBindings: { getSession: () => next } }, next, { type: 'plan_mode_changed', data: { enabled: false } }); + await withSessionPermissionChange('plan', async () => {}); + assert.equal(permissionRow(r, 'plan').plan, 1); +}); + +// Rule (botPermissionSync.ts, now bound on the Host): a permission save of a Bot task is followed by its +// other lanes: each is reconciled behind its own permission queue, its grant observers revoked, and the +// clients told. Gap: bound to nothing, the other lanes' rows changed (the shared transaction) but no client +// heard of it and their grants stayed. +test('Bot: a permission change of a Bot task reaches its other lanes\' rows, grants and clients', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + const now = Date.now(); + await r.createTask('bot-main'); + await r.createTask('bot-topic'); + r.db.db.prepare("UPDATE sessions SET source = 'bot' WHERE id IN ('bot-main', 'bot-topic')").run(); + r.db.db.prepare("INSERT INTO bot_profiles (id, display_name, current_version, created_at, updated_at) VALUES ('bot-1', 'Bot', 1, ?, ?)").run(now, now); + r.db.db.prepare("INSERT INTO bot_profile_versions (id, bot_id, version, capabilities_json, created_at) VALUES ('bot-1-v1', 'bot-1', 1, ?, ?)") + .run(JSON.stringify({ permissions: 'ask' }), now); + const link = r.db.db.prepare('INSERT INTO bot_session_links (id, bot_id, session_id, role, created_at) VALUES (?, ?, ?, ?, ?)'); + link.run('link-main', 'bot-1', 'bot-main', 'canonical', now); + link.run('link-topic', 'bot-1', 'bot-topic', 'channel', now); + let topicRevoked = 0; + const unwatch = watchCredentialGrantRevocation('bot-topic', () => { topicRevoked += 1; }); + t.after(unwatch); + await r.selection.setPermissionMode('bot-main', 'auto'); + assert.equal(permissionRow(r, 'bot-main').mode, 'auto'); + assert.equal(permissionRow(r, 'bot-topic').mode, 'auto'); + assert.deepEqual(sessionPatches(r, 'bot-topic').at(-1), { permissionMode: 'auto' }); + assert.ok(topicRevoked >= 1, 'the other lane\'s grants are dropped'); +}); + +// Guard: main.ts casts the untyped queue api to the runtime selection's inputQueue port. Every member +// that port declares (listed in runtime-selection.ts, checked complete at compile time) is a function +// of a real queue, and startPorts() gives every runtime start function. +test('the queue api has every member the runtime selection calls', { timeout: 30_000 }, async t => { + const h = createHarness(); + t.after(() => h.queue.dispose()); + for (const member of HOST_RUNTIME_SELECTION_QUEUE_MEMBERS) assert.equal(typeof h.queue[member], 'function', member); + const startPorts = h.queue.startPorts(); + for (const port of HOST_RUNTIME_START_PORTS) assert.equal(typeof startPorts[port], 'function', port); +}); + test('context recovery assembly: an overflow rebuilds the task and replays the message on a new runtime, with no error left', { timeout: 30_000 }, async t => { const r = await assembledRecovery(t); const first = await r.overflow('assembled-ok'); @@ -3104,6 +4590,9 @@ test('context recovery through /api/chat: the stream carries the replay\'s answe assert.match(c.writes.at(-1), /event: end/); assert.equal(c.rows('chat-recovered', 'user').length, 1, 'the replay writes no second user row'); assert.deepEqual(c.rows('chat-recovered', 'user').map(row => row.client_id), ['chat-input']); + // The stream ends on the done; the turn's last writes (the reply's turn seal) settle after it, + // and the fixture closes the database before the queue: let them land first. + await waitFor(() => !c.h.queue.projection('chat-recovered').turnInProgress); }); test('context recovery through /api/chat: a stop during the replay ends the stream with the message\'s interrupted receipt', { timeout: 30_000 }, async t => { @@ -3216,32 +4705,256 @@ test('context recovery assembly: input queued while the replayed turn runs waits assert.deepEqual(replayed.sent, [replay, 'next'], 'the summary went with the replay only'); }); -test('context recovery assembly: a summary not yet sent when the Host restarts goes with the next send, once', { timeout: 30_000 }, async t => { +// Checkpoint 4a. Rule: as on the desktop, the coordinator gets an overflow-class terminal error when it +// arrives, before context recovery claims it, and holds that error until the rebuild clears it +// (contextRecoveryRebuilt); recovery still owns the error's row, so none is written. Gap: the Host handed +// the error to the coordinator only after the turn's rows settled. Tier: unit, real database, Host event path. +test('context recovery assembly: the coordinator holds an overflow error from its arrival until the rebuild clears it, with no error row', { timeout: 30_000 }, async t => { const r = await assembledRecovery(t); - // The replay's runtime cannot start: the rebuild is committed, its summary never sent. - const create = r.h.maker.createSession.bind(r.h.maker); - let created = 0; - r.h.maker.createSession = async (...args) => { - if ((created += 1) === 2) throw new Error('engine unavailable'); - return create(...args); - }; - await r.overflow('assembled-restart'); - await waitFor(() => r.rows('assembled-restart', 'error').length === 1); - const { handoff, consumed } = r.marker('assembled-restart'); - assert.equal(consumed, false); - await r.h.queue.dispose(); - // A new Host process: a new queue and a new registry on the same database. - const restarted = assembledRuntime(t, r.db); - await restarted.h.queue.enqueue('assembled-restart', { clientId: 'after-restart', text: 'continue' }); - await waitFor(() => restarted.h.maker.sessions.get('assembled-restart')?.sent.length === 1); - const session = restarted.h.maker.sessions.get('assembled-restart'); - assert.deepEqual(session.sent, [`${handoff}\n\ncontinue`]); - await waitFor(() => r.marker('assembled-restart').consumed === true); - session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); - await waitFor(() => !restarted.h.queue.projection('assembled-restart').running); - await restarted.h.queue.enqueue('assembled-restart', { clientId: 'after-restart-2', text: 'and again' }); - await waitFor(() => session.sent.length === 2); - assert.equal(session.sent[1], 'and again', 'sent once'); + const id = 'assembled-handed'; + const first = await r.overflow(id); + assert.ok(r.h.queue.projection(id).error, 'the coordinator has the error on arrival'); + await waitFor(() => { const next = r.h.maker.sessions.get(id); return next && next !== first && next.sent.length === 1; }); + await waitFor(() => !r.h.queue.projection(id).error); + assert.deepEqual(r.rows(id, 'error'), []); +}); + +// §3.2, integration. A saved Codex history error can outlive the harness that emitted it. +// Exercise queued sends, real SQLite and the same native locator as main.ts. All Codex +// discovery, including its external HOME fallback, stays inside this test's directories. +async function preSendRecovery(t, agent = 'codex') { + const db = await recoveryDatabase(t); + const home = path.join(db.root, 'home'); + mkdirSync(home); + const keys = ['HOME', 'USERPROFILE', 'CODEX_HOME', 'APPDATA', 'XDG_CONFIG_HOME']; + const before = Object.fromEntries(keys.map(key => [key, process.env[key]])); + Object.assign(process.env, { HOME: home, USERPROFILE: home, APPDATA: home, XDG_CONFIG_HOME: home }); + delete process.env.CODEX_HOME; + t.after(() => { + for (const key of keys) { + if (before[key] === undefined) delete process.env[key]; + else process.env[key] = before[key]; + } + }); + const id = 'pre-send-task'; + const thread = '04111111-2222-4333-8444-555555555551'; + const profile = path.join(db.root, 'profile'); + const codexHistory = createHostCodexThreadStorage({ + profileDir: profile, accounts: { codexAccountHome: key => path.join(profile, 'codex-accounts', key) }, + check: () => {}, + }); + const lookup = t.mock.method(codexHistory, 'readCodexThreadStorageReadOnly'); + let h; + const pendingHandoff = createHostAgentHandoffPending({ getOwner: getCurrentDbClientSnapshot, + publish: event => h.events.push(event), log: quiet }); + h = createHarness({ + ...createHostContextRecoveryWiring({ + openKinds: new Set(['context-overflow']), pendingHandoff, + getGraph: () => ({ maker: h.maker, contextRecovery: { codexHistory, resolveVerifiedWindow: () => null, resolveHandoffWindow: () => null } }), + persistMessage: (...args) => db.persistMessage(...args), publish: event => h.events.push(event), log: quiet, + }), + getOwner: getCurrentDbClientSnapshot, pendingHandoff, persistMessage: db.persistMessage, + readSession: async () => { + const row = db.db.prepare('SELECT sdk_session_id FROM sessions WHERE id = ?').get(id); + return { id, agentKind: agent, status: 'active', model: 'stored-model', providerId: 'xd', + permissionMode: 'ask', workingDir: db.root, sdkSessionId: row.sdk_session_id }; + }, + }); + const originalOwner = getCurrentDbClientSnapshot(); + t.after(async () => { + if (getCurrentDbClientSnapshot() === originalOwner) await h.queue.dispose(); + else await assertOwnerChangedDisposal(h.queue.dispose()); + }); + await db.createTask(id); + db.db.prepare('UPDATE sessions SET agent_kind = ? WHERE id = ?').run(agent === 'claude-code' ? 'cc' : agent, id); + const send = text => h.queue.enqueue(id, { clientId: text, text }); + await send('first'); + await waitFor(() => h.maker.getSession(id)?.sent.length === 1); + const first = h.maker.getSession(id); + function done(session) { + session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + return waitFor(() => !h.queue.projection(id).running); + } + await done(first); + await db.persistMessage(id, { role: 'assistant', clientId: 'first-reply', content: 'previous answer to retain' }); + db.db.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run(thread, id); + const close = t.mock.method(h.maker, 'closeSession'); + const markers = () => db.db.prepare("SELECT content FROM messages WHERE session_id = ? AND role = 'context_rebuild'").all(id); + const seedError = () => db.persistMessage(id, { clientId: 'old-error', role: 'error', content: { reason: CODEX_HISTORY_OVERSIZED_REASON } }); + function writeRollout(folder, oversized = false) { + const dir = path.join(folder, 'sessions', '2026', '11', '18'); + mkdirSync(dir, { recursive: true }); + const meta = { type: 'session_meta', timestamp: '2026-11-18T00:00:00Z', payload: { id: thread, source: 'cli', cwd: home } }; + const lines = [JSON.stringify(meta)]; + if (oversized) lines.push(JSON.stringify({ payload: { type: 'custom_tool_call_output', + output: 'data:image/png;base64,' + 'A'.repeat(CODEX_LIVE_TAIL_OVERSIZED_BYTES) } })); + writeFileSync(path.join(dir, 'rollout-2026-11-18T00-00-00-' + thread + '.jsonl'), lines.join('\n') + '\n'); + } + return { db, h, id, first, home, profile, close, lookup, send, done, markers, seedError, writeRollout, pendingHandoff }; +} + +for (const [scenario, rebuild] of [ + ['healthy Host history', false], ['healthy history only in the external Codex home', false], + ['oversized Host history', true], ['missing history', true], ['a task now using another engine', true], +]) { + test('pre-send recovery: ' + scenario, async t => { + const codex = scenario !== 'a task now using another engine'; + const r = await preSendRecovery(lifoCleanup(t), codex ? 'codex' : 'claude-code'); + if (scenario !== 'missing history') { + const external = scenario === 'healthy history only in the external Codex home'; + r.writeRollout(external ? path.join(r.home, '.codex') : path.join(r.profile, 'codex-home'), scenario === 'oversized Host history'); + } + await r.seedError(); + await r.send('next'); + await waitFor(() => r.h.maker.getSession(r.id)?.sent.some(text => text.endsWith('next'))); + const live = r.h.maker.getSession(r.id); + assert.equal(r.lookup.mock.callCount(), codex ? 1 : 0); + assert.equal(r.close.mock.callCount(), rebuild ? 1 : 0); + assert.equal(r.markers().length, rebuild ? 1 : 0); + if (!rebuild) { + assert.equal(live, r.first); + assert.deepEqual(live.sent, ['first', 'next']); + return; + } + assert.notEqual(live, r.first); + assert.equal(live.options.resumeSessionId, undefined); + const handoff = JSON.parse(r.markers()[0].content).handoff; + assert.match(handoff, /previous answer to retain/); + assert.deepEqual(live.sent, [handoff + '\n\nnext']); + await r.done(live); + await r.send('again'); + await waitFor(() => live.sent.length === 2); + assert.equal(live.sent[1], 'again'); + assert.equal(r.markers().length, 1); + }); +} + +test('pre-send recovery: a live oversized-history error stays on the ordinary terminal path', async t => { + const r = await preSendRecovery(lifoCleanup(t)); + await r.send('second'); + await waitFor(() => r.first.sent.length === 2); + r.first.emit({ type: 'error', data: { reason: CODEX_HISTORY_OVERSIZED_REASON, message: 'old history limit' }, + sessionTurnGeneration: r.first.generation, sessionInstanceId: r.first.instanceId }); + await waitFor(() => r.db.errorRows(r.id).length === 1 && r.h.queue.projection(r.id).error); + assert.equal(r.h.events.filter(event => event.type === 'error' && event.sessionId === r.id).length, 1); + assert.equal(r.lookup.mock.callCount(), 0); + assert.equal(r.close.mock.callCount(), 0); + assert.equal(r.markers().length, 0); +}); + +test('pre-send recovery: a rebuild write failure refuses the input before dispatch', async t => { + const r = await preSendRecovery(lifoCleanup(t)); + await r.seedError(); + r.db.db.exec("CREATE TRIGGER reject_rebuild BEFORE INSERT ON messages WHEN NEW.role = 'context_rebuild' BEGIN SELECT RAISE(ABORT, 'fixture rebuild failed'); END"); + await r.send('next'); + await waitFor(() => Boolean(r.h.queue.projection(r.id).error)); + assert.match(r.h.queue.projection(r.id).error, /fixture rebuild failed/); + assert.deepEqual(r.first.sent, ['first']); + assert.equal(r.h.maker.getSession(r.id), null); + assert.equal(r.markers().length, 0); +}); + +// Switch owners before close, during close, or after the old owner's rebuild commits. +// A second account has the same task id; a stale decision must never commit to that database. +for (const boundary of ['before close', 'before commit', 'before handoff']) { + test('pre-send recovery: an owner change ' + boundary + ' protects the new account', async t => { + t = lifoCleanup(t); + const other = await recoveryDatabase(t); + const otherClient = getCurrentDbClientSnapshot().client; + const r = await preSendRecovery(t, 'claude-code'); + await other.createTask(r.id); + other.db.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run('other-thread', r.id); + await r.seedError(); + const switchOwner = () => setCurrentDbClient(otherClient, 'other-account'); + if (boundary === 'before close') { + r.first.getUsageSnapshot = () => { switchOwner(); return { contextTokens: 0, contextWindow: 100 }; }; + } else if (boundary === 'before commit') { + const close = r.h.maker.closeSession.bind(r.h.maker); + r.h.maker.closeSession = async (...args) => { await close(...args); switchOwner(); }; + } else { + const persist = r.db.persistMessage; + t.mock.method(r.db, 'persistMessage', async (...args) => { await persist(...args); switchOwner(); }); + } + await assert.rejects(r.h.queue.contextRecoveryRollover().prepareUnhealthySession(r.id), /owner changed/); + assert.equal(r.close.mock.callCount(), boundary === 'before close' ? 0 : 1); + assert.equal(other.db.prepare('SELECT sdk_session_id AS thread FROM sessions WHERE id = ?').get(r.id).thread, 'other-thread'); + assert.equal(other.db.prepare("SELECT count(*) AS count FROM messages WHERE role = 'context_rebuild'").get().count, 0); + assert.equal(r.markers().length, boundary === 'before handoff' ? 1 : 0); + assert.equal(await r.pendingHandoff.peek(r.id), null); + }); +} + +test('pre-send recovery: a healthy decision cannot reuse the next owner\'s live session', async t => { + t = lifoCleanup(t); + const other = await recoveryDatabase(t); + const otherClient = getCurrentDbClientSnapshot().client; + const r = await preSendRecovery(t, 'claude-code'); + let changed = false; + r.first.getUsageSnapshot = () => { + setCurrentDbClient(otherClient, 'other-account'); + changed = true; + return { contextTokens: 1, contextWindow: 100 }; + }; + const getStatus = t.mock.fn(() => 'idle'); + r.first.getStatus = () => changed ? getStatus() : 'idle'; + await r.send('next'); + await waitFor(() => changed && Boolean(r.h.queue.projection(r.id).error)); + assert.equal(getStatus.mock.callCount(), 0, 'the old send never inspects the replacement owner\'s live session'); + assert.deepEqual(r.first.sent, ['first']); +}); + +// §3.2, integration. #4170 gives an already queued input priority over the failed turn. +// Its send independently checks the live window; a full window needs one new native instance. +for (const full of [false, true]) { + test('queued overflow gives way without replay or error: ' + (full ? 'full window rebuilds before dispatch' : 'healthy window keeps the runtime'), async t => { + const r = await assembledRecovery(lifoCleanup(t)); + const id = 'assembled-queued-behind'; + await r.db.createTask(id); + await r.h.queue.enqueue(id, { clientId: 'original', text: 'long task' }); + await waitFor(() => r.h.maker.getSession(id)?.sent.length === 1); + const first = r.h.maker.getSession(id); + r.db.db.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run('native-before-overflow', id); + first.getUsageSnapshot = () => ({ contextTokens: full ? 200_000 : 25_000, contextWindow: 200_000 }); + await r.h.queue.enqueue(id, { clientId: 'queued-behind', text: 'next' }); + first.emit({ type: 'error', data: OVERFLOW, sessionTurnGeneration: first.generation, sessionInstanceId: first.instanceId }); + await waitFor(() => r.h.maker.getSession(id)?.sent.some(text => text.endsWith('next'))); + const live = r.h.maker.getSession(id); + assert.equal(first === live, !full); + assert.deepEqual(first.sent, full ? ['long task'] : ['long task', 'next']); + assert.equal(r.rows(id, 'context_rebuild').length, full ? 1 : 0); + if (full) assert.deepEqual(live.sent, [r.marker(id).handoff + '\n\nnext']); + assert.deepEqual(r.rows(id, 'error'), []); + assert.equal(r.h.queue.projection(id).error, null); + assert.equal(r.h.events.some(event => event.sessionId === id && event.type === 'error'), false); + }); +} + +test('context recovery assembly: a summary not yet sent when the Host restarts goes with the next send, once', { timeout: 30_000 }, async t => { + const r = await assembledRecovery(t); + // The replay's runtime cannot start: the rebuild is committed, its summary never sent. + const create = r.h.maker.createSession.bind(r.h.maker); + let created = 0; + r.h.maker.createSession = async (...args) => { + if ((created += 1) === 2) throw new Error('engine unavailable'); + return create(...args); + }; + await r.overflow('assembled-restart'); + await waitFor(() => r.rows('assembled-restart', 'error').length === 1); + const { handoff, consumed } = r.marker('assembled-restart'); + assert.equal(consumed, false); + await r.h.queue.dispose(); + // A new Host process: a new queue and a new registry on the same database. + const restarted = assembledRuntime(t, r.db); + await restarted.h.queue.enqueue('assembled-restart', { clientId: 'after-restart', text: 'continue' }); + await waitFor(() => restarted.h.maker.sessions.get('assembled-restart')?.sent.length === 1); + const session = restarted.h.maker.sessions.get('assembled-restart'); + assert.deepEqual(session.sent, [`${handoff}\n\ncontinue`]); + await waitFor(() => r.marker('assembled-restart').consumed === true); + session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + await waitFor(() => !restarted.h.queue.projection('assembled-restart').running); + await restarted.h.queue.enqueue('assembled-restart', { clientId: 'after-restart-2', text: 'and again' }); + await waitFor(() => session.sent.length === 2); + assert.equal(session.sent[1], 'and again', 'sent once'); }); test('context recovery assembly: an engine switch summary left by the desktop goes with the Host\'s next send and its boundary is shown consumed', { timeout: 30_000 }, async t => { @@ -3273,3 +4986,3584 @@ test('context recovery assembly: an overflow of a closed kind takes the normal e assert.equal(r.h.maker.sessions.get('assembled-closed'), first, 'the runtime is not replaced'); assert.match(r.h.queue.projection('assembled-closed').error, /prompt is too long/); }); + +// Idle release (idle-release.ts) lives with one owner's input runtime: it scans only after main.ts +// starts it, and disposing the runtime (Host shutdown, sign-out, account switch) stops its watchers +// before the tasks are stopped, so nothing is released from a runtime that is going away. +test('idle release: watchers scan once started and stop when the owner runtime is disposed', async t => { + t.mock.timers.enable({ apis: ['setInterval'] }); + let scans = 0; + const h = createHarness({ readClaudeIdleMinutes: () => 30 }); + h.maker.listActiveSessions = () => { scans += 1; return []; }; + t.mock.timers.tick(60_000); + assert.equal(scans, 0, 'nothing scans before the runtime is ready'); + h.queue.startIdleRelease(); + t.mock.timers.tick(60_000); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(scans, 2, 'the Claude and Codex watchers scan each minute'); + await h.queue.dispose(); + scans = 0; + t.mock.timers.tick(120_000); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(scans, 0, 'a disposed runtime scans no more'); +}); + +// Rule: ordinary Claude tasks use the desktop's idle deadline after the Host resumes accepting input. +// Gap: lifting a hold disposed the original watchers but never started their replacements. +// Minimal input: hold and release, then let one ordinary live task reach the idle limit. +// Tier: unit through the Host queue and actual idle watcher, with a fixture DB and clock. +test('idle release: a task still releases on schedule after a desktop hold', async t => { + t = lifoCleanup(t); + t.mock.timers.enable({ apis: ['setInterval'] }); + const db = await recoveryDatabase(t); + const id = 'idle-after-hold'; + const sdkId = 'idle-native-session'; + await db.createTask(id); + db.db.prepare('UPDATE sessions SET sdk_session_id = ? WHERE id = ?').run(sdkId, id); + + let now = 0; + const h = createHarness({ readClaudeIdleMinutes: () => 1, idleReleaseClock: { monotonic: () => now, wall: () => now } }); + t.after(() => h.queue.dispose()); + h.queue.startIdleRelease(); + h.queue.holdForDesktop('Desktop is using the profile'); + assert.equal(await h.queue.releaseDesktopHold(), true); + assert.equal(await h.queue.releaseDesktopHold(), true, 'a duplicate release has nothing to rebuild'); + + const session = await h.maker.createSession({ id, agentKind: 'claude-code' }); + Object.assign(session, { + sdkSessionId: sdkId, getStatus: () => 'active', listBackgroundTasks: () => [], + countPendingWakeContinuations: () => 0, manageAsyncUserQuestions: () => ({ questions: [] }), + }); + t.mock.timers.tick(60_000); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(h.maker.getSession(id), session, 'the first scan starts the task’s idle clock'); + + now = 60_000; + t.mock.timers.tick(60_000); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(h.maker.getSession(id), null, 'the next scan releases the idle task'); +}); + +// Claude's background-activity detection (claude-session-background-activity.ts) needs the logical +// turn's start and end; the Host feeds them from its event stream at the desktop's points, so model +// calls the proxy records after the turn ended mark the task busy (idle release keeps it). +test('idle release: a Claude turn\'s start and end reach background-activity detection', async t => { + t.mock.timers.enable({ apis: ['Date'], now: Date.parse('2026-11-15T00:00:00Z') }); + const { recordClaudeApiActivity, getClaudeSessionBackgroundActivity, resetClaudeBackgroundActivityForTests } = + await import('../../../desktop/src/main/maker-host/claude-session-background-activity.ts'); + t.after(() => resetClaudeBackgroundActivityForTests()); + const h = createHarness(); + t.after(() => h.queue.dispose()); + await h.queue.enqueue('bg', { clientId: 'first', text: 'work' }); + await waitFor(() => h.maker.sessions.get('bg')?.sent.length === 1); + const session = h.maker.sessions.get('bg'); + session.emit({ type: 'status', data: { isRunning: true } }); + recordClaudeApiActivity('native-bg', 'bg'); + assert.equal(getClaudeSessionBackgroundActivity('bg'), false, 'calls during the turn are the turn\'s own'); + session.emit({ type: 'done', data: {} }); + t.mock.timers.tick(5_000); + recordClaudeApiActivity('native-bg', 'bg'); + assert.equal(getClaudeSessionBackgroundActivity('bg'), true, 'calls after the turn ended are background work'); +}); + +// Unit: a send to an archived task makes it active before the turn is dispatched (the send +// transaction's restoreArchivedSessionForSend, which main.ts binds to task-restore.ts; the restore +// itself is tested in session-update.test.mjs). Gap: the Host sent without restoring. +test('a send restores the task through the send transaction before the turn is dispatched', async () => { + const restores = []; + let h; + h = createHarness({ restoreArchivedSessionForSend: async id => { + restores.push([id, h.maker.getSession(id)?.sent.length ?? 0]); + } }); + try { + await enqueue(h, 'archived-task', { clientId: 'resumes', text: 'continue' }); + // Restored once, while nothing had been sent to the Agent yet. + assert.deepEqual(restores, [['archived-task', 0]]); + assert.equal(h.maker.getSession('archived-task').sent.length, 1); + } finally { + await h.queue.dispose(); + } +}); + +// Unit: the send's working-directory check is the desktop's (working-directory.ts over +// createWorkingDirectoryPreflight). Real directories on disk; the Agent is the fake Maker. +// - An ordinary directory that was deleted (its disk still there) is recreated empty, and the send +// carries the recovery note once (Gap: the Host failed the send). A conversation recovery directory +// in the profile is used only when the disk itself is unavailable, as on the desktop. +// - A managed worktree that is gone fails the send at once with the Host's failure, and no recovery +// directory is taken: the Host must not answer `gone` before it can restore worktrees. +test('a send to a task whose ordinary directory was deleted recreates it and carries the note once', async t => { + const gone = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-gone-dir-')); + rmSync(gone, { recursive: true, force: true }); + t.after(() => rmSync(gone, { recursive: true, force: true })); + const h = createHarness({ statDirectory: undefined, + readSession: async id => ({ id, status: 'active', agentKind: 'claude-code', model: 'm', workingDir: gone, providerId: 'xd', + permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + await enqueue(h, 'gone-dir', { clientId: 'first', text: 'first' }); + const session = h.maker.getSession('gone-dir'); + assert.equal(h.maker.sessions.get('gone-dir').options.workingDir, gone); + assert.equal(existsSync(gone), true, 'the directory is recreated'); + assert.match(session.sent[0], /\[Working directory recovery\]\nThe working directory was missing\. Cindy recreated the directory/); + assert.match(session.sent[0], /first$/); + session.emit({ type: 'done', data: {} }); + await enqueueUntilSent(h, 'gone-dir', { clientId: 'second', text: 'second' }, 2); + assert.equal(session.sent[1], 'second', 'the note is carried once'); +}); + +// Rule (main e322628568, the desktop's working directory recovery: canRecreateOwnerWorkingDirectory): +// generic recovery recreates a missing directory only inside the active owner's namespace; a folder +// under another owner's directory in the profile is not recreated. Gap: the Host bound no such check, +// so a send could recreate an inactive owner's folder. +test('a send to a task whose directory was in another owner\'s namespace does not recreate it', async t => { + // The profile root as the recovery reads it now (other tests in this file reconfigure it). + const root = getUserDataDir(); + const other = path.join(root, 'owners', 'another-owner-key', 'workspace', 'gone'); + t.after(() => rmSync(path.join(root, 'owners', 'another-owner-key'), { recursive: true, force: true })); + const h = createHarness({ statDirectory: undefined, + readSession: async id => ({ id, status: 'active', agentKind: 'claude-code', model: 'm', workingDir: other, providerId: 'xd', + permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + await h.queue.enqueue('other-owner-dir', { clientId: 'first', text: 'first' }); + await waitFor(() => h.queue.projection('other-owner-dir').error); + assert.equal(existsSync(other), false, 'the other owner\'s folder is not recreated'); + assert.equal(h.maker.getSession('other-owner-dir') ?? null, null, 'no Agent started'); +}); + +test('a send to a task whose managed worktree is gone fails at once without a recovery directory', async t => { + const repo = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-worktree-repo-')); + t.after(() => rmSync(repo, { recursive: true, force: true })); + const worktree = path.join(repo, '.cindy-worktrees', 'gone-tree'); + const h = createHarness({ statDirectory: undefined, + readSession: async id => ({ id, status: 'active', agentKind: 'claude-code', model: 'm', workingDir: worktree, providerId: 'xd', + permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + await h.queue.enqueue('gone-tree', { clientId: 'first', text: 'first' }); + await waitFor(() => h.queue.projection('gone-tree').error); + assert.match(h.queue.projection('gone-tree').error, /working directory is missing for session gone-tree/); + assert.equal(h.maker.getSession('gone-tree') ?? null, null, 'no Agent started'); + assert.equal(existsSync(worktree), false); + const dialogues = path.join(unitProfile, 'owners'); + const recoveryDirs = existsSync(dialogues) + ? readdirSync(dialogues, { recursive: true }).filter(entry => String(entry).includes('worktree-recovery')) : []; + assert.deepEqual(recoveryDirs, [], 'no "unrestored worktree" recovery directory'); +}); + +// Unit, over a migrated profile database: the send transaction's plan reconciliation, goal and +// model-attribution ports (turn-executor.mjs), with the desktop's shared readers and writers. +// - Rule: a send carries the open plan of an interrupted Codex plan and the inactive-goal note +// after a goal verdict, read behind the task's durable writes; a dispatched user turn records +// the model that ran it, and a change of model adds one model-change card (register.ts). +// - Gap: the Host carried neither note and recorded no model. +async function notesFixture(t) { + // The queue's owner is the database it opens: close the queue before the database (last in, first out). + t = lifoCleanup(t); + const db = await recoveryDatabase(t); + const stored = { model: 'model-a' }; + const h = createHarness({ persistMessage: db.persistMessage, getOwner: getCurrentDbClientSnapshot, + readSession: async id => ({ id, status: 'active', agentKind: 'codex', model: stored.model, workingDir: db.root, + providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + return { db, h, stored }; +} + +test('a send carries the open steps of an interrupted Codex plan', { timeout: 30_000 }, async t => { + const { db, h } = await notesFixture(t); + await db.createTask('plan-task'); + db.db.prepare("UPDATE sessions SET agent_kind = 'codex' WHERE id = 'plan-task'").run(); + await writeCodexPlanUpdate('plan-task', { turnId: 'turn-1', plan: [ + { step: 'Read the code', status: 'completed' }, { step: 'Write the fix', status: 'in_progress' }] }); + await markCodexPlanInterrupted('plan-task', 'turn-1'); + await enqueue(h, 'plan-task', { clientId: 'next', text: 'continue' }); + const sent = h.maker.getSession('plan-task').sent[0]; + assert.ok(sent.includes(buildPlanReconcileNote({ openSteps: ['Write the fix'], totalSteps: 2 })), sent); + assert.match(sent, /continue$/); +}); + +test('a send after a goal verdict, with no running goal, carries the inactive-goal note', { timeout: 30_000 }, async t => { + const { db, h } = await notesFixture(t); + await db.createTask('goal-task'); + await db.persistMessage('goal-task', { clientId: 'verdict', role: 'assistant', + content: 'Done.\n```json\n{"goal_status":"achieved","reason":"all set"}\n```' }); + await enqueue(h, 'goal-task', { clientId: 'next', text: 'one more thing' }); + const sent = h.maker.getSession('goal-task').sent[0]; + assert.ok(sent.startsWith(buildGoalInactiveNote()), sent); +}); + +test('a dispatched user turn records its model, and a changed model adds one model-change card', { timeout: 30_000 }, async t => { + const { db, h, stored } = await notesFixture(t); + await db.createTask('model-task'); + await enqueue(h, 'model-task', { clientId: 'first', text: 'first' }); + const session = h.maker.getSession('model-task'); + const meta = clientId => JSON.parse(db.db.prepare('SELECT agent_meta FROM messages WHERE session_id = ? AND client_id = ?') + .get('model-task', clientId)?.agent_meta ?? 'null'); + await waitFor(() => meta('first')?.executionModel); + assert.deepEqual(meta('first').executionModel, { agentKind: 'codex', model: 'model-a', providerId: 'xd' }); + session.emit({ type: 'done', data: {} }); + // The task's model changes between the two turns (the next send applies the stored settings). + stored.model = 'model-b'; + await h.queue.enqueue('model-task', { clientId: 'second', text: 'second' }); + await waitFor(() => meta('model-change:second')); + assert.equal(meta('second').executionModel.model, 'model-b'); + assert.deepEqual(Object.keys(meta('model-change:second')), ['modelChange']); + assert.equal(db.db.prepare("SELECT count(*) AS n FROM messages WHERE session_id = 'model-task' AND client_id LIKE 'model-change:%'").get().n, 1); +}); + +// Unit, over a migrated profile database: a user turn stored but not dispatched (the coordinator's +// persistTerminalSendError and onPersistedSendRejected, register.ts). +// - Rule: the task gets a retryable error row with the failure, as on the desktop; a Pi prompt +// timeout also closes the stuck native process, without a replay. +// - Gap: the Host kept only the projection's error: after a restart the task showed the user's +// message with no error and no retry. +async function undispatchedFixture(t, failure) { + // The queue's owner is the database it opens: close the queue before the database (last in, first out). + t = lifoCleanup(t); + const db = await recoveryDatabase(t); + const h = createHarness({ persistMessage: db.persistMessage, getOwner: getCurrentDbClientSnapshot, + readSession: async id => ({ id, status: 'active', agentKind: 'claude-code', model: 'm', workingDir: db.root, + providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + const create = h.maker.createSession.bind(h.maker); + h.maker.createSession = async opts => { + const session = await create(opts); + // The vendor fails after the transaction accepted the turn (its user row is stored). + session.send = async (_text, sendOpts = {}) => { + sendOpts.onTurnReserved?.(++session.generation); + await sendOpts.beforeProviderStart?.(); + await sendOpts.onAccepted?.(sendOpts.signal); + throw new Error(failure); + }; + return session; + }; + return { db, h }; +} + +test('a stored user turn that fails to dispatch leaves a retryable error row', { timeout: 30_000 }, async t => { + const { db, h } = await undispatchedFixture(t, 'vendor failed'); + await db.createTask('undispatched'); + await h.queue.enqueue('undispatched', { clientId: 'lost', text: 'hello' }); + await waitFor(() => db.errorRows('undispatched').length > 0); + const rows = db.db.prepare("SELECT role, content FROM messages WHERE session_id = 'undispatched' ORDER BY rowid").all(); + assert.deepEqual(rows.map(row => row.role), ['user', 'error']); + assert.match(rows[1].content, /vendor failed/); + assert.match(h.queue.projection('undispatched').error, /vendor failed/); + assert.ok(h.maker.getSession('undispatched'), 'an ordinary failure keeps the runtime'); +}); + +test('a Pi prompt timeout after the user turn is stored also closes the stuck runtime', { timeout: 30_000 }, async t => { + const { db, h } = await undispatchedFixture(t, 'Pi RPC timeout after 30000ms: prompt'); + await db.createTask('pi-timeout'); + await h.queue.enqueue('pi-timeout', { clientId: 'stuck', text: 'hello' }); + await waitFor(() => db.errorRows('pi-timeout').length > 0); + await waitFor(() => !h.maker.getSession('pi-timeout')); + const [error] = db.db.prepare("SELECT agent_meta FROM messages WHERE session_id = 'pi-timeout' AND role = 'error'").all(); + assert.ok(error); +}); + +// Unit, over a migrated profile database: a zero-output retry replaces the failed turn +// (supersedeRetriedUserTurn, retriedUserTurnSupersede.ts): the old user row and its error row are +// hidden and clients are told they were deleted. Gap: the Host kept both turns. +test('a retried turn hides the user row and error row it replaces', { timeout: 30_000 }, async t => { + const db = await recoveryDatabase(t); + await db.createTask('retry-task'); + await db.persistMessage('retry-task', { clientId: 'old-user', role: 'user', content: 'hello' }); + await db.persistMessage('retry-task', { clientId: 'old-error', role: 'error', content: 'failed' }); + await db.persistMessage('retry-task', { clientId: 'retry-user', role: 'user', content: 'hello' }); + const events = []; + const recovery = createHostMessageRecovery({ getOwner: getCurrentDbClientSnapshot, publish: event => events.push(event) }); + const hidden = await recovery.supersedeRetriedUserTurn('retry-task', { supersededUserClientId: 'old-user', retryUserClientId: 'retry-user' }); + assert.deepEqual(hidden.sort(), ['old-error', 'old-user']); + const visible = db.db.prepare("SELECT client_id FROM messages WHERE session_id = 'retry-task' AND rewind_at IS NULL").all(); + assert.deepEqual(visible.map(row => row.client_id), ['retry-user']); + assert.equal(events.filter(event => event.type === 'message_deleted').length, 1); +}); + +// Unit, over a migrated profile database: session references from the composer +// (resolveSessionReferences, sessionReferenceResolverCore.ts). Rule: a referenced task's messages +// reach the Agent with the input; another device's task needs Device Link, which the Host lacks, so +// it is unavailable as on a desktop with no link, and the message goes without it. Gap: the Host +// dropped every reference. +test('a send carries a referenced task\'s messages; another device\'s task is left out', { timeout: 30_000 }, async t => { + t = lifoCleanup(t); // close the queue before the database it is owned by + const db = await recoveryDatabase(t); + const h = createHarness({ persistMessage: db.persistMessage, getOwner: getCurrentDbClientSnapshot, + resolveSessionReferences: (refs, options) => resolveSessionReferencesWithPorts({ + getSelfDeviceId: () => 'host-device', + invokeRemote: async () => ({ ok: false, error: { code: 'NOT_CONNECTED', message: 'Host has no Device Link' } }), + }, refs, options), + readSession: async id => ({ id, status: 'active', agentKind: 'claude-code', model: 'm', workingDir: db.root, + providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + await db.createTask('quoted'); + await db.persistMessage('quoted', { clientId: 'q-user', role: 'user', content: 'the quoted question' }); + await db.persistMessage('quoted', { clientId: 'q-reply', role: 'assistant', content: 'the quoted answer' }); + await db.createTask('quoting'); + await enqueue(h, 'quoting', { clientId: 'with-ref', text: 'look at this', sessionRefs: [{ sessionId: 'quoted' }] }); + const wire = JSON.stringify(h.maker.getSession('quoting').sent[0]); + assert.match(wire, /the quoted answer/); + + // Unavailable references are an optional enrichment on the desktop: the message is still sent, + // without quoted history (agent-input-coordinator.ts resolveReferenceContexts). + await db.createTask('remote-quoting'); + await enqueue(h, 'remote-quoting', { clientId: 'remote-ref', text: 'and this', sessionRefs: [{ sessionId: 'elsewhere', deviceId: 'other-device' }] }); + assert.equal(JSON.stringify(h.maker.getSession('remote-quoting').sent[0]), JSON.stringify('and this')); +}); + +// Unit, over a migrated profile database: how /api/chat (chat.mjs) ends a message's stream when the +// turn stops on an error. Rule: a user turn stored but not dispatched gets its error row, then the +// input's interrupted receipt, and the stream ends; a reconnect with the same clientId is told +// "interrupted" at once. An error after dispatch still ends on its terminal event, with no receipt. +// Gap: the stream for a stored-but-undispatched turn never ended. (Context recovery through +// /api/chat, whose claimed error stores no row, keeps its stream open: tests above.) +async function chatFixture(t, { failAfterAccept = false } = {}) { + // The queue's owner is the database it opens: close the queue before the database (last in, first out). + t = lifoCleanup(t); + const hub = createEventHub(); + const db = await recoveryDatabase(t); + const h = createHarness({ hub, + persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: event => hub.publish(event) }), + getOwner: getCurrentDbClientSnapshot, getPersistedClientIds: getPersistedInputClientIds, + readSession: async id => ({ id, status: 'active', agentKind: 'claude-code', model: 'm', workingDir: db.root, + providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + if (failAfterAccept) { + const create = h.maker.createSession.bind(h.maker); + h.maker.createSession = async opts => { + const session = await create(opts); + session.send = async (_text, sendOpts = {}) => { + sendOpts.onTurnReserved?.(++session.generation); + await sendOpts.beforeProviderStart?.(); + await sendOpts.onAccepted?.(sendOpts.signal); + throw new Error('vendor failed'); + }; + return session; + }; + } + const open = async (id, clientId) => { + const writes = []; + const response = Object.assign(new EventEmitter(), { + writableEnded: false, headersSent: false, + writeHead(status) { this.statusCode = status; this.headersSent = true; }, + write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); }, + }); + const chat = createChatHandler({ events: hub, readSession: async sid => ({ id: sid, status: 'active' }), + createSession: async () => { throw new Error('the task exists'); }, + enqueue: (sid, input) => h.queue.enqueue(sid, input), inputStatus: (sid, cid) => h.queue.inputStatus(sid, cid) }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId: id, clientId, prompt: 'hello' }))]), response); + const streamed = () => writes.join('').split('\n\n').filter(line => line.startsWith('data: ')).map(line => JSON.parse(line.slice(6))); + return { response, streamed }; + }; + return { db, h, open }; +} + +test('/api/chat: a stored turn that fails to dispatch streams its error row, then its interrupted receipt, and ends; a reconnect ends at once', { timeout: 30_000 }, async t => { + const c = await chatFixture(t, { failAfterAccept: true }); + await c.db.createTask('chat-undispatched'); + const first = await c.open('chat-undispatched', 'chat-lost'); + await waitFor(() => first.response.writableEnded); + const types = first.streamed().map(event => event.type); + const errorRow = types.indexOf('error_persisted'); + const receipt = first.streamed().findIndex(event => event.type === 'input_receipt' && event.inputClientId === 'chat-lost'); + assert.ok(errorRow >= 0 && receipt > errorRow, `error row, then receipt: ${types.join(',')}`); + assert.equal(first.streamed()[receipt].status, 'interrupted'); + assert.equal(first.streamed().filter(event => event.type === 'input_receipt').length, 1); + assert.equal(c.db.errorRows('chat-undispatched').length, 1); + + const again = await c.open('chat-undispatched', 'chat-lost'); + assert.equal(again.response.writableEnded, true, 'the reconnect ends at once'); + assert.deepEqual(again.streamed().filter(event => event.type === 'input_receipt').map(event => event.status), ['interrupted']); + assert.equal(c.db.errorRows('chat-undispatched').length, 1, 'the reconnect does not resend'); +}); + +test('/api/chat: an error after dispatch ends the stream on its terminal event, with no interrupted receipt', { timeout: 30_000 }, async t => { + const c = await chatFixture(t); + await c.db.createTask('chat-terminal'); + const stream = await c.open('chat-terminal', 'chat-runs'); + await waitFor(() => c.h.maker.getSession('chat-terminal')?.sent.length === 1); + const session = c.h.maker.getSession('chat-terminal'); + session.emit({ type: 'error', data: { message: 'model failed' }, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + await waitFor(() => stream.response.writableEnded); + assert.equal(stream.streamed().filter(event => event.type === 'input_receipt').length, 0); + assert.ok(stream.streamed().some(event => event.type === 'error' && event.inputClientId === 'chat-runs')); +}); + +// Unit, over the assembled recovery: a reconnect to /api/chat while context recovery is rebuilding +// (the claimed turn has ended, its replay is not yet accepted). Rule: the input is still being +// answered, so the reconnect's stream stays open and ends after the replay's done with its answer. +// Gap: inputStatus took the recovery point for an interrupted input and the stream ended at once. +test('/api/chat: a reconnect while context recovery rebuilds stays open and ends after the replay', { timeout: 30_000 }, async t => { + const hub = createEventHub(); + const r = await assembledRecovery(t, { hub }); + let releaseRebuild; + const rebuildHeld = new Promise(resolve => { releaseRebuild = resolve; }); + // Hold the rebuild where it closes the overflowed runtime, before the replay starts. + const close = r.h.maker.closeSession.bind(r.h.maker); + let closing = 0; + r.h.maker.closeSession = async id => { closing += 1; await rebuildHeld; return close(id); }; + const first = await r.overflow('reconnect-recovery'); + await waitFor(() => closing > 0); + await waitFor(() => !first.running && r.h.queue.projection('reconnect-recovery').recovery); + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + const writes = []; + const response = Object.assign(new EventEmitter(), { + writableEnded: false, headersSent: false, + writeHead(status) { this.statusCode = status; this.headersSent = true; }, + write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); }, + }); + const chat = createChatHandler({ events: hub, readSession: async id => ({ id, status: 'active' }), + createSession: async () => { throw new Error('the task exists'); }, + enqueue: (id, input) => r.h.queue.enqueue(id, input), inputStatus: (id, clientId) => r.h.queue.inputStatus(id, clientId) }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId: 'reconnect-recovery', clientId: 'reconnect-recovery-input', prompt: 'long task' }))]), response); + assert.equal(response.writableEnded, false, 'the reconnect stays open while the recovery rebuilds'); + releaseRebuild(); + await waitFor(() => { const next = r.h.maker.sessions.get('reconnect-recovery'); return next && next !== first && next.sent.length === 1; }); + const replayed = r.h.maker.sessions.get('reconnect-recovery'); + const stamp = { sessionTurnGeneration: replayed.generation, sessionInstanceId: replayed.instanceId }; + replayed.emit({ type: 'text', data: { text: 'replayed answer' }, ...stamp }); + replayed.emit({ type: 'done', data: {}, ...stamp }); + await waitFor(() => response.writableEnded); + const streamed = writes.join('').split('\n\n').filter(line => line.startsWith('data: ')).map(line => JSON.parse(line.slice(6))); + assert.ok(streamed.some(event => event.type === 'text' && event.inputClientId === 'reconnect-recovery-input'), 'the replay\'s answer reaches the reconnect'); + assert.equal(streamed.filter(event => event.type === 'input_receipt' && event.status === 'interrupted').length, 0); + // As above: the turn's last writes settle after the stream ends; the fixture closes the database first. + await waitFor(() => !r.h.queue.projection('reconnect-recovery').turnInProgress); +}); + + +// ── Checkpoint 4b: interrupted-turn auto-resume through /api/chat ───────────────────────────────── +// Rule: an automatic resume answers the input whose turn was interrupted (register.ts, the shared +// hooks); the stream of that input follows the resume and every way the resume ends gives the stream +// an end, with the held error row written exactly once when it gives up (release table 4b). +const INTERRUPTION = { message: 'Upstream overloaded', reason: 'upstream-overload', isTerminal: true }; +async function resumeHarness(t, overrides = {}) { + const hub = createEventHub(); + const h = createHarness({ hub, hasAssistantProgressAfter: async () => true, ...overrides }); + const writes = []; + const response = Object.assign(new EventEmitter(), { + writableEnded: false, headersSent: false, + writeHead() { this.headersSent = true; }, + write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); }, + }); + const chat = createChatHandler({ events: hub, readSession: async id => ({ id, status: 'active' }), + enqueue: (id, input) => h.queue.enqueue(id, input), inputStatus: (id, clientId) => h.queue.inputStatus(id, clientId) }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId: 'r', clientId: 'a', prompt: 'long job' }))]), response); + await waitFor(() => h.maker.sessions.get('r')?.sent.length === 1); + const session = h.maker.sessions.get('r'); + t.mock.timers.enable({ apis: ['setTimeout'] }); + const streamed = () => writes.filter(w => w.startsWith('data:')).map(w => JSON.parse(w.slice(5))); + const errorRows = () => h.persisted.filter(row => row.role === 'error'); + // As Maker stamps every event of a turn with the attempt token its send carried (maker-core + // session.ts; the resume's send carries it): the guard clears a resume's pending attempt on its + // first stamped event, so an unstamped fixture would never resume twice. + const interrupt = async () => { + const token = session.sendOptions.at(-1)?.turnAttemptToken; + const stamp = typeof token === 'number' ? { turnAttemptToken: token } : {}; + session.emit({ type: 'text', data: { text: 'half done', isFinal: true }, ...stamp }); + session.emit({ type: 'error', data: INTERRUPTION, ...stamp }); + await settle(); + }; + // Until the engine has received `count` messages: a message reaches it only after its send's + // working-directory check, which a fixed settle() does not wait for (settleUntil). + const dispatched = count => settleUntil(() => session.sent.length >= count, `${count} message(s) sent to the engine`); + // The resume's backoff on the mocked clock, then the resume's own send. + const backoff = async (sent) => { + for (let i = 0; i < 100 && session.sent.length < sent; i += 1) { t.mock.timers.tick(500); await settle(); } + await dispatched(sent); + }; + return { h, session, response, streamed, errorRows, interrupt, backoff, dispatched }; +} + +test('auto-resume exit 1: the resumed turn answers the input and ends its stream, with no error row', async t => { + const r = await resumeHarness(t); + await r.interrupt(); + assert.equal(r.response.writableEnded, false, 'the stream follows the resume'); + assert.ok(r.streamed().some(e => e.type === 'error' && e.autoResumePending?.attempt === 1)); + assert.equal(await r.h.queue.inputStatus('r', 'a'), 'running'); + await r.backoff(2); + r.session.emit({ type: 'text', data: { text: 'resumed and finished', isFinal: true } }); + r.session.emit({ type: 'done', data: {} }); + await settle(); + assert.equal(r.response.writableEnded, true); + assert.ok(r.streamed().some(e => e.type === 'text' && e.autoResumeOf === 'a')); + assert.deepEqual(r.errorRows(), []); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +test('auto-resume exit 2: interruptions until the budget is spent end the stream on the last error, written once', async t => { + const r = await resumeHarness(t); + for (let sent = 2; sent < 20; sent += 1) { + await r.interrupt(); + if (r.response.writableEnded) break; + await r.backoff(sent); + } + assert.equal(r.response.writableEnded, true); + // Consecutive interruptions are each resumed until the budget is spent (more than one resume). + assert.ok(r.session.sent.length > 2, `resumed ${r.session.sent.length - 1} time(s)`); + const last = r.streamed().filter(e => e.type === 'error').at(-1); + assert.equal(last.autoResumePending, undefined); + assert.equal(r.errorRows().length, 1); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +// Rule: a person's message is written through the one user-row entry (register.ts +// createUserMessageDurably, wired into the send transaction at register.ts:17811), which recharges the +// resume budget. Gap: the Host's send transaction wrote the user row directly, so after a spent +// budget a person's next message was never resumed. Minimal failing input: spend the budget, send a +// new message, interrupt its turn. +test('auto-resume budget: a person\'s message after a spent budget is resumed again', async t => { + const r = await resumeHarness(t); + let sent = 2; + for (; sent < 20; sent += 1) { + await r.interrupt(); + if (r.response.writableEnded) break; + await r.backoff(sent); + } + assert.equal(r.response.writableEnded, true, 'the budget is spent'); + const before = r.session.sent.length; + await r.h.queue.enqueue('r', { clientId: 'b', text: 'try once more' }); + await r.dispatched(before + 1); + assert.equal(r.session.sent.length, before + 1); + await r.interrupt(); + await r.backoff(before + 2); + assert.equal(r.session.sent.length, before + 2, 'the new message\'s turn is resumed'); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +// Rule: the user row is written behind the task's reply rows, and a failed one goes back to the +// caller as on the desktop, whose write FIFO never pauses (messagePersistBroadcaster.ts +// enqueueDurableWrite without onPersistenceError): the input stays as an error with its retry text, +// a retry writes and sends it once, and a new message replaces it without its row ever appearing. +// Gap: through the Host's pausing FIFO the failed row was replayed on resume, so a replaced input +// left a row it never ran under (and a retried one stayed undispatched). Minimal failing input: a +// user row that fails once, then a new message, or a retry. +test('a failed user row leaves its input to retry or replace, and is never written later', async t => { + let failUser = true; + const attempts = []; + const hub = createEventHub(); + const h = createHarness({ hub, persistMessage: async (sessionId, input) => { + if (input.role === 'user') { attempts.push(input.clientId); if (failUser) throw new Error('disk full'); } + h.persisted.push({ sessionId, ...input }); + } }); + t.after(() => h.queue.dispose()); + const writes = []; + const response = Object.assign(new EventEmitter(), { writableEnded: false, headersSent: false, + writeHead() { this.headersSent = true; }, write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); } }); + const chat = createChatHandler({ events: hub, readSession: async id => ({ id, status: 'active' }), + enqueue: (id, input) => h.queue.enqueue(id, input), inputStatus: (id, clientId) => h.queue.inputStatus(id, clientId) }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId: 'u', clientId: 'a', prompt: 'first' }))]), response); + await waitFor(() => h.queue.projection('u').error === 'disk full'); + const session = () => h.maker.sessions.get('u'); + const userRows = () => h.persisted.filter(row => row.role === 'user').map(row => row.clientId); + // The failed input: not sent, not written, kept with its retry text; its stream ended interrupted. + assert.deepEqual(session()?.sent ?? [], []); + assert.equal(h.queue.projection('u').queuePaused, false, 'reply writes are not paused'); + assert.equal(h.queue.projection('u').errorRetryText, 'first'); + assert.equal(response.writableEnded, true); + const streamed = writes.filter(w => w.startsWith('data:')).map(w => JSON.parse(w.slice(5))); + assert.ok(streamed.some(e => e.type === 'input_receipt' && e.status === 'interrupted')); + assert.equal(await h.queue.inputStatus('u', 'a'), 'interrupted'); + // A new message replaces it: its row never appears, even after later writes drain. + failUser = false; + await h.queue.enqueue('u', { clientId: 'b', text: 'instead' }); + await waitFor(() => session()?.sent.length === 1); + session().emit({ type: 'text', data: { text: 'answer', isFinal: true } }); + session().emit({ type: 'done', data: {} }); + await waitFor(() => !h.queue.projection('u').turnInProgress); + await h.queue.resume('u'); + await settle(); + assert.deepEqual(session().sent, ['instead']); + assert.deepEqual(userRows(), ['b']); + assert.deepEqual(attempts, ['a', 'b']); +}); + +// Rule: an auto-resume's user row registers its pending outcome before the write and releases it +// when the write fails (userMessageDurableWrite.ts releasePendingOutcomeOnFailure). Gap: the Host's +// wrapper decides how a failure reaches that shared branch (the error is turned into a value inside +// the write FIFO and thrown after it); a wrapper that swallowed it would leave the outcome pending. +// Minimal failing input: the resume's user row fails once; the task must still resume a later turn. +test('an auto-resume whose user row fails leaves the task able to resume again', async t => { + let failResumeRow = true; + let resumeRowAttempts = 0; + const r = await resumeHarness(t, { persistMessage: async (sessionId, input) => { + if (input.role === 'user' && input.agentMeta?.autoResume === true) { + resumeRowAttempts += 1; + if (failResumeRow) throw new Error('disk full'); + } + } }); + await r.interrupt(); + for (let i = 0; i < 100 && resumeRowAttempts === 0; i += 1) { t.mock.timers.tick(500); await settle(); } + // The resume writes its user row after its send's working-directory check (settleUntil). + await settleUntil(() => resumeRowAttempts > 0, 'the resume reached its user row'); + assert.equal(resumeRowAttempts, 1, 'the resume reached its user row'); + assert.equal(r.session.sent.length, 1, 'the resume whose row failed was not sent'); + failResumeRow = false; + await r.h.queue.enqueue('r', { clientId: 'b', text: 'carry on' }); + await r.dispatched(2); + assert.equal(r.session.sent.length, 2); + await r.interrupt(); + await r.backoff(3); + assert.equal(r.session.sent.length, 3, 'the next interrupted turn is resumed'); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +test('a retried user row is written and sent once', async t => { + let failUser = true; + const h = createHarness({ persistMessage: async (sessionId, input) => { + if (input.role === 'user' && failUser) throw new Error('disk full'); + h.persisted.push({ sessionId, ...input }); + } }); + t.after(() => h.queue.dispose()); + await h.queue.enqueue('v', { clientId: 'a', text: 'first' }); + await waitFor(() => h.queue.projection('v').error === 'disk full'); + failUser = false; + await h.queue.retryLastError('v'); + await waitFor(() => h.maker.sessions.get('v')?.sent.length === 1); + await settle(); + assert.deepEqual(h.maker.sessions.get('v').sent, ['first']); + assert.deepEqual(h.persisted.filter(row => row.role === 'user').map(row => row.clientId), ['a']); +}); + +test('auto-resume exit 3: a new message during the wait cancels the resume and ends the stream interrupted', async t => { + const r = await resumeHarness(t); + await r.interrupt(); + await r.h.queue.enqueue('r', { clientId: 'b', text: 'never mind, do this instead' }); + await r.dispatched(2); + await settle(); + assert.equal(r.response.writableEnded, true); + assert.ok(r.streamed().some(e => e.type === 'input_receipt' && e.status === 'interrupted')); + assert.equal(r.errorRows().length, 1); + t.mock.timers.tick(30_000); await settle(); + assert.deepEqual(r.session.sent, ['long job', 'never mind, do this instead']); + assert.notEqual(await r.h.queue.inputStatus('r', 'a'), 'running'); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +test('auto-resume exit 4: a stop during the wait ends the stream interrupted, with the error row once', async t => { + const r = await resumeHarness(t); + await r.interrupt(); + await r.h.queue.stop('r'); + await settle(); + assert.equal(r.response.writableEnded, true); + assert.equal(r.errorRows().length, 1); + t.mock.timers.tick(30_000); await settle(); + assert.equal(r.session.sent.length, 1, 'no resume after the stop'); + t.mock.timers.reset(); + await r.h.queue.dispose(); + assert.equal(r.errorRows().length, 1); +}); + +test('auto-resume exit 5: closing the task during the wait ends the stream interrupted, with the error row once', async t => { + const r = await resumeHarness(t); + await r.interrupt(); + await r.h.queue.disposeSession('r'); + await settle(); + assert.equal(r.response.writableEnded, true); + assert.equal(r.errorRows().length, 1); + t.mock.timers.tick(30_000); await settle(); + assert.equal(r.session.sent.length, 1); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +test('auto-resume exit 6: a Host shutdown during the wait gives the resume up first and writes the error row once', async t => { + const r = await resumeHarness(t); + await r.interrupt(); + await r.h.queue.dispose(); + assert.equal(r.errorRows().length, 1); + t.mock.timers.tick(30_000); await settle(); + assert.equal(r.session.sent.length, 1); + t.mock.timers.reset(); +}); + +function providePiWindows(r) { + const create = r.h.maker.createSession; + r.h.maker.createSession = async options => { + const session = await create(options); + session.previewModelSwitch = async model => ({ action: 'hot', targetContextWindow: SWITCH_WINDOWS[model], windowVerified: true }); + session.getUsageSnapshot = () => ({ contextTokens: 0, tokenUsage: 0, contextWindow: SWITCH_WINDOWS[session.model], costUsd: 0 }); + return session; + }; +} + +function runtimeCancellations(r, id) { + const persisted = r.db.db.prepare("SELECT content FROM messages WHERE session_id = ? AND role = 'error'").all(id) + .map(row => JSON.parse(row.content)).filter(error => error.reason === 'runtime-selection-cancelled'); + const surfaced = r.h.events.filter(event => event.sessionId === id && event.type === 'error' + && event.data?.reason === 'runtime-selection-cancelled'); + return { history: persisted.length, surfaced: surfaced.length }; +} + +async function interruptedFallbackTask(t, id, agent, queue = {}) { + const r = await modelChangeRuntime(t, { agent, queue: { hasAssistantProgressAfter: async () => true, ...queue } }); + if (agent === 'pi') providePiWindows(r); + const twoProviders = ['prov-a', 'prov-b'].map(id => ({ ...switchViews(agent)[0], id })); + r.views.current = twoProviders; + writeFileSync(path.join(r.db.root, 'profile', 'session-runtime-fallback-settings.json'), JSON.stringify({ enabled: true })); + await r.createTask(id); + await r.h.queue.enqueue(id, { clientId: 'fb-1', text: 'long job' }); + await waitFor(() => r.h.maker.sessions.get(id)?.sent.length === 1); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + const interrupt = async session => { + const token = session.sendOptions.at(-1)?.turnAttemptToken; + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId, + ...(typeof token === 'number' ? { turnAttemptToken: token } : {}) }; + session.emit({ type: 'text', data: { text: 'half done', isFinal: true }, ...stamp }); + session.emit({ type: 'error', data: INTERRUPTION, ...stamp }); + await settle(); + }; + const advanceUntil = async (ready, what) => { + for (let i = 0; i < 200 && !ready(); i += 1) { t.mock.timers.tick(500); await settle(); } + await settleUntil(ready, what); + }; + const resumed = async (before, sent) => { + const ready = () => { + const now = r.h.maker.sessions.get(id); + return Boolean(now && (now !== before ? now.sent.length >= 1 : now.sent.length >= sent)); + }; + await advanceUntil(ready, 'the resume reached the engine'); + return r.h.maker.sessions.get(id); + }; + return { r, interrupt, resumed, advanceUntil }; +} + +// A local picker and set-effort during a turn must retain the desktop's timing. Real task settings, +// queue and migrated DB, three consecutive inputs: effort alone, a model/source pick with effort, +// then a cross-engine pick. Existing send tests cover landing but do not distinguish control.pending. +test('runtime control inputs: local picker and engine choices wait for a send, effort alone applies directly', async t => { + const r = await modelChangeRuntime(t); + const id = 'local-runtime-choices'; + const models = ['big', 'small'].map(model => ({ ...switchModel(model), efforts: ['medium', 'high'], defaultEffort: 'medium' })); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('claude-code')[0], id: provider, + agents: ['claude-code', 'codex'], models: { 'claude-code': models, codex: [switchModel('gpt-x')] } })); + const control = () => getSessionRuntimeControlSnapshot(id).pending; + const end = async live => { + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'the running turn ended'); + }; + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'one', text: 'one' }); + const first = r.h.maker.getSession(id); + await r.selection.setEffort(id, 'high'); + assert.deepEqual([control(), first.options.effort, r.row(id).effort], [null, 'high', 'high']); + const picked = await r.selection.setModel(id, 'small', 'prov-b', undefined, undefined); + assert.equal(picked.pendingUntilSend, true); + await r.selection.setEffort(id, 'medium'); + await end(first); + assert.deepEqual([control(), r.selection.projectIntent(id)?.effort, r.row(id).model], [null, 'medium', 'big']); + await r.h.queue.enqueue(id, { clientId: 'two', text: 'two' }); + await settleUntil(() => r.h.maker.getSession(id)?.sent.includes('two'), 'the model pick landed on the second turn'); + const second = r.h.maker.getSession(id); + assert.deepEqual([second.model, r.row(id).provider_id, r.row(id).effort], ['small', 'prov-b', 'medium']); + const engine = await r.selection.switchAgent({ sessionId: id, targetAgentKind: 'codex', model: 'gpt-x', providerId: 'prov-b' }); + assert.equal(engine.deferred, true); + await end(second); + assert.deepEqual([control(), r.selection.projectIntent(id)?.targetAgentKind, r.row(id).agent_kind], [null, 'codex', 'cc']); + await r.h.queue.enqueue(id, { clientId: 'three', text: 'three' }); + await settleUntil(() => r.h.maker.getSession(id)?.sent.some(text => text.endsWith('three')) || r.h.queue.projection(id).error, 'the third input settled'); + assert.equal(r.h.queue.projection(id).error ?? null, null); + assert.deepEqual([r.h.maker.getSession(id).agentKind, r.h.maker.getSession(id).model, control()], ['codex', 'gpt-x', null]); +}); + +// Rule (register.ts wires sessionRuntimeFallback.ts into the interrupted-turn resume, and its +// bootstrapSession starts the next runtime on the accepted override): with the user's route fallback +// setting on, the second interruption of an episode moves the task to another provider's candidate, +// and the resume runs on that route. Gap: the Host accepted the fallback but started the rebuilt +// runtime from the task row (which a fallback does not write), so the resume ran on the failing route +// again. Minimal failing input: two interruptions in a row on a task whose provider has a sibling. +test('auto-resume route switch: the second interruption resumes on another provider when the setting is on', { timeout: 30_000 }, async t => { + const { r, interrupt, resumed } = await interruptedFallbackTask(t, 'fb', 'claude-code'); + const first = r.h.maker.sessions.get('fb'); + await interrupt(first); + const second = await resumed(first, 2); + assert.equal(second, first, 'the first resume stays on the route'); + assert.equal(second.options.providerId, 'prov-a'); + await interrupt(second); + const third = await resumed(second, 3); + assert.notEqual(third, second, 'the second resume runs on a rebuilt runtime'); + assert.equal(third.options.providerId, 'prov-b', 'the resume runs on the sibling provider'); + // As the desktop: a start on the accepted override keeps the task row's saved provider baseline. + assert.equal(r.row('fb').provider_id, 'prov-a', 'the task row keeps its saved provider'); +}); + +// A permission change awaiting the engine's acknowledgement counts as busy in maker-core Session. +// Exercise its actual accounting. The test engine supplies only the acknowledgement and turn state. +function holdEnginePermissionAck(live) { + const started = Promise.withResolvers(); + const ack = Promise.withResolvers(); + const native = new Session({ + id: live.id, agentKind: live.agentKind, workDir: live.workDir, permissionMode: 'ask', turnStallMs: 0, + capabilities: { permissionModes: [{ id: 'ask' }, { id: 'auto' }], setPermissionModeMidSession: { supported: true } }, + handle: { setInteractionResolver() {}, isTurnRunning: () => live.running, + setPermissionMode() { started.resolve(); return ack.promise; } }, + logger: { child() { return this; }, info() {}, debug() {}, warn() {}, error() {} }, + }); + live.setPermissionMode = mode => native.setPermissionMode(mode); + live.isTurnRunning = () => native.isTurnRunning(); + return { started: started.promise, release: ack.resolve }; +} + +async function acceptedPiFallback(t, id, queue = {}) { + const { r, interrupt, resumed, advanceUntil } = await interruptedFallbackTask(t, id, 'pi', queue); + const first = r.h.maker.getSession(id); + await interrupt(first); + const live = await resumed(first, 2); + const ack = holdEnginePermissionAck(live); + const edit = r.selection.setPermissionMode(id, 'auto'); + try { + await ack.started; + await interrupt(live); + await advanceUntil(() => getSessionRuntimeControlSnapshot(id).pending?.profile.providerId === 'prov-b', + 'the second automatic fallback accepted the sibling provider as runtimePending'); + } finally { + ack.release(); + await edit; + } + return { r, resume: () => resumed(live, 3) }; +} + +function attachRuntimeHookFixture(r, hooks, answer, manifest = {}) { + const plugin = { manifest: { id: 'router', name: 'Router', version: '1.0.0', + subscribe: { hooks }, ...manifest }, enabled: true, dir: path.join(r.db.root, 'router'), + approval: { state: 'approved', revision: 'fixture' } }; + const pluginId = installedGhostStoragePart(plugin); + const pluginHost = createRuntimePluginHost({ + availableGhosts: () => [plugin], listGhostNotificationCandidates: async () => [plugin], + findGhostNotificationTarget: key => key === pluginId ? plugin : null, + findGhostForInstanceId: () => plugin, + getGhostRuntime: () => ({ stateOf: () => 'running' }), + broadcastGhostWindowPush() {}, log: { ...quiet, debug() {} }, + getGhostOwnerPushStamp: () => undefined, isGhostOwnerStampCurrent: () => true, + ghostOwnerScope: { capture: () => 'test', isCurrent: () => true, isStable: () => true }, + modelRouteSources: () => ({ localViews: async () => r.views.current, localAgents: () => ['pi', 'claude-code'] }), + sendToGhostLogic(key, event) { + queueMicrotask(() => { + const verdict = answer(event); + if (verdict) pluginHost.getGhostSubscriptionGateway().handleVerdict(key, { + type: 'event-verdict', hookId: event.hookId, ...verdict, + }); + }); + return true; + }, + }); + const taskPlugins = createHostTaskRuntimePlugins({ getMaker: () => r.h.maker, pluginHost, + selection: r.selection, publish: event => r.h.events.push(event), log: quiet }); + return { taskPlugins, pluginId }; +} + +// Integration, 8i §二: execute the normal input transaction with the real installed-plugin gateway, +// Host route writer, and SQLite. The cold/lazy engine and sandbox delivery are the external fixtures. +// A hold can arrive after the hot selection is accepted, so a rejected receipt alone is insufficient. +for (const onFailure of ['allow', 'block']) { + test(`plugin route at Pi acknowledgement: ${onFailure} leaves one consistent route across hold and release`, async t => { + const id = `plugin-hold-${onFailure}`; + let taskPlugins, pluginId; + const r = await modelChangeRuntime(t, { agent: 'pi', queue: { getTaskRuntimePlugins: () => taskPlugins } }); + providePiWindows(r); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('pi')[0], id: provider })); + ({ taskPlugins, pluginId } = attachRuntimeHookFixture(r, ['will-start-turn'], () => ({ + action: 'route', route: { agentKind: 'pi', providerId: 'prov-b', model: 'big' }, + }))); + await r.createTask(id); + const first = await r.runTurn(id, 'initial', { contextTokens: 100, contextWindow: 200_000 }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'initial Pi turn ended'); + await writeRuntimePluginSettings(id, { 'will-start-turn': [{ pluginId, onFailure }] }); + const changes = () => r.db.db.prepare('SELECT total_changes() AS count').get().count; + const closed = []; + const closeSessionIfCurrent = r.h.maker.closeSessionIfCurrent.bind(r.h.maker); + r.h.maker.closeSessionIfCurrent = async (...args) => { + const before = changes(); + await closeSessionIfCurrent(...args); + // Deliver the same production Host session:closed handler inside the audited close. + r.selection.onSessionClosed(id, args[0]); + closed.push({ instance: args[0], writes: changes() - before }); + }; + const setModel = first.setModel.bind(first); + first.setModel = async (...args) => { + await setModel(...args); + r.h.queue.holdForDesktop(HELD); + }; + const eventStart = r.h.events.length; + await r.h.queue.enqueue(id, { clientId: 'second', text: 'second' }); + await settleUntil(() => onFailure === 'allow' + ? r.h.maker.getSession(id)?.sent.includes('second') + : Boolean(r.h.queue.projection(id).error), 'held input was sent or blocked'); + assert.equal(closed.length, 1, 'the original instance retired exactly once'); + assert.equal(closed[0].instance, first); + assert.equal(closed[0].writes, 0, 'close did not touch the shared SQLite database'); + assert.equal(r.row(id).provider_id, 'prov-a'); + assert.equal(getSessionProvider(id), 'prov-a'); + assert.deepEqual(first.sent, ['work initial']); + const events = r.h.events.slice(eventStart); + assert.equal(events.some(event => event.type === 'session_changed' && + (event.patch?.providerId === 'prov-b' || event.patch?.runtimeEffective?.providerId === 'prov-b')), false); + assert.equal(events.some(event => event.channel === 'maker:session-credential-switch-applied'), false); + const live = r.h.maker.getSession(id); + if (onFailure === 'allow') { + assert.equal(live.options.providerId, 'prov-a'); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'allowed input settled'); + } else { + assert.equal(live, null); + assert.match(JSON.stringify(r.h.queue.projection(id).error), /selected runtime plugin stopped/i); + } + assert.equal(await r.h.queue.releaseDesktopHold(), true); + await writeRuntimePluginSettings(id, {}); + // The next input uses ordinary cold start, even if the allow case already spawned a replacement. + if (r.h.maker.getSession(id)) await r.h.maker.closeSession(id); + await enqueue(r.h, id, { clientId: 'after-hold', text: 'after' }); + assert.equal(r.h.maker.getSession(id).options.providerId, 'prov-a'); + }); +} + +// §3.2, integration: account commits clear the outgoing route and may +// immediately hydrate another owner's task with the same id. Only the old +// runtime may be retired when its outstanding Pi operation settles. +test('a plugin route refused after an account change leaves the new owner route alone', async t => { + const id = 'route-owner-changed'; + const r = await modelChangeRuntime(t, { agent: 'pi' }); + t.after(bindHostSessionRuntimeHooks(r.selection)); + providePiWindows(r); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('pi')[0], id: provider })); + await r.createTask(id); + const live = await r.runTurn(id, 'initial', { contextTokens: 100, contextWindow: 200_000 }); + const setModel = live.setModel.bind(live); + live.setModel = async (...args) => { + await setModel(...args); + configureHostOwner({ userDataDir: path.join(r.db.root, 'profile'), ownerId: 'other-route-owner' }); + assert.equal(getSessionProvider(id), null, 'the committed boundary already cleared the outgoing cache'); + setSessionProvider(id, 'new-account'); + }; + await assert.rejects(r.selection.applyPluginRoute(id, { agentKind: 'pi', model: 'big', providerId: 'prov-b' }, () => {}, () => {})); + assert.equal(r.h.maker.getSession(id), null); + assert.equal(getSessionProvider(id), 'new-account'); + assert.equal(r.row(id).provider_id, 'prov-a'); +}); + +// §3.2, integration: a queued route from the previous owner must reject before +// it captures the new owner's same-id runtime as its own rollback target. +test('a plugin route waiting for the task lock cannot retire the next owner’s instance', async t => { + const id = 'route-owner-changed-under-lock'; + const r = await modelChangeRuntime(t, { agent: 'pi' }); + t.after(bindHostSessionRuntimeHooks(r.selection)); + providePiWindows(r); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('pi')[0], id: provider })); + await r.createTask(id); + const old = await r.runTurn(id, 'initial', { contextTokens: 100, contextWindow: 200_000 }); + const lock = await holdSendLock(id); + const held = sendToSessionLocks.get(id); + const update = assert.rejects(r.selection.applyPluginRoute(id, { + agentKind: 'pi', model: 'big', providerId: 'prov-b', + }, () => {}, () => {})); + let next; + try { + await settleUntil(() => sendToSessionLocks.get(id) !== held, 'the route is queued behind the task lock'); + configureHostOwner({ userDataDir: path.join(r.db.root, 'profile'), ownerId: 'other-owner-under-lock' }); + await r.h.maker.closeSession(id); + next = await r.h.maker.createSession({ ...old.options, providerId: 'next-owner' }); + setSessionProvider(id, 'next-owner'); + } finally { + await lock.release(); + await update; + } + assert.equal(r.h.maker.getSession(id), next); + assert.equal(getSessionProvider(id), 'next-owner'); + assert.equal(r.row(id).provider_id, 'prov-a'); +}); + +// §3.2, integration: the same Pi acknowledgement race can affect the runtime +// that the shared window check creates. There is no instance at write admission. +test('a cold plugin route retires the Pi instance that window verification opened', async t => { + let taskPlugins; + const id = 'cold-hook-rejected'; + const r = await modelChangeRuntime(t, { agent: 'pi', queue: { getTaskRuntimePlugins: () => taskPlugins } }); + providePiWindows(r); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('pi')[0], id: provider })); + await r.createTask(id); + await r.runTurn(id, 'initial', { contextTokens: 100, contextWindow: 200_000 }); + await settle(); + await r.h.maker.closeSession(id); + forgetSessionLastLiveUsage(id); + let rejectedInstance; + const create = r.h.maker.createSession.bind(r.h.maker); + r.h.maker.createSession = async opts => { + const live = await create(opts); + if (!rejectedInstance) { + rejectedInstance = live; + const setModel = live.setModel.bind(live); + live.setModel = async (...args) => { + await setModel(...args); + r.h.queue.holdForDesktop(HELD); + }; + } + return live; + }; + const { taskPlugins: hooks, pluginId } = attachRuntimeHookFixture(r, ['will-start-turn'], () => ({ + action: 'route', route: { agentKind: 'pi', providerId: 'prov-b', model: 'big' }, + })); + taskPlugins = hooks; + await writeRuntimePluginSettings(id, { 'will-start-turn': [{ pluginId, onFailure: 'allow' }] }); + await enqueue(r.h, id, { clientId: 'cold', text: 'cold' }); + assert.equal(r.h.queue.isHeldForDesktop(), true, 'Pi changed before the hold'); + assert.ok(rejectedInstance); + assert.notEqual(r.h.maker.getSession(id), rejectedInstance); + assert.equal(rejectedInstance.sent.length, 0); + assert.equal(r.h.maker.getSession(id).options.providerId, 'prov-a'); + assert.equal(getSessionProvider(id), 'prov-a'); + assert.equal(r.row(id).provider_id, 'prov-a'); +}); + +// §3.2, integration. Without a hold, a route returned by an approved plugin +// must take effect on the normal dispatch. The rejection tests only exercise a late refusal. +test('a plugin route commits and sends through the selected Pi provider without a hold', async t => { + const id = 'plugin-route-unheld'; + let taskPlugins; + const r = await modelChangeRuntime(t, { agent: 'pi', queue: { getTaskRuntimePlugins: () => taskPlugins } }); + providePiWindows(r); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('pi')[0], id: provider })); + await r.createTask(id); + const live = await r.runTurn(id, 'initial', { contextTokens: 100, contextWindow: 200_000 }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'initial Pi turn ended'); + const { taskPlugins: hooks, pluginId } = attachRuntimeHookFixture(r, ['will-start-turn'], () => ({ + action: 'route', route: { agentKind: 'pi', providerId: 'prov-b', model: 'big' }, + })); + taskPlugins = hooks; + await writeRuntimePluginSettings(id, { 'will-start-turn': [{ pluginId, onFailure: 'block' }] }); + await enqueueUntilSent(r.h, id, { clientId: 'route', text: 'route' }, 2); + assert.equal(r.h.maker.getSession(id), live); + assert.equal(live.options.providerId, 'prov-b'); + assert.equal(getSessionProvider(id), 'prov-b'); + assert.equal(r.row(id).provider_id, 'prov-b'); +}); + +// §3.2, integration: an already-held replay, and a hold that arrives while the +// replay waits for a verdict. The no-plugin/normal replay is covered beside the recovery fixture. +for (const timing of ['before-replay', 'during-verdict']) { + test(`plugin overflow replay: ${timing} follows onFailure=block without changing the stored route`, async t => { + const id = `plugin-replay-${timing}`; + let taskPlugins; + const r = await modelChangeRuntime(t, { agent: 'pi', queue: { getTaskRuntimePlugins: () => taskPlugins } }); + providePiWindows(r); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('pi')[0], id: provider })); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'original', text: 'work' }); + const live = r.h.maker.getSession(id); + const { taskPlugins: hooks, pluginId } = attachRuntimeHookFixture(r, ['will-start-turn'], () => { + if (timing === 'during-verdict') r.h.queue.holdForDesktop(HELD); + return { action: 'route', route: { agentKind: 'pi', providerId: 'prov-b', model: 'big' } }; + }); + taskPlugins = hooks; + await writeRuntimePluginSettings(id, { 'will-start-turn': [{ pluginId, onFailure: 'block' }] }); + if (timing === 'before-replay') r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'error', data: OVERFLOW, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => r.db.errorRows(id).length || + (r.h.maker.getSession(id) !== live && r.h.maker.getSession(id)?.sent.length), 'replay recovered or failed'); + assert.equal(r.h.maker.getSession(id), null); + assert.equal(r.db.errorRows(id).length, 1); + assert.equal(r.row(id).provider_id, 'prov-a'); + }); +} + +test('task runtime plugins apply the selected prompt and contextual note on a cold queued send', async t => { + let taskPlugins; + const r = await modelChangeRuntime(t, { queue: { getTaskRuntimePlugins: () => taskPlugins } }); + const { taskPlugins: hooks, pluginId } = attachRuntimeHookFixture(r, ['will-compose-context'], + () => ({ action: 'context', blocks: [{ id: 'note', text: 'Fixture reference text' }] }), + { systemPrompt: [{ id: 'prompt', order: 0, text: 'Fixture task prompt' }] }); + taskPlugins = hooks; + const id = 'plugin-prompt-context'; + await r.createTask(id); + await writeRuntimePluginSettings(id, { 'system-prompt': [{ pluginId, onFailure: 'block' }], + 'will-compose-context': [{ pluginId, onFailure: 'block' }] }); + const prefs = ownerScopedPath('runtime-plugin-prefs.json'); + const saved = readFileSync(prefs); + await enqueue(r.h, id, { clientId: 'note', text: 'work' }); + const session = r.h.maker.getSession(id); + assert.match(session.options.userPrompt, /Fixture task prompt/); + assert.doesNotMatch(session.options.userPrompt, /Fixture reference text/); + assert.match(JSON.stringify(session.sent), /Fixture reference text/); + assert.deepEqual(readFileSync(prefs), saved, 'applying the stored selection leaves its bytes untouched'); +}); + +for (const action of ['block', 'rewrite']) { + test(`plugin user message: ${action} applies before storage and reaches the client`, async t => { + let taskPlugins; + const r = await modelChangeRuntime(t, { queue: { getTaskRuntimePlugins: () => taskPlugins } }); + const id = `plugin-message-${action}`; + const { taskPlugins: hooks } = attachRuntimeHookFixture(r, ['will-user-message'], + () => action === 'block' ? { action, reason: 'fixture block' } : { action, text: 'approved replacement' }); + taskPlugins = hooks; + await r.createTask(id); + await r.h.queue.enqueue(id, { clientId: 'message', text: 'unreviewed input' }); + await settleUntil(() => (action === 'rewrite' && r.h.maker.getSession(id)?.sent.length) || + r.h.events.some(e => e.channel === 'ghosts:user-message-blocked'), 'plugin decision became visible'); + const rows = r.userRows(id).map(row => row.content); + if (action === 'block') { + assert.deepEqual(rows, []); + assert.equal(r.h.maker.getSession(id), null); + } else { + assert.match(rows.join(' '), /approved replacement/); + assert.doesNotMatch(rows.join(' '), /unreviewed input/); + assert.match(JSON.stringify(r.h.maker.getSession(id).sent), /approved replacement/); + } + assert.equal(r.h.events.filter(event => event.channel === (action === 'block' + ? 'ghosts:user-message-blocked' : 'ghosts:user-message-rewritten')).length, 1); + }); +} + +// §3.2, integration: checkpoint ②'s real terminal settlement can cross the same hold window. +// Invalidate its accepted route before opening the gate and verify the next input's actual engine. +test('deferred Pi settlement clears the rejected route on release after a desktop edit', async t => { + const id = 'deferred-pi-held-ack'; + const r = await modelChangeRuntime(t, { agent: 'pi' }); + providePiWindows(r); + r.views.current = ['prov-a', 'prov-b', 'prov-c'].map(provider => ({ ...switchViews('pi')[0], id: provider })); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'first', text: 'work' }); + const live = r.h.maker.getSession(id); + acceptSessionRuntimeMutation({ sessionId: id, source: 'fallback', deferred: true, + profile: { agentKind: 'pi', model: 'big', providerId: 'prov-b', effort: null, fastMode: false } }); + const setModel = live.setModel.bind(live); + live.setModel = async (...args) => { + await setModel(...args); + r.h.queue.holdForDesktop(HELD); + }; + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => r.h.queue.isHeldForDesktop(), 'hold arrived during Pi acknowledgement'); + await settle(); + assert.equal(r.h.maker.getSession(id), live); + assert.equal(getSessionProvider(id), 'prov-b'); + assert.equal(r.row(id).provider_id, 'prov-a'); + assert.equal(getSessionRuntimeControlSnapshot(id).pending?.profile.providerId, 'prov-b'); + // The desktop writes the new authoritative route while it owns this profile. + r.db.db.prepare('UPDATE sessions SET provider_id = ? WHERE id = ?').run('prov-c', id); + assert.equal(await r.h.queue.releaseDesktopHold(), true); + assert.equal(getSessionRuntimeControlSnapshot(id).pending, null); + assert.equal(r.h.maker.getSession(id), null); + assert.equal(getSessionProvider(id), null, 'release clears the old in-memory route before normal sends resume'); + assert.equal(runtimeCancellations(r, id).surfaced, 1); + await enqueue(r.h, id, { clientId: 'next', text: 'next' }); + assert.equal(r.h.maker.getSession(id).options.providerId, 'prov-c'); + assert.equal(r.row(id).provider_id, 'prov-c'); +}); + +// §3.2, integration: settings admission must survive waiting for the real +// cross-process lock. The desktop settings tests have no Host profile boundary. +test('plugin settings refused under the write lock preserve the file and emit no patch', async t => { + const r = await modelChangeRuntime(t); + const id = 'locked-runtime-prefs'; + await r.createTask(id); + const previous = { 'will-start-turn': [{ pluginId: 'fixture', onFailure: 'block' }] }; + await writeRuntimePluginSettings(id, previous); + const prefs = ownerScopedPath('runtime-plugin-prefs.json'); + const bytes = readFileSync(prefs); + const entered = Promise.withResolvers(); + const events = []; + const settings = createHostRuntimePluginSettings({ + maker: r.h.maker, selection: r.selection, publish: event => events.push(event), + profileHold: () => r.h.queue.isHeldForDesktop() ? HELD : null, + holdGeneration: r.h.queue.profileHoldGeneration, + resolveGhostControlPointPlugin: (_point, pluginId) => { entered.resolve(); return pluginId; }, + }); + let result; + await withCrossProcessLock(prefs + '.lock', { label: 'fixture-holder', waitMs: 1000 }, async lease => { + assert.equal(lease.held, true); + result = settings(id, { 'will-start-turn': [{ pluginId: 'fixture', onFailure: 'allow' }] }); + // Observe rejection even if the lock completes before assert.rejects attaches. + void result.catch(() => {}); + await entered.promise; + await settle(); + r.h.queue.holdForDesktop(HELD); + assert.equal(await r.h.queue.releaseDesktopHold(), true, 'even a hold that ends invalidates this admission'); + }); + await assert.rejects(result, /HOST_PROFILE_IN_USE_BY_DESKTOP/); + assert.deepEqual(readFileSync(prefs), bytes); + assert.deepEqual(events, []); + assert.deepEqual(await settings(id), previous); +}); + +// Rule: the desktop settles an accepted runtime control at the final terminal and reports a +// runtime-selection-cancelled error if it fails. The ordinary fallback case has an idle engine at +// selection time. Tier: db, two interrupted turns and a permission acknowledgement overlapping the +// second retry, via the real queue, permission entry, automatic fallback, and session projection. +for (const withdraw of [false, true]) { + test(`auto-resume route switch: a deferred Pi fallback ${withdraw ? 'reports cancellation if the source disappears' : 'runs the subsequent turn on the accepted source'}`, async t => { + const id = withdraw ? 'fb-pi-cancel' : 'fb-pi-apply'; + const { r, resume } = await acceptedPiFallback(t, id); + const control = () => getSessionRuntimeControlSnapshot(id); + assert.equal(control().pending.source, 'fallback'); + if (withdraw) r.views.current = r.views.current.filter(view => view.id !== 'prov-b'); + const continuation = await resume(); + continuation.emit({ type: 'done', data: {}, sessionTurnGeneration: continuation.generation, sessionInstanceId: continuation.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'the continued turn ended'); + await settle(); + await r.h.maker.closeSession(id); + await enqueue(r.h, id, { clientId: 'next-input', text: 'next' }); + const nextRoute = r.h.maker.getSession(id).options; + assert.deepEqual({ pending: control().pending?.profile.providerId ?? null, next: nextRoute.providerId, ...runtimeCancellations(r, id) }, + { pending: null, next: withdraw ? 'prov-a' : 'prov-b', history: withdraw ? 1 : 0, surfaced: withdraw ? 1 : 0 }); + }); +} + +// The Pi provider list is asynchronous. A permission edit can begin after an idle send, rename +// recovery or budget rebuild passes its initial admission. Pause the real catalog read to place +// that edit at the decision, without writing a pending control or forcing isTurnRunning. +for (const operation of ['picker', 'rename', 'budget']) { + test(`runtime control producer: Pi ${operation} overlapping a permission acknowledgement`, async t => { + const id = 'control-' + operation; + const r = await modelChangeRuntime(t, { agent: 'pi' }); + providePiWindows(r); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'original', text: 'work' }); + const live = r.h.maker.getSession(id); + const ack = holdEnginePermissionAck(live); + t.after(() => { appliedContextWindowBudgets.delete(id); pendingSessionContextWindowBudgetReconciles.delete(id); }); + if (operation === 'budget') await taskListUpdate(r)(id, { contextWindowBudget: 100_000 }); + if (operation === 'picker') assert.equal((await r.selection.setModel(id, 'small', undefined, undefined, undefined)).pendingUntilSend, true); + if (operation === 'rename') r.rename('big', 'xai/big'); + assert.equal(getSessionRuntimeControlSnapshot(id).pending, null); + const entered = Promise.withResolvers(); + const listing = Promise.withResolvers(); + const interceptList = () => { + r.views.beforeList = () => { + delete r.views.beforeList; + entered.resolve(); + return listing.promise; + }; + }; + if (operation === 'budget') interceptList(); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'the original turn ended'); + if (operation !== 'budget') { + interceptList(); + await r.h.queue.enqueue(id, { clientId: 'next', text: 'next input' }); + } + await entered.promise; + const edit = r.selection.setPermissionMode(id, 'auto'); + try { + await ack.started; + listing.resolve(); + await settle(); + const pending = getSessionRuntimeControlSnapshot(id).pending; + assert.deepEqual({ source: pending?.source, model: pending?.profile.model }, { + source: 'agent', model: operation === 'picker' ? 'small' : operation === 'rename' ? 'xai/big' : 'big', + }); + } finally { + listing.resolve(); ack.release(); await edit; + } + if (operation === 'budget') { + await r.h.queue.enqueue(id, { clientId: 'next', text: 'next input' }); + } else { + await settleUntil(() => r.h.queue.projection(id).recovery?.kind === 'queue-head', 'the route change deferred before send'); + await r.h.queue.retryLastError(id); + } + await settleUntil(() => r.h.maker.getSession(id)?.sent.includes('next input'), 'the first input after the edit reached the engine'); + const next = r.h.maker.getSession(id); + next.emit({ type: 'done', data: {}, sessionTurnGeneration: next.generation, sessionInstanceId: next.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'the next turn ended'); + await settle(); + await r.h.queue.enqueue(id, { clientId: 'following', text: 'following input' }); + await settleUntil(() => r.h.maker.getSession(id)?.sent.includes('following input'), 'the following turn reached its runtime'); + assert.deepEqual({ pending: getSessionRuntimeControlSnapshot(id).pending?.profile.model ?? null, + nextModel: r.h.maker.getSession(id).model, ...runtimeCancellations(r, id) }, + { pending: null, nextModel: operation === 'picker' ? 'small' : operation === 'rename' ? 'xai/big' : 'big', + history: 0, surfaced: 0 }); + }); +} + +// An automatic route fallback on a task of the model-change runtime: the shared fallback step accepts it +// as the interrupted-turn auto-resume does (sessionRuntimeFallback.ts acceptSessionRuntimeMutation, +// source 'fallback'); the task row keeps its saved route ('big' on prov-a). +const FALLBACK_ROUTE = { agentKind: 'claude-code', model: 'big', providerId: 'prov-b', effort: null, fastMode: false }; +async function fallenBackTask(t, id) { + const r = await modelChangeRuntime(t); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('claude-code')[0], id: provider })); + await r.createTask(id); + acceptSessionRuntimeMutation({ sessionId: id, source: 'fallback', profile: FALLBACK_ROUTE, deferred: false }); + return r; +} +const startedOn = async (r, id, clientId) => { + await r.h.queue.enqueue(id, { clientId, text: 'next' }); + await waitFor(() => r.h.maker.sessions.get(id)?.sent.length === 1); + const { model, providerId } = r.h.maker.sessions.get(id).options; + return { model, providerId }; +}; + +// Rule (the desktop's set-model, sessionRuntimeSelectionApply.ts, records a user mutation, which drops +// the accepted override; bootstrapSession then starts on the row): a user who picks a model after an +// automatic fallback gets the pick at the next start, not the fallback route. Gap: no Host test picks +// after a fallback; the start reads the override (applySessionRuntimeOverrideForStart). Minimal failing +// input: a fallback to prov-b, then a pick of 'small' on prov-a. +test('runtime override: a model the user picks after an automatic fallback is what the next start uses', { timeout: 30_000 }, async t => { + const r = await fallenBackTask(t, 'pick'); + await r.selection.setModel('pick', 'small', 'prov-a', undefined, undefined); + assert.deepEqual(await startedOn(r, 'pick', 'pick-1'), { model: 'small', providerId: 'prov-a' }); +}); + +// Rule (bootstrap-electron.ts setAppSessionCommitBoundaryHook → clearOwnerScopedSessionRuntimeSelection, +// bound for the Host by bindHostSessionRuntimeHooks): an owner commit drops every task's runtime control +// state. Gap: the Host bound no boundary hook, so after signing out and in again (same account, same task +// ids) the next start ran on the route a fallback chose before. Minimal failing input: a fallback, a +// sign-out and a sign-in, a send. +test('runtime override: after signing out and in again a task starts on its saved route, not a fallback from before', { timeout: 30_000 }, async t => { + const r = await fallenBackTask(t, 'relogin'); + t.after(bindHostSessionRuntimeHooks(r.selection)); + const profile = path.join(r.db.root, 'profile'); + // As main.ts: signing out commits signed-out (configureHostOwner), signing in commits the owner again. + configureHostOwner({ userDataDir: profile, ownerId: null }); + configureHostOwner({ userDataDir: profile, ownerId: 'owner-recovery' }); + assert.deepEqual(await startedOn(r, 'relogin', 'relogin-1'), { model: 'big', providerId: 'prov-a' }); +}); + +const RUNTIME_READ_FIELDS = ['agentKind', 'model', 'providerId', 'effort', 'fastMode', 'runtimeGeneration', 'runtimeBaseline', + 'runtimeEffective', 'runtimePending', 'runtimeBaselineRecoveryPending', 'runtimePluginsSelected']; +const runtimeRead = async id => { + const read = await readHostSession(getDbClient().drizzle, id); + return Object.fromEntries(RUNTIME_READ_FIELDS.map(key => [key, read[key]])); +}; +// The model-change fixture's task row: 'big' on prov-a at effort 'high'. +const SAVED_ROUTE = { agentKind: 'claude-code', model: 'big', providerId: 'prov-a', effort: 'high', fastMode: false }; + +// Rule (register.ts setSessionRuntimeProjector, now createSessionRuntimeProjector, bound for the Host by +// bindHostSessionRuntimeHooks): a task read shows the route the task runs on, so after an automatic +// fallback the task's model and provider read as the fallback route, the saved one as the baseline. Gap: +// the Host bound no projector, so a read returned the row: the model label went back to the saved route +// on every reread while the task ran (and was billed) on the fallback. Minimal failing input: a fallback. +test('runtime override: a task read shows the fallback route the task runs on, with the saved route as its baseline', { timeout: 30_000 }, async t => { + const r = await fallenBackTask(t, 'shown'); + t.after(bindHostSessionRuntimeHooks(r.selection)); + assert.deepEqual(await runtimeRead('shown'), { + agentKind: 'cc', model: 'big', providerId: 'prov-b', effort: '', fastMode: false, + runtimeGeneration: 1, runtimeBaseline: SAVED_ROUTE, runtimeEffective: FALLBACK_ROUTE, runtimePending: null, + runtimeBaselineRecoveryPending: false, runtimePluginsSelected: false, + }); +}); + +// Reverse (the same projector): with no runtime change a read is the task row, and the runtime fields have +// the desktop's shape (projectSessionRuntimeControl: generation 0, the row as both baseline and effective, +// no pending change; runtimePluginsSelected false, as the Host runs no runtime plugins). Failure: binding +// the projector changes what an ordinary task reads. +test('runtime override: with no runtime change a task read is its row, in the desktop\'s runtime shape', { timeout: 30_000 }, async t => { + const r = await modelChangeRuntime(t); + t.after(bindHostSessionRuntimeHooks(r.selection)); + await r.createTask('plain'); + assert.deepEqual(await runtimeRead('plain'), { + agentKind: 'cc', model: 'big', providerId: 'prov-a', effort: 'high', fastMode: false, + runtimeGeneration: 0, runtimeBaseline: SAVED_ROUTE, runtimeEffective: SAVED_ROUTE, runtimePending: null, + runtimeBaselineRecoveryPending: false, runtimePluginsSelected: false, + }); +}); + +// Integration, coexistence §二. Exercise an overflow replay through the same send ports as an +// ordinary input. The original overflow tests do not cover a pending engine choice or a task +// that the desktop archives as the replay reaches send preparation. +for (const held of [true, false]) { + test(`overflow replay: a pending engine switch ${held ? 'waits for release and a fresh send' : 'lands before replay'}`, async t => { + const r = await modelChangeRuntime(t); + const id = 'replay-engine-switch'; + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'original', text: 'work' }); + const first = r.h.maker.getSession(id); + await r.selection.switchAgent({ sessionId: id, targetAgentKind: 'codex', model: 'gpt-x', providerId: 'prov-a' }); + assert.equal(r.selection.projectIntent(id)?.targetAgentKind, 'codex'); + if (held) r.h.queue.holdForDesktop(HELD); + first.emit({ type: 'error', data: OVERFLOW, sessionTurnGeneration: first.generation, sessionInstanceId: first.instanceId }); + await settleUntil(() => { + const replacement = r.h.maker.getSession(id); + return replacement && replacement !== first && replacement.sent.length > 0; + }, 'overflow replay reached an engine'); + const replay = r.h.maker.getSession(id); + assert.deepEqual([replay.agentKind, r.row(id).agent_kind, r.selection.projectIntent(id)?.targetAgentKind], + held ? ['claude-code', 'cc', 'codex'] : ['codex', 'codex', undefined]); + if (held) { + replay.emit({ type: 'done', data: {}, sessionTurnGeneration: replay.generation, sessionInstanceId: replay.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'replay settled'); + assert.equal(await r.h.queue.releaseDesktopHold(), true); + await enqueue(r.h, id, { clientId: 'fresh', text: 'next' }); + assert.equal(r.h.maker.getSession(id).agentKind, 'codex'); + assert.equal(r.row(id).agent_kind, 'codex'); + } + }); + + test(`overflow replay: a just-archived task ${held ? 'stays archived and refuses replay' : 'is restored and receives replay'}`, async t => { + let r, restore; + let sends = 0; + const id = 'replay-archived-task'; + r = await modelChangeRuntime(t, { queue: { restoreArchivedSessionForSend: async sessionId => { + if (++sends === 2) r.db.db.prepare('UPDATE sessions SET status = ? WHERE id = ?').run('archived', id); + await restore.restoreArchivedSessionForSend(sessionId); + } } }); + restore = createHostTaskRestore({ getOwner: getCurrentDbClientSnapshot, publish: event => r.h.events.push(event), + isHeldForDesktop: () => r.h.queue.isHeldForDesktop() }); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'original', text: 'work' }); + const first = r.h.maker.getSession(id); + if (held) r.h.queue.holdForDesktop(HELD); + first.emit({ type: 'error', data: OVERFLOW, sessionTurnGeneration: first.generation, sessionInstanceId: first.instanceId }); + await settleUntil(() => r.db.errorRows(id).length > 0 || + (r.h.maker.getSession(id) !== first && r.h.maker.getSession(id)?.sent.length > 0), + 'replay reached a terminal failure or the replacement engine'); + assert.equal(sends, 2); + assert.equal(r.row(id).status, held ? 'archived' : 'active'); + assert.equal(Boolean(r.h.maker.getSession(id)?.sent.length), !held); + }); +} + +// Rule (the desktop's status writers run cleanupSessionRuntimeForTerminalStatus at an archive or delete, +// which runs the cleanup register.ts set, now createSessionRuntimeCleanup, bound for the Host by +// bindHostSessionRuntimeHooks): an archived task's runtime override does not outlive the archive. Gap: the +// Host's archive only wrote the column, so a task archived after an automatic fallback and restored +// started on the fallback route again. Minimal failing input: a fallback, an archive, a restore, a send. +// The task list's archive and restore, as main.ts builds the update entry (under the task's route lock). +const taskListUpdate = r => { + const taskRestore = createHostTaskRestore({ getOwner: () => getDbClient(), publish: event => r.h.events.push(event) }); + return lockSessionRoute(createHostSessionUpdate({ + restoreTaskToActive: taskRestore.restoreTaskToActive, + persistSessionFields: (...args) => r.selection.persistSessionFields(...args), + publish: event => r.h.events.push(event), + setModel: (...args) => r.selection.setModel(...args), + move: async () => { throw new Error('Unexpected move'); }, + })); +}; + +// §3.2 profile coexistence, tier db. A fallback produced by the real retry and +// a credential change registered on a busy runtime must survive the same boundary. +// A desktop can edit the stored route while holding the profile; an owner can +// sign out. Observe the task's state, committed UPDATEs, history and client events. +for (const kind of ['runtime', 'credential']) { + for (const boundary of ['held', 'unchanged', 'route changed', 'owner changed']) { + test(`profile hold settlement: ${kind} with ${boundary}`, { timeout: 30_000 }, async t => { + const id = `hold-${kind}-${boundary.replace(' ', '-')}`; + let r, live; + if (kind === 'runtime') { + const fallback = await acceptedPiFallback(t, id); + r = fallback.r; + live = await fallback.resume(); + } else { + r = await modelChangeRuntime(t); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('claude-code')[0], id: provider })); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'one' }); + live = r.h.maker.getSession(id); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-b' }); + } + t.after(bindHostSessionRuntimeHooks(r.selection)); + const readPending = () => kind === 'runtime' ? getSessionRuntimeControlSnapshot(id).pending : r.selection.hasPendingCredentialSwitch(id); + const registered = readPending(); + assert.ok(registered, 'the real switch has been accepted'); + const writes = observeRouteUpdates(r, id); + const applied = () => r.h.events.filter(e => e.channel === 'maker:session-credential-switch-applied' && e.payload.sessionId === id); + const failed = () => r.h.events.filter(e => e.channel === 'maker:session-credential-switch-failed' && e.payload.sessionId === id); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'the held turn ended'); + await settle(); + assert.deepEqual({ pending: readPending(), updates: writes(), applied: applied().length, + ...runtimeCancellations(r, id) }, { pending: registered, updates: [], applied: 0, history: 0, surfaced: 0 }); + if (boundary === 'held') return; + if (boundary === 'route changed') { + // The desktop's edit writes the original database while Host is holding. + r.db.db.prepare('UPDATE sessions SET model = ? WHERE id = ?').run('small', id); + } else if (boundary === 'owner changed') { + const profile = path.join(r.db.root, 'profile'); + configureHostOwner({ userDataDir: profile, ownerId: null }); + configureHostOwner({ userDataDir: profile, ownerId: 'other-owner' }); + } + const priorWrites = writes(); + assert.equal(await r.h.queue.releaseDesktopHold(), true); + await settle(); + if (boundary === 'unchanged') { + assert.ok(!readPending(), 'accepted switch settled on release'); + if (kind === 'credential') { + assert.deepEqual(writes().slice(priorWrites.length), [{ model: 'small', provider_id: 'prov-b' }]); + assert.equal(applied().length, 1); + } else { + const settled = getSessionRuntimeControlSnapshot(id); + assert.equal(settled.effectiveOverride?.providerId, 'prov-b'); + const generation = settled.generation; + await r.h.queue.releaseDesktopHold(); + assert.equal(getSessionRuntimeControlSnapshot(id).generation, generation); + } + } else { + assert.ok(!readPending(), 'the stale choice no longer gates sends'); + assert.deepEqual(writes(), priorWrites); + assert.equal(applied().length, 0); + assert.equal(failed().length, 0, 'non-Pi credential failures have no desktop failure push'); + const cancel = kind === 'runtime' && boundary === 'route changed' ? 1 : 0; + assert.deepEqual(runtimeCancellations(r, id), { history: cancel, surfaced: cancel }); + } + }); + } +} + +// §3.2, db. Use the runtime selection's actual acceptance write, then deliver +// the engine terminal before the producer's next awaited metadata read can +// publish its projection (sessionRuntimeSelectionApply.ts). Observe the stored +// fallback, both cancellation deliveries and the projection seen by the client. +for (const held of [false, true]) { + test(`unobserved runtime control: a terminal before projection ${held ? 'cancels on release and refreshes the client' : 'settles the accepted route'}`, async t => { + const id = held ? 'unobserved-held' : 'unobserved-open'; + const r = await modelChangeRuntime(t); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('claude-code')[0], id: provider })); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'first' }); + const live = r.h.maker.getSession(id); + acceptSessionRuntimeMutation({ sessionId: id, source: 'fallback', profile: FALLBACK_ROUTE, deferred: true }); + if (held) r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'turn ended before projection'); + if (held) { + assert.equal(getSessionRuntimeControlSnapshot(id).pending?.profile.providerId, 'prov-b'); + assert.equal(await r.h.queue.releaseDesktopHold(), true); + } + await settleUntil(() => !getSessionRuntimeControlSnapshot(id).pending, 'control was resolved'); + await settle(); + const control = getSessionRuntimeControlSnapshot(id); + assert.equal(control.effectiveOverride?.providerId ?? null, held ? null : 'prov-b'); + assert.deepEqual(runtimeCancellations(r, id), held ? { history: 1, surfaced: 1 } : { history: 0, surfaced: 0 }); + assert.ok(r.h.events.some(e => e.type === 'session_changed' && e.sessionId === id && e.patch?.runtimePending === null), + 'the client sees that there is no pending selection'); + }); +} + +// §3.2, db. The missing receipt cannot justify delivering the old account's +// cancellation to the account that now owns the rebuilt queue. +test('unobserved runtime control: a new account receives no cancellation from the previous hold', async t => { + const id = 'unobserved-other-account'; + const r = await modelChangeRuntime(t); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'first' }); + const live = r.h.maker.getSession(id); + acceptSessionRuntimeMutation({ sessionId: id, source: 'fallback', profile: FALLBACK_ROUTE, deferred: true }); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'old turn ended'); + const profile = path.join(r.db.root, 'profile'); + configureHostOwner({ userDataDir: profile, ownerId: null }); + configureHostOwner({ userDataDir: profile, ownerId: 'replacement-owner' }); + assert.ok(getSessionRuntimeControlSnapshot(id).pending, 'the old choice still awaits release'); + assert.equal(await r.h.queue.releaseDesktopHold(), true); + assert.equal(getSessionRuntimeControlSnapshot(id).pending, null); + assert.deepEqual(runtimeCancellations(r, id), { history: 0, surfaced: 0 }); +}); + +// §3.2, db. A failing history delivery can start a newer generation in the +// desktop factory's finally. The Host must handle the first rejection and +// wait for the second catalog lookup before notifying the restart service. +test('turn settlement handles a rejected delivery and waits for its successor generation', async t => { + const id = 'delivery-successor'; + const notified = []; + const { r, resume } = await acceptedPiFallback(t, id, { + afterTurnSettled: task => notified.push(getSessionRuntimeControlSnapshot(task).effectiveOverride?.providerId), + }); + const live = await resume(); + const profile = getSessionRuntimeControlSnapshot(id).pending.profile; + const providers = r.views.current; + r.views.current = providers.filter(view => view.id !== 'prov-b'); + const lookup = settlementCheckpoint('successor catalog read'); + const finish = Promise.withResolvers(); + const record = r.h.queue.recordRuntimeControlError; + r.h.queue.recordRuntimeControlError = (task, error) => { + record(task, error); + r.h.queue.recordRuntimeControlError = record; + r.views.current = providers; + acceptSessionRuntimeMutation({ sessionId: task, source: 'fallback', profile, deferred: true }); + r.views.beforeList = () => { + delete r.views.beforeList; + lookup.enter(); + return finish.promise; + }; + throw new Error('history delivery failed after a newer selection'); + }; + notified.length = 0; + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + try { + await lookup.wait(); + await settle(); + assert.deepEqual(notified, []); + } finally { finish.resolve(); } + await settleUntil(() => notified.length > 0, 'restart notified after both generations'); + assert.deepEqual(notified, ['prov-b']); +}); + +// §3.2, db. The first released task fails to settle. The second has only a +// runtime control, so its route has to land during this release, without a timer. +test('profile release continues to a runtime-only task after another task throws', async t => { + const id = 'release-second'; + const first = 'release-first'; + const { r, resume } = await acceptedPiFallback(t, id); + const live = await resume(); + await r.createTask(first); + await enqueue(r.h, first, { clientId: 'work', text: 'first' }); + const other = r.h.maker.getSession(first); + acceptSessionRuntimeMutation({ sessionId: first, source: 'fallback', profile: { ...FALLBACK_ROUTE, agentKind: 'pi' }, deferred: true }); + r.h.queue.holdForDesktop(HELD); + for (const session of [live, other]) { + session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + } + await settleUntil(() => !r.h.queue.isTurnRunning(id) && !r.h.queue.isTurnRunning(first), 'both held turns ended'); + const pending = r.selection.deferredTurnSettlements; + assert.deepEqual(pending().sort(), [first, id]); + r.selection.deferredTurnSettlements = () => pending().sort(); + const settleTask = r.selection.onTurnSettled; + const visited = []; + r.selection.onTurnSettled = task => { + visited.push(task); + if (task === first) throw new Error('first task history unavailable'); + return settleTask(task); + }; + assert.equal(await r.h.queue.releaseDesktopHold(), true); + assert.deepEqual(visited, [first, id]); + assert.equal(getSessionRuntimeControlSnapshot(id).effectiveOverride?.providerId, 'prov-b'); +}); + +// §3.2, unit. A device or gateway restart may still be pending when a +// terminal arrives. Observe the restart hook and a different task's admitted +// input through the actual queue, with the ten-second retry clock frozen. +for (const outcome of ['deferred', 'failed']) { + test(`unheld terminal notifies restart and external credential waiters after ${outcome} settlement`, async t => { + const notifications = []; + const hooks = hostRuntimeSelectionQueueHooks(() => ({ + onTurnSettled: async () => { + if (outcome === 'failed') throw new Error('settlement unavailable'); + return false; + }, + }), { isSessionRestarting: () => false, afterTurnSettled: id => notifications.push(id) }); + const h = await waitForOtherTasksCredentials(t, { onSessionSettled: hooks.onSessionSettled, afterTurnSettled: hooks.afterTurnSettled }); + await finishCredentialBlocker(h); + assert.deepEqual(notifications, ['blocker']); + // The notification only schedules dispatch. The retry still checks its working directory. + await settleUntil(() => h.maker.getSession('waiter')?.sent.length, 'the waiting input reaches its engine'); + assert.deepEqual(h.maker.getSession('waiter')?.sent, ['needs the switch']); + }); +} + +function settlementCheckpoint(label) { + let reached = false; + return { enter: () => { reached = true; }, wait: () => settleUntil(() => reached, label) }; +} + +// §3.2, db. Replace an accepted credential choice while its revalidation is +// suspended. A late result cannot write the old choice or delete the replacement. +test('profile hold settlement: an older generation cannot commit over a replacement during release', async t => { + const r = await modelChangeRuntime(t); + const id = 'held-credential-generation'; + r.views.current = ['prov-a', 'prov-b', 'prov-c'].map(provider => ({ ...switchViews('claude-code')[0], id: provider })); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'first', text: 'job' }); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-b' }); + const live = r.h.maker.getSession(id); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'held turn ended'); + const writes = observeRouteUpdates(r, id); + const read = settlementCheckpoint('read reached'); + const resume = Promise.withResolvers(); + let catalogReads = 0; + r.views.beforeList = () => { + if (++catalogReads !== 2) return; // suspend the final persistence lookup + delete r.views.beforeList; + read.enter(); + return resume.promise; + }; + const release = r.h.queue.releaseDesktopHold(); + try { + await read.wait(); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-c' }); + } finally { resume.resolve(); } + assert.equal(await release, true); + assert.deepEqual(writes(), []); + assert.equal(r.selection.hasPendingCredentialSwitch(id), true); + t.mock.timers.tick(10_000); + await settleUntil(() => !r.selection.hasPendingCredentialSwitch(id), 'the current generation settled'); + assert.deepEqual(writes(), [{ model: 'small', provider_id: 'prov-c' }]); + assert.deepEqual(r.h.events.filter(e => e.channel === 'maker:session-credential-switch-applied').map(e => e.payload.providerId), ['prov-c']); +}); + +// §3.2, db. A new scheduled turn can acquire a rebuilt runtime while the +// credential write is awaiting its catalog. Keep the choice until its actual end. +test('profile hold settlement: a new running turn delays the released credential switch', async t => { + const r = await modelChangeRuntime(t); + const id = 'running-on-release'; + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'first', text: 'job' }); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + const old = r.h.maker.getSession(id); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-a' }); + r.h.queue.holdForDesktop(HELD); + old.emit({ type: 'done', data: {}, sessionTurnGeneration: old.generation, sessionInstanceId: old.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'first turn ended'); + const writes = observeRouteUpdates(r, id); + const lookup = settlementCheckpoint('lookup reached'); + const finish = Promise.withResolvers(); + let reads = 0; + r.views.beforeList = () => { + if (++reads !== 2) return; + delete r.views.beforeList; + lookup.enter(); + return finish.promise; + }; + const release = r.h.queue.releaseDesktopHold(); + let scheduled; + try { + await lookup.wait(); + scheduled = await r.h.maker.createSession(old.options); + await r.h.queue.beginHostTurn(id); + } finally { finish.resolve(); } + assert.equal(await release, true); + assert.equal(r.selection.hasPendingCredentialSwitch(id), true); + assert.deepEqual(writes(), []); + scheduled.emit({ type: 'done', data: {}, sessionTurnGeneration: scheduled.generation, sessionInstanceId: scheduled.instanceId }); + await settleUntil(() => !r.selection.hasPendingCredentialSwitch(id), 'scheduled turn released its pending switch'); + assert.deepEqual(writes(), [{ model: 'small', provider_id: 'prov-a' }]); +}); + +// §3.2, db. beginStop can overlap the last close of the old runtime. Rebuilding +// that runtime must not give its successor permission to settle the former owner. +test('profile hold settlement: beginStop during rebuild keeps the pending route untouched', async t => { + const r = await modelChangeRuntime(t); + const id = 'stop-during-rebuild'; + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'job' }); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-a' }); + const live = r.h.maker.getSession(id); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'held turn ended'); + const writes = observeRouteUpdates(r, id); + const closing = settlementCheckpoint('closing reached'); + const resume = Promise.withResolvers(); + const close = r.h.maker.closeSession; + r.h.maker.closeSession = async (...args) => { closing.enter(); await resume.promise; return close(...args); }; + const release = r.h.queue.releaseDesktopHold(); + try { + await closing.wait(); + r.h.queue.beginStop(); + } finally { resume.resolve(); } + assert.equal(await release, false); + t.mock.timers.tick(10_000); + await settle(); + assert.deepEqual(writes(), []); + assert.equal(r.h.events.filter(e => e.channel === 'maker:session-credential-switch-applied').length, 0); +}); + +// §3.2, db. Both accepted choices are present when the desktop edits the route. +// Completion of the credential check precedes the runtime cancellation on the client. +test('profile hold settlement: resolves stale credentials before delivering runtime cancellation', async t => { + const id = 'both-held-choices'; + const { r, resume } = await acceptedPiFallback(t, id); + const live = await resume(); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-a' }); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'held turn ended'); + r.db.db.prepare("UPDATE sessions SET provider_id = 'desktop-route' WHERE id = ?").run(id); + const updates = observeRouteUpdates(r, id); + assert.equal(await r.h.queue.releaseDesktopHold(), true); + assert.deepEqual(updates(), []); + const order = r.h.events.flatMap(event => { + if (event.channel === 'maker:session-credential-switch-failed' && event.payload.sessionId === id) return ['credentials']; + if (event.sessionId === id && event.data?.reason === 'runtime-selection-cancelled') return ['runtime']; + return []; + }); + assert.deepEqual(order, ['credentials', 'runtime']); +}); + +// §3.2, db. An external waiter may acquire its runtime only after the blocking +// task's deferred choice has actually finished, even when catalog I/O is pending. +test('turn settlement: other credential waiters start after the pending source reaches clients', async t => { + const r = await modelChangeRuntime(t); + for (const id of ['blocking-source', 'waiting-source']) await r.createTask(id); + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('claude-code')[0], id: provider })); + await enqueue(r.h, 'blocking-source', { clientId: 'work', text: 'job' }); + const live = r.h.maker.getSession('blocking-source'); + const create = r.h.maker.createSession; + let attempts = 0; + let appliedAtStart = false; + r.h.maker.createSession = async options => { + if (options.id === 'waiting-source') { + if (++attempts === 1) throw new CredentialModeSwitchBusyError(['blocking-source']); + appliedAtStart = r.h.events.some(e => e.channel === 'maker:session-credential-switch-applied' && e.payload.sessionId === 'blocking-source'); + } + return create(options); + }; + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await r.h.queue.enqueue('waiting-source', { clientId: 'wait', text: 'wait' }); + await settleUntil(() => r.h.queue.projection('waiting-source').credentialSwitchWait?.clientId === 'wait', 'waiter registered'); + await r.selection.registerPendingCredentialSwitch('blocking-source', { model: 'small', providerId: 'prov-b' }); + const entered = settlementCheckpoint('entered reached'); + const resume = Promise.withResolvers(); + r.views.beforeList = () => { + delete r.views.beforeList; + entered.enter(); + return resume.promise; + }; + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + try { + await entered.wait(); + await settle(); + assert.equal(attempts, 1); + } finally { resume.resolve(); } + await settleUntil(() => r.h.maker.getSession('waiting-source')?.sent.length > 0, 'waiter dispatched'); + assert.equal(appliedAtStart, true); +}); + +// §3.2, db. The runtime settlement factory is asynchronous. Hold its real Pi +// catalog lookup and check the runtime chosen when another task first dispatches. +test('turn settlement: other tasks wait until the deferred runtime control finishes', async t => { + const id = 'blocking-fallback'; + const { r, resume } = await acceptedPiFallback(t, id); + const live = await resume(); + const waiter = 'waiting-fallback'; + await r.createTask(waiter); + const create = r.h.maker.createSession; + let attempts = 0; + let routeAtDispatch; + r.h.maker.createSession = async options => { + if (options.id === waiter) { + if (++attempts === 1) throw new CredentialModeSwitchBusyError([id]); + routeAtDispatch = getSessionRuntimeControlSnapshot(id).effectiveOverride?.providerId; + } + return create(options); + }; + await r.h.queue.enqueue(waiter, { clientId: 'waiting', text: 'waiting' }); + await settleUntil(() => r.h.queue.projection(waiter).credentialSwitchWait?.clientId === 'waiting', 'waiter registered'); + const lookup = settlementCheckpoint('lookup reached'); + const finish = Promise.withResolvers(); + r.views.beforeList = () => { delete r.views.beforeList; lookup.enter(); return finish.promise; }; + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + try { + await lookup.wait(); + await settle(); + assert.equal(attempts, 1); + } finally { finish.resolve(); } + await settleUntil(() => r.h.maker.getSession(waiter)?.sent.length > 0, 'other task dispatched'); + assert.equal(routeAtDispatch, 'prov-b'); +}); + +// §3.2, db. When a desktop has replaced the Pi route, writing the previous +// route would destroy its edit. Observe the existing client failure and all SQL writes. +test('profile hold settlement: aborts a stale Pi credential choice without restoring the former route', async t => { + const id = 'held-pi-credential-stale'; + const r = await modelChangeRuntime(t, { agent: 'pi' }); + providePiWindows(r); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'job' }); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + const live = r.h.maker.getSession(id); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-a' }); + const updates = observeRouteUpdates(r, id); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'held turn ended'); + r.db.db.prepare("UPDATE sessions SET provider_id = 'desktop-provider' WHERE id = ?").run(id); + assert.equal(await r.h.queue.releaseDesktopHold(), true); + assert.equal(r.selection.hasPendingCredentialSwitch(id), false); + assert.deepEqual(updates(), [{ model: 'big', provider_id: 'desktop-provider' }]); + assert.deepEqual(r.h.events.filter(e => e.channel?.startsWith('maker:session-credential-switch-')).map(e => [e.channel, e.payload]), + [['maker:session-credential-switch-failed', { sessionId: id, reason: 'apply-failed' }]]); +}); + +// §3.2, tier db. The retry and Maker's close notification can arrive without a +// turn-end callback. Neither may apply a same-route rebuild while the desktop owns +// the profile. Count UPDATEs as well as pushes, since the stored values match. +for (const source of ['retry timer', 'session close']) { + test(`profile hold: a pending credential switch survives the ${source}`, async t => { + const r = await modelChangeRuntime(t); + const id = `held-credential-${source.replace(' ', '-')}`; + t.after(() => { appliedContextWindowBudgets.delete(id); pendingSessionContextWindowBudgetReconciles.delete(id); }); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'first', text: 'long job' }); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await taskListUpdate(r)(id, { contextWindowBudget: 100_000 }); + assert.equal(r.selection.hasPendingCredentialSwitch(id), true); + const routeWrites = observeRouteUpdates(r, id); + r.h.queue.holdForDesktop(HELD); + const session = r.h.maker.getSession(id); + await r.h.maker.closeSession(id); + if (source === 'retry timer') { + t.mock.timers.tick(10_000); + } else { + const listeners = new Set(); + r.h.maker.on = fn => { listeners.add(fn); return () => listeners.delete(fn); }; + t.after(r.selection.attachMaker(r.h.maker)); + session.getUsageSnapshot = () => undefined; + for (const listener of listeners) listener({ type: 'session:closed', sessionId: id, session }); + } + await settle(); + assert.deepEqual({ + updates: routeWrites(), pending: r.selection.hasPendingCredentialSwitch(id), + applied: r.h.events.filter(e => e.channel === 'maker:session-credential-switch-applied').map(e => e.payload.sessionId), + }, { updates: [], pending: true, applied: [] }); + }); +} + +// §3.2 coexistence rule, tier db. A hold may arrive after settlement started. The last +// provider catalog read inside persistence follows route revalidation and precedes +// SQLite's UPDATE. Hold at that boundary and observe both the actual write and the client. +test('profile hold: a credential switch already inside persistence cannot write or notify', { timeout: 20_000 }, async t => { + const r = await modelChangeRuntime(t); + const id = 'held-during-persist'; + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('claude-code')[0], id: provider })); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'long job' }); + const live = r.h.maker.getSession(id); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-b' }); + const entered = settlementCheckpoint('entered reached'); + const resume = Promise.withResolvers(); + let reads = 0; + r.views.beforeList = async () => { + if (++reads !== 2) return; // first: route revalidation; second: persistence's final catalog lookup + entered.enter(); + await resume.promise; + }; + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + try { + await entered.wait(); + assert.equal(r.row(id).provider_id, 'prov-a'); + r.h.queue.holdForDesktop(HELD); + const routeWrites = observeRouteUpdates(r, id); + resume.resolve(); + await settle(); + const client = await readHostSession(getDbClient().drizzle, id); + assert.deepEqual({ + memory: getSessionProvider(id), database: r.row(id).provider_id, client: client.providerId, + pushedRoutes: r.h.events.filter(e => e.type === 'session_changed' && e.sessionId === id && e.patch?.providerId === 'prov-b').length, + updates: routeWrites(), pending: r.selection.hasPendingCredentialSwitch(id), + applied: r.h.events.filter(e => e.channel === 'maker:session-credential-switch-applied').map(e => e.payload.sessionId), + }, { memory: 'prov-a', database: 'prov-a', client: 'prov-a', pushedRoutes: 0, updates: [], pending: true, applied: [] }); + } finally { + resume.resolve(); + } +}); + +function observeRouteUpdates(r, id) { + const sql = r.db.db; + sql.exec(`CREATE TEMP TABLE held_route_writes (id TEXT, model TEXT, provider_id TEXT); + CREATE TEMP TRIGGER record_held_route_write AFTER UPDATE OF model, provider_id ON sessions + BEGIN INSERT INTO held_route_writes VALUES (NEW.id, NEW.model, NEW.provider_id); END`); + return () => sql.prepare('SELECT model, provider_id FROM held_route_writes WHERE id = ?').all(id); +} + +// The actual target source must stay pending across a held turn end. The adjacent budget edit +// exercises external registration, but requests a same-route rebuild. Tier: db, two sources, +// registration through the real credential switch service and the blocking turn's real terminal. +test('profile hold: a credential switch to another source leaves the stored source intact', async t => { + const r = await modelChangeRuntime(t); + const id = 'held-new-source'; + r.views.current = ['prov-a', 'prov-b'].map(provider => ({ ...switchViews('claude-code')[0], id: provider })); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'long job' }); + const live = r.h.maker.getSession(id); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await r.selection.registerPendingCredentialSwitch(id, { model: 'small', providerId: 'prov-b' }); + assert.equal(r.selection.hasPendingCredentialSwitch(id), true); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'the held running turn finishes'); + await settle(); + assert.deepEqual({ pending: r.selection.hasPendingCredentialSwitch(id), stored: r.row(id).provider_id, + model: r.row(id).model, applied: r.h.events.filter(e => e.channel === 'maker:session-credential-switch-applied').map(e => e.payload.providerId) }, + { pending: true, stored: 'prov-a', model: 'big', applied: [] }); +}); + +// Coexistence rule: the running turn may finish during a profile hold. The budget update registers +// a rebuild with the credential switch service. The earlier credential tests registered it directly +// and only covered the open gate. Tier: db, one live task, a budget edit, a hold, then its terminal. +test('profile hold: a credential switch registered by a budget change waits when the running turn ends', async t => { + const r = await modelChangeRuntime(t); + const id = 'held-budget'; + t.after(() => { appliedContextWindowBudgets.delete(id); pendingSessionContextWindowBudgetReconciles.delete(id); }); + await r.createTask(id); + await enqueue(r.h, id, { clientId: 'work', text: 'long job' }); + const live = r.h.maker.getSession(id); + t.mock.timers.enable({ apis: ['setTimeout'] }); + t.after(() => t.mock.timers.reset()); + await taskListUpdate(r)(id, { contextWindowBudget: 100_000 }); + assert.equal(r.selection.hasPendingCredentialSwitch(id), true, 'the budget edit registered a switch'); + // Same-route rebuilds write the same model/provider values. Observe the UPDATE itself. + const routeWrites = observeRouteUpdates(r, id); + r.h.queue.holdForDesktop(HELD); + live.emit({ type: 'done', data: {}, sessionTurnGeneration: live.generation, sessionInstanceId: live.instanceId }); + await settleUntil(() => !r.h.queue.isTurnRunning(id), 'the held running turn finishes'); + await settle(); + assert.deepEqual({ + pending: r.selection.hasPendingCredentialSwitch(id), + sameRuntime: r.h.maker.getSession(id) === live, + routeWrites: routeWrites(), + applied: r.h.events.filter(e => e.channel === 'maker:session-credential-switch-applied').map(e => e.payload.sessionId), + }, { pending: true, sameRuntime: true, routeWrites: [], applied: [] }); +}); + +test('runtime override: a task archived after a fallback and restored starts on its saved route', { timeout: 30_000 }, async t => { + const r = await fallenBackTask(t, 'shelved'); + t.after(bindHostSessionRuntimeHooks(r.selection)); + const update = taskListUpdate(r); + await update('shelved', { status: 'archived' }); + await update('shelved', { status: 'active' }); + assert.equal(r.row('shelved').status, 'active'); + assert.deepEqual(await startedOn(r, 'shelved', 'shelved-1'), { model: 'big', providerId: 'prov-a' }); +}); + +// Rule (the cleanup createSessionRuntimeCleanup runs at an archive or delete discards the task's +// working-directory recovery, register.ts workingDirectoryRecovery.discard; the Host reaches it through the +// input queue and the executor): a recovery note the Agent never received does not outlive the archive. The +// send transaction consumes the note only once the engine accepts the send (makerSendTransaction.ts), so a +// refused send leaves it pending. Gap: no test failed when the discard was not wired. Minimal failing input: +// a send to a task whose directory is gone, refused; an archive and a restore; another send. +test('runtime cleanup: a task archived with an unsent recovery note does not carry it after the restore', { timeout: 30_000 }, async t => { + const gone = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-archived-gone-dir-')); + rmSync(gone, { recursive: true, force: true }); + t.after(() => rmSync(gone, { recursive: true, force: true })); + let r; + r = await modelChangeRuntime(t, { queue: { statDirectory: undefined, readSession: async id => { + const stored = r.row(id); + return { id, status: stored.status, agentKind: 'claude-code', model: stored.model, workingDir: gone, + providerId: stored.provider_id, permissionMode: 'ask', planModeEnabled: false }; + } } }); + t.after(bindHostSessionRuntimeHooks(r.selection)); + await r.createTask('noted'); + // The engine refuses the first send, after the recovery recreated the directory and wrote the note. + // The test waits for the matching send itself to reach the engine (on a loaded machine it arrives after + // waitFor's 200 polls). + const refused = []; + const waiting = []; + const arrival = pattern => new Promise(resolve => { waiting.push({ pattern, resolve }); }); + const arrived = text => { + for (const waiter of waiting.splice(0)) { + if (waiter.pattern.test(text)) waiter.resolve(); else waiting.push(waiter); + } + }; + const create = r.h.maker.createSession; + r.h.maker.createSession = async opts => { + const session = await create(opts); + const send = session.send; + session.send = async (text, sendOpts = {}) => { + const content = typeof text === 'string' ? text : text.content; + if (refused.length > 0) { + const result = await send(text, sendOpts); + arrived(content); + return result; + } + refused.push(content); + arrived(content); + return { accepted: false }; + }; + return session; + }; + const refusedSend = arrival(/first$/); + await r.h.queue.enqueue('noted', { clientId: 'noted-1', text: 'first' }); + await refusedSend; + assert.match(refused[0], /^\[Working directory recovery\]/, 'the refused send carried the note'); + assert.equal(existsSync(gone), true, 'the directory was recreated'); + const update = taskListUpdate(r); + await update('noted', { status: 'archived' }); + await update('noted', { status: 'active' }); + const secondSend = arrival(/second$/); + await r.h.queue.enqueue('noted', { clientId: 'noted-2', text: 'second' }); + await secondSend; + assert.ok(r.h.maker.sessions.get('noted').sent.some(text => /second$/.test(text)), 'the second message reached the engine'); + const sent = r.h.maker.sessions.get('noted').sent; + assert.ok(sent.every(text => !text.includes('[Working directory recovery]')), `no send after the restore carries the old note: ${JSON.stringify(sent)}`); +}); + +// Working-directory move (A5, session-move.ts with the executor's own close): +// - Rule: as the desktop (bootstrap-electron.ts closeIdleSessionForMove), a move closes the task's idle +// runtime so the next send starts one in the new directory; the executor lets go of the closed +// instance (its events no longer reach the task). A Claude task is closed by Maker itself whether or not +// a turn runs (register.ts setLiveCcSessionBridge): Maker settles that turn with its terminal before it +// drops its listeners, so the executor's turn ends instead of staying "running". +// - Gap: the Host had no move; the executor binding was released only on a send's own refresh. +// - Minimal failing input: an idle task moved, a late event from its old runtime, the next send; a Claude +// task moved mid-turn. +// - Tier: unit; the first through the fixture Maker, the second through maker-core's Maker over a fixture +// agent handle (its close semantics are the ones under test). +test('move: an idle runtime closed for a move is let go by the executor, and the next send starts in the new directory with a fresh context', async t => { + t = lifoCleanup(t); + const workingDir = { current: '/tmp/move-from' }; + const h = createHarness({ readSession: async id => ({ id, status: 'active', agentKind: 'codex', model: 'stored-model', + workingDir: workingDir.current, providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + // A remote input: its device note goes to a native context once (see the deduplication test above). + const send = (clientId, count) => runDeviceLinkInvokeContext({ controllerDeviceId: 'phone', controllerPlatform: 'ios', channel: 'maker:input:enqueue' }, + () => h.queue.enqueue('move-idle', { clientId, text: clientId })).then(() => waitFor(() => h.maker.getSession('move-idle')?.sent.length === count)); + await send('first', 1); + const old = h.maker.getSession('move-idle'); + assert.notEqual(old.sent[0], 'first', 'the first input carries the device note'); + old.emit({ type: 'done', data: {} }); + await waitFor(() => !h.queue.isTurnRunning('move-idle')); + const ports = createHostSessionMovePorts({ profileDir: '/nonexistent-profile', getMakerIfReady: () => h.maker, + isTurnRunning: id => h.queue.isTurnRunning(id), closeRuntime: id => h.queue.closeRuntime(id), publish: () => {} }); + assert.equal(await ports.move.closeIdleSessionForMove('move-idle'), true); + assert.equal(h.maker.getSession('move-idle'), null, 'the runtime is closed'); + workingDir.current = '/tmp/move-to'; + await send('second', 1); + const next = h.maker.getSession('move-idle'); + assert.notEqual(next, old); + assert.equal(next.workDir, '/tmp/move-to'); + assert.notEqual(next.sent[0], 'second', 'the new runtime\'s context gets the device note again'); + assert.match(String(next.sent[0]), /second/); +}); + +test('move: a Claude task moved during its turn is closed by Maker, and the executor\'s turn ends', { timeout: 30_000 }, async t => { + const handles = []; + const agent = { + capabilities: Object.fromEntries(['switchModel', 'effort', 'setPermissionModeMidSession', 'rewind', 'memory'] + .map(key => [key, { supported: false, reason: 'not-implemented' }]).concat([['permissionModes', []]])), + startSession: async opts => { + const handle = { id: `native-move-${handles.length}`, agentKind: 'claude-code', model: opts.model, closed: false, + // The turn runs until the runtime is closed: no terminal of its own. + sent: 0, send: async () => { handle.sent += 1; }, steer: async () => {}, abort: async () => {}, + close: async () => { handle.closed = true; }, + events: async function* () { await new Promise(() => {}); }, + getUsageSnapshot: () => undefined, setInteractionResolver: () => {} }; + handles.push(handle); + return handle; + }, + dispose: async () => {}, + }; + const rows = new Map(); + const storage = { + create: async meta => { const row = { ...meta, createdAt: Date.now(), updatedAt: Date.now() }; rows.set(row.id, row); return row; }, + get: async id => rows.get(id) ?? null, + list: async () => [...rows.values()], + update: async (id, patch) => { const next = { ...rows.get(id), ...patch, updatedAt: Date.now() }; rows.set(id, next); return next; }, + compareAndClearSdkSessionId: async () => false, + delete: async id => { rows.delete(id); }, + }; + const silent = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return silent; } }; + const maker = new Maker({ agents: { 'claude-code': agent }, storage, logger: silent }); + t.after(() => maker.shutdown()); + const h = createHarness({ getMaker: () => maker }); + await h.queue.enqueue('move-claude-turn', { clientId: 'c1', text: 'long work', model: 'stored-model' }); + await waitFor(() => handles[0]?.sent === 1); + assert.equal(h.queue.isTurnRunning('move-claude-turn'), true); + const ports = createHostSessionMovePorts({ profileDir: '/nonexistent-profile', getMakerIfReady: () => maker, + isTurnRunning: id => h.queue.isTurnRunning(id), closeRuntime: id => h.queue.closeRuntime(id), publish: () => {} }); + await ports.liveCcSessionBridge.closeSession('move-claude-turn'); + assert.equal(handles[0].closed, true, 'the runtime in the old directory is closed'); + await waitFor(() => !h.queue.isTurnRunning('move-claude-turn') && h.queue.projection('move-claude-turn').turnInProgress === false); +}); + + +// ── Coexistence plan A: the profile hold (input-queue.mjs holdForDesktop / releaseDesktopHold) ───── +// 测试价值 +// - 生产入口:createInputQueue 的 holdForDesktop / releaseDesktopHold(main.ts 按 profile-coexistence.ts 的重扫 +// 调用),以及 enqueue、steer、resume、retryLastError、调度入队、/api/chat、自动续跑和快照恢复这些真实入口。 +// - 规则:并存方案 A(审核方 2026-11-17 定)。开库的桌面在跑时,新的发送一律拒绝,错误码 PRECONDITION_FAILED, +// 带固定标记 HOST_PROFILE_IN_USE_BY_DESKTOP;在跑的回合跑完;排队的不开始;用量上限后的自动继续、中断自动续跑、 +// 快照恢复都不发出(交互锁加 execution-pause 两样都加)。重新打开:等在跑的回合结束 → 重建输入队列运行时 → +// 按库里的快照恢复 → 解锁;桌面期间处理掉的输入不再发,没处理的照常发。 +// - 现有覆盖缺口:之前 Host 不知道桌面在用同一份数据,没有任何闸门。 +// - 最小失败输入:一条在跑、两条排队的任务;一次中断;一份落库的快照;桌面处理掉其中一条(直接改库模拟)。 +// tier:unit(内存假 Maker 与临时 SQLite,计时用假时钟)。 +const HELD = 'HOST_PROFILE_IN_USE_BY_DESKTOP: held for this test'; +const isHeldRefusal = error => error?.code === 'PRECONDITION_FAILED' && error.message === `[PRECONDITION_FAILED] ${HELD}`; + +/** A Host input queue over a temporary SQLite queue store, as in the restart test above. */ +function durableHold(t) { + t = lifoCleanup(t); + const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-hold-')); + const sqlite = new Database(path.join(root, 'queue.sqlite')); + sqlite.exec(`CREATE TABLE IF NOT EXISTS messages(client_id TEXT, session_id TEXT, PRIMARY KEY(session_id, client_id)); + CREATE TABLE IF NOT EXISTS agent_input_queue_snapshots(session_id TEXT PRIMARY KEY, payload TEXT NOT NULL, updated_at INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS sessions(id TEXT PRIMARY KEY, active_turn_started_at INTEGER, last_turn_ended_at INTEGER, provider_id TEXT); + INSERT OR IGNORE INTO sessions(id) VALUES ('held')`); + setCurrentDbClient({ drizzle: drizzle(sqlite) }, 'isolated-test'); + t.after(() => { clearCurrentDbClient(); sqlite.close(); rmSync(root, { recursive: true, force: true }); }); + const record = (id, clientId) => sqlite.prepare('INSERT OR IGNORE INTO messages(session_id,client_id) VALUES (?,?)').run(id, clientId); + const h = createHarness({ + markStarted: markSessionTurnStartedDurable, + markEnded: async (id, at) => { markSessionTurnEnded(id, at); await drainSessionActiveTurnWrites(id); }, + persistQueueSnapshot: saveAgentInputQueueSnapshot, loadQueueSnapshot: loadAgentInputQueueSnapshot, + getPersistedClientIds: getPersistedInputClientIds, + persistMessage: async (id, row) => { if (row.role === 'user') record(id, row.clientId); }, + }); + t.after(() => h.queue.dispose()); + return { ...h, record }; +} + +test('profile hold: every new send is refused, typed; the running turn ends; nothing queued starts', async t => { + const h = durableHold(t); + await h.queue.enqueue('held', { clientId: 'running', text: 'long job' }); + await waitFor(() => h.maker.sessions.get('held')?.sent.length === 1); + await h.queue.enqueue('held', { clientId: 'queued', text: 'next job' }); + h.queue.holdForDesktop(HELD); + assert.equal(h.queue.isHeldForDesktop(), true); + await assert.rejects(h.queue.enqueue('held', { clientId: 'new', text: 'more' }), isHeldRefusal); + await assert.rejects(h.queue.steer('held', { clientId: 'steer', text: 'also this' }), isHeldRefusal); + await assert.rejects(h.queue.resume('held'), isHeldRefusal); + await assert.rejects(h.queue.retryLastError('held'), isHeldRefusal); + await assert.rejects(h.queue.schedulerQueue().enqueuePrompt({ sessionId: 'held' }), isHeldRefusal); + // A new task's first send, and /api/chat: the stream carries the same typed refusal. + await assert.rejects(h.queue.enqueue('other', { clientId: 'first', text: 'hello' }), isHeldRefusal); + const writes = []; + const response = Object.assign(new EventEmitter(), { writableEnded: false, headersSent: false, + writeHead() { this.headersSent = true; }, write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); } }); + const chat = createChatHandler({ events: createEventHub(), readSession: async id => ({ id, status: 'active' }), + enqueue: (id, input) => h.queue.enqueue(id, input), inputStatus: (id, clientId) => h.queue.inputStatus(id, clientId) }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId: 'held', clientId: 'chat', prompt: 'via chat' }))]), response); + assert.ok(writes.some(chunk => chunk.includes(`[PRECONDITION_FAILED] ${HELD}`)), 'the stream says why'); + // An input accepted before the hold still answers its reconnect. + assert.deepEqual((await h.queue.enqueue('held', { clientId: 'queued', text: 'next job' })).pendingQueue.map(i => i.clientId), ['queued']); + assert.equal(await h.queue.releaseDesktopHold(), false, 'not while a turn runs'); + // Editing, removing or moving a queued input writes the queue the desktop may be using: refused too. + await assert.rejects(h.queue.updateText('held', 'queued', 'next job, edited'), isHeldRefusal); + await assert.rejects(h.queue.updateContent('held', 'queued', { text: 'edited' }), isHeldRefusal); + await assert.rejects(h.queue.remove('held', 'queued'), isHeldRefusal); + await assert.rejects(h.queue.move('held', 'queued', 0), isHeldRefusal); + + const session = h.maker.sessions.get('held'); + session.emit({ type: 'done', data: {} }); + await settleUntil(() => !h.queue.isTurnRunning('held'), 'the held turn finished'); + await settle(); + assert.deepEqual(session.sent, ['long job'], 'the queued input does not start'); + const projection = h.queue.projection('held'); + assert.deepEqual(projection.pendingQueue.map(i => i.clientId), ['queued']); + assert.deepEqual(projection.queueInteractionLocks.filter(lock => [PROFILE_HOLD_LOCK, 'execution-pause'].includes(lock)).sort(), + ['execution-pause', PROFILE_HOLD_LOCK].sort(), 'both locks, so the window can show why'); +}); + +test('profile hold: the desktop answered one queued input meanwhile; reopened, the Host sends only the other', async t => { + const h = durableHold(t); + await h.queue.enqueue('held', { clientId: 'running', text: 'long job' }); + await waitFor(() => h.maker.sessions.get('held')?.sent.length === 1); + await h.queue.enqueue('held', { clientId: 'answered', text: 'the desktop sends this' }); + await h.queue.enqueue('held', { clientId: 'waiting', text: 'still waiting' }); + h.queue.holdForDesktop(HELD); + h.maker.sessions.get('held').emit({ type: 'done', data: {} }); + await settleUntil(() => !h.queue.isTurnRunning('held'), 'the held turn finished before the desktop writes'); + // The desktop, on the same database: it sends "answered" (its user row) and saves its queue without it. + h.record('held', 'answered'); + await saveAgentInputQueueSnapshot('held', (await loadAgentInputQueueSnapshot('held')).filter(i => i.clientId !== 'answered')); + assert.equal(await h.queue.releaseDesktopHold(), true); + assert.equal(h.queue.isHeldForDesktop(), false); + const reopened = await h.queue.getProjection('held'); + assert.deepEqual(reopened.pendingQueue.map(i => i.clientId), ['waiting'], 'the queue comes from the database'); + await h.queue.resume('held'); + await waitFor(() => h.maker.sessions.get('held')?.sent.length === 1); + assert.deepEqual(h.maker.sessions.get('held').sent, ['still waiting']); +}); + +test('profile hold: a durable queue restored while held stays unsent, and resume is refused', async t => { + const h = durableHold(t); + // A queue saved before this runtime read it (a restart, or another process). + await saveAgentInputQueueSnapshot('held', [{ clientId: 'saved', text: 'saved work', persistedContent: 'saved work', + model: 'stored-model', workingDir: '/tmp', effort: '', permissionMode: 'ask', + chatMessage: { clientId: 'saved', role: 'user', content: 'saved work' }, + createOpts: { agentKind: 'claude-code', model: 'stored-model', workingDir: '/tmp' } }]); + h.queue.holdForDesktop(HELD); + const restored = await h.queue.getProjection('held'); + assert.deepEqual(restored.pendingQueue.map(i => i.clientId), ['saved']); + assert.ok(restored.queueInteractionLocks.includes(PROFILE_HOLD_LOCK) && restored.queueInteractionLocks.includes('execution-pause'), + 'a task first read while held is held too'); + await assert.rejects(h.queue.resume('held'), isHeldRefusal); + await settle(); + assert.equal(h.maker.sessions.size, 0, 'nothing started'); +}); + +test('profile hold: an interrupted turn waiting for its automatic resume is not resumed', async t => { + const r = await resumeHarness(t); + await r.interrupt(); + r.h.queue.holdForDesktop(HELD); + for (let i = 0; i < 60; i += 1) { t.mock.timers.tick(500); await settle(5); } + assert.equal(r.session.sent.length, 1, 'no automatic resume while held'); + assert.deepEqual(r.h.queue.projection('r').pendingQueue, [], 'and no hidden continuation is queued (or saved)'); + await settle(); + assert.equal(r.errorRows().length, 1, 'the interruption is written to its history, once'); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +test('profile hold: a silent stop decided while held settles without a continuation', async t => { + const r = await silentStopHarness(t); + await r.turn('half done'); + r.h.queue.holdForDesktop(HELD); + await r.decide(); + await settleUntil(() => r.response.writableEnded, 'the stream ends'); + assert.equal(r.session.sent.length, 1, 'no continuation while held'); + assert.ok(r.streamed().some(e => e.type === 'input_receipt' && e.status === 'recorded')); + assert.equal(r.h.queue.projection('s').turnInProgress, false); +}); + +// Regression for 8bcdaae10b, unit tier: the permanent profile hold does not exercise +// the pause spanning a queue write. Edit a queued message while a retry comes due. +test('a retry due during a queue write records the interruption without a retry or banner', async t => { + const write = Promise.withResolvers(); + let writing = false; + const r = await resumeHarness(t, { persistQueueSnapshot: async (_id, snapshot) => { + if (snapshot.some(item => item.text === 'edited tail')) { + writing = true; + await write.promise; + } + } }); + try { + await r.h.queue.enqueue('r', { clientId: 'tail', text: 'later' }); + await r.interrupt(); + assert.ok(r.h.queue.projection('r').autoResumePending); + const editing = r.h.queue.updateText('r', 'tail', 'edited tail'); + await settleUntil(() => writing, 'the edited snapshot reached persistence'); + t.mock.timers.tick(30_000); + await settle(); + assert.equal(r.errorRows().length, 1); + assert.equal(r.h.queue.projection('r').error, null); + assert.deepEqual(r.session.sent, ['long job']); + write.resolve(); + await editing; + t.mock.timers.tick(30_000); + await settle(); + assert.equal(r.session.sendOptions.some(options => options.turnAttemptToken != null), false); + assert.equal(r.errorRows().length, 1); + } finally { + write.resolve(); + t.mock.timers.reset(); + await r.h.queue.dispose(); + } +}); + +// The generic startup-failure test has no proven stopped-subscription receipt. +// Unit: send through /chat, then observe the original input's terminal receipt. +test('a stopped subscription-limited startup rejects the chat input without taking over the retry', async t => { + const hub = createEventHub(); + const h = createHarness({ hub }); + t.after(() => h.queue.dispose()); + const failure = new Error('[SUBSCRIPTION_ACCOUNT_LIMITED] waiting for reset'); + let starts = 0; + h.maker.createSession = async () => { starts++; throw new AgentStartupStoppedError(failure); }; + const writes = []; + const response = Object.assign(new EventEmitter(), { writableEnded: false, headersSent: false, + writeHead() { this.headersSent = true; }, write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); } }); + const chat = createChatHandler({ events: hub, readSession: async id => ({ id, status: 'active' }), + enqueue: (id, input) => h.queue.enqueue(id, input), inputStatus: (id, clientId) => h.queue.inputStatus(id, clientId) }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId: 'limited', clientId: 'original', prompt: 'run' }))]), response); + await waitFor(() => response.writableEnded); + const events = writes.filter(chunk => chunk.startsWith('data:')).map(chunk => JSON.parse(chunk.slice(5))); + assert.ok(events.some(e => e.type === 'input_receipt' && e.clientId === 'original' && e.status === 'interrupted')); + const projection = h.queue.projection('limited'); + assert.match(projection.error, /SUBSCRIPTION_ACCOUNT_LIMITED/); + assert.equal(projection.autoResumePending ?? null, null); + assert.equal(starts, 1); + assert.equal(h.persisted.some(row => row.role === 'user'), false); +}); + +// The Host does not continue after a usage limit yet (coordinator-deps.ts onUsageLimitedTurnError, the +// third batch). The continuation it will run is the coordinator's continueAfterUsageLimitReset; the +// hold's two locks keep that from reaching the agent. +test('profile hold: a usage-limit continuation that comes due is not sent', async () => { + const sent = []; + const coordinator = new AgentInputCoordinator({ + sendToAgent: async (_id, item) => { sent.push(item.text ?? item.content); return 'accepted'; }, + steerToAgent: async () => {}, abortSession: async () => {}, + isTurnRunning: () => false, getTurnGeneration: () => 0, hasPendingInteraction: () => false, + getAgentKind: () => 'claude-code', getSdkSessionId: async () => undefined, + hasAssistantProgressAfter: async () => false, createUserMessage: async () => undefined, + touchUserSend: async () => {}, emitProjection: () => {}, + }); + const item = { clientId: 'quota', text: 'original work', persistedContent: 'original work', model: 'm', effort: '', + permissionMode: 'ask', workingDir: '/tmp', chatMessage: { clientId: 'quota', role: 'user', content: 'original work' }, + createOpts: { agentKind: 'claude-code', model: 'm', workingDir: '/tmp' } }; + const info = { reason: USAGE_LIMIT_RESET_AUTO_RESUME_REASON, attempt: 1, maxAttempts: 3, sessionTotal: 0 }; + const token = coordinator.restoreUsageLimitRecovery('quota-task', + { kind: 'active-turn', item, error: 'weekly limit' }, coordinator.getGeneration('quota-task')); + assert.ok(coordinator.armUsageLimitWait('quota-task', token, Date.now() + 60_000)); + holdTaskForProfile(coordinator, 'quota-task'); + await coordinator.continueAfterUsageLimitReset('quota-task', token, info); + await settle(); + assert.deepEqual(sent, [], 'held: not sent'); +}); + +// ── Owner boundary: the stop comes first (agent/owner-boundary.ts) ───────────────────────────────── +// 测试价值 +// - 生产入口:runOwnerBoundary / createOwnerBoundaryStop(main.ts 的退出登录、会话失效、有序关闭都经它,server.mjs 的 +// HTTP 退出登录先调 begin),配真实的输入队列、执行器、迁移过的 owner 库与回合标记写入(markSessionTurnEnded), +// 退出登录配真实的 logoutHostSession,/chat 配真实的 createChatHandler 与事件中心。 +// - 规则:放行表第五节甲(账号边界停止提前置位,2026-11-17 审核方定)。边界一开始,在跑的回合就成为中断:不写结束时间, +// 下次启动列入中断;退出登录先停运行时、再吊销,吊销失败不让退出登录失败;/chat 流以中断回执收尾。照桌面 +// (bootstrap-electron.ts 账号边界的 beginSessionTurnEndedSuppression,退出时 freezeSessionActiveTurnMarkers)。 +// - 现有覆盖缺口:停止态要到 inputQueue.dispose 才置位;之前拆依赖(暂停请求、关确认窗与插件、服务端吊销)时失败收尾的 +// 回合写下结束时间与错误行,显示成错误;/chat 流在边界时收不到任何回执。 +// - 最小失败输入:一个在跑的回合,在边界开始之后、dispose 之前失败(确定性地在 beforeDispose 里发错误事件)。 +// - tier:unit(内存假 Maker 与迁移过的临时 owner 库,无真实等待)。 +async function boundaryTask(t, id) { + ensureUnitOwner(); + await new OwnerSessionStorage({ db: () => getCurrentDbClientSnapshot().client }).create({ + id, title: 'Owner boundary fixture', agentKind: 'claude-code', model: 'stored-model', providerId: 'xd', workDir: process.cwd() }); + const ended = []; + const hub = createEventHub(); + const h = createHarness({ + hub, + markStarted: markSessionTurnStartedDurable, + markEnded: async (sessionId, at) => { ended.push(sessionId); markSessionTurnEnded(sessionId, at); await drainSessionActiveTurnWrites(sessionId); }, + }); + t.after(() => h.queue.dispose()); + const boundary = createOwnerBoundaryStop({ beginStop: () => h.queue.beginStop() }); + const markers = () => getCurrentDbClientSnapshot().client.queryOne( + 'SELECT active_turn_started_at AS startedAt, last_turn_ended_at AS endedAt FROM sessions WHERE id = ?', [id]); + const errorRows = () => h.persisted.filter(row => row.sessionId === id && row.role === 'error'); + /** The next Host start: its boot time is after this turn started (sessionInterruptionBoot.ts). */ + const interruptedAtNextStart = async () => { + const boot = getSessionInterruptionBootAt(); + _setBootAtMsForTests(Date.now() + 1); + try { return (await listInterruptedPendingRows()).map(row => row.sessionId).includes(id); } + finally { _setBootAtMsForTests(boot); } + }; + const startTurn = async (clientId = `${id}-input`) => { + await h.queue.enqueue(id, { clientId, text: 'long job' }); + await waitFor(() => h.maker.sessions.get(id)?.sent.length === 1); + await drainSessionActiveTurnWrites(id); + return h.maker.sessions.get(id); + }; + return { h, hub, boundary, ended, markers, errorRows, interruptedAtNextStart, startTurn }; +} + +/** A failure of the running turn caused by the boundary's own teardown (a revoke, a closed confirmation). */ +const failRunningTurn = async session => { + session.emit({ type: 'error', data: { message: 'torn down under the turn', isTerminal: true } }); + await settle(); +}; + +const signOutStore = () => { + const records = new Map([[AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'boundary-refresh')]]); + return { records, store: { read: key => records.get(key) ?? null, write: (key, value) => records.set(key, value), remove: key => records.delete(key) } }; +}; + +test('owner boundary, logout: the running turn stops before the revoke, stays interrupted with no error row, and a failed revoke still signs out', async t => { + const b = await boundaryTask(t, 'boundary-logout'); + const session = await b.startTurn(); + const { records, store } = signOutStore(); + const { result, errors } = await runOwnerBoundary(b.boundary, { + beforeDispose: async () => {}, + dispose: () => b.h.queue.dispose(), + afterDispose: () => logoutHostSession({ store, + refresh: async () => { await failRunningTurn(session); return { accessToken: 'boundary-access' }; }, + logout: async () => { throw new Error('revoke unavailable'); } }), + }); + assert.deepEqual(errors, [], 'a failed revoke does not fail the logout'); + assert.equal(result.signedOut, true); + assert.equal(result.serverRevoked, false); + assert.equal(records.has(AUTH_SESSION_KEY), false, 'signed out locally'); + assert.equal(session.aborted, 1, 'stopped before the revoke'); + assert.deepEqual(b.errorRows(), [], 'the revoke reached no running turn'); + assert.deepEqual(b.ended, []); + const markers = await b.markers(); + assert.equal(typeof markers.startedAt, 'number'); + assert.equal(markers.endedAt, null); + assert.equal(await b.interruptedAtNextStart(), true); +}); + +// Review item 3 (8g B, 2026-11-18): a silent-stop decision that comes due after the boundary began sends no +// continuation (a write, torn down at once); the turn ends as an interruption. +test('owner boundary: a silent stop decided after the boundary began sends no continuation, and the turn ends', async t => { + const id = 'boundary-silent-stop'; + const b = await boundaryTask(t, id); + const session = await b.startTurn(); + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: Date.now() }); + t.after(() => t.mock.timers.reset()); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + session.emit({ type: 'text', data: { text: 'half done', isFinal: true }, ...stamp }); + session.emit({ type: 'status', data: { isRunning: false }, ...stamp }); + session.emit({ type: 'done', data: { silentStop: true }, ...stamp }); + await settle(); + const release = b.boundary.begin(); + t.after(release); + t.mock.timers.tick(SILENT_STOP_DECISION_DELAY_MS); + await settleUntil(() => !b.h.queue.projection(id).turnInProgress, 'the turn ends'); + assert.equal(session.sent.length, 1, 'no continuation once the boundary began'); + await drainSessionActiveTurnWrites(id); + assert.equal((await b.markers()).endedAt, null, 'no turn end is written'); + assert.equal(await b.interruptedAtNextStart(), true, 'it is an interrupted task at the next start'); +}); + +// Review item 2 (8g B, 2026-11-18): while a silent-stop continuation runs, the task's turn is still running in +// its markers, so a crash or a boundary then leaves it interrupted ("continue the interrupted task" at the +// next start); its end is written when the continuation ends. +test('owner boundary: a silent-stop continuation that is running counts as a running turn until it ends', async t => { + const id = 'boundary-silent-continuation'; + const b = await boundaryTask(t, id); + const session = await b.startTurn(); + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: Date.now() }); + t.after(() => t.mock.timers.reset()); + const emitTurn = done => { + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'status', data: { isRunning: true }, ...stamp }); + session.emit({ type: 'text', data: { text: 'some work', isFinal: true }, ...stamp }); + session.emit({ type: 'status', data: { isRunning: false }, ...stamp }); + session.emit({ ...done, ...stamp }); + }; + emitTurn({ type: 'done', data: { silentStop: true } }); + await settle(); + t.mock.timers.tick(SILENT_STOP_DECISION_DELAY_MS); + await settleUntil(() => session.sent.length === 2, 'the continuation is sent'); + await drainSessionActiveTurnWrites(id); + assert.equal((await b.markers()).endedAt, null, 'no end while the continuation runs'); + assert.equal(await b.interruptedAtNextStart(), true, 'a crash now leaves an interrupted task'); + emitTurn({ type: 'done', data: {} }); + await settleUntil(() => !b.h.queue.projection(id).turnInProgress, 'the turn ends'); + await drainSessionActiveTurnWrites(id); + assert.equal(typeof (await b.markers()).endedAt, 'number', 'the end is written once the continuation ends'); + assert.equal(await b.interruptedAtNextStart(), false); +}); + +for (const [path, steps] of [ + // Session invalidation: requests paused, confirmations and plugins closed before the runtime (main.ts). + ['session invalidation', session => ({ beforeDispose: () => failRunningTurn(session) })], + // Shutdown: the server stops accepting, codex tool trees are reaped, writers drain (main.ts stop). + ['shutdown', session => ({ beforeDispose: () => failRunningTurn(session) })], + // Logout: the in-flight refresh settles first (main.ts logout). + ['logout', session => ({ beforeDispose: () => failRunningTurn(session), afterDispose: async () => ({ signedOut: true }) })], +]) { + test(`owner boundary, ${path}: a turn that ends on the teardown before dispose writes no end and is interrupted at the next start`, async t => { + const b = await boundaryTask(t, `boundary-teardown-${path.replace(/\W+/g, '-')}`); + const session = await b.startTurn(); + const { errors } = await runOwnerBoundary(b.boundary, { ...steps(session), dispose: () => b.h.queue.dispose() }); + assert.deepEqual(errors, []); + assert.deepEqual(b.ended, [], 'the executor marks no end once the boundary began'); + assert.equal((await b.markers()).endedAt, null); + assert.equal(await b.interruptedAtNextStart(), true); + }); +} + +test('owner boundary: no input is accepted once it began, and the shared turn-end suppression holds until the teardown ends', async t => { + const b = await boundaryTask(t, 'boundary-suppression'); + await b.startTurn(); + let suppressedEnd; + const { errors } = await runOwnerBoundary(b.boundary, { + beforeDispose: async () => { + await assert.rejects(b.h.queue.enqueue('boundary-suppression', { clientId: 'late', text: 'after the boundary' }), /session is closed/); + // Any other turn-end write in the boundary (the desktop's second line): not written. + markSessionTurnEnded('boundary-suppression'); + await drainSessionActiveTurnWrites('boundary-suppression'); + suppressedEnd = (await b.markers()).endedAt; + }, + dispose: () => b.h.queue.dispose(), + }); + assert.deepEqual(errors, []); + assert.equal(suppressedEnd, null); + // Released once the boundary's teardown ended: writes go through again. + markSessionTurnEnded('boundary-suppression'); + await drainSessionActiveTurnWrites('boundary-suppression'); + assert.equal(typeof (await b.markers()).endedAt, 'number'); +}); + +/** A /chat stream into the boundary fixture's queue, as main.ts wires it (onBoundaryStop). */ +async function boundaryChat(b, sessionId, clientId) { + const writes = []; + const response = Object.assign(new EventEmitter(), { writableEnded: false, headersSent: false, destroyed: false, + writeHead() { this.headersSent = true; }, write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); } }); + const chat = createChatHandler({ events: b.hub, readSession: async id => ({ id, status: 'active' }), + enqueue: (id, input) => b.h.queue.enqueue(id, input), inputStatus: (id, input) => b.h.queue.inputStatus(id, input), + onBoundaryStop: b.boundary.onStop }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId, clientId, prompt: 'via chat' }))]), response); + await waitFor(() => b.h.maker.sessions.get(sessionId)?.sent.length === 1); + const events = () => writes.filter(chunk => chunk.startsWith('data: ')).map(chunk => JSON.parse(chunk.slice(6))); + return { response, events }; +} + +test('owner boundary, /chat: the stream ends with the interrupted receipt when the boundary begins, the same receipt a stopped turn gets', async t => { + const b = await boundaryTask(t, 'boundary-chat'); + const stopped = await boundaryChat(b, 'boundary-chat', 'chat-stopped'); + // A turn the user stops: the executor publishes its interrupted receipt, and the stream ends on it. + await b.h.queue.stop('boundary-chat'); + await waitFor(() => stopped.response.writableEnded); + const stoppedReceipt = stopped.events().at(-1); + + const running = await boundaryChat(b, 'boundary-chat-2', 'chat-boundary'); + const teardown = runOwnerBoundary(b.boundary, { dispose: () => b.h.queue.dispose() }); + // Ended as the boundary began, not when the turn would have finished on its own. + assert.equal(running.response.writableEnded, true); + await teardown; + const boundaryReceipt = running.events().at(-1); + const { seq, ...stoppedFields } = stoppedReceipt; + assert.equal(typeof seq, 'number', 'the stopped turn\'s receipt went through the event hub'); + assert.deepEqual(stoppedFields, { type: 'input_receipt', sessionId: 'boundary-chat', inputClientId: 'chat-stopped', + clientId: 'chat-stopped', status: 'interrupted' }); + // The same receipt, written by the stream itself (as its queue-head and reconnect receipts): no hub sequence. + assert.deepEqual(boundaryReceipt, { type: 'input_receipt', sessionId: 'boundary-chat-2', inputClientId: 'chat-boundary', + clientId: 'chat-boundary', status: 'interrupted' }); +}); + +/* + * Turn seal on the last reply (release table 甲 9). + * - Production entry and observable result: the Host executor's turn end (turn-executor.mjs finish) over a + * real profile database; the last top-level assistant row's agent_meta.turnCompleted (and the native fork + * anchor of a successful done). + * - Rule: the desktop's terminal stage (sessionEventTerminal.ts) seals that row through the shared + * persistence core (markAssistantTurnCompleted / markAssistantTurnFailed): completed for a successful + * done (for Codex, raw status completed), failed for a terminal error or an interrupted Codex done. + * History reads use the seal to pick the final answer and the title material, the fork anchor to fork + * natively, and a failed seal so a stopped Codex plan is not shown as finished. + * - Coverage gap: the Host never sealed, every row stayed without turnCompleted. + * - Minimal failing input: one reply then a done leaves no turnCompleted on the row. + * - Tier: unit (node:test, real profile database, the Host event path; no account, network or engine). + * The desktop's terminal stage imports Electron and does not load under Node, so the decisions are + * pinned against its rules rather than run side by side. + */ +test('turn seal: the Host seals the last reply of a turn as the desktop does', { timeout: 30_000 }, async t => { + const db = await recoveryDatabase(t); + const { h } = assembledRuntime(t, db); + const anchor = { agentKind: 'codex', sdkSessionId: 'thread-1', kind: 'turn', id: 'turn-1' }; + const cases = [ + { id: 'seal-done', terminal: { type: 'done', data: {}, agentMeta: { nativeForkAnchor: anchor } }, + meta: { turnCompleted: true, nativeForkAnchor: anchor } }, + { id: 'seal-codex-done', terminal: { type: 'done', source: 'codex', data: { raw: { id: 'turn-2', status: 'completed' } }, + agentMeta: { nativeForkAnchor: anchor } }, meta: { turnCompleted: true, nativeForkAnchor: anchor } }, + { id: 'seal-codex-stopped', terminal: { type: 'done', source: 'codex', data: { raw: { id: 'turn-3', status: 'interrupted' } }, + agentMeta: { nativeForkAnchor: anchor } }, meta: { turnCompleted: false, nativeForkAnchor: anchor } }, + { id: 'seal-error', terminal: { type: 'error', data: { message: 'provider failed', isTerminal: true } }, + meta: { turnCompleted: false } }, + ]; + for (const { id, terminal, meta } of cases) { + await db.createTask(id); + await h.queue.enqueue(id, { clientId: `${id}-input`, text: 'work' }); + await waitFor(() => h.maker.sessions.get(id)?.sent.length === 1); + const session = h.maker.sessions.get(id); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'text', data: { text: `reply of ${id}` }, ...stamp }); + session.emit({ ...terminal, ...stamp }); + await waitFor(() => !h.queue.projection(id).turnInProgress); + const [row] = db.db.prepare("SELECT agent_meta FROM messages WHERE session_id = ? AND role = 'assistant'").all(id); + const agentMeta = JSON.parse(row.agent_meta ?? '{}'); + // The anchor also comes with the done's agent meta when the reply block is written (as on the desktop, + // flushAssistantBlock with the event's meta); the seal adds it for a successful done. + assert.deepEqual({ turnCompleted: agentMeta.turnCompleted, ...(agentMeta.nativeForkAnchor ? { nativeForkAnchor: agentMeta.nativeForkAnchor } : {}) }, + meta, id); + } +}); + +// Rule: the desktop terminal pipeline seals a cancelled done as failed without an error row. +// Gap: the Host only checked Codex's raw status and treated Pi and Claude cancellation as success. +// Minimal input: one partial reply followed by done with status cancelled. Tier: unit through +// the Host input queue and turn executor with a fixture owner database. +for (const [source, status] of [['pi', 'cancelled'], ['claude-code', 'cancelled'], ['claude-code', 'completed']]) { + test(`turn seal: a ${status} ${source} done records the correct completion`, { timeout: 30_000 }, async t => { + t = lifoCleanup(t); + const db = await recoveryDatabase(t); + const id = 'seal-reply'; + await db.createTask(id); + if (source === 'pi') db.db.prepare("UPDATE sessions SET agent_kind = 'pi' WHERE id = ?").run(id); + const { h } = assembledRuntime(t, db, { + readSession: async id => ({ id, status: 'active', agentKind: source, model: 'stored-model', + workingDir: db.root, providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }), + }); + await h.queue.enqueue(id, { clientId: 'seal-input', text: 'work' }); + await waitFor(() => h.maker.getSession(id)?.sent.length === 1); + const session = h.maker.getSession(id); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'text', source, data: { text: 'reply so far' }, ...stamp }); + session.emit({ type: 'done', source, data: { status }, ...stamp }); + await waitFor(() => !h.queue.projection(id).turnInProgress); + + const [reply] = db.db.prepare("SELECT agent_meta FROM messages WHERE session_id = ? AND role = 'assistant'").all(id); + const meta = JSON.parse(reply.agent_meta); + assert.equal(meta.turnCompleted, status === 'completed'); + assert.equal(meta.nativeForkAnchor, undefined); + assert.deepEqual(db.errorRows(id), [], 'a cancelled done adds no error row'); + }); +} + +// The same seal at the boundaries that do not end the Host's turn (release table 甲 9): the desktop's +// terminal stage runs on every done and terminal error, so a continuation boundary of the foreground turn +// and a background turn's terminal each write their reply and seal it. Gap: the Host sealed only at its +// turn end, so the segment before a continuation kept no seal (and was written with the next one only +// when that one began). Minimal failing input: reply, continuation done, reply, done. +test('turn seal: continuation boundaries and background turns are sealed as the desktop seals them', { timeout: 30_000 }, async t => { + const db = await recoveryDatabase(t); + const { h } = assembledRuntime(t, db); + await db.createTask('seal-continued'); + await h.queue.enqueue('seal-continued', { clientId: 'seal-continued-input', text: 'work' }); + await waitFor(() => h.maker.sessions.get('seal-continued')?.sent.length === 1); + const session = h.maker.sessions.get('seal-continued'); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + const replies = () => db.db.prepare("SELECT content, agent_meta FROM messages WHERE session_id = ? AND role = 'assistant' ORDER BY rowid") + .all('seal-continued').map(row => ({ text: row.content, turnCompleted: JSON.parse(row.agent_meta ?? '{}').turnCompleted })); + session.emit({ type: 'text', data: { text: 'first segment' }, ...stamp }); + session.emit({ type: 'done', data: {}, turnContinuationId: 0, ...stamp }); + // The boundary writes and seals the first segment now, before the next one starts. + await waitFor(() => replies().length === 1 && replies()[0].turnCompleted === true); + session.emit({ type: 'text', data: { text: 'second segment' }, ...stamp }); + session.emit({ type: 'done', data: {}, ...stamp }); + await waitFor(() => !h.queue.projection('seal-continued').turnInProgress); + // A background turn after the foreground one ended goes through the same terminal stage. + session.emit({ type: 'text', data: { text: 'background reply' }, turnScope: 'background' }); + session.emit({ type: 'done', data: {}, turnScope: 'background' }); + await waitFor(() => replies().length === 3 && replies()[2].turnCompleted !== undefined); + assert.deepEqual(replies(), [ + { text: 'first segment', turnCompleted: true }, + { text: 'second segment', turnCompleted: true }, + { text: 'background reply', turnCompleted: true }, + ]); +}); + +/* + * Task list activity time at dispatch and steer (release table 甲 10, the coordinator half). + * - Production entry and observable result: the input coordinator over the Host executor and a real profile + * database, with the activity write main.ts gives it (agent/session-activity.ts); the task row's + * last_activity_at and the session_changed patch. + * - Rule: the desktop's coordinator hooks (register.ts onDispatchedUserTurn / onSteerAccepted) write + * touchSessionActivityInDb for a person's input: at dispatch with the time before the vendor call, at an + * accepted steer with now; an automatic resume writes nothing. Same write, now shared + * (localDb/sessionActivityWrite.ts). + * - Coverage gap: the Host left the port empty, so the activity time stayed as the send set it. + * - Minimal failing input: one dispatched input leaves last_activity_at unset. + * - Tier: unit (node:test, real profile database, the Host coordinator). + */ +test('list activity: a dispatched or steered input moves the task\'s activity time forward, as the desktop does', { timeout: 30_000 }, async t => { + const db = await recoveryDatabase(t); + const { createHostSessionActivity } = await import('./session-activity.ts'); + const events = []; + const write = createHostSessionActivity({ getOwner: getCurrentDbClientSnapshot, publish: event => events.push(event) }); + const calls = []; + const { h } = assembledRuntime(t, db, { + touchSessionActivity: async (id, atMs) => { calls.push({ id, atMs }); await write(id, atMs); }, + }); + const activity = id => db.db.prepare('SELECT last_activity_at FROM sessions WHERE id = ?').get(id).last_activity_at; + await db.createTask('activity'); + const beforeDispatch = Date.now(); + await h.queue.enqueue('activity', { clientId: 'activity-input', text: 'work' }); + await waitFor(() => h.maker.sessions.get('activity')?.sent.length === 1); + await waitFor(() => calls.length === 1); + assert.equal(calls[0].id, 'activity'); + // The coordinator's own pre-vendor time is one millisecond before now (agent-input-coordinator.ts). + assert.ok(calls[0].atMs >= beforeDispatch - 1 && calls[0].atMs <= Date.now(), 'the time before the vendor call'); + await waitFor(() => activity('activity') >= calls[0].atMs); + // A steer writes now. Move the stored time back so the forward-only write shows within the same millisecond. + db.db.prepare('UPDATE sessions SET last_activity_at = 1, updated_at = 1 WHERE id = ?').run('activity'); + const session = h.maker.sessions.get('activity'); + session.steer = async () => {}; + await h.queue.steer('activity', { clientId: 'activity-steer', text: 'continue' }); + await waitFor(() => calls.length === 2 && activity('activity') > 1); + assert.equal(calls[1].atMs, undefined, 'a steer writes the current time'); + const row = db.db.prepare('SELECT last_activity_at, updated_at FROM sessions WHERE id = ?').get('activity'); + // The patch the clients get, as broadcastSessionPatched sends it. + assert.deepEqual(events.at(-1), { type: 'session_changed', sessionId: 'activity', + patch: { lastActivityAt: new Date(row.last_activity_at).toISOString(), updatedAt: new Date(row.updated_at).toISOString() } }); +}); + +/* + * List preview after a done (release table 甲 13, the preview half). + * - Production entry and observable result: the Host executor's turn end over a real profile database; the + * session_changed event with the task's list preview. + * - Rule: after a done the desktop's terminal stage drains the write queue and refreshes the list preview + * from the latest visible message (sessionTaskSummary.ts refreshSessionListPreview), whatever the pinned + * section shows; a terminal error does not. + * - Coverage gap: the Host never refreshed it at a turn's end; the task list kept the line it had at send. + * - Minimal failing input: a reply then a done publishes no preview. + * - Tier: unit (node:test, real profile database, the Host event path). + */ +test('list preview: after a done the Host publishes the latest visible message as the task\'s preview', { timeout: 30_000 }, async t => { + const db = await recoveryDatabase(t); + const { h } = assembledRuntime(t, db); + const { latestVisiblePreview } = await import('../../../desktop/src/main/localDb/latestMessageText.ts'); + const previews = id => h.events.filter(event => event.type === 'session_changed' && event.sessionId === id + && event.patch && 'preview' in event.patch).map(event => event.patch.preview); + for (const [id, terminal] of [['preview-done', { type: 'done', data: {} }], + ['preview-error', { type: 'error', data: { message: 'provider failed', isTerminal: true } }]]) { + await db.createTask(id); + await h.queue.enqueue(id, { clientId: `${id}-input`, text: 'work' }); + await waitFor(() => h.maker.sessions.get(id)?.sent.length === 1); + const session = h.maker.sessions.get(id); + const stamp = { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }; + session.emit({ type: 'text', data: { text: `final words of ${id}` }, ...stamp }); + session.emit({ ...terminal, ...stamp }); + await waitFor(() => !h.queue.projection(id).turnInProgress); + } + await waitFor(() => previews('preview-done').length > 0); + // The same line the desktop's own reader gives for this history. + assert.deepEqual(previews('preview-done'), [await latestVisiblePreview('preview-done')]); + assert.match(previews('preview-done')[0], /final words of preview-done/); + assert.deepEqual(previews('preview-error'), [], 'a terminal error refreshes no preview'); + // A background turn's done refreshes it too (the desktop excludes only continuation boundaries). + const session = h.maker.sessions.get('preview-done'); + session.emit({ type: 'text', data: { text: 'background words' }, turnScope: 'background' }); + session.emit({ type: 'done', data: {}, turnScope: 'background' }); + await waitFor(() => previews('preview-done').length === 2); + assert.match(previews('preview-done')[1], /background words/); + assert.deepEqual(previews('preview-done')[1], await latestVisiblePreview('preview-done')); +}); + +// Unit, over a migrated profile database and the Host's media store: a Codex generated image in a turn +// (甲 11). Rule: as the desktop (sessionEventPreparation.ts, generatedImageDelivery.ts), the image's bytes +// go into the media store, the task gets its imagegen tool rows with the stored address and a media +// reference, and clients get those rows and tool events, never the raw image event or its base64; when +// storing fails, the rows and events say so (the desktop's failure path), still without the bytes. +// Gap: the Host listener published the raw event, base64 included, and saved nothing. +// Minimal input: one image event of a running turn, valid or not an image. +const PNG_1X1 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; +async function generatedImageFixture(t, id) { + t = lifoCleanup(t); + const db = await recoveryDatabase(t); + const published = []; + const hub = { publish: event => published.push(event) }; + const persistMessage = createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: event => hub.publish(event) }); + let resumeImageRecovery; + const images = createHostGeneratedImages({ createMessage: persistMessage, publish: event => hub.publish(event), + isProfileHeld: () => h.queue.isHeldForDesktop(), + registerProfileRelease: resumeRecovery => { resumeImageRecovery = resumeRecovery; } }); + const h = createHarness({ hub, persistMessage, getOwner: getCurrentDbClientSnapshot, + deliverCodexGeneratedImage: images.deliverCodexGeneratedImage, + readSession: async sid => ({ id: sid, status: 'active', agentKind: 'codex', model: 'm', workingDir: db.root, + providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }) }); + t.after(() => h.queue.dispose()); + // The fixture's database is fresh: every media reference in it is one of its tasks' images. + const refs = () => db.db.prepare('SELECT hash, ref_kind, ref_id FROM media_refs ORDER BY ref_id').all(); + // A running task of this queue, which can emit a Codex image (its stream hold is recorded). + const openTask = async taskId => { + await db.createTask(taskId); + await enqueue(h, taskId, { clientId: `${taskId}-input`, text: 'draw it' }); + const session = h.maker.getSession(taskId); + const holds = []; + session.holdEventStream = followUps => { holds.push(followUps); return true; }; + const emitImage = data => session.emit({ type: 'image', source: 'codex', sessionTurnGeneration: session.generation, + sessionInstanceId: session.instanceId, data: { kind: 'generation', blockId: 'block-1', threadId: 'thread-1', + turnId: 'turn-1', status: 'completed', ...data } }); + const rows = () => db.db.prepare('SELECT client_id, role, content FROM messages WHERE session_id = ? AND role IN (?, ?) ORDER BY created_at') + .all(taskId, 'tool_use', 'tool_result'); + const endTurn = async () => { + session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + await waitFor(() => published.some(event => event.type === 'done' && event.sessionId === taskId)); + }; + return { session, holds, emitImage, rows, endTurn }; + }; + const first = await openTask(id); + return { ...first, db, h, resumeImageRecovery, published, refs, openTask }; +} +const resultOf = row => JSON.parse(JSON.parse(row.content)); + +test('a Codex generated image is stored, saved as its imagegen rows with a media reference, and published by address, never as base64', { timeout: 30_000 }, async t => { + const f = await generatedImageFixture(t, 'image-stored'); + f.emitImage({ data: PNG_1X1 }); + assert.equal(f.holds.length, 1, 'the stream waits for the delivery'); + const followUps = await f.holds[0]; + assert.deepEqual(followUps.map(event => event.type), ['tool_use', 'tool_result_full', 'tool_result']); + const [use, result] = f.rows(); + assert.equal(use.role, 'tool_use'); + const content = resultOf(result); + assert.equal(content.native_image_delivery.state, 'stored'); + const hash = createHash('sha256').update(Buffer.from(PNG_1X1, 'base64')).digest('hex'); + assert.equal(content.xdt_image_url, `cindy-media://blobs/${hash}.png`); + assert.ok(existsSync(hostBlobStore.resolveSafe(content.xdt_image_url).absPath), 'the bytes are in the media store'); + // The delivery's own pin is released once the delivery settles, after the events are out. + await waitFor(() => f.refs().length === 1); + assert.deepEqual(f.refs(), [{ hash, ref_kind: 'session-attachment', ref_id: 'image-stored' }]); + const wire = JSON.stringify(f.published); + assert.equal(wire.includes(PNG_1X1), false, 'no published event carries the bytes'); + assert.equal(f.published.some(event => event.type === 'image'), false); + assert.ok(f.published.some(event => event.type === 'tool_result_full' && event.persistId === result.client_id + && event.resolvedContent.includes(content.xdt_image_url))); + // The result row reaches clients twice, as on the desktop: when written, and once committed + // (broadcastMessageRow, for the devices that read rows). + assert.equal(f.published.filter(event => event.type === 'message_created' && event.message.clientId === result.client_id + && JSON.stringify(event.message.content).includes(content.xdt_image_url)).length, 2); +}); + +test('a Codex generated image that cannot be stored, arriving after its turn ended, is saved and published as a failed delivery, never as base64', { timeout: 30_000 }, async t => { + bindHostUiText(() => ['en']); + t.after(() => configureUiText((_key, fallback) => fallback)); + const f = await generatedImageFixture(t, 'image-failed'); + const notAnImage = Buffer.from('these bytes are not an image').toString('base64'); + // After the turn has ended, as the desktop handles it in or out of a turn. + await f.endTurn(); + f.emitImage({ data: notAnImage }); + assert.deepEqual((await f.holds[0]).map(event => event.type), ['tool_use', 'tool_result_full', 'tool_result']); + const content = resultOf(f.rows()[1]); + assert.deepEqual(content.native_image_delivery, { id: content.native_image_delivery.id, state: 'failed', errorCode: 'INVALID_IMAGE' }); + assert.equal(content.ok, false); + assert.equal(content.text, 'Image delivery failed. Retry transferring the existing image.'); + assert.deepEqual(f.refs(), []); + assert.equal(JSON.stringify(f.published).includes(notAnImage), false, 'no published event carries the bytes'); + assert.equal(f.published.some(event => event.type === 'image'), false); +}); + +// Unit, over a migrated profile database: three steps of the desktop's event preparation +// (sessionEventPreparationSteps.ts) in the Host listener (甲 12, 甲 14, 甲 15). Rules, as the desktop: +// a card the runtime closes itself leaves the pending cards and its question's decision is saved with +// the withdrawal reason, also once the turn has ended; a standalone notice is its own row and not a +// client text event, in or out of a turn; a Claude Opus plan-mode terminal error carries the +// normalized reason and consumes its observation. Gaps: the Host left the card pending and unsaved +// (and dropped a dismissal outside a turn), kept a notice as reply text, and stored the raw error. +// Minimal input: one question then its withdrawal after done; two notices around a reply; one +// observed Opus 400 then the terminal error. +async function preparationFixture(t, id, { getOwner = getCurrentDbClientSnapshot } = {}) { + t = lifoCleanup(t); + const db = await recoveryDatabase(t); + const published = []; + const hub = { publish: event => published.push(event) }; + const interactions = createInteractionBroker({ hub }); + const persistMessage = createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: event => hub.publish(event) }); + const h = createHarness({ hub, persistMessage, getOwner, interactions, + readSession: async sid => ({ id: sid, status: 'active', agentKind: 'claude-code', model: 'm', workingDir: db.root, + providerId: 'xd', permissionMode: 'ask', planModeEnabled: false }) }); + // As a runtime: the shared interaction router installs its listener on the session. + const create = h.maker.createSession.bind(h.maker); + h.maker.createSession = async opts => { + const session = await create(opts); + session.setInteractionListener = listener => { session.interactionListener = listener; }; + // As maker-core's Session: a runtime recovery receipt has its own listeners, never onEvent. + const recoveryListeners = new Set(); + session.onRuntimeRecovery = listener => { recoveryListeners.add(listener); return () => recoveryListeners.delete(listener); }; + session.emitRuntimeRecovery = event => { for (const listener of [...recoveryListeners]) listener(event); }; + return session; + }; + t.after(() => { interactions.dispose(); return h.queue.dispose(); }); + await db.createTask(id); + await enqueue(h, id, { clientId: `${id}-input`, text: 'go' }); + const session = h.maker.getSession(id); + const turnEvent = event => session.emit({ ...event, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + const endTurn = async () => { + turnEvent({ type: 'done', data: {} }); + await waitFor(() => published.some(event => event.type === 'done')); + }; + const rows = role => db.db.prepare('SELECT content FROM messages WHERE session_id = ? AND role = ?').all(id, role) + .map(row => { try { return JSON.parse(row.content); } catch { return row.content; } }); + return { db, h, published, interactions, session, turnEvent, endTurn, rows }; +} + +test('a question the runtime withdraws after its turn ended leaves the pending cards, and its withdrawal is saved', { timeout: 30_000 }, async t => { + const f = await preparationFixture(t, 'withdrawn'); + const answer = f.session.interactionListener({ requestId: 'question-1', kind: 'ask_user_question', + questions: [{ question: 'Which one?', options: [] }] }, new AbortController().signal); + await waitFor(() => f.interactions.pending('withdrawn').length === 1 && f.rows('ask_user').length === 1); + await f.endTurn(); + f.session.emit({ type: 'interaction_dismissed', data: { requestId: 'question-1', reason: 'question_withdrawn', + withdrawalReason: 'answered in the conversation' } }); + // Before awaiting the answer: a card left pending fails here instead of never settling. + await waitFor(() => f.interactions.pending('withdrawn').length === 0); + assert.deepEqual(await answer, { kind: 'ask_user_question', answers: {}, dismissed: true }); + await waitFor(() => f.rows('ask_user')[0]?.status === 'cancelled'); + assert.equal(f.rows('ask_user')[0].withdrawalReason, 'answered in the conversation'); + assert.deepEqual(f.published.filter(event => event.type === 'interaction_dismissed'), [{ type: 'interaction_dismissed', + sessionId: 'withdrawn', requestId: 'question-1', reason: 'question_withdrawn', withdrawalReason: 'answered in the conversation' }]); +}); + +test('a standalone notice is its own row in and out of a turn, never reply text or a client text event', { timeout: 30_000 }, async t => { + const f = await preparationFixture(t, 'notices'); + f.turnEvent({ type: 'text', standaloneText: true, data: { text: 'Extension ready' } }); + f.turnEvent({ type: 'text', data: { text: 'The reply', isFinal: true }, agentMeta: { uuid: 'reply-1' } }); + await f.endTurn(); + f.session.emit({ type: 'text', standaloneText: true, data: { text: 'Extension stopped' } }); + await waitFor(() => f.rows('assistant').length === 3); + assert.deepEqual(f.rows('assistant').sort(), ['Extension ready', 'Extension stopped', 'The reply']); + assert.equal(f.published.some(event => event.type === 'text' && /Extension/.test(event.data?.text ?? '')), false); +}); + +test('a Claude Opus plan-mode terminal error carries its normalized reason and consumes the observation', { timeout: 30_000 }, async t => { + const f = await preparationFixture(t, 'opus-plan'); + // The observer the Host's Claude proxy installs (anthropicCompatProxyHostCore.ts), on the task's latest request. + recordClaudeRequestRoute(91, 'opus-plan', 'gateway'); + const sink = createClaudeGatewayErrorObserver()({ reqId: 91, method: 'POST', url: '/v1/messages', + upstreamBase: 'https://gateway.example.com', status: 400, requestHeaders: {}, responseHeaders: {}, + requestBody: Buffer.from(JSON.stringify({ model: 'claude-opus-5' })) }); + sink.onData(Buffer.from(JSON.stringify({ type: 'error', error: { type: 'invalid_request', + message: 'Claude Opus is not available with the Claude Pro plan.' } }))); + sink.onEnd(); + f.turnEvent({ type: 'error', data: { message: 'Claude Opus is not available with the Claude Pro plan.' } }); + await waitFor(() => f.published.some(event => event.type === 'error')); + assert.equal(f.published.find(event => event.type === 'error').data.reason, CLAUDE_GATEWAY_OPUS_PLAN_MISMATCH_REASON); + assert.equal(consumeClaudeOpusPlanMismatch('opus-plan'), null, 'the observation was consumed'); + await waitFor(() => f.db.errorRows('opus-plan').length === 1); +}); +/* + * Task list activity at a turn's end, and the held turns (release table 甲 10). + * - Production entries and observable results: the Host executor and coordinator (the queue harness, the + * auto-resume runtime, a stub context-recovery factory), the activity writes the tracker hands to the + * task list write (`touchSessionActivity` with skipActiveGoal true; the coordinator's dispatch and steer + * writes pass none), and the error rows. + * - Rule: the desktop (sessionEventTerminal.ts, register.ts, productTurnFailureOwner.ts) ends a turn's list + * activity at its done or terminal error. A terminal that an automatic resume or a context recovery holds + * ends it held and leaves its owner in the deferred failure gate; the holder's final failure commits it, + * once, at the time the turn ended, but only if that owner is still the current turn: a newer turn keeps + * its own activity and writes it at its own end. The held error row is written once either way. + * - Coverage gap: the Host wrote no activity at a turn's end, and had neither the gate nor the finalizer. + * - Minimal failing inputs: a done writes nothing; a resume that gives up writes nothing; a recovery that + * fails after a newer turn started marks that turn settled, which then writes nothing at its end. + * - Tier: unit (node:test, the queue harness with fake runtimes; no database, account or engine). + */ +const turnEndWrites = calls => calls.filter(call => call.skipActiveGoal === true); +const activitySpy = () => { + const calls = []; + return { calls, touchSessionActivity: async (id, atMs, skipActiveGoal) => { calls.push({ id, atMs, skipActiveGoal }); } }; +}; + +test('list activity: a turn\'s done writes the task\'s activity time at its end, once', async t => { + const spy = activitySpy(); + const h = createHarness({ touchSessionActivity: spy.touchSessionActivity }); + t.after(() => h.queue.dispose()); + await enqueue(h, 'turn-end', { clientId: 'turn-end-input', text: 'work' }); + const session = h.maker.getSession('turn-end'); + session.emit({ type: 'status', data: { isRunning: true } }); + session.emit({ type: 'text', data: { text: 'answer', isFinal: true } }); + const before = Date.now(); + session.emit({ type: 'done', data: {} }); + const after = Date.now(); + await waitFor(() => !h.queue.projection('turn-end').turnInProgress); + session.emit({ type: 'status', data: { isRunning: false } }); + await settle(); + assert.equal(turnEndWrites(spy.calls).length, 1, 'a done and its idle status write once'); + assert.ok(turnEndWrites(spy.calls)[0].atMs >= before && turnEndWrites(spy.calls)[0].atMs <= after); +}); + +test('list activity: a turn an automatic resume holds writes its end time only when the resume gives up, with one error row', async t => { + const spy = activitySpy(); + const r = await resumeHarness(t, { touchSessionActivity: spy.touchSessionActivity }); + r.session.emit({ type: 'status', data: { isRunning: true } }); + const before = Date.now(); + await r.interrupt(); + const after = Date.now(); + assert.deepEqual(turnEndWrites(spy.calls), [], 'held while the resume owns the turn'); + assert.deepEqual(r.errorRows(), []); + // The resume's own send fails: it gives up (the held error row is written, the banner shown). + r.session.send = async () => { throw new Error('vendor failed'); }; + for (let i = 0; i < 100 && !r.response.writableEnded; i += 1) { t.mock.timers.tick(500); await settle(); } + assert.equal(r.response.writableEnded, true); + await settle(); + assert.equal(turnEndWrites(spy.calls).length, 1, 'committed once by the give-up'); + assert.ok(turnEndWrites(spy.calls)[0].atMs >= before && turnEndWrites(spy.calls)[0].atMs <= after, 'at the turn\'s own end'); + assert.equal(r.errorRows().length, 1, 'the held error row exactly once'); + t.mock.timers.reset(); + await r.h.queue.dispose(); + assert.equal(r.errorRows().length, 1); + assert.equal(turnEndWrites(spy.calls).length, 1); +}); + +/* + * A failed turn's paired done is not a successful completion (release table §五 甲, noteFailedTurnCompletionTail). + * - Production entry and observable result: the input queue and the Host turn executor (listen) with the + * shared coordinator, an automatic resume and the product-turn gate; the client stream, the list + * activity write and the turn the queue reports in progress. + * - Rule: the desktop notes a product terminal error's completion tail (sessionEventTerminal.ts) and does + * not treat the unclaimed done of the same generation that follows as a successful completion (no + * onSuccessfulProductTurn, which would clear the held failure; no Worker terminal). The Host has no tail: + * its turn ends at the terminal error (finish), so a same-generation done afterwards takes the ended-turn + * branch (turn.terminal) and an earlier generation's done the generation filter; neither reaches the + * success decision (settleProductTurn) nor the clients. These tests pin that structure. + * - Coverage gap: the coordinator test above pins only that the paired done is not published; nothing pinned + * that it cannot settle the failed turn as completed or end the next turn. + * - Minimal failing input: a terminal error the resume holds, then a done with successful data. + * - Tier: unit (node:test, the queue harness with fake runtimes; no database, account or engine). + */ +test('failed turn tail: the done after a held terminal error does not complete the failed turn', async t => { + const spy = activitySpy(); + const r = await resumeHarness(t, { touchSessionActivity: spy.touchSessionActivity }); + r.session.emit({ type: 'status', data: { isRunning: true } }); + const before = Date.now(); + await r.interrupt(); + const after = Date.now(); + const streamedBefore = r.streamed().length; + // The engine's unclaimed done of the failed turn, with successful data (as Codex and Claude send it). + const token = r.session.sendOptions.at(-1)?.turnAttemptToken; + r.session.emit({ type: 'done', data: {}, ...(typeof token === 'number' ? { turnAttemptToken: token } : {}) }); + await settle(); + assert.equal(r.response.writableEnded, false, 'the stream still follows the resume'); + assert.equal(r.streamed().slice(streamedBefore).some(event => event.type === 'done'), false, 'the paired done reaches no client'); + assert.deepEqual(turnEndWrites(spy.calls), [], 'the failure stays held, not completed'); + // The resume gives up: the held failure is settled at the failed turn's own end. + r.session.send = async () => { throw new Error('vendor failed'); }; + for (let i = 0; i < 100 && !r.response.writableEnded; i += 1) { t.mock.timers.tick(500); await settle(); } + await settle(); + assert.equal(turnEndWrites(spy.calls).length, 1, 'committed once by the give-up'); + assert.ok(turnEndWrites(spy.calls)[0].atMs >= before && turnEndWrites(spy.calls)[0].atMs <= after, 'at the failed turn\'s end'); + assert.equal(r.errorRows().length, 1); + t.mock.timers.reset(); + await r.h.queue.dispose(); +}); + +test('failed turn tail: an earlier generation\'s done does not end the next turn', async t => { + const h = createHarness(); + t.after(() => h.queue.dispose()); + await enqueue(h, 'tail-next', { clientId: 'failed-input', text: 'first' }); + const session = h.maker.getSession('tail-next'); + const failedGeneration = session.generation; + session.emit({ type: 'error', data: { message: 'upstream failed', isTerminal: true }, sessionTurnGeneration: failedGeneration }); + await waitFor(() => !h.queue.projection('tail-next').turnInProgress); + // The failure pauses the queue (as the desktop); the person's next message goes once they resume it. + await h.queue.enqueue('tail-next', { clientId: 'next-input', text: 'second' }); + await h.queue.resume('tail-next'); + await waitFor(() => session.sent.length === 2); + assert.ok(session.generation > failedGeneration); + const published = h.events.length; + session.emit({ type: 'done', data: {}, sessionTurnGeneration: failedGeneration }); + await settle(); + assert.equal(h.queue.projection('tail-next').turnInProgress, true, 'the next turn is still running'); + assert.equal(h.events.slice(published).some(event => event.type === 'done'), false, 'no done reaches the clients'); + session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation }); + await waitFor(() => !h.queue.projection('tail-next').turnInProgress); +}); + +for (const newerTurn of [false, true]) { + test(`list activity: a context recovery that finally fails ${newerTurn ? 'after a newer turn started leaves that turn its own write' : 'commits the held end time'}`, { timeout: 10_000 }, async t => { + const spy = activitySpy(); + let fail; + const failed = new Promise(resolve => { fail = resolve; }); + let started; + const recovering = new Promise(resolve => { started = resolve; }); + const r = recoveryHarness(t, { claim: (_id, _turn, recoverable) => (recoverable ? 'claimed' : 'idle'), + tryRecover: async () => { started(); await failed; return false; } }, { touchSessionActivity: spy.touchSessionActivity }); + const id = newerTurn ? 'recovery-newer' : 'recovery-failed'; + await r.h.queue.enqueue(id, { clientId: `${id}-input`, text: 'long task' }); + await waitFor(() => r.h.maker.sessions.get(id)?.sent.length === 1); + const session = r.h.maker.sessions.get(id); + session.emit({ type: 'status', data: { isRunning: true }, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + const before = Date.now(); + session.emit({ type: 'error', data: OVERFLOW, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + const after = Date.now(); + await recovering; + assert.deepEqual(turnEndWrites(spy.calls), [], 'held while the recovery owns the turn'); + if (newerTurn) { + // A newer turn starts while the recovery still runs. + await r.h.queue.enqueue(id, { clientId: `${id}-next`, text: 'next' }); + await waitFor(() => session.sent.length === 2); + session.emit({ type: 'status', data: { isRunning: true }, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + } + fail(); + await waitFor(() => r.errorRows(id).length === 1); + await settle(); + if (!newerTurn) { + assert.equal(turnEndWrites(spy.calls).length, 1, 'committed once by the final failure'); + assert.ok(turnEndWrites(spy.calls)[0].atMs >= before && turnEndWrites(spy.calls)[0].atMs <= after); + return; + } + assert.deepEqual(turnEndWrites(spy.calls), [], 'the old owner is not the current turn: nothing is committed'); + const beforeDone = Date.now(); + session.emit({ type: 'text', data: { text: 'next answer', isFinal: true }, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + session.emit({ type: 'done', data: {}, sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId }); + await settle(); + assert.equal(turnEndWrites(spy.calls).length, 1, 'the newer turn writes at its own end'); + assert.ok(turnEndWrites(spy.calls)[0].atMs >= beforeDone); + assert.equal(r.errorRows(id).length, 1); + }); +} + +// The product-turn bookkeeping runs in the event callback before the turn's finish (turn-executor.mjs +// guardProductTurn). Rule (release table 甲 10, reviewer 2026-11-18): a failure there costs at most the +// turn's activity time, never its end. Gap: an unguarded throw left the turn without its finish. +// Minimal failing input: a runtime whose turn generation cannot be read, and a terminal error without one. +test('list activity: a failing product-turn step still ends the turn and writes its error row, with one warning', async t => { + const warnings = []; + const h = createHarness({ productTurnLog: { warn: (...args) => warnings.push(args) } }); + t.after(() => h.queue.dispose()); + await enqueue(h, 'guarded', { clientId: 'guarded-input', text: 'work' }); + const session = h.maker.getSession('guarded'); + session.getTurnGeneration = () => { throw new TypeError('generation unavailable'); }; + session.emit({ type: 'error', data: { message: 'provider failed', isTerminal: true } }); + await waitFor(() => !h.queue.projection('guarded').turnInProgress); + assert.equal(h.persisted.filter(row => row.sessionId === 'guarded' && row.role === 'error').length, 1); + assert.deepEqual(warnings, [['product turn bookkeeping failed', { sessionId: 'guarded', error: 'TypeError' }]]); +}); + +// Unit, over a migrated profile database: a runtime retirement that failed after its turn (甲 16). Rule, +// as the desktop (register.ts wires session.onRuntimeRecovery into its pipeline; the preparation step +// localizeRuntimeRecoveryEvent): the receipt becomes a notice in the user's language, saved as an +// assistant row and published, outside any turn, and only for the owner the runtime was wired under. +// Gap: the Host did not subscribe, so a failed Pi retirement left no notice and no row. +// Minimal input: the Host's own retirement receipt (pi-package-runtime-invalidation.ts) after done. +const retirementReceipt = session => ({ type: 'text', source: 'pi', runtimeRecovery: true, + data: { isFinal: true, text: 'restart-cindy-to-refresh-packages' }, + sessionInstanceId: session.instanceId, sessionTurnGeneration: session.generation }); + +test('a runtime retirement that failed after its turn is saved and published as a notice in the user\'s language', { timeout: 30_000 }, async t => { + bindHostUiText(() => ['zh-CN']); + t.after(() => configureUiText((_key, fallback) => fallback)); + const f = await preparationFixture(t, 'retired'); + await f.endTurn(); + f.session.emitRuntimeRecovery(retirementReceipt(f.session)); + const notice = 'Pi 扩展未能完成刷新。请重启 Cindy 后再使用 Pi。'; + await waitFor(() => f.rows('assistant').includes(notice)); + assert.deepEqual(f.rows('assistant'), [notice]); + assert.deepEqual(f.published.filter(event => event.type === 'text').map(event => event.data.text), [notice]); +}); + +test('a runtime retirement receipt after the owner changed saves and publishes nothing', { timeout: 30_000 }, async t => { + let otherOwner = null; + const f = await preparationFixture(t, 'retired-owner', { getOwner: () => otherOwner ?? getCurrentDbClientSnapshot() }); + await f.endTurn(); + const before = f.published.length; + // Another account becomes the owner; this task's runtime was wired under the first one. + otherOwner = { userId: 'another-owner' }; + f.session.emitRuntimeRecovery(retirementReceipt(f.session)); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(f.published.length, before); + assert.deepEqual(f.rows('assistant'), []); + otherOwner = null; // the fixture closes under its own owner +}); + +// Unit, over a migrated profile database and the Host's media store: what the Host's bindings of the +// shared image recovery (agent/generated-images.ts setGeneratedImageRecovery) do to stored images +// (甲 11, the reviewer's four additions). Rules, as the desktop: deleting a task releases its own +// image references and leaves another task's use of the same image; the startup reconcile keeps an +// image the history still references and clears one no task references; reading the history +// recovers an image whose delivery failed once its source is there. Gap: these bindings had no test. +// Minimal input: the same image in two tasks, then one task deleted (with and without its release); +// one image whose file appears after its first delivery failed. +test('deleting a task releases only its own generated-image references; another task\'s use of the same image stays', { timeout: 30_000 }, async t => { + const a = await generatedImageFixture(t, 'image-delete-a'); + const b = await a.openTask('image-delete-b'); + a.emitImage({ data: PNG_1X1 }); + b.emitImage({ data: PNG_1X1 }); + await Promise.all([a.holds[0], b.holds[0]]); + const hash = createHash('sha256').update(Buffer.from(PNG_1X1, 'base64')).digest('hex'); + await waitFor(() => a.refs().length === 2); + // As main.ts deleteSession: the task row goes, then the shared recovery releases its images. + await a.db.deleteTask('image-delete-a'); + await recoverGeneratedImagesForHistory('image-delete-a'); + assert.deepEqual(a.refs(), [{ hash, ref_kind: 'session-attachment', ref_id: 'image-delete-b' }]); + assert.ok(existsSync(hostBlobStore.resolveSafe(resultOf(b.rows()[1]).xdt_image_url).absPath), 'the shared bytes stay'); +}); + +test('the startup reconcile keeps an image the history still references and clears one no task references', { timeout: 30_000 }, async t => { + const kept = await generatedImageFixture(t, 'image-kept'); + const orphan = await kept.openTask('image-orphan'); + kept.emitImage({ data: PNG_1X1 }); + orphan.emitImage({ data: PNG_1X1 }); + await Promise.all([kept.holds[0], orphan.holds[0]]); + await waitFor(() => kept.refs().length === 2); + // A task deleted without its release (the process stopped first): only the reconcile can clear it. + await kept.db.deleteTask('image-orphan'); + await reconcileGeneratedImageRecovery(); + const hash = createHash('sha256').update(Buffer.from(PNG_1X1, 'base64')).digest('hex'); + assert.deepEqual(kept.refs(), [{ hash, ref_kind: 'session-attachment', ref_id: 'image-kept' }]); + assert.equal(resultOf(kept.rows()[1]).native_image_delivery.state, 'stored'); +}); + +test('reading the history recovers a generated image whose delivery failed, once its source is there', { timeout: 30_000 }, async t => { + const f = await generatedImageFixture(t, 'image-recover'); + const file = path.join(f.db.root, 'generated image.png'); + f.emitImage({ path: file }); + await f.holds[0]; + assert.deepEqual(resultOf(f.rows()[1]).native_image_delivery.state, 'failed'); + writeFileSync(file, Buffer.from(PNG_1X1, 'base64')); + // The first page of the task's messages (/api/messages/list, main.ts messagesList), as the + // desktop's messages list, starts the recovery. + await readMessagesList('image-recover'); + await waitFor(() => resultOf(f.rows()[1]).native_image_delivery.state === 'stored'); + const hash = createHash('sha256').update(Buffer.from(PNG_1X1, 'base64')).digest('hex'); + assert.equal(resultOf(f.rows()[1]).xdt_image_url, `cindy-media://blobs/${hash}.png`); + await waitFor(() => f.refs().length === 1); + assert.deepEqual(f.refs(), [{ hash, ref_kind: 'session-attachment', ref_id: 'image-recover' }]); +}); + +// Rule: history reads remain available during a desktop hold without writing shared images. +// Gap: the history hook retried failed deliveries even on the read-only path. Minimal input: +// one failed image whose source becomes available during a hold. Tier: unit with a fixture +// owner database, the Host history reader, and the real image delivery and media stores. +test('reading history during a desktop hold defers image recovery until release', { timeout: 30_000 }, async t => { + const id = 'image-recover-held'; + const f = await generatedImageFixture(t, id); + const file = path.join(f.db.root, 'generated image.png'); + f.emitImage({ path: file }); + await f.holds[0]; + await f.endTurn(); + await waitFor(() => !f.h.queue.projection(id).turnInProgress); + const before = f.rows(); + assert.equal(resultOf(before[1]).native_image_delivery.state, 'failed'); + writeFileSync(file, Buffer.from(PNG_1X1, 'base64')); + f.h.queue.holdForDesktop('Desktop is using the profile'); + assert.ok((await readMessagesList(id)).length > 0, 'history remains available'); + // Join the read-side hook if it started a recovery so the write check does not race it. + await recoverGeneratedImagesForHistory(id); + assert.deepEqual(f.rows(), before); + assert.deepEqual(f.refs(), []); + + assert.equal(await f.h.queue.releaseDesktopHold(), true); + await f.resumeImageRecovery(); + assert.equal(resultOf(f.rows()[1]).native_image_delivery.state, 'stored'); + assert.equal(f.refs().length, 1); +}); + +// Unit: the Host broker's clearPending only takes the dismissing task's own card (甲 12). Rule: a +// runtime closes its own cards; another task's request id leaves the card pending and unsaved. +// Gap: the check had no test. Minimal input: one pending question, dismissed by another task's runtime. +test('a dismissal from another task\'s runtime leaves this task\'s card pending and unsaved', { timeout: 30_000 }, async t => { + const f = await preparationFixture(t, 'card-owner'); + await f.db.createTask('card-other'); + await enqueue(f.h, 'card-other', { clientId: 'card-other-input', text: 'go' }); + const other = f.h.maker.getSession('card-other'); + const answer = f.session.interactionListener({ requestId: 'question-own', kind: 'ask_user_question', + questions: [{ question: 'Which one?', options: [] }] }, new AbortController().signal); + await waitFor(() => f.interactions.pending('card-owner').length === 1 && f.rows('ask_user').length === 1); + other.emit({ type: 'interaction_dismissed', data: { requestId: 'question-own', reason: 'question_withdrawn', withdrawalReason: 'not this task' } }); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(f.interactions.pending('card-owner').length, 1); + assert.notEqual(f.rows('ask_user')[0].status, 'cancelled'); + // The task's own runtime still closes it. + f.session.emit({ type: 'interaction_dismissed', data: { requestId: 'question-own', reason: 'question_withdrawn' } }); + await waitFor(() => f.interactions.pending('card-owner').length === 0); + assert.deepEqual(await answer, { kind: 'ask_user_question', answers: {}, dismissed: true }); +}); + +/* + * The silent-stop continuation (release table row 31, 8g B; agent/silent-stop.ts). + * - Production entries and observable results: the Host's input queue, executor and coordinator with the + * auto-resume runtime's silent-stop guard, and /api/chat (chat.mjs). Observed: what the engine receives + * (the hidden 继续), the rows written (its user row, the exhausted marker), the stream's events and end, + * the runtime's continuation claim, and the task list activity writes (touchSessionActivity). + * - Rule: the desktop (sessionTurnObserver.ts, sessionEventPreparation.ts, silentStopTurnEnd.ts, + * silentStopSettle.ts, sessionEventTerminal.ts:496): a silent-stop done keeps its turn (the runtime keeps + * the generation) and is decided 1.5 s later: a hidden 继续 continues the same turn on a new generation + * (two per person's message), or the turn settles (queued work, the setting off, a held profile), or it + * pauses with the 继续 banner. The turn's activity end is held until then and written once. Reviewer + * 2026-11-18: /api/chat follows the continuation to its end. + * - Coverage gap: the Host ended a silent-stop done as a finished turn and never continued it. + * - Minimal failing input: one silent-stop done of a person's message. + * - Tier: unit (node:test, the queue harness with a fake runtime; mocked setTimeout and Date). + */ +const SILENT_STOP_DONE = { type: 'done', data: { silentStop: true } }; +async function silentStopHarness(t, { disabled = false, failBanner = false, queue = {} } = {}) { + const profile = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-silent-stop-')); + if (disabled) writeFileSync(path.join(profile, SILENT_STOP_AUTO_RESUME_SETTINGS_FILE), JSON.stringify({ enabled: false })); + const spy = activitySpy(); + const hub = createEventHub(); + // failBanner: publishing the exhausted banner throws (a failing subscriber of the Host's event hub). + const publishing = failBanner ? { publish(event) { + if (event.type === 'error' && event.data?.reason === 'silent-stop-exhausted') throw new Error('event hub failed'); + hub.publish(event); + } } : hub; + const h = createHarness({ hub: publishing, userDataDir: () => profile, touchSessionActivity: spy.touchSessionActivity, + hasAssistantProgressAfter: async () => true, ...queue }); + t.after(async () => { t.mock.timers.reset(); await h.queue.dispose(); rmSync(profile, { recursive: true, force: true }); }); + const writes = []; + const response = Object.assign(new EventEmitter(), { + writableEnded: false, headersSent: false, + writeHead() { this.headersSent = true; }, + write(chunk) { writes.push(String(chunk)); }, + end(chunk) { if (chunk) writes.push(String(chunk)); this.writableEnded = true; this.emit('close'); }, + }); + const chat = createChatHandler({ events: hub, readSession: async id => ({ id, status: 'active' }), + enqueue: (id, input) => h.queue.enqueue(id, input), inputStatus: (id, clientId) => h.queue.inputStatus(id, clientId) }); + await chat(Readable.from([Buffer.from(JSON.stringify({ sessionId: 's', clientId: 'a', prompt: 'long job' }))]), response); + await waitFor(() => h.maker.sessions.get('s')?.sent.length === 1); + const session = h.maker.sessions.get('s'); + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: Date.now() }); + const streamed = () => writes.filter(w => w.startsWith('data:')).map(w => JSON.parse(w.slice(5))); + // As Maker stamps a turn's events: its generation and runtime instance, and the attempt token its send carried. + const stamp = () => { + const token = session.sendOptions.at(-1)?.turnAttemptToken; + return { sessionTurnGeneration: session.generation, sessionInstanceId: session.instanceId, + ...(typeof token === 'number' ? { turnAttemptToken: token } : {}) }; + }; + // One engine turn: it starts, writes, goes idle and ends with a silent-stop done unless another done is + // given (the translators send the idle status before the done). + const turn = async (text, done = SILENT_STOP_DONE) => { + session.emit({ type: 'status', data: { isRunning: true }, ...stamp() }); + session.emit({ type: 'text', data: { text, isFinal: true }, ...stamp() }); + session.emit({ type: 'status', data: { isRunning: false }, ...stamp() }); + session.emit({ ...done, ...stamp() }); + await settle(); + }; + const decide = async () => { t.mock.timers.tick(SILENT_STOP_DECISION_DELAY_MS); await settle(); }; + const sent = count => settleUntil(() => session.sent.length >= count, `${count} message(s) sent to the engine`); + const ended = () => settleUntil(() => r.response.writableEnded, 'the stream ends'); + const r = { h, session, response, streamed, spy, turn, decide, sent, ended, + rows: role => h.persisted.filter(row => row.role === role), + turnEnds: () => turnEndWrites(spy.calls).map(call => call.atMs) }; + return r; +} + +test('silent stop: the turn continues on a new generation with a hidden 继续; the stream and the activity time follow it to its end', async t => { + const r = await silentStopHarness(t); + await r.turn('half done'); + assert.equal(r.response.writableEnded, false, 'the stream waits for the decision'); + assert.equal(r.h.queue.projection('s').turnInProgress, true, 'the turn still runs'); + assert.equal(r.session.continuationClaim, 1, 'the runtime keeps its generation for the continuation'); + assert.deepEqual(r.turnEnds(), [], 'the end is held'); + await r.decide(); + await r.sent(2); + assert.equal(r.session.sent[1], '继续'); + assert.deepEqual(r.rows('user').filter(row => row.content === '继续').map(row => row.agentMeta), + [{ delivery: 'turn', autoResume: true }], 'one hidden user row, marked as automatic'); + t.mock.timers.tick(1_000); + const continuationEnd = Date.now(); + await r.turn('the rest', { type: 'done', data: {} }); + await r.ended(); + assert.ok(r.streamed().some(e => e.type === 'text' && e.data?.text === 'the rest'), 'the continuation reaches the stream'); + await settle(); + assert.deepEqual(r.turnEnds(), [continuationEnd], 'written once, at the continuation\'s end'); + assert.equal(r.h.queue.projection('s').turnInProgress, false); +}); + +test('silent stop: once the continuations are spent the turn pauses with the 继续 banner, its marker row written once', async t => { + const r = await silentStopHarness(t); + await r.turn('one'); + await r.decide(); + await r.sent(2); + t.mock.timers.tick(6_000); + await r.turn('two'); + await r.decide(); + await r.sent(3); + t.mock.timers.tick(6_000); + const doneAt = Date.now(); + await r.turn('three'); + await r.decide(); + await r.ended(); + assert.equal(r.session.sent.length, 3, 'no third continuation for one message'); + assert.deepEqual(r.rows('error').map(row => [row.content.reason, row.content.silentStopFailureCause]), + [['silent-stop-exhausted', 'budget']]); + assert.ok(r.streamed().some(e => e.type === 'error' && e.data?.reason === 'silent-stop-exhausted'), 'the banner reaches the clients'); + await settleUntil(() => !r.h.queue.projection('s').turnInProgress, 'the turn ends'); + assert.deepEqual(r.turnEnds(), [doneAt], 'written once, at the stopped turn\'s end'); +}); + +// Review item 1 (2026-11-18): a step of the shared decision that throws before its settle (here the banner's +// broadcast) must not leave the turn open and the task's next inputs queued until a restart. +test('silent stop: a decision that fails before its settle still ends the turn, and the next input runs', async t => { + const r = await silentStopHarness(t, { failBanner: true }); + await r.turn('one'); + await r.decide(); + await r.sent(2); + t.mock.timers.tick(6_000); + await r.turn('two'); + await r.decide(); + await r.sent(3); + t.mock.timers.tick(6_000); + await r.turn('three'); + await r.decide(); + await settleUntil(() => !r.h.queue.projection('s').turnInProgress, 'the turn ends'); + await r.ended(); + assert.ok(r.streamed().some(e => e.type === 'input_receipt' && e.status === 'recorded'), 'the stream ends with the recorded receipt'); + assert.equal(r.session.continuationClaim, null, 'the claim is released'); + await r.h.queue.enqueue('s', { clientId: 'b', text: 'next' }); + await r.sent(4); + assert.equal(r.session.sent[3], 'next'); +}); + +test('silent stop: a message sent within the decision window takes over; the stopped turn ends once, at its done', async t => { + const r = await silentStopHarness(t); + const doneAt = Date.now(); + await r.turn('half done'); + await r.h.queue.enqueue('s', { clientId: 'b', text: 'something else' }); + await r.decide(); + await r.sent(2); + assert.equal(r.session.sent[1], 'something else', 'the message runs, no continuation'); + await r.ended(); + assert.ok(r.streamed().some(e => e.type === 'input_receipt' && e.status === 'recorded')); + assert.deepEqual(r.turnEnds(), [doneAt]); +}); + +test('silent stop: with the continuation switched off in the profile, the turn ends as a done after the decision', async t => { + const r = await silentStopHarness(t, { disabled: true }); + const doneAt = Date.now(); + await r.turn('half done'); + await r.decide(); + await r.ended(); + assert.equal(r.session.sent.length, 1, 'no continuation'); + assert.deepEqual(r.rows('error'), []); + assert.deepEqual(r.turnEnds(), [doneAt]); + assert.equal(r.session.continuationClaim, null, 'the claim is released'); +}); + +test('silent stop: a resumed turn that stops silently continues too; the stream of the input it resumed ends with it', async t => { + const r = await silentStopHarness(t); + r.session.emit({ type: 'text', data: { text: 'half done', isFinal: true }, ...{ sessionTurnGeneration: r.session.generation } }); + r.session.emit({ type: 'error', data: INTERRUPTION, sessionTurnGeneration: r.session.generation }); + await settle(); + for (let i = 0; i < 100 && r.session.sent.length < 2; i += 1) { t.mock.timers.tick(500); await settle(); } + await r.sent(2); + await r.turn('resumed half'); + assert.equal(r.response.writableEnded, false); + await r.decide(); + await r.sent(3); + assert.equal(r.session.sent[2], '继续'); + t.mock.timers.tick(1_000); + const continuationEnd = Date.now(); + await r.turn('the rest', { type: 'done', data: {} }); + await r.ended(); + assert.deepEqual(r.rows('error'), [], 'no error row: the resume and the continuation answered the input'); + await settle(); + assert.deepEqual(r.turnEnds(), [continuationEnd], 'the activity time once, at the continuation\'s end'); +}); + +test('silent stop: the caller leaving during the decision does not stop the continuation', async t => { + const r = await silentStopHarness(t); + await r.turn('half done'); + r.response.emit('close'); + await r.decide(); + await r.sent(2); + assert.equal(r.session.sent[1], '继续'); + await r.turn('the rest', { type: 'done', data: {} }); + await settleUntil(() => !r.h.queue.projection('s').turnInProgress, 'the turn ends'); +}); + +/* + * A credential switch that waits for another task's turn (release table, 8g B review item 4). + * - Production entries and observable results: the Host's input queue, executor and the shared coordinator; + * observed: whether task B's input reaches its engine once task A's turn ends. + * - Rule: the desktop's coordinator keeps B's input at the head while a credential switch waits for A's turn + * (CREDENTIAL_SWITCH_BUSY) and drains it when any task's turn settles (register.ts sessionEventDelivery.ts + * onExternalTurnSettled), or after its 10 s fallback timer. + * - Coverage gap: the Host's turn end (finish) does not call onExternalTurnSettled. + * - Minimal failing input: A runs, B's start reports A busy, A's turn ends. + * - Tier: unit (queue harness, fake runtimes; mocked setTimeout so the fallback timer never fires). + */ +async function waitForOtherTasksCredentials(t, queue = {}) { + const h = createHarness(queue); + t.after(async () => { t.mock.timers.reset(); await h.queue.dispose(); }); + await enqueue(h, 'blocker', { clientId: 'a1', text: 'long job' }); + const create = h.maker.createSession; + let refused = 0; + h.maker.createSession = async opts => { + if (opts.id === 'waiter' && refused === 0) { + refused += 1; + throw new CredentialModeSwitchBusyError(['blocker']); + } + return create(opts); + }; + t.mock.timers.enable({ apis: ['setTimeout'] }); + await h.queue.enqueue('waiter', { clientId: 'b1', text: 'needs the switch' }); + await settleUntil(() => h.queue.projection('waiter').credentialSwitchWait?.clientId === 'b1', 'the input waits for the switch'); + return h; +} + +async function finishCredentialBlocker(h) { + h.maker.getSession('blocker').emit({ type: 'done', data: {} }); + await settleUntil(() => !h.queue.projection('blocker').turnInProgress, 'the blocking turn ends'); + await settle(); +} + +test('credential switch: a task waiting for another task\'s turn sends once that turn ends', async t => { + const h = await waitForOtherTasksCredentials(t); + await finishCredentialBlocker(h); + await settleUntil(() => h.maker.getSession('waiter')?.sent.length, 'the waiting input reaches its engine'); + assert.equal(h.maker.getSession('waiter')?.sent.length, 1, 'the waiting input reaches its engine when the blocking turn ends'); +}); + +// Coexistence and owner-boundary rules: a blocker finishing may drain another task only while +// dispatch is allowed. The existing same-task hold and shutdown tests have no credential waiter. +// Tier: unit, through queue admission, both boundary entries and the blocking engine's terminal; +// one running task and one waiting input, with the credential retry clock frozen. +for (const [boundary, enter] of [ + ['profile hold', queue => queue.holdForDesktop(HELD)], + ['beginStop', queue => queue.beginStop()], +]) { + test(`credential switch: a blocker ending during ${boundary} leaves the other task queued`, async t => { + const h = await waitForOtherTasksCredentials(t); + enter(h.queue); + await finishCredentialBlocker(h); + assert.deepEqual(h.maker.getSession('waiter')?.sent ?? [], []); + assert.equal(h.queue.projection('waiter').credentialSwitchWait?.clientId, 'b1'); + }); +} diff --git a/apps/host/src/agent/interactions.mjs b/apps/host/src/agent/interactions.mjs index 8c555284242..198f70e2619 100644 --- a/apps/host/src/agent/interactions.mjs +++ b/apps/host/src/agent/interactions.mjs @@ -1,5 +1,6 @@ import { installDesktopInteractionHandler, requestHostInteraction, allowHostPagePermission } from '../../../desktop/src/main/maker-ipc/interactionRouter.ts'; import { redactToolInputForUntrustedBoundary } from '../../../desktop/src/main/toolInputRedaction.ts'; +import { defaultDecisionForPending } from '../../../desktop/src/main/maker-ipc/sessionEventPreparationSteps.ts'; /** Client presentation for the shared Session interaction router. Routing, * aborts and unattended-turn policy remain the same as Desktop and IM. */ @@ -7,10 +8,8 @@ export function createInteractionBroker(deps) { const pending = new Map(); const bindings = new Map(); - /** @returns {import('@cindy/maker-core').InteractionDecision} */ - const fallback = (request, reason) => request.kind === 'ask_user_question' - ? { kind: request.kind, answers: {}, dismissed: true } - : { kind: request.kind, behavior: 'deny', reason, dismissed: true }; + // A card closed without an answer (abort, replaced runtime, owner change, duplicate request id) gets + // the desktop's default decision (register.ts uses the same defaultDecisionForPending). function settle(entry, decision, reason) { if (pending.get(entry.request.requestId) !== entry) return false; @@ -32,7 +31,7 @@ export function createInteractionBroker(deps) { if (!binding) return; bindings.delete(sessionId); for (const entry of pending.values()) { - if (entry.binding === binding) settle(entry, fallback(entry.request, reason), reason); + if (entry.binding === binding) settle(entry, defaultDecisionForPending(entry.request.kind, reason), reason); } } @@ -46,10 +45,10 @@ export function createInteractionBroker(deps) { bindings.set(sessionId, binding); installDesktopInteractionHandler(session, request => { if (!binding.isCurrent() || bindings.get(sessionId) !== binding) { - return Promise.resolve(fallback(request, 'owner_changed')); + return Promise.resolve(defaultDecisionForPending(request.kind, 'owner_changed')); } if (!request.requestId || pending.has(request.requestId)) { - return Promise.resolve(fallback(request, 'duplicate_request_id')); + return Promise.resolve(defaultDecisionForPending(request.kind, 'duplicate_request_id')); } return new Promise(resolve => { binding.history?.flushAssistantBlock(sessionId); @@ -82,7 +81,7 @@ export function createInteractionBroker(deps) { requestHost(sessionId, request, signal, options) { signal.throwIfAborted(); - if (!options.isCurrent()) return Promise.resolve(fallback(request, 'owner_changed')); + if (!options.isCurrent()) return Promise.resolve(defaultDecisionForPending(request.kind, 'owner_changed')); // Historical cards have no running Agent. The interaction-only object is // the same surface used by Desktop; it cannot execute a task or grant FS. const session = options.session ?? bindings.get(sessionId)?.session @@ -106,7 +105,7 @@ export function createInteractionBroker(deps) { const entry = pending.get(String(requestId ?? '')); if (!entry || (sessionId && entry.binding.sessionId !== sessionId)) return false; if (!entry.binding.isCurrent() || bindings.get(entry.binding.sessionId) !== entry.binding) { - settle(entry, fallback(entry.request, 'owner_changed'), 'owner_changed'); + settle(entry, defaultDecisionForPending(entry.request.kind, 'owner_changed'), 'owner_changed'); return false; } if (entry.binding.isPaused()) return false; @@ -122,6 +121,16 @@ export function createInteractionBroker(deps) { return settle(entry, { ...decision, kind }, 'resolved'); }, + /** As the desktop's clearPendingInteraction (register.ts): the card leaves the pending ones, unsettled; + * the caller resolves it and saves its decision (sessionEventPreparationSteps.ts). Only the task's own + * card: another task's request id is not this runtime's to close. */ + clearPending(requestId, sessionId) { + const entry = pending.get(requestId); + if (!entry || entry.binding.sessionId !== sessionId) return null; + pending.delete(requestId); + return { kind: entry.request.kind, request: entry.request, persistId: entry.persistId, resolve: entry.resolve }; + }, + detach, dispose() { for (const id of bindings.keys()) detach(id); }, }; diff --git a/apps/host/src/agent/interactions.test.mjs b/apps/host/src/agent/interactions.test.mjs index 326f97c6244..d10944c4e57 100644 --- a/apps/host/src/agent/interactions.test.mjs +++ b/apps/host/src/agent/interactions.test.mjs @@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url'; import { createInteractionBroker } from './interactions.mjs'; import { redactToolInputForUntrustedBoundary } from '../../../desktop/src/main/toolInputRedaction.ts'; import { beginUnattendedTurn } from '../../../desktop/src/main/mcp-integrations/unattendedTurn.ts'; +import { defaultDecisionForPending } from '../../../desktop/src/main/maker-ipc/sessionEventPreparationSteps.ts'; function createSession(id = 'task') { const session = { @@ -200,3 +201,22 @@ test('permission requests leave the Host with the desktop tool-input redaction', assert.deepEqual(events.at(-1).request, question); broker.dispose(); }); + +// Unit, the broker's real attach and detach: a task stopped with its cards pending (main.ts passes the +// abort's reason to detach). Rule: each card gets the desktop's default decision for a card closed +// without an answer (register.ts defaultDecisionForPending), the same one the clients are told. +// Gap: the broker had its own fallback, whose permission decision also carried dismissed: true. +// Minimal input: one pending card of each kind, then the task's abort. +test('a stopped task closes its pending cards with the desktop\'s default decisions', async () => { + const events = []; + const broker = createInteractionBroker({ hub: { publish: event => events.push(event) } }); + const session = createSession('stopped'); + broker.attach(session, 'stopped'); + const kinds = ['permission', 'ask_user_question', 'plan_review']; + const decisions = kinds.map(kind => session.listener({ requestId: `${kind}-card`, kind })); + broker.detach('stopped', 'session_aborted'); + const expected = kinds.map(kind => defaultDecisionForPending(kind, 'session_aborted')); + assert.deepEqual(await Promise.all(decisions), expected); + assert.deepEqual(expected[0], { kind: 'permission', behavior: 'deny', reason: 'session_aborted' }); + assert.deepEqual(events.filter(event => event.type === 'interaction_dismissed').map(event => event.decision), expected); +}); diff --git a/apps/host/src/agent/learn-send.test.mjs b/apps/host/src/agent/learn-send.test.mjs index faa416dca56..34db079b132 100644 --- a/apps/host/src/agent/learn-send.test.mjs +++ b/apps/host/src/agent/learn-send.test.mjs @@ -71,6 +71,8 @@ function recordingMaker(f) { async function harness(t) { const f = await learnFixture(t); + // The runtime start writes the task's provider (as the desktop's bootstrapSession): the column it writes. + f.sqlite.exec('CREATE TABLE sessions(id TEXT PRIMARY KEY, provider_id TEXT)'); const maker = recordingMaker(f); const persisted = []; const queue = createInputQueue({ @@ -82,6 +84,8 @@ async function harness(t) { persistMessage: async (sessionId, input) => { persisted.push({ sessionId, ...input }); }, readAuthorizationHistory: async id => persisted.filter(row => row.sessionId === id), sent: () => {}, + // Fixture does not test admission (夹具不测准入): the runtime start admission lets every start through. + admitLocalRoute: async () => {}, }); t.after(() => queue.dispose()); // One turn: returns what the engine was given and the persisted user row. diff --git a/apps/host/src/agent/mcp-runtime.ts b/apps/host/src/agent/mcp-runtime.ts index 56967cac8be..074c2d4a838 100644 --- a/apps/host/src/agent/mcp-runtime.ts +++ b/apps/host/src/agent/mcp-runtime.ts @@ -12,8 +12,9 @@ export function createHostMcpRuntime(ports: { appServerIds(): string[]; getRemot const codex = createCodexEnvironment({ ...http, ...ports }); const pi = createPiEnvironment(http); const logger = createMakerLogger('maker/mcp'); - const codexDeps: Pick = { + // Required: every member is set, and the engine bags in runtime.ts count them as written. + const codexDeps: Required> = { prepareCodexExtraSpawnConfig: providers => codex.getCodexExtraSpawnConfig({ mcpProviders: providers, logger }), registerCodexMcpThreadContext: ({ threadId, ...context }) => { const disabled = readDisabledBuiltinPluginIds(context.vendorOptions) @@ -26,7 +27,7 @@ export function createHostMcpRuntime(ports: { appServerIds(): string[]; getRemot withCodexMcpDiscoveryContext: (context, run) => codex.withCodexMcpDiscoveryContext({ ...context, agentKind: 'codex' }, run), }; // PiAgent calls (providers, ctx); the shared environment also takes the logger. - const piDeps: Pick = { + const piDeps: Required> = { preparePiExtraSpawnConfig: (providers, ctx) => pi.getPiExtraSpawnConfig(providers, logger, ctx), }; return { diff --git a/apps/host/src/agent/memory-manager-ports.ts b/apps/host/src/agent/memory-manager-ports.ts new file mode 100644 index 00000000000..f75d4c2fc5f --- /dev/null +++ b/apps/host/src/agent/memory-manager-ports.ts @@ -0,0 +1,61 @@ +/** + * The port bag the Host hands to the shared memory manager factory (maker-core + * `createMakerMemoryManagerForHost`, desktop counterpart `maker-host/maker-memory-host.ts`). + * + * It lives in a .ts file so `explicitPorts` is checked: every optional port of the factory is + * written out below, bound for real or `undefined` with the reason. memory.mjs only calls it. + */ + +import type { MakerMemoryHostContext } from '@cindy/maker-core'; + +import { dataOwnerStorageKey } from '../../../desktop/src/main/dataOwnerPath.ts'; +import { createBetterSqliteDatabase } from '../../../desktop/src/main/localDb/betterSqliteFactory.ts'; +import { getActiveAppSession, isAppSessionBoundaryPending } from '../../../desktop/src/main/appSessionState.ts'; +import { teammateProjectMemoryStorageDir } from '../../../desktop/src/main/maker-ipc/botProjectMemory.ts'; +import { explicitPorts } from './explicit-ports.ts'; +import { LOGGER } from './runtime.ts'; + +const sqliteFactory: MakerMemoryHostContext['sqliteFactory'] = (filePath) => { + const db = createBetterSqliteDatabase(filePath); + db.pragma('journal_mode = WAL'); + db.pragma('busy_timeout = 5000'); + return db; +}; + +export interface HostMemoryManagerPortInput { + userDataDir: string; + ownerId: string; + /** Generation of the app session the manager was created in; a later one reads as no owner. */ + generation: number; + readEnabled: MakerMemoryHostContext['readEnabled']; + review?: Required>; +} + +export function hostMemoryManagerPorts({ userDataDir, ownerId, generation, readEnabled, review }: HostMemoryManagerPortInput): MakerMemoryHostContext { + return explicitPorts({ + userDataDir, + readSession: () => { + const current = getActiveAppSession(); + const invalid = current.dataOwnerId !== ownerId || current.generation !== generation; + return { dataOwnerId: invalid ? null : ownerId, generation: current.generation, + mode: current.mode, boundaryPending: invalid || isAppSessionBoundaryPending() }; + }, + ownerSegment: (id) => dataOwnerStorageKey(id), + readEnabled, + sqliteFactory, + logger: LOGGER.child('maker-memory'), + // Only `bot:` scopes read it (maker-core memory/host-factory.ts:79-80), and only teammate tasks + // run in those scopes; the Host refuses teammate tasks before a send, steer or restore + // (send-preflight.ts:19-22, called from turn-executor.mjs). + botMemoryDir: undefined, + // Same function as the desktop (maker-host/maker-memory-host.ts:65). It maps a scope that is one + // of this owner's teammate projects to the project's own memory folder and every other scope to + // null (the historical place), so both processes sharing the profile put one scope in one place. + projectMemoryDir: (scopeKey, ownerRoot) => teammateProjectMemoryStorageDir(scopeKey, ownerRoot), + // Before the runtime binds its auxiliary chain, never fall back to a default agent model. + isOneShotRouteDisabled: review?.isOneShotRouteDisabled ?? (async () => true), + reviewOneShot: review?.reviewOneShot, + reviewAgentOneShot: undefined, + reviewAgent: 'claude-code', + }); +} diff --git a/apps/host/src/agent/memory-mcp-ports.ts b/apps/host/src/agent/memory-mcp-ports.ts new file mode 100644 index 00000000000..fb1753edb59 --- /dev/null +++ b/apps/host/src/agent/memory-mcp-ports.ts @@ -0,0 +1,133 @@ +/** + * The `memory` port bag of the Host's cindy_memory provider (memory.mjs createHostMemoryMcpProviders), + * desktop counterpart `mcp-integrations/mcp-providers.ts` (the `memory:` entry, 679-708). + * + * In a .ts file so `explicitPorts` is checked: every optional port of the provider's memory deps is + * written out below, bound for real or `undefined` with the reason. + */ + +import type { MakerMemoryManager } from '@cindy/maker-core'; +import type { MemoryMcpDeps, SessionSearchFn } from '@cindy/mcps'; +import { AsyncLocalStorage } from 'node:async_hooks'; + +import { searchSessionsWithBotScopeCore } from '../../../desktop/src/main/maker-host/sessionSearchCore.ts'; +import { resolveHelperSurface } from '../../../desktop/src/main/mcp-integrations/helperSurface.ts'; +import { tryGetDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { isAppSessionBoundaryPending } from '../../../desktop/src/main/appSessionState.ts'; +import { getPluginHostToolCaller } from '../../../desktop/src/main/mcp-integrations/hostToolCaller.ts'; +import { explicitPorts } from './explicit-ports.ts'; +import { LOGGER } from './runtime.ts'; +import { HOST_PROFILE_IN_USE_BY_DESKTOP } from './profile-coexistence.js'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; + +export interface HostMemoryMcpPortInput { + /** host-tools.ts readsAccountHistory: the cindy_helper history decision for this task. */ + readsAccountHistory(sessionId: string | undefined): Promise; + /** This computer's device id for the task links in the results ('' while unknown). */ + deviceId(): string; + searchProviders?: MemoryMcpDeps['searchProviders']; + profileHold?(): string | null; +} + +/** + * session_search with the desktop's checks, in the desktop's order (mcp-providers.ts:687-706, copied: + * that closure is inline there and pluginTaskHelperScope.test.ts reads it from the source text, so it + * cannot move; release table section 7). The search itself is the desktop's shared core. + */ +export function createHostSessionSearch(input: HostMemoryMcpPortInput): SessionSearchFn { + return async (query, opts = {}) => { + const dbClient = tryGetDbClient(); + if (!dbClient || isAppSessionBoundaryPending() || !opts.callerSessionId) + throw new Error('Task history caller unavailable'); + // session_search bypasses cindy_helper, so share its account-data surface. + if (await resolveHelperSurface(dbClient, opts.callerSessionId) === 'restricted') + throw new Error('Task history search is unavailable for this task'); + if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) + throw new Error('Task history caller unavailable'); + const hits = await searchSessionsWithBotScopeCore(query, opts, { + botAccountWide: await input.readsAccountHistory(opts.callerSessionId), + readDeviceId: input.deviceId, + }); + if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) + throw new Error('Task history caller unavailable'); + if (await resolveHelperSurface(dbClient, opts.callerSessionId) === 'restricted') + throw new Error('Task history search is unavailable for this task'); + if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) + throw new Error('Task history caller unavailable'); + return hits; + }; +} + +/** + * The account-data check the desktop wraps every cindy_memory call in (mcp-providers.ts:409-424, + * copied: that closure is inline there and pluginTaskHelperScope.test.ts reads it from the source + * text, so it cannot move; release table section 7). The calling task must be a task of the current + * database, not restricted, and the database must still be current when the call returns. Any + * failure reaches the Agent as the provider's CAPABILITY_NOT_AVAILABLE result + * (packages/lizi-mcps/src/account-data-access.ts), the same as on the desktop. + */ +export async function hostAccountDataAccess(sessionId: string | undefined, operation: (assertCurrent: () => Promise) => Promise): Promise { + const dbClient = tryGetDbClient(); + const plugin = !sessionId ? getPluginHostToolCaller() : undefined; + if (!dbClient || (!sessionId && !plugin)) throw new Error('Account data caller unavailable'); + const assertAccess = async () => { + plugin?.assertCurrent(); + if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) throw new Error('Account changed'); + if (sessionId && await resolveHelperSurface(dbClient, sessionId) === 'restricted') + throw new Error('Account data is unavailable for this task'); + if (isAppSessionBoundaryPending() || dbClient !== tryGetDbClient()) throw new Error('Account changed'); + }; + await assertAccess(); + const result = await operation(assertAccess); + await assertAccess(); + return result; +} + +export function hostMemoryMcpPorts(manager: MakerMemoryManager, input: HostMemoryMcpPortInput): Omit { + // The account-access port receives a callback, not a tool name. The shared + // withStore path requests the manager inside this scope; metadata and history + // calls do not. The provider's availability check runs outside the scope. + const memoryCall = new AsyncLocalStorage<{ admitted: boolean }>(); + return explicitPorts>({ + getManager: () => { + const admission = memoryCall.getStore(); + if (admission && !admission.admitted) { + const held = input.profileHold?.(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + admission.admitted = true; + } + return manager; + }, + // As the desktop binds it (mcp-providers.ts:684). session_search keeps its own checks inside, as + // the desktop's does. + withAccountDataAccess: (sessionId, operation) => hostAccountDataAccess(sessionId, async assertCurrent => { + const result = await memoryCall.run({ admitted: false }, () => operation(assertCurrent)); + // packages/lizi-mcps/src/memory/_shared.ts withStore uses + // memory/errors.ts classifyMemoryError, then buildJsonResult encodes + // {ok:false, code:"INTERNAL", message} as the first text block. The + // [CODE] prefix comes from createIpcError in apps/desktop/src/shared/ipc-errors.ts. + // Keep this mapping in sync if either format changes. + if (!result || typeof result !== 'object' || !('isError' in result) || result.isError !== true + || !('content' in result) || !Array.isArray(result.content)) return result; + const block = result.content[0]; + if (block?.type !== 'text' || typeof block.text !== 'string') return result; + try { + const body = JSON.parse(block.text); + if (body?.code === 'INTERNAL' && typeof body.message === 'string' + && body.message.startsWith(`[PRECONDITION_FAILED] ${HOST_PROFILE_IN_USE_BY_DESKTOP}`)) { + return { ...result, content: [{ type: 'text', text: JSON.stringify({ ...body, code: 'PRECONDITION_FAILED' }) }] }; + } + } catch { /* Non-memory tool responses keep their original shape. */ } + return result; + }), + searchProviders: input.searchProviders, + // Only teammate learning records use it (botLearningTracker.ts:35-38); the Host refuses teammate + // tasks (send-preflight.ts:19-22). + beginWrite: undefined, + // The provider sets it for each task (packages/lizi-mcps/src/providers.ts:470); the desktop does + // not pass it either. + getSessionContext: undefined, + searchSessions: createHostSessionSearch(input), + logger: LOGGER.child('mcp/cindy_memory'), + }); +} diff --git a/apps/host/src/agent/memory.mjs b/apps/host/src/agent/memory.mjs index 15a866806f6..2a43e014351 100644 --- a/apps/host/src/agent/memory.mjs +++ b/apps/host/src/agent/memory.mjs @@ -12,10 +12,10 @@ import path from 'node:path'; import { attachAgentsToMakerMemory, createMakerMemoryManagerForHost } from '@cindy/maker-core'; import { createLiziMcpProviders } from '../../../../packages/lizi-mcps/src/index.ts'; -import { dataOwnerStorageKey } from '../../../desktop/src/main/dataOwnerPath.ts'; -import { createBetterSqliteDatabase } from '../../../desktop/src/main/localDb/betterSqliteFactory.ts'; -import { LOGGER } from './runtime.ts'; import { getActiveAppSession, isAppSessionBoundaryPending } from '../../../desktop/src/main/appSessionState.ts'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; +import { hostMemoryManagerPorts } from './memory-manager-ports.ts'; +import { hostMemoryMcpPorts } from './memory-mcp-ports.ts'; const DEFAULTS = Object.freeze({ maker: true, claudeCode: true, codex: true, pi: true }); @@ -38,48 +38,42 @@ export function readMemorySettings(ownerRoot) { } } -const sqliteFactory = (filePath) => { - const db = createBetterSqliteDatabase(filePath); - db.pragma('journal_mode = WAL'); - db.pragma('busy_timeout = 5000'); - return db; -}; - /** - * @param {{ userDataDir: string, ownerId: string, getMaker?: () => import('@cindy/maker-core').Maker | null }} options + * The port bag is written out in memory-manager-ports.ts, where `explicitPorts` is type-checked. + * @param {Pick & {profileHold?: () => string | null}} options */ -export function createHostMemoryManager({ userDataDir, ownerId, getMaker }) { +export function createHostMemoryManager({ userDataDir, ownerId, review, profileHold }) { const scope = getActiveAppSession(); if (scope.dataOwnerId !== ownerId || isAppSessionBoundaryPending()) throw new Error('Memory owner is not ready'); - return createMakerMemoryManagerForHost({ + const manager = createMakerMemoryManagerForHost(hostMemoryManagerPorts({ userDataDir, - readSession: () => { - const current = getActiveAppSession(); - const invalid = current.dataOwnerId !== ownerId || current.generation !== scope.generation; - return { dataOwnerId: invalid ? null : ownerId, generation: current.generation, - mode: current.mode, boundaryPending: invalid || isAppSessionBoundaryPending() }; - }, - ownerSegment: (id) => dataOwnerStorageKey(id), + ownerId, + generation: scope.generation, + review, readEnabled: (ownerRoot) => readMemorySettings(ownerRoot).maker, - sqliteFactory, - logger: LOGGER.child('maker-memory'), - reviewAgent: 'claude-code', - ...(getMaker ? { reviewAgentOneShot: (agentKind, prompt, options) => { - const maker = getMaker(); - if (!maker) throw new Error('Memory review agent is not ready'); - return maker.oneShot(agentKind, prompt, { ...options, source: 'memory-review' }); - } } : {}), - }); + })); + // Engine prompt injection can initialize a store and Pi compaction calls + // manager.write(), which also opens its store here without going through MCP. + if (profileHold) { + const getStore = manager.getStore.bind(manager); + manager.getStore = async (...args) => { + const held = profileHold(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + return getStore(...args); + }; + } + return manager; } -/** The cindy_memory MCP server; Codex reaches it through the Host MCP bridge (mcp-runtime codexDeps), checked by codex-runtime.e2e.mjs. */ -export function createHostMemoryMcpProviders(manager) { +/** + * The cindy_memory MCP server; Codex reaches it through the Host MCP bridge (mcp-runtime codexDeps), checked by codex-runtime.e2e.mjs. + * The port bag is written out in memory-mcp-ports.ts, where `explicitPorts` is type-checked. + * @param {import('./memory-mcp-ports.ts').HostMemoryMcpPortInput} ports + */ +export function createHostMemoryMcpProviders(manager, ports) { return createLiziMcpProviders({ enabled: ['cindy_memory'], - memory: { - getManager: () => manager, - logger: LOGGER.child('mcp/cindy_memory'), - }, + memory: hostMemoryMcpPorts(manager, ports), }); } diff --git a/apps/host/src/agent/memory.test.mjs b/apps/host/src/agent/memory.test.mjs index a80e5a6a850..842f590df48 100644 --- a/apps/host/src/agent/memory.test.mjs +++ b/apps/host/src/agent/memory.test.mjs @@ -4,16 +4,27 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import Database from 'better-sqlite3'; -import { drizzle } from 'drizzle-orm/better-sqlite3'; -import { createServer } from 'node:http'; -import { Maker, ClaudeCodeAgent, attachAgentsToMakerMemory } from '@cindy/maker-core'; -import { getModelUsageSince } from '../../../desktop/src/main/localDb/dailyModelUsage.ts'; -import { createOneShotUsageRecorder } from '../../../desktop/src/main/usage/auxiliaryUsage.ts'; -import { setCurrentDbClient, clearCurrentDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; -import { readMemorySettings, createHostMemoryManager } from './memory.mjs'; +import { createRequire } from 'node:module'; + +import { readMemorySettings, createHostMemoryManager, createHostMemoryMcpProviders, attachAgentsToMakerMemory } from './memory.mjs'; import { configureHostOwner } from './claude-auth.mjs'; import { beginAppSessionBoundary } from '../../../desktop/src/main/appSessionState.ts'; +import { dataOwnerStorageKey } from '../../../desktop/src/main/dataOwnerPath.ts'; +import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { openOwnerDatabase } from '../../../desktop/src/main/localDb/startupCore.ts'; +import { createDbClientForHandle } from '../../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { hostRuntimeLayout } from '../runtime-layout.mjs'; +import { lifoCleanup } from '../test-support/cleanup.mjs'; +import { createHostAutoReview } from './auto-review.ts'; +import { hostOutbound } from '../outbound.mjs'; +import { getModelAccessCredentialsStore } from '../../../desktop/src/main/model-access/credentialsStore.ts'; +import { ownerScopedUserDataPath } from '../../../desktop/src/main/appSessionState.ts'; +import { setModelsDisabled } from '../../../desktop/src/main/maker-host/model-disable-store.ts'; + +const require = createRequire(new URL('../../../desktop/package.json', import.meta.url)); +const { Client } = require('@modelcontextprotocol/sdk/client/index.js'); +const { InMemoryTransport } = require('@modelcontextprotocol/sdk/inMemory.js'); /** * The toggle decides whether cindy_memory is registered at all, so a corrupt or @@ -61,70 +72,291 @@ test('memory retained by an old task cannot reopen storage across an account bou } }); -// Run the actual Host memory manager -> Maker -> agent -> auxiliary SQLite chain. -// Real SDK HTTP uses a loopback fixture, with no paid provider or CLI process. -test('legacy memory review retains its route and budget while recording observed usage', async (t) => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'host-memory-usage-')); - const db = new Database(':memory:'); - db.exec(`CREATE TABLE auxiliary_usage_receipts (receipt_id TEXT PRIMARY KEY, provider_id TEXT, model TEXT, - source TEXT, session_id TEXT, transport TEXT, day TEXT, recorded_at INTEGER, input_tokens INTEGER, - output_tokens INTEGER, cache_read_tokens INTEGER, cache_create_tokens INTEGER)`); - db.exec(`CREATE TABLE daily_model_usage (day TEXT, agent_kind TEXT, model TEXT, cost_usd REAL, - cost_amount REAL, cost_currency TEXT, cost_is_approximate INTEGER, input_tokens INTEGER, - output_tokens INTEGER, cache_read_tokens INTEGER, cache_create_tokens INTEGER)`); - let manager, maker; let fail = false; const calls = []; - const logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return this; } }; - const server = createServer((req, res) => { - req.resume(); req.on('end', () => { - res.writeHead(200, { 'content-type': 'application/json' }); - res.end(JSON.stringify({ id: 'fixture-response', type: 'message', role: 'assistant', model: 'served-memory', - content: fail ? [] : [{ type: 'text', text: 'review suggestions' }], stop_reason: 'end_turn', stop_sequence: null, - usage: { input_tokens: 60, cache_read_input_tokens: 40, output_tokens: 2 }, - })); +/** + * cindy_memory on the Host, called the way an Agent calls it: the provider main.ts registers + * (createHostMemoryMcpProviders), over MCP, with the review agent attached as main.ts attaches the + * agent graph. The attached agent counts its one-shot calls: in runReview it is the only way to a + * model once no auxiliary chain is injected. The owner database is open and current, as in main.ts, + * with the calling task 'task-memory' in it: every memory call checks its caller against it. + */ +async function hostMemoryFixture(t, ownerId, makeReview, profileHold) { + // The database lives in the fixture's profile: close it before the profile is removed. + t = lifoCleanup(t); + // Real path: a teammate project is recognised from its absolute path, which macOS tmp links hide. + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'host-memory-review-'))); + t.after(() => fs.rmSync(root, { recursive: true, force: true })); + configureHostOwner({ userDataDir: root, ownerId }); + t.after(() => configureHostOwner({ userDataDir: root, ownerId: null })); + // The development build refuses to migrate what it takes for the official shared profile + // (XDT_OFFICIAL_SHARED_PROFILE=1 inside a Cindy task); this is a fixture profile. + const sharedProfile = process.env.XDT_OFFICIAL_SHARED_PROFILE; + delete process.env.XDT_OFFICIAL_SHARED_PROFILE; + t.after(() => { if (sharedProfile !== undefined) process.env.XDT_OFFICIAL_SHARED_PROFILE = sharedProfile; }); + configureAppDataDir(path.join(root, 'app-data')); + const layout = hostRuntimeLayout(); + const opened = await openOwnerDatabase({ userDataDir: root, ownerId, isPackaged: false, + drizzleDir: layout.drizzleDir, sqliteVecExtPath: layout.sqliteVecPath }); + const database = createDbClientForHandle({ db: opened.db, drizzle: opened.drizzle, dispose: async () => opened.db.close() }); + setCurrentDbClient(database, ownerId); + t.after(async () => { clearCurrentDbClient(); await database.dispose(); }); + opened.db.exec(`INSERT INTO sessions(id,source,status,created_at,updated_at) VALUES ('task-memory','desktop','active',1,1);`); + + const manager = createHostMemoryManager({ userDataDir: root, ownerId, review: makeReview?.(root), profileHold }); + t.after(() => manager.dispose()); + const oneShots = []; + attachAgentsToMakerMemory(manager, { 'claude-code': { oneShot: async prompt => { oneShots.push(prompt); return 'merge nothing'; } } }); + const helperDecisions = []; + // Runs inside session_search, between its first checks and the search (memory-mcp-ports.ts). + const hooks = { duringHistoryDecision: () => {} }; + const provider = createHostMemoryMcpProviders(manager, { + readsAccountHistory: async sessionId => { helperDecisions.push(sessionId); hooks.duringHistoryDecision(); return false; }, + deviceId: () => 'host-device', + profileHold, + }).find(p => p.name === 'cindy_memory'); + const connect = async (workingDir, sessionId = 'task-memory') => { + const { instance } = provider.toClaudeSdkConfig({ sessionId, agentKind: 'claude-code', workingDir }); + const client = new Client({ name: 'host-memory-test', version: '1' }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await Promise.all([client.connect(a), instance.connect(b)]); + t.after(async () => { await client.close(); await instance.close(); }); + return Object.assign((name, args = {}) => client.callTool({ name: 'call_tool', arguments: { name, args } }), { + listTools: () => client.callTool({ name: 'list_tools', arguments: {} }), }); + }; + return { root, db: opened.db, drizzle: opened.drizzle, database, ownerId, oneShots, connect, helperDecisions, hooks, manager }; +} + +const NOTE = { type: 'project', name: 'release-notes', title: 'Release notes', description: 'Where the release notes live', body: 'docs/release.md' }; + +// §3.2 integration: a live MCP caller can still reach memory after Host input +// is paused. All store calls must be refused before opening even a cold scope. +// Use the real owner files and FTS and both MCP entry points. +test('profile hold refuses memory store tools and preserves the existing files', async t => { + const message = 'HOST_PROFILE_IN_USE_BY_DESKTOP: The desktop window is using this profile.'; + let held = null; + const f = await hostMemoryFixture(t, 'memory-hold-owner', () => ({ + isOneShotRouteDisabled: async () => false, + reviewOneShot: async () => 'Keep the note', + }), () => held); + const call = await f.connect(f.root); + const body = result => JSON.parse(result.content[0].text); + const seed = await call('memory_write', NOTE); + assert.equal(body(seed).ok, true); + const filename = body(seed).data.filename; + const scope = path.join(f.root, 'owners', dataOwnerStorageKey(f.ownerId), 'maker-memory'); + const snapshot = () => fs.readdirSync(scope, { recursive: true, withFileTypes: true }) + .map(entry => path.join(entry.parentPath, entry.name)).sort() + .map(file => [file, fs.statSync(file).isDirectory() ? null : fs.readFileSync(file)]); + const before = snapshot(); + const cases = [ + ['memory_list', {}], + ['memory_read', { filename }], + ['memory_search', { query: 'release' }], + ['memory_review', {}], + ['memory_write', { ...NOTE, name: 'second-note' }], + ['memory_consolidate', { sources: ['project_second-note.md'], target: { ...NOTE, name: 'merged-note' } }], + ['memory_delete', { filename }], + ]; + held = message; + for (const [tool, args] of cases) { + const result = await call(tool, args); + assert.equal(result.isError, true, tool); + assert.deepEqual(body(result), { ok: false, code: 'PRECONDITION_FAILED', message: '[PRECONDITION_FAILED] ' + message }, tool); + } + const cold = await f.connect(path.join(f.root, 'cold-task')); + assert.equal(body(await cold('memory_list')).code, 'PRECONDITION_FAILED'); + assert.equal(body(await call.listTools()).ok, true); + assert.equal(body(await call('session_search', { query: 'release' })).ok, true); + assert.deepEqual(snapshot(), before); + held = null; + for (const [tool, args] of cases) { + const result = await call(tool, args); + assert.equal(body(result).ok, true, JSON.stringify({ tool, result })); + } +}); + +// §3.2 integration: engines open memory for prompt injection and Pi compaction +// writes a digest straight through the manager, outside MCP. +test('profile hold fences engine store initialization and Pi digest writes', async t => { + let held = 'HOST_PROFILE_IN_USE_BY_DESKTOP: The desktop window is using this profile.'; + const f = await hostMemoryFixture(t, 'memory-engine-hold-owner', undefined, () => held); + const workdir = path.join(f.root, 'engine-task'); + const note = { ...NOTE, type: 'digest' }; + await assert.rejects(f.manager.getStore(workdir), { code: 'PRECONDITION_FAILED' }); + await assert.rejects(f.manager.write(workdir, note), { code: 'PRECONDITION_FAILED' }); + assert.equal(fs.existsSync(path.join(f.root, 'owners', dataOwnerStorageKey(f.ownerId), 'maker-memory')), false); + held = null; + const written = await f.manager.write(workdir, note); + assert.equal((await (await f.manager.getStore(workdir)).read(written.filename)).body, NOTE.body); +}); + +// §3.2 integration: real MCP, manager, dispatch and temporary SQLite. A stored +// memory under a chosen auxiliary chain produces the selected request and one +// receipt. The baseline always refused review; its default fallback must remain unused. +test('memory_review respects the auxiliary chain, holds and the request owner', async t => { + let held = null, defaultDisabled = false; + let onRequest = () => {}; + const requests = []; + t.mock.method(hostOutbound, 'outboundUndiciFetch', async (_url, init) => { + requests.push(JSON.parse(init.body)); + onRequest(); + return Response.json({ choices: [{ message: { content: 'Keep both notes' } }], + usage: { prompt_tokens: 9, completion_tokens: 4 } }); }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const endpoint = `http://127.0.0.1:${server.address().port}`; - const agent = new ClaudeCodeAgent({ binaryPath: 'unused-fixture-cli', runtimeConfig: { endpoint }, logger, - auth: { getState: async () => ({ authenticated: true }), getAuthEnv: async () => ({ ANTHROPIC_API_KEY: 'fixture-key' }), - getOneShotAuth: async () => ({ apiKey: 'fixture-key', baseURL: endpoint }) }, + const endpoint = 'https://memory-unit.test'; + const f = await hostMemoryFixture(t, 'memory-review-owner', userDataDir => { + getModelAccessCredentialsStore().setServerCredentials(endpoint); + return createHostAutoReview({ + userDataDir, + getMaker: () => ({ listAvailableAgents: () => [] }), + gateway: { credential: 'fixture-key', endpoint }, + providerConfig: { publicViews: async () => defaultDisabled + ? [{ id: 'xd', connected: true, suspended: true, agents: ['claude-code'], models: {} }] : [] }, + logger: { debug() {}, info() {}, warn() {} }, + }).memoryReview(() => held); }); - const oneShot = agent.oneShot; - t.mock.method(agent, 'oneShot', function(prompt, options) { - calls.push({ prompt, options }); return oneShot.call(this, prompt, options); + const workdir = path.join(f.root, 'project'); + fs.mkdirSync(workdir); + const call = await f.connect(workdir); + const written = await call('memory_write', NOTE); + assert.notEqual(written.isError, true, JSON.stringify(written)); + const settings = ownerScopedUserDataPath('auxiliary-model-settings.json'); + const chain = models => fs.writeFileSync(settings, JSON.stringify({ models })); + const selected = 'litellm-deepseek-v4-flash'; + const model = 'deepseek/deepseek-v4-flash'; + const review = () => call('memory_review'); + const refuse = async pattern => { + requests.length = 0; + const result = await review(); + assert.equal(result.isError, true); + assert.match(result.content[0].text, pattern); + assert.deepEqual(requests, []); + }; + chain([selected]); + await t.test('dispatches the selected auxiliary model', async () => { + const result = await review(); + assert.equal(result.isError, undefined, JSON.stringify(result)); + assert.deepEqual(requests.map(request => request.model), [model]); }); - try { - configureHostOwner({ userDataDir: root, ownerId: 'memory-owner' }); - setCurrentDbClient({ drizzle: drizzle(db), query: async (sql, params) => db.prepare(sql).all(...params) }, 'memory-owner'); - manager = createHostMemoryManager({ userDataDir: root, ownerId: 'memory-owner', getMaker: () => maker ?? null }); - maker = new Maker({ agents: { 'claude-code': agent }, storage: {}, logger, createOneShotUsageRecorder }); - attachAgentsToMakerMemory(manager, { 'claude-code': agent }); - if (!manager.isEnabled()) await manager.enable({ skipAgentSync: true }); - await manager.write(root, { type: 'user', name: 'preference', title: 'Preference', description: 'Durable preference', body: 'Keep it.' }); - assert.equal((await manager.runReview(root)).suggestions, 'review suggestions'); - fail = true; - await assert.rejects(manager.runReview(root), /Empty response from model/); - assert.equal(calls.length, 2); - for (const { prompt, options } of calls) { - assert.ok(prompt.includes('Keep it.')); - assert.equal(options.source, 'memory-review'); - assert.equal(options.maxTokens, 800); assert.equal(options.timeoutMs, 60000); - assert.equal(options.model, undefined, 'no route/model override introduced'); - } - const rows = db.prepare('SELECT source,model,input_tokens,cache_read_tokens,output_tokens FROM auxiliary_usage_receipts').all(); - assert.deepEqual(rows, [1, 2].map(() => ({ source: 'memory-review', model: 'served-memory', input_tokens: 60, cache_read_tokens: 40, output_tokens: 2 }))); - const read = () => getModelUsageSince('0000-01-01'); - const total = rows => rows.reduce((n, r) => n + r.inputTokens + r.cacheReadTokens + r.cacheCreateTokens + r.outputTokens, 0); - const projected = await read(); - assert.equal(total(projected), 204, 'real Usage SQL reader equals raw receipt total'); - assert.equal(projected.reduce((n, r) => n + r.requestCount, 0), 2); - assert.ok(projected.every(r => r.source === 'memory-review' && r.model === 'served-memory')); - assert.equal(total(await read()), 204, 'reading never inserts receipts'); - assert.equal(db.prepare('SELECT COUNT(*) n FROM auxiliary_usage_receipts').get().n, 2); - } finally { - manager?.dispose(); await agent.dispose(); clearCurrentDbClient(); db.close(); - server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); - configureHostOwner({ userDataDir: root, ownerId: null }); - fs.rmSync(root, { recursive: true, force: true }); - } + await t.test('skips a disabled auxiliary candidate with zero requests', async () => { + setModelsDisabled('xd', [model], true); + try { await refuse(/auxiliary model chain produced no text/); } + finally { setModelsDisabled('xd', [model], false); } + }); + await t.test('rejects an unavailable auxiliary chain without falling back', async () => { + chain(['codex-gpt-5.4-mini']); + try { await refuse(/auxiliary model chain produced no text/); } + finally { chain([selected]); } + }); + await t.test('returns the Host hold refusal with zero requests', async () => { + held = 'HOST_PROFILE_IN_USE_BY_DESKTOP: The desktop window is using this profile.'; + try { await refuse(/"code":"PRECONDITION_FAILED".*desktop window/); } + finally { held = null; } + }); + await t.test('records the usage once in the database captured before dispatch', async () => { + const incoming = []; + const incomingDb = { drizzle: { insert() { incoming.push(true); throw new Error('wrong account'); } } }; + f.db.exec('DELETE FROM auxiliary_usage_receipts'); + onRequest = () => setCurrentDbClient(incomingDb, 'next-memory-owner'); + try { await review(); } + finally { setCurrentDbClient(f.database, f.ownerId); onRequest = () => {}; } + assert.deepEqual(f.db.prepare('SELECT source, model, input_tokens, output_tokens FROM auxiliary_usage_receipts').all(), + [{ source: 'memory-review', model, input_tokens: 9, output_tokens: 4 }]); + assert.deepEqual(incoming, []); + }); + await t.test('rejects a disabled default source with zero requests', async () => { + defaultDisabled = true; + try { await refuse(/one-shot route for 'claude-code' is disabled/); } + finally { defaultDisabled = false; } + const result = await review(); + assert.equal(result.isError, undefined, JSON.stringify(result)); + assert.deepEqual(requests.map(request => request.model), [model]); + }); + assert.deepEqual(f.oneShots, []); +}); + +// The desktop maps a scope that is one of this owner's teammate projects to the project's own +// memory folder (maker-memory-host.ts projectMemoryDir); the Host did not bind it, so a Host task +// in that folder stored the memory at the historical place the desktop no longer reads. +// Minimal failing input: a memory_write from a task whose working directory is a teammate project. +test('a memory written from a teammate project lands in the project folder, as on the desktop', async t => { + const ownerId = 'memory-project-owner'; + const f = await hostMemoryFixture(t, ownerId); + const workspace = path.join(f.root, 'owners', dataOwnerStorageKey(ownerId), 'bots', 'helper', 'workspace'); + fs.mkdirSync(workspace, { recursive: true }); + const call = await f.connect(workspace); + const written = await call('memory_write', NOTE); + assert.notEqual(written.isError, true, JSON.stringify(written)); + assert.deepEqual(fs.readdirSync(path.join(workspace, '.cindy', 'memory')).filter(name => name.endsWith('.md') && name.includes('release-notes')).length, 1); +}); + +// The desktop binds session_search to the messages_fts search (mcp-providers.ts searchSessions); the +// Host did not, so the tool was not registered and a Host task could not search its task history. +// Minimal failing input: one stored message, then session_search from a task of the same account. +// Tier: unit, real migrated owner database in a temp profile, in-process MCP. +test('session_search on the Host finds task history, with the desktop checks on the caller', async t => { + const f = await hostMemoryFixture(t, 'memory-search-owner'); + f.db.exec(`INSERT INTO sessions(id,source,status,created_at,updated_at) VALUES ('task-earlier','desktop','active',1,1); + INSERT INTO messages(id,client_id,session_id,role,content,created_at) + VALUES ('m-earlier','c-earlier','task-earlier','user','"where is the release checklist"',1);`); + const workdir = path.join(f.root, 'project'); + fs.mkdirSync(workdir); + + const search = await (await f.connect(workdir))('session_search', { query: 'checklist' }); + assert.notEqual(search.isError, true, JSON.stringify(search)); + const { hits } = JSON.parse(search.content[0].text).data; + assert.deepEqual(hits.map(hit => [hit.sessionId, hit.messageId, hit.sessionUrl]), + [['task-earlier', 'm-earlier', 'cindy://session/task-earlier?device=host-device']]); + assert.deepEqual(f.helperDecisions, ['task-memory']); + + // A caller that is not a task of this account (the desktop's restricted surface) is refused. + const stranger = await (await f.connect(workdir, 'task-elsewhere'))('session_search', { query: 'checklist' }); + assert.equal(stranger.isError, true); + assert.match(stranger.content[0].text, /unavailable for this task/); +}); + +// The desktop wraps every cindy_memory call in withAccountDataAccess (mcp-providers.ts): the calling +// task must be in the current database. The Host bound nothing there, so after an account change a +// task of the previous account still read and wrote memories, now the new account's: only +// session_search checked its caller. Gap: the tests above call from a task of the current database. +// Minimal failing input: memory_write from a task id the current database does not have, and from a +// task whose database is no longer current. Tier: unit, real migrated owner database, in-process MCP. +test('a memory call from a task outside the current account is refused, as on the desktop', async t => { + const f = await hostMemoryFixture(t, 'memory-access-owner'); + const workdir = path.join(f.root, 'project'); + fs.mkdirSync(workdir); + const refused = { isError: true, content: [{ type: 'text', text: JSON.stringify({ + ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE', message: 'Account data is unavailable for this task.' }) }] }; + + const previousAccountTask = await f.connect(workdir, 'task-previous-account'); + assert.deepEqual(await previousAccountTask('memory_write', NOTE), refused); + assert.deepEqual(await previousAccountTask('memory_search', { query: 'release' }), refused); + + // The account's database is closed for an account change while its task is still running. + const task = await f.connect(workdir); + clearCurrentDbClient(); + assert.deepEqual(await task('memory_write', NOTE), refused); + + const stored = fs.readdirSync(f.root, { recursive: true }).filter(name => String(name).includes('release-notes')); + assert.deepEqual(stored, []); +}); + +// The checks run again before a result leaves (the desktop closures re-check the database after the +// operation): an account change during the call must not hand back what was read for the old one. +// Gap: the test above changes the account between calls. Minimal failing input: another database +// becomes current while session_search runs, after its history decision; the search itself still +// finds the hit (the same file under a new client), so only the re-check stops it. Tier: unit, as above. +test('session_search refuses its result when the account changes during the call', async t => { + const f = await hostMemoryFixture(t, 'memory-midcall-owner'); + f.db.exec(`INSERT INTO messages(id,client_id,session_id,role,content,created_at) + VALUES ('m-own','c-own','task-memory','user','"where is the release checklist"',1);`); + const workdir = path.join(f.root, 'project'); + fs.mkdirSync(workdir); + const search = await f.connect(workdir); + const next = createDbClientForHandle({ db: f.db, drizzle: f.drizzle }); + f.hooks.duringHistoryDecision = () => setCurrentDbClient(next, f.ownerId); + const result = await search('session_search', { query: 'checklist' }); + assert.deepEqual(f.helperDecisions, ['task-memory']); + assert.deepEqual(result, { isError: true, content: [{ type: 'text', text: JSON.stringify({ + ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE', message: 'Account data is unavailable for this task.' }) }] }); }); diff --git a/apps/host/src/agent/model-window-gate.ts b/apps/host/src/agent/model-window-gate.ts deleted file mode 100644 index 3bddeb23d4d..00000000000 --- a/apps/host/src/agent/model-window-gate.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { - type RuntimeModelSwitchGateInput, -} from '../../../desktop/src/shared/runtimeModelSwitchGate.ts'; -import { lookupVerifiedContextWindow } from '../../../desktop/src/main/maker-ipc/contextOverflowRollover.ts'; - -/** The desktop's refusal on this path (register.ts, applySessionRuntimeSelection, `reject`). */ -export const MODEL_WINDOW_REBUILD_UNSUPPORTED = - 'remote model-window rebuild is unsupported; runtime selection was not changed'; - -/** What the gate reads from a running task, as the desktop does from its live session. */ -export interface ModelSwitchLiveRuntime { - model?: string; - isTurnRunning?(): boolean; - getUsageSnapshot?(): { contextTokens?: number; contextWindow?: number } | undefined; - previewModelSwitch?(model: string, options: { providerId: string | null }): Promise<{ - action?: string; - windowVerified?: boolean; - targetContextWindow?: number; - } | undefined>; -} - -export interface ModelSwitchWindowInput { - /** The task's engine, as Maker names it (claude-code, codex, pi). */ - agentKind: string; - live: ModelSwitchLiveRuntime | null; - /** The task row before the change. */ - stored: { model: string | null; providerId: string | null; contextTokens: number | null }; - target: { model: string; providerId: string | null }; - /** The configured window of a route with the task's window budget (model-context-settings.ts). */ - resolveRouteWindow?(agentKind: string, modelId: string, providerId: string | null): number | null; -} - -const positive = (value: unknown): value is number => - typeof value === 'number' && Number.isFinite(value) && value > 0; - -/** - * The window gate's input for a model change a client asks the Host for, computed as the desktop - * does for a model change from a Device Link client (register.ts applySessionRuntimeSelection: - * target and current windows and context usage). The legacy session update rejects verified - * pressured shrinks. Owner Device Link intent is evaluated separately at actual dispatch. - */ -export async function modelSwitchGateInput(input: ModelSwitchWindowInput): Promise { - const { agentKind, live, stored, target } = input; - const currentModel = live?.model ?? stored.model ?? undefined; - const runtimeRouteChanged = currentModel !== undefined - && (currentModel !== target.model || stored.providerId !== target.providerId); - const resolve = input.resolveRouteWindow - ? (kind: string, modelId: string, providerId: string | null) => input.resolveRouteWindow!(kind, modelId, providerId) - : undefined; - // A running Pi task previews the target route itself (pi-host previewModelSwitch). The desktop - // also refuses a change whose preview is unavailable; the Host takes it as an unverified window. - const piPreview = agentKind === 'pi' && runtimeRouteChanged && live?.previewModelSwitch - ? await live.previewModelSwitch(target.model, { providerId: target.providerId }).catch(() => undefined) - : undefined; - const catalogTargetWindow = lookupVerifiedContextWindow(resolve, target.model, target.providerId, agentKind); - const verifiedTargetWindow = agentKind === 'pi' && piPreview?.windowVerified === true && positive(piPreview.targetContextWindow) - ? catalogTargetWindow === null ? piPreview.targetContextWindow : Math.min(piPreview.targetContextWindow, catalogTargetWindow) - : catalogTargetWindow; - const usage = live?.getUsageSnapshot?.(); - const verifiedCurrentWindow = agentKind === 'pi' - ? (positive(usage?.contextWindow) ? usage.contextWindow : undefined) - : lookupVerifiedContextWindow(resolve, currentModel, stored.providerId, agentKind) ?? undefined; - const persistedContextTokens = typeof stored.contextTokens === 'number' && Number.isFinite(stored.contextTokens) - && stored.contextTokens >= 0 ? stored.contextTokens : null; - const liveContextTokens = typeof usage?.contextTokens === 'number' && Number.isFinite(usage.contextTokens) - ? usage.contextTokens : null; - const liveUsageIsAuthoritative = liveContextTokens !== null && (liveContextTokens > 0 || persistedContextTokens === 0); - return { - piCanVerifyLiveWindow: piPreview?.action === 'hot' || piPreview?.action === 'refresh', - inTurn: false, - isRemote: true, - agentKind, - runtimeRouteChanged, - verifiedTargetWindow, - verifiedCurrentWindow, - contextTokensKnown: liveUsageIsAuthoritative || persistedContextTokens !== null, - contextTokens: liveUsageIsAuthoritative ? liveContextTokens : (persistedContextTokens ?? 0), - }; -} diff --git a/apps/host/src/agent/native-auth.test.mjs b/apps/host/src/agent/native-auth.test.mjs index da2b8319713..76b711577c9 100644 --- a/apps/host/src/agent/native-auth.test.mjs +++ b/apps/host/src/agent/native-auth.test.mjs @@ -14,6 +14,7 @@ import { buildClaudeEnv } from '../../../../packages/maker-core/src/agents/claud import { CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY } from '../../../desktop/src/main/maker-host/claude-gateway-config.ts'; import { CODEX_PROVIDER_OAUTH_PLACEHOLDER_KEY } from '../../../desktop/src/main/maker-host/codex-gateway-config.ts'; import { writeInvalidatedSystemCodexAuthMarker } from '../../../desktop/src/main/maker-host/codex-auth-invalidation.ts'; +import { publishClaudeCliLoginStatus, resetClaudeCliLoginStatusForTest } from '../../../desktop/src/main/maker-host/claude-native-cli-status.ts'; test('Codex uses only its isolated home and requires the current account binding', async () => { const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'host-native-auth-')); @@ -184,3 +185,49 @@ test('through the loopback proxy, Claude carries only the proxy secrets, each pa ready = false; assert.deepEqual(await spawn(() => false), [UPSTREAM, 'fixture-gateway'], 'never ready: the key on the upstream, as on the desktop'); }); + +/* + * 测试价值 + * - 生产入口:createClaudeGatewayAuth 的 getState(/api/agents/auth-state 与 /api/agents/status 不带参数调用它), + * 直连网关和经本机代理两条线各走一遍。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。`claude auth status` 会不会在 CLI 内部刷新令牌、写回它的配置目录, + * 仓库代码查不到,按会写处理:闸门关着时不起这个子进程,只用已经读到的状态作答;一次也没读到过(Host 刚启动) + * 时报“暂不可用”(errorReason 为原因码),不能报成“未登录”。 + * - 现有覆盖缺口:之前读状态时缓存过期就起 CLI。 + * - 最小失败输入:闸门关着、Claude 订阅已授权,缓存为空或有值时各读一次状态。 + * - tier:unit(CLI 是记录调用的桩;登录态缓存是真实的进程内缓存;授权写在临时 profile 里)。 + */ +test('while a desktop uses the profile, the Claude state starts no CLI: the status read before, or unknown', async t => { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'host-native-auth-held-')); + t.after(() => { resetClaudeCliLoginStatusForTest(); configureHostOwner({ userDataDir: profile, ownerId: null }); fs.rmSync(profile, { recursive: true, force: true }); }); + configureHostOwner({ userDataDir: profile, ownerId: 'native-auth-owner-held' }); + bindNativeProviderAuth('anthropic', { sharedSystem: true }); + let spawns = 0; + const cli = { readClaudeCliLoginStatus: async () => { spawns++; return { loggedIn: true }; }, claudeCliNetworkEnv: async () => ({}) }; + const proxy = { isReady: () => true, endpoint: () => 'http://127.0.0.1:4545', inboundSecret: () => 'runtime-secret-fixture', + gatewayInboundSecret: () => 'gateway-secret-fixture' }; + let held = true; + const lanes = { direct: createClaudeGatewayAuth(null, undefined, cli, null, undefined, () => held), + proxy: createClaudeGatewayAuth(null, undefined, cli, proxy, undefined, () => held) }; + // Host just started: nothing read yet. Unknown, never "not signed in". + resetClaudeCliLoginStatusForTest(); + for (const [lane, auth] of Object.entries(lanes)) { + assert.deepEqual(await auth.getState(), { authenticated: false, errorReason: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }, lane); + } + assert.equal(spawns, 0, 'no claude auth status while held'); + // A status read before the hold answers, signed in or not, still without the CLI. + for (const loggedIn of [true, false]) { + publishClaudeCliLoginStatus({ loggedIn }); + for (const [lane, auth] of Object.entries(lanes)) { + const state = await auth.getState(); + assert.equal(state.authenticated, loggedIn, `${lane}, signed in: ${loggedIn}`); + assert.notEqual(state.errorReason, 'HOST_PROFILE_IN_USE_BY_DESKTOP', lane); + } + } + assert.equal(spawns, 0, 'no claude auth status while held'); + // Released, the same read runs the CLI again (the direct lane's 30 s and the proxy's 60 s have passed for a reset cache). + held = false; + resetClaudeCliLoginStatusForTest(); + for (const auth of Object.values(lanes)) await auth.getState(); + assert.equal(spawns, 2); +}); diff --git a/apps/host/src/agent/outbound-path-fact.test.mjs b/apps/host/src/agent/outbound-path-fact.test.mjs new file mode 100644 index 00000000000..9e1ea9e1c3a --- /dev/null +++ b/apps/host/src/agent/outbound-path-fact.test.mjs @@ -0,0 +1,136 @@ +/* + * 测试价值(放行表第 28 行 28a,第二节“Codex 后端不可达时的出站路径”) + * - 生产入口与可观察结果:经生产的 Host Codex 运行时(真实回环代理)与 createHostAgentGraph 组装出的 Codex + * 依赖 getOutboundPathFact:一条带 thread-id 的请求经主代理发往网关、网关连不上之后,按这个线程取到的是 + * 这次请求实际出口的判定(代理环境变量给的代理,地址已脱敏,属于网关的 origin);没走过的线程、没有 + * 线程号时是 null,错误保留通用文案。代理环境变量带用户名和密码时,判定和解析器的快照里都没有它们。maker-core 在“后端不可达”终局升级时把它渲染进用户看到的错误。 + * - 规则依据:桌面 maker-host/index.ts 的 getOutboundPathFact(Codex 代理记的线程出口 origin,加出站代理 + * 解析器按 origin 的判定);Host 原来写 undefined,上游不可达时只有通用猜测。 + * - 现有覆盖缺口:engine-deps.test.mjs 不起代理;codex-proxy-gate.test.mjs 的上游都是本机地址,解析器 + * 被跳过,也不读这个依赖。 + * - 最小失败输入:依赖写回 undefined;取线程出口时读错代理实例;按别的线程或别的 origin 取判定;快照记下带凭据的代理地址。 + * - tier:integration(真实代理;网关是保留域名,经代理环境变量指向本测试自己的本机监听,监听拒绝 + * CONNECT,模拟后端不可达;本机不解析也不直连,没有请求离开本机;假 key,不起 Codex,HOME 隔离)。 + * - 实测耗时:见 PR(单独运行本文件)。 + */ +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import { createServer } from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; + +import { configureHostOwner } from './claude-auth.mjs'; +import { createHostProviderConfig } from './provider-config.ts'; +import { createHostModelAccess } from './model-access.ts'; +import { createHostCodexRuntime } from './codex-runtime.ts'; +import { createHostMcpRuntime } from './mcp-runtime.ts'; +import { createHostAgentGraph } from './runtime.ts'; +import { CODEX_PROXY_TOKEN_HEADER } from './codex-proxy-inbound.ts'; +import { getHostOutboundPathSnapshotFor } from '../outbound-proxy.ts'; +import { createCredentialStore } from '../credentials/store.mjs'; +import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { createAvailabilityPolicy } from '../../../desktop/src/main/device-link/providerShareAvailabilityPolicyCore.ts'; +import { hostRuntimeLayout } from '../runtime-layout.mjs'; +import { openOwnerDatabase } from '../../../desktop/src/main/localDb/startupCore.ts'; +import { createDbClientForHandle } from '../../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { lifoCleanup } from '../test-support/cleanup.mjs'; + +const GATEWAY_KEY = 'synthetic-gateway-key'; +// A reserved name: through the proxy it is never resolved or dialled from this machine. +const GATEWAY = 'https://gateway.example.test'; +// Credentials in the proxy variable: forwarding needs them, the diagnostics must never carry them. +const PROXY_USER = 'proxy-user-fixture'; +const PROXY_PASS = 'proxy-pass-fixture'; + +test('a Codex thread whose backend is unreachable reports the outbound path its request took', { timeout: 120_000 }, async t => { + t = lifoCleanup(t); + const root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-host-outbound-fact-'))); + t.after(() => fs.rm(root, { recursive: true, force: true })); + const savedEnv = { ...process.env }; + t.after(() => { for (const key of Object.keys(process.env)) if (!(key in savedEnv)) delete process.env[key]; Object.assign(process.env, savedEnv); }); + process.env.HOME = process.env.USERPROFILE = path.join(root, 'home'); + const fixtureHome = process.env.HOME; + t.mock.method(os, 'homedir', () => fixtureHome); + await fs.mkdir(process.env.HOME); + for (const key of ['XDT_OFFICIAL_SHARED_PROFILE', 'OPENAI_API_KEY', 'CODEX_API_KEY', 'CODEX_HOME', 'XDT_CODEX_API_KEY', 'ANTHROPIC_API_KEY', + 'http_proxy', 'https_proxy', 'ALL_PROXY', 'all_proxy', 'no_proxy']) delete process.env[key]; + + // The proxy the environment names: it refuses every tunnel, so the gateway is unreachable. + const connects = []; + const proxy = createServer((_req, res) => res.writeHead(502).end()); + proxy.on('connect', (req, socket) => { connects.push(req.url); socket.destroy(); }); + await new Promise(resolve => proxy.listen(0, '127.0.0.1', resolve)); + t.after(() => { proxy.closeAllConnections(); return new Promise(resolve => proxy.close(resolve)); }); + const proxyUrl = `http://127.0.0.1:${proxy.address().port}`; + // The fact goes into a user-visible error; the snapshot is kept for the life of the process. + process.env.HTTP_PROXY = process.env.HTTPS_PROXY = `http://${PROXY_USER}:${PROXY_PASS}@127.0.0.1:${proxy.address().port}`; + process.env.NO_PROXY = '127.0.0.1,localhost'; + + const profile = path.join(root, 'profile'); + await fs.mkdir(profile, { recursive: true }); + const ownerId = 'outbound-fact-fixture'; + configureHostOwner({ userDataDir: profile, ownerId }); + t.after(() => configureHostOwner({ userDataDir: profile, ownerId: null })); + configureAppDataDir(path.join(root, 'app-data')); + const layout = hostRuntimeLayout(); + const opened = await openOwnerDatabase({ userDataDir: profile, ownerId, isPackaged: false, + drizzleDir: layout.drizzleDir, sqliteVecExtPath: layout.sqliteVecPath }); + const database = createDbClientForHandle({ db: opened.db, drizzle: opened.drizzle, dispose: async () => opened.db.close() }); + setCurrentDbClient(database, ownerId); + t.after(async () => { clearCurrentDbClient(database); await database.dispose(); }); + const credentials = await createCredentialStore({ userDataDir: profile, platform: 'linux', keyPromise: Promise.resolve(Buffer.alloc(16, 7)) }); + let modelAccess; + const config = createHostProviderConfig({ profileDir: profile, ownerId, credentials, getCodexBinary: () => null, + gatewayConnected: () => Boolean(modelAccess?.gateway.credential), openExternal: async () => { throw new Error('Unexpected browser request'); } }); + t.after(() => config.close()); + modelAccess = createHostModelAccess({ ownerId, region: 'global', readKey: () => config.builtinStore.get('xd'), + writeKey: value => config.builtinStore.set('xd', value), request: async () => ({ endpoint: GATEWAY, apiKey: GATEWAY_KEY }), + onKeyChanged: () => {}, publish: () => {} }); + await modelAccess.start(); + t.after(() => modelAccess.close()); + const mcp = createHostMcpRuntime({ appServerIds: () => [], getRemoteMcpBridgeToken: config.remoteBridgeToken }); + t.after(() => mcp.close()); + const runtime = createHostCodexRuntime({ profileDir: profile, binaryPath: path.join(root, 'no-codex-binary'), config, modelAccess, mcp, + availabilityPolicy: createAvailabilityPolicy(async () => { throw new Error('Unexpected share mutation'); }), publish: () => {} }); + t.after(() => runtime.close()); + const harnessRoot = path.join(root, 'harnesses'); + const ripgrepDir = path.join(harnessRoot, 'ripgrep-bin', `${process.platform}-${process.arch}`); + await fs.mkdir(ripgrepDir, { recursive: true }); + // Pi resolves the search binary during assembly. No engine or search binary runs in this test. + await fs.writeFile(path.join(ripgrepDir, process.platform === 'win32' ? 'rg.exe' : 'rg'), ''); + const graph = createHostAgentGraph({ userDataDir: profile, providerConfig: config, mcpRuntime: mcp, codexRuntime: runtime, storage: {}, + gateway: null, mcpProviders: [], harnessRoot, + // Never spawned: only the constructed Codex agent's dependency is called. + binaryPath: path.join(root, 'claude'), codexBinaryPath: path.join(root, 'codex'), piBinaryPath: path.join(root, 'pi') }); + const getOutboundPathFact = graph.codex.deps.getOutboundPathFact; + + // Codex's own request, as it sends it: through the main proxy, naming its thread. + const spawn = await runtime.deps.prepareCodexExtraSpawnConfig([], { credentialMode: 'gateway-key', codexHome: path.join(profile, 'codex-home') }); + const args = spawn.extraArgs; + const mainProxy = args.map(arg => /^model_providers\.cindy_gateway\.base_url="([^"]*)"$/.exec(arg)?.[1]).find(Boolean); + assert.ok(mainProxy, 'the main proxy is in the spawn config'); + const threadId = 'thread-unreachable-gateway'; + const res = await fetch(`${mainProxy.replace(/\/$/, '')}/responses`, { method: 'POST', + headers: { 'content-type': 'application/json', authorization: `Bearer ${GATEWAY_KEY}`, 'thread-id': threadId, + [CODEX_PROXY_TOKEN_HEADER]: runtime.inboundToken() }, + body: JSON.stringify({ model: 'gpt-5.4', input: 'hi', stream: true }) }); + await res.text(); + assert.ok(res.status >= 500, `the gateway is unreachable (${res.status})`); + assert.deepEqual([...new Set(connects)], ['gateway.example.test:443'], 'the request went to the proxy the environment names'); + + const fact = getOutboundPathFact({ threadId }); + assert.ok(fact, 'a fact for the thread whose request failed'); + const { at, ...rest } = fact; + assert.equal(typeof at, 'number'); + assert.deepEqual(rest, { source: 'env', kind: 'proxy', proxy: proxyUrl, upstream: GATEWAY }); + // Neither the user name nor the password, in any field, of the fact or of the resolver's snapshot. + for (const [what, value] of [['fact', fact], ['snapshot', getHostOutboundPathSnapshotFor([GATEWAY])]]) { + const text = JSON.stringify(value); + assert.ok(value && !text.includes(PROXY_USER) && !text.includes(PROXY_PASS) && !text.includes('@'), `${what} without credentials: ${text}`); + } + // No request of its own, or no thread: the generic error text stays. + assert.equal(getOutboundPathFact({ threadId: 'thread-never-sent' }), null); + assert.equal(getOutboundPathFact({}), null); +}); diff --git a/apps/host/src/agent/owner-boundary.ts b/apps/host/src/agent/owner-boundary.ts new file mode 100644 index 00000000000..506a627aee8 --- /dev/null +++ b/apps/host/src/agent/owner-boundary.ts @@ -0,0 +1,83 @@ +import { beginSessionTurnEndedSuppression } from '../../../desktop/src/main/localDb/sessionActiveTurn.ts'; + +/** + * The first step of every owner boundary on the Host: logout, session invalidation and shutdown (an + * account switch reuses it). From `begin()` on, a turn that ends is an interruption, as on the desktop + * (bootstrap-electron.ts: the account boundary holds beginSessionTurnEndedSuppression, quit freezes the + * turn markers): it keeps `activeTurnStartedAt > lastTurnEndedAt`, shows the interruption banner and is + * listed as interrupted at the next start, instead of reading as finished or as an error. + * - The input runtime is stopping (input-queue.mjs beginStop): no new input is accepted, and the executor + * writes no turn end for a turn that ends from now on (turn-executor.mjs interruptedByShutdown). + * - The shared turn-end suppression is held as a second line, until the boundary's teardown, the owner's + * storage close included, has finished. + * - Open /chat streams end with the interrupted receipt (chat.mjs), so no caller waits on a turn that + * is being stopped. + * Begun before anything a running turn depends on is taken apart (requests paused, confirmations and + * plugins closed, the server revoke at logout); otherwise a turn that fails on that teardown is written as + * ended, with an error row. + * + * Invariant: a begin must reach dispose, and its release must run. beginStop cannot be undone; only the + * input runtime's dispose replaces it with a fresh one (input-queue.mjs api.dispose). A path that begins + * and can fail before dispose either still reaches dispose or rebuilds the input runtime, and releases the + * suppression in a finally; otherwise the Host stays signed in with every send refused ("session is + * closed") and no turn end written until it restarts. The calls of `begin()`, checked against it: + * 1. main.ts logout, through runOwnerBoundary: dispose runs whatever the steps before it do; release in finally. + * 2. main.ts invalidateHostSession, through runOwnerBoundary: the same. + * 3. main.ts stop (shutdown), through runOwnerBoundary: the same. + * 4. server.mjs logout() (the HTTP logout entry, `beginOwnerBoundaryStop`): each of its own steps runs on its + * own, a failed one skips neither the others nor deps.logout() (which is 1), and the release is in the + * flight's finally. + * A new call (the account switch) is added to this list and checked the same way. + */ +export interface OwnerBoundaryStop { + /** Enter the stopping state; returns the release of the turn-end suppression (idempotent). */ + begin(): () => void; + /** Called on each begin, before it returns (a /chat stream ends itself). Returns the unsubscribe. */ + onStop(listener: () => void): () => void; +} + +export function createOwnerBoundaryStop(ports: { beginStop(): void }): OwnerBoundaryStop { + const listeners = new Set<() => void>(); + return { + begin() { + ports.beginStop(); + const release = beginSessionTurnEndedSuppression(); + for (const listener of [...listeners]) { + try { listener(); } catch { /* a stream that is already closed */ } + } + return release; + }, + onStop(listener) { + listeners.add(listener); + return () => { listeners.delete(listener); }; + }, + }; +} + +/** + * One owner boundary: begin the stop, then the path's own teardown, then the owner's runtime, then (logout) + * the stored session. Logout keeps the desktop's order (authManager.ts logout: the local boundary first, + * `revokeLoggedOutAccountBestEffort` last): the running turns stop before the server revokes the session + * they use. A failing step does not skip the later ones; the failures are returned for the path to report. + */ +export async function runOwnerBoundary(boundary: OwnerBoundaryStop, steps: { + /** The path's teardown before the runtime: requests paused, waits cancelled, the refresh settled. */ + beforeDispose?(): Promise | unknown; + dispose(): Promise; + /** Logout only: the stored session is signed out, the server revoke best effort (auth/logout.mjs). */ + afterDispose?(): Promise; +}): Promise<{ result: T | undefined; errors: unknown[] }> { + const release = boundary.begin(); + const errors: unknown[] = []; + try { + try { await steps.beforeDispose?.(); } catch (error) { errors.push(error); } + try { await steps.dispose(); } catch (error) { errors.push(error); } + let result: T | undefined; + if (steps.afterDispose) { + try { result = await steps.afterDispose(); } catch (error) { errors.push(error); } + } + return { result, errors }; + } finally { + release(); + } +} diff --git a/apps/host/src/agent/pi-native-providers.ts b/apps/host/src/agent/pi-native-providers.ts index 61123987085..6c868fa8691 100644 --- a/apps/host/src/agent/pi-native-providers.ts +++ b/apps/host/src/agent/pi-native-providers.ts @@ -39,6 +39,8 @@ export function createHostPiNativeProviders(options: { grok: { hasGrokOAuthLogin(providerId?: string): boolean }; codexAccounts: { isOpenAiSubscriptionProviderId(providerId?: string | null): boolean }; }; + /** The desktop's first step before a local Pi (release table row 25); no-op when absent. */ + ensureSharedGlobalSkills?: () => Promise; }) { const config = options.providerConfig; return createPiNativeProviderResolver({ @@ -50,7 +52,7 @@ export function createHostPiNativeProviders(options: { hasGrokOAuthLogin: id => config.grok.hasGrokOAuthLogin(id), listCustomProvidersWithSecureHeaders: () => config.list(), readCustomProviderKey: (...args) => config.readKey(...args), - ensureSharedGlobalSkills: async () => {}, + ensureSharedGlobalSkills: () => options.ensureSharedGlobalSkills?.() ?? Promise.resolve(), ensureManagedOllamaReadyForSession: input => hostManagedLocalModelNotReady(input), getUserDataDir: () => options.userDataDir, }); diff --git a/apps/host/src/agent/product-turn.ts b/apps/host/src/agent/product-turn.ts new file mode 100644 index 00000000000..1e363b7a720 --- /dev/null +++ b/apps/host/src/agent/product-turn.ts @@ -0,0 +1,91 @@ +import type { AgentEvent, Session } from '@cindy/maker-core'; +import { + captureProductTurnFailureOwner, + createDeferredProductTurnFailureGate, + createProductTurnFailureFinalizer, + type ProductTurnFailureOwner, +} from '../../../desktop/src/main/maker-ipc/productTurnFailureOwner.js'; +import { SessionListActivityTracker } from '../../../desktop/src/main/maker-ipc/sessionTurnActivityTracker.js'; + +/** + * The desktop's product-turn failure handling (register.ts) over the Host's runtime: the deferred + * failure gate and the failure finalizer (maker-ipc/productTurnFailureOwner.ts) and the task list's + * activity tracker (SessionListActivityTracker), one set per owner runtime. + * + * A terminal that an automatic resume or a context recovery holds ends the turn's activity held and + * leaves its owner (task, runtime instance, turn generation) in the gate. When that holder finally gives + * up, the gate settles the owner if it is still the current turn, and the finalizer commits the held + * activity at the time the turn ended. A newer turn that started meanwhile has replaced the owner's + * runtime or generation, so the old owner is dropped and the newer turn keeps its own activity. + * + * The finalizer's other two steps have no Host subsystem yet and are bound empty: plugin task + * receipts (settlePluginTasks; the plugin batch, release table row 33) and the Cindy Make upstream + * merge turn (interrupt; cindy-make/upstreamMergeRuntime.ts, which needs Electron and is not loaded). + */ +export function createHostProductTurn(deps: { + /** The runtime the Host currently binds for a task (the desktop's sessionBindings.getSession). */ + getBoundSession: (sessionId: string) => Session | undefined; + /** The task list's activity write (session-activity.ts), as register.ts's tracker writes it. */ + touchActivity?: (sessionId: string, atMs: number, skipActiveGoal: boolean) => Promise; + log: { warn(message: string): void }; +}) { + const gate = createDeferredProductTurnFailureGate(); + const listActivity = new SessionListActivityTracker((sessionId, atMs) => { + void deps.touchActivity?.(sessionId, atMs, true); + }); + + /** register.ts isCurrentProductTurnFailureOwner, over the Host's bindings. */ + function isCurrentOwner(owner: ProductTurnFailureOwner): boolean { + const bound = deps.getBoundSession(owner.sessionId); + // A closed owner may still be settled by its holder. If a replacement is already bound, the old + // identity is stale; while no replacement exists, the captured runtime and generation decide. + if (bound && bound !== owner.session) return false; + if (owner.session.instanceId !== owner.instanceId) return false; + try { + return owner.session.getTurnGeneration() === owner.generation; + } catch { + return false; + } + } + + const finalize = createProductTurnFailureFinalizer({ + gate, + isCurrentOwner, + commitActivity: (sessionId) => listActivity.commit(sessionId), + settlePluginTasks: () => {}, + interrupt: async () => {}, + }); + + return { + listActivity, + capture: (session: Session, event: AgentEvent): ProductTurnFailureOwner => + captureProductTurnFailureOwner(session, event, (event as AgentEvent & { agentMeta?: unknown }).agentMeta), + /** A held terminal: its failure is settled later by its holder (the desktop's deferUnsuccessfulProductTurn). */ + defer: (owner: ProductTurnFailureOwner) => gate.defer(owner), + /** An unheld unsuccessful terminal, or a holder's final failure (register.ts interruptProductTurn). */ + interrupt(sessionId: string, owner: ProductTurnFailureOwner): void { + void finalize(sessionId, owner).catch(() => deps.log.warn('Could not interrupt product turn follow-up')); + }, + /** A successful done (register.ts finishProductTurn): its owner no longer has a failure to settle. */ + finish(owner: ProductTurnFailureOwner): void { + gate.clear(owner); + }, + /** A holder gave up (register.ts settleDeferredProductTurnFailure). */ + settleDeferred(sessionId: string): void { + gate.settle(sessionId, isCurrentOwner, (owner) => { + void finalize(sessionId, owner).catch(() => deps.log.warn('Could not interrupt product turn follow-up')); + }); + }, + /** A runtime that replaces a task's runtime takes over its held owners (register.ts onBind). */ + rebind: (sessionId: string, session: Session) => gate.rebindSession(sessionId, session), + /** A closed runtime (sessionBindingLifecycle.ts teardown and finalizeClosedSession). */ + closed(sessionId: string, session: Session): void { + gate.clearSession(sessionId, session); + listActivity.deleteSession(sessionId); + }, + /** An explicit stop (register.ts resetAutomaticRecoveryForExplicitStop). */ + stopped: (sessionId: string) => gate.clearSession(sessionId), + }; +} + +export type HostProductTurn = ReturnType; diff --git a/apps/host/src/agent/profile-coexistence.test.mjs b/apps/host/src/agent/profile-coexistence.test.mjs new file mode 100644 index 00000000000..90cad659485 --- /dev/null +++ b/apps/host/src/agent/profile-coexistence.test.mjs @@ -0,0 +1,169 @@ +/* + * 测试价值 + * - 生产入口:profile-coexistence.ts 的 createDesktopScanner(启动和运行中重扫共用,内部是桌面的 + * findConcurrentLiveInstancePids)与 createCoexistenceMonitor(10 秒一次加目录监听,main.ts 据此关、开闸门)。 + * - 规则:并存方案 A(审核方 2026-11-17 定)。开库的桌面挡住 Host:没有 `runtime` 字段的旧记录按开库处理, + * 只放行 `runtime: 'client'`;`passive: true` 的开发实例也开库,照样挡(审核方 2026-11-17 定);只在 SingletonLock + * 里出现的 PID 也挡;进程已结束的残留和 + * PID 被复用的记录不挡。同一份记录只问一次进程身份。闸门遇到桌面立刻关,连续两次干净扫描才报可开, + * 扫描失败按有桌面处理。 + * - 现有覆盖缺口:桌面的 ownerNamespaceMigration.test.ts 只测这个扫描在迁移里的用法,不测 runtime 的放行与 + * passive 的阻挡,也没有重扫和闸门状态。 + * - 最小失败输入:一个空转子进程的 PID 加一份记录;监听回调与定时器手动触发。tier:unit(子进程按 PID 结束, + * 没有 100ms 以上的真实等待)。 + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { createCoexistenceMonitor, createDesktopScanner, nodeProfileScanPorts } from './profile-coexistence.ts'; + +async function liveChild(t) { + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1 << 30)'], { stdio: 'ignore' }); + await once(child, 'spawn'); + t.after(async () => { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = once(child, 'exit'); + child.kill(); + await exited; + }); + return child; +} + +function profile(t) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-coexistence-')); + fs.mkdirSync(path.join(dir, '.dev-instances')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const write = (pid, fields = {}) => fs.writeFileSync(path.join(dir, '.dev-instances', `${pid}.json`), + JSON.stringify({ schemaVersion: 1, pid, startedAtMs: Date.now(), userDataDir: dir, state: 'ready', passive: false, ...fields })); + return { dir, write }; +} + +/** The real ports, counting the OS identity queries. */ +function countingPorts() { + const asked = []; + return { asked, ports: { ...nodeProfileScanPorts, readProcessIdentities: async pids => { + asked.push([...pids]); + return nodeProfileScanPorts.readProcessIdentities(pids); + } } }; +} + +test('a live desktop record blocks, a passive instance too, unless it is a Host client', async t => { + const child = await liveChild(t); + const p = profile(t); + const { asked, ports } = countingPorts(); + const scan = createDesktopScanner(p.dir, ports); + // Written by an older desktop: no `runtime` field. It opens the database. + p.write(child.pid); + assert.deepEqual(await scan(), [child.pid]); + p.write(child.pid, { runtime: 'embedded' }); + assert.deepEqual(await scan(), [child.pid]); + p.write(child.pid, { runtime: 'client' }); + assert.deepEqual(await scan(), []); + // A passive dev instance skips migrations and the scheduler but opens and writes the same database. + p.write(child.pid, { passive: true }); + assert.deepEqual(await scan(), [child.pid]); + // An unreadable record keeps the PID visible through its file name, and blocks. + fs.writeFileSync(path.join(p.dir, '.dev-instances', `${child.pid}.json`), '{ torn'); + assert.deepEqual(await scan(), [child.pid]); + assert.ok(asked.length >= 1); +}); + +test('an out-of-range registered PID does not block the profile', async t => { + const p = profile(t); + p.write(2 ** 40); + assert.deepEqual(await createDesktopScanner(p.dir)(), []); +}); + +test('the same record asks the OS for its identity once; a changed record asks again', async t => { + const child = await liveChild(t); + const p = profile(t); + const { asked, ports } = countingPorts(); + const scan = createDesktopScanner(p.dir, ports); + const startedAtMs = Date.now(); + p.write(child.pid, { startedAtMs }); + assert.deepEqual(await scan(), [child.pid]); + assert.deepEqual(await scan(), [child.pid]); + assert.deepEqual(await scan(), [child.pid]); + assert.equal(asked.length, 1, 'three scans of the same record ask once'); + p.write(child.pid, { startedAtMs, state: 'starting' }); + await scan(); + assert.equal(asked.length, 2); +}); + +test('a record whose process ended, or whose PID now belongs to another program, does not block', async t => { + const child = await liveChild(t); + const p = profile(t); + const scan = createDesktopScanner(p.dir); + // Recorded an hour before this process started, by a Cindy at another path: the PID was reused. + p.write(child.pid, { startedAtMs: Date.now() - 3_600_000, rootDir: path.join(p.dir, 'some-other-cindy') }); + assert.deepEqual(await scan(), []); + p.write(child.pid); + assert.deepEqual(await scan(), [child.pid]); + const exited = once(child, 'exit'); + child.kill(); + await exited; + assert.deepEqual(await scan(), [], 'a leftover record of an ended process'); +}); + +test('a PID seen only through the SingletonLock blocks', { skip: process.platform === 'win32' }, async t => { + const child = await liveChild(t); + const p = profile(t); + fs.symlinkSync(`some-host-${child.pid}`, path.join(p.dir, 'SingletonLock')); + assert.deepEqual(await createDesktopScanner(p.dir)(), [child.pid]); +}); + +test('the monitor closes at once, reports clear after two clean scans, and fails closed', async () => { + const results = []; + const reports = []; + const intervals = []; + const timeouts = []; + let watched = null; + const monitor = createCoexistenceMonitor({ + scan: async () => { const next = results.shift(); if (next instanceof Error) throw next; return next ?? []; }, + registryDir: '/registry', onScan: state => reports.push(state), log: { warn() {} }, + timers: { + setInterval: (fn, ms) => { intervals.push({ fn, ms }); return intervals.length; }, + clearInterval() {}, + setTimeout: (fn, ms) => { timeouts.push({ fn, ms }); return timeouts.length; }, + clearTimeout() {}, + }, + watch: (dir, listener) => { watched = { dir, listener }; return { close() { watched = null; } }; }, + }); + monitor.start(); + assert.equal(intervals[0].ms, 10_000); + assert.equal(watched.dir, '/registry'); + + const settle = async () => { for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); }; + results.push([42]); + intervals[0].fn(); await settle(); + assert.equal(reports.length, 1, 'the interval scans'); + assert.deepEqual(reports.at(-1), { state: 'desktop-running', desktops: [42] }); + // The desktop restarts: one clean scan in between does not open. + results.push([]); + watched.listener(); watched.listener(); + assert.equal(timeouts.length, 2); + assert.equal(timeouts[1].ms, 250); + timeouts[1].fn(); await settle(); + assert.equal(reports.length, 2, 'two registry changes, debounced into one scan'); + assert.equal(reports.at(-1).state, 'desktop-running'); + results.push([]); + await monitor.scanNow(); + assert.deepEqual(reports.at(-1), { state: 'clear', desktops: [] }); + // Clear repeats on each clean scan, so a reopen that waited for a turn is tried again. + await monitor.scanNow(); + assert.equal(reports.at(-1).state, 'clear'); + // An unreadable registry: in use, with no PIDs. + results.push(new Error('EACCES')); + await monitor.scanNow(); + assert.deepEqual(reports.at(-1), { state: 'desktop-running', desktops: [] }); + monitor.stop(); + assert.equal(watched, null); + const count = reports.length; + await monitor.scanNow(); + assert.equal(reports.length, count, 'nothing after stop'); +}); diff --git a/apps/host/src/agent/profile-coexistence.ts b/apps/host/src/agent/profile-coexistence.ts new file mode 100644 index 00000000000..4adb76dad36 --- /dev/null +++ b/apps/host/src/agent/profile-coexistence.ts @@ -0,0 +1,385 @@ +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; + +import { + findConcurrentLiveInstancePids, parseRegisteredInstanceCandidate, recordedPidMayStillBeLive, + type ConcurrentInstanceScanDeps, +} from '../../../desktop/src/main/concurrentInstanceScan.js'; +import { + readProcessIdentities, + type ProcessIdentitySnapshot, +} from '../../../desktop/src/main/processIdentity.js'; +import { explicitPorts } from './explicit-ports.js'; + +/** + * The Host and a desktop that opens the same profile's database (coexistence plan A, release table). + * + * Until a desktop started beside a running Host connects to it (plan B), the Host refuses to start + * on a profile a desktop is using, and while it runs it rescans: once a desktop that opens the + * database is live there, it accepts no new sends until the desktop is gone. Desktops are found with + * the desktop's own scan of `.dev-instances` and the Chromium SingletonLock (concurrentInstanceScan.ts), + * which keeps its stale-PID proofs in this process. The Host does not register in `.dev-instances`. + * + * Allowed beside the Host: a record that says `runtime: 'client'` (a client of a Host, which never + * opens the database). Everything else is a desktop that opens the database: a record without + * `runtime` (older desktops), a `passive: true` dev instance (it skips migrations and the scheduler but + * opens and writes the same database: localDb/index.ts 171–197), a record that cannot be read, a PID + * seen only through the SingletonLock. + */ +export const HOST_PROFILE_IN_USE_BY_DESKTOP = 'HOST_PROFILE_IN_USE_BY_DESKTOP'; + +/** + * The Host's start refused because a desktop that opens this profile's database is running. Its own + * code: `DB_SCHEMA_LOCKED` names the database migration lease, which this is not. + */ +export class HostProfileInUseError extends Error { + readonly code = HOST_PROFILE_IN_USE_BY_DESKTOP; + constructor(message: string) { + super(message); + this.name = 'HostProfileInUseError'; + } +} + +export interface ProfileScanPorts { + readdir(dir: string): Promise; + readFile(file: string): Promise; + readlink(file: string): Promise; + lstat(file: string): Promise<{ isDirectory(): boolean; mtimeMs?: number }>; + selfPid(): number; + isPidAlive(pid: number): boolean; + /** The OS identity of live PIDs (one `ps` or PowerShell query for the batch). */ + readProcessIdentities(pids: readonly number[]): Promise>; +} + +export const nodeProfileScanPorts: ProfileScanPorts = { + readdir: dir => fsp.readdir(dir), + readFile: file => fsp.readFile(file, 'utf8'), + readlink: file => fsp.readlink(file), + lstat: file => fsp.lstat(file), + selfPid: () => process.pid, + isPidAlive: pid => { + try { process.kill(pid, 0); return true; } + catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } + }, + readProcessIdentities: pids => readProcessIdentities(pids), +}; + +interface Registration { + fingerprint: string; + recordedAtMs?: number; + rootDir?: string; + client: boolean; +} + +type StartupScanResult = 'clear' | 'desktop' | 'unknown' | 'deadline'; +interface StartupScanClock { + now(): number; + sleep(ms: number): Promise; +} +const startupClock: StartupScanClock = { + now: () => performance.now(), + sleep: ms => new Promise(resolve => setTimeout(resolve, ms)), +}; +const STARTUP_RECHECK_DELAYS_MS = [500, 1_000, 2_000]; +const STARTUP_RECHECK_BUDGET_MS = 10_000; +type ReportRound = (round: number, elapsedMs: number, result: StartupScanResult) => void; + +/** + * One scan of a profile for desktops that open its database. Returns their PIDs (empty: none). + * + * Runtime scans cache positive identities. An uncertain startup rereads both the registry and the OS. + * Between runtime scans, a live PID's OS identity is kept with the record + * text (or the SingletonLock target and time) it was read for, and asked again only when that + * changes. While a desktop runs, its record does not change, so a rescan starts no `ps`. An identity + * the OS did not give is not kept (it is asked again; meanwhile the PID counts as live, as the scan + * treats it). Throws when the registry exists but cannot be read, as the desktop's scan does. + */ +export function createDesktopScanner(profileDir: string, ports: ProfileScanPorts = nodeProfileScanPorts, + clock: StartupScanClock = startupClock) { + const identities = new Map(); + + // Capture only the provenance the shared scanner actually read. Its canonical/backup + // handling, profile matching and PID-reuse decisions stay authoritative. + async function discover(identityFor: (pid: number, registration?: Registration) => ProcessIdentitySnapshot | null) { + const registrations = new Map(); + let lock: { pid: number; target: string } | undefined; + const live = await findConcurrentLiveInstancePids(explicitPorts({ + readdir: ports.readdir, selfPid: ports.selfPid, isPidAlive: ports.isPidAlive, + readFile: async file => { + const raw = await ports.readFile(file); + const name = path.basename(file).replace(/\.bak$/, ''); + const entry = parseRegisteredInstanceCandidate(raw, name); + if (entry) registrations.set(entry.pid, { fingerprint: `registry\u0000${raw}`, client: allowedBesideHost(raw), + recordedAtMs: entry.recordedAtMs, rootDir: entry.rootDir }); + return raw; + }, + readlink: async file => { + const target = await ports.readlink(file); + const match = /-(\d+)$/.exec(target); + if (match) lock = { pid: Number(match[1]), target }; + return target; + }, + lstat: async file => { + // The shared scanner asks for the lock identity only after this stat (also when it fails). + let mtimeMs: number | undefined; + try { const stat = await ports.lstat(file); mtimeMs = stat.mtimeMs; return stat; } + finally { + if (lock) registrations.set(lock.pid, { fingerprint: `lock\u0000${lock.target}\u0000${mtimeMs}`, + client: false, recordedAtMs: mtimeMs }); + } + }, + readProcessIdentity: pid => identityFor(pid, registrations.get(pid)), + }), profileDir); + return new Map(live.filter(pid => !registrations.get(pid)?.client).map(pid => [pid, registrations.get(pid)!])); + } + + async function scanRound(previous?: Map) { + const candidates = await discover(() => null); + const key = (pid: number, entry: Registration) => `${pid}\u0000${entry.fingerprint}`; + const query = new Map(candidates); + // A vanished registration alone cannot clear a still-live, unidentified PID. + for (const [pid, entry] of previous ?? []) if (!query.has(pid) && ports.isPidAlive(pid)) query.set(pid, entry); + const keys = new Set([...query].map(([pid, entry]) => key(pid, entry))); + for (const cached of identities.keys()) if (previous || !keys.has(cached)) identities.delete(cached); + const ask = [...query].filter(([pid, entry]) => !identities.has(key(pid, entry))).map(([pid]) => pid); + if (ask.length) { + for (const [pid, identity] of await ports.readProcessIdentities(ask)) { + if (identity) identities.set(key(pid, query.get(pid)!), identity); + } + } + const identityFor = (pid: number, entry?: Registration) => entry ? identities.get(key(pid, entry)) ?? null : null; + // Re-read after the OS query. A replacement record cannot inherit its predecessor's evidence. + const blockers = await discover(identityFor); + for (const [pid, entry] of query) { + if (!blockers.has(pid) && ports.isPidAlive(pid) && + recordedPidMayStillBeLive(entry.recordedAtMs, entry.rootDir, identityFor(pid, entry))) blockers.set(pid, entry); + } + const confirmed = [...blockers].some(([pid, entry]) => identityFor(pid, entry) !== null || + (previous !== undefined && previous.get(pid)?.fingerprint !== entry.fingerprint)); + return { blockers, confirmed }; + } + + return async function scan(report?: ReportRound): Promise { + if (!report) return [...(await scanRound()).blockers.keys()]; + const start = clock.now(); + const retryDeadline = start + STARTUP_RECHECK_BUDGET_MS; + let previous: Map | undefined; + for (let round = 1; ; round++) { + const { blockers, confirmed } = await scanRound(previous); + const result = !blockers.size ? 'clear' : confirmed ? 'desktop' : 'unknown'; + const now = clock.now(); + report(round, Math.round(now - start), result); + const delay = STARTUP_RECHECK_DELAYS_MS[round - 1]; + if (result !== 'unknown' || delay === undefined) return [...blockers.keys()]; + + // Budget the wait for another observation. A completed scan always decides. + if (now + delay <= retryDeadline) { + await clock.sleep(delay); + if (clock.now() <= retryDeadline) { + previous = blockers; + continue; + } + } + report(round, Math.round(clock.now() - start), 'deadline'); + return [...blockers.keys()]; + } + }; +} + +/** A client of a Host. Anything else (a passive instance, an unreadable record, no field) is not. */ +function allowedBesideHost(raw: string | undefined): boolean { + if (raw === undefined) return false; + try { + const record = JSON.parse(raw) as { runtime?: unknown } | null; + return record?.runtime === 'client'; + } catch { return false; } +} + +export interface CoexistenceState { + /** `clear`: no desktop opens this profile's database; `desktop-running`: one does (PIDs below). */ + state: 'clear' | 'desktop-running'; + /** PIDs only: no paths or command lines. */ + desktops: number[]; +} + +export interface CoexistenceTimers { + setInterval(fn: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; + setTimeout(fn: () => void, ms: number): unknown; + clearTimeout(handle: unknown): void; +} + +export interface CoexistenceMonitor { + /** Start rescanning on the interval and on registry changes. */ + start(): void; + scanNow(): Promise; + state(): CoexistenceState; + stop(): void; +} + +export interface CoexistenceMonitorOptions { + scan(): Promise; + /** The `.dev-instances` directory; watched while it exists, rescanned on the interval regardless. */ + registryDir: string; + /** + * After every scan: `desktop-running` closes the gate (or keeps it closed); `clear` comes only + * after two clean scans in a row and repeats on each later clean scan, so a reopen that had to wait + * (a turn still running) is tried again. Both must be safe to receive repeatedly. + */ + onScan(state: CoexistenceState): void; + log: { warn(message: string, fields?: Record): void }; + intervalMs?: number; + debounceMs?: number; + timers?: CoexistenceTimers; + watch?(dir: string, listener: () => void): { close(): void }; +} + +export const COEXISTENCE_RESCAN_MS = 10_000; +const WATCH_DEBOUNCE_MS = 250; + +/** + * Rescans every 10 seconds and on changes in `.dev-instances` (debounced). One scan at a time; a + * trigger during a scan runs one more after it. A desktop is reported at once; clear only after two + * clean scans in a row, so a desktop restarting (old record gone, new one not yet written) does not + * open the gate in between. A scan that fails is reported as a desktop (fail closed), with no PIDs. + */ +export function createCoexistenceMonitor(options: CoexistenceMonitorOptions): CoexistenceMonitor { + const timers: CoexistenceTimers = options.timers ?? { + setInterval: (fn, ms) => { const handle = setInterval(fn, ms); handle.unref?.(); return handle; }, + clearInterval: handle => clearInterval(handle as ReturnType), + setTimeout: (fn, ms) => setTimeout(fn, ms), + clearTimeout: handle => clearTimeout(handle as ReturnType), + }; + const watch = options.watch ?? ((dir, listener) => fs.watch(dir, { persistent: false }, () => listener())); + let state: CoexistenceState = { state: 'clear', desktops: [] }; + let cleanScans = 2; + let running: Promise | null = null; + let again = false; + let interval: unknown = null; + let debounce: unknown = null; + let watcher: { close(): void } | null = null; + let stopped = false; + + function ensureWatcher() { + if (watcher || stopped) return; + try { + watcher = watch(options.registryDir, () => { + if (debounce !== null) timers.clearTimeout(debounce); + debounce = timers.setTimeout(() => { debounce = null; void scanNow(); }, options.debounceMs ?? WATCH_DEBOUNCE_MS); + }); + } catch { watcher = null; } // no registry yet: the interval scan keeps looking + } + + async function runScan() { + let desktops: number[] | null; + try { desktops = [...new Set(await options.scan())].sort((a, b) => a - b); } + catch (error) { + options.log.warn('profile coexistence scan failed; treating the profile as in use', { + error: error instanceof Error ? error.message : String(error), + }); + desktops = null; + } + if (desktops === null || desktops.length) { + cleanScans = 0; + state = { state: 'desktop-running', desktops: desktops ?? [] }; + } else { + cleanScans += 1; + if (cleanScans >= 2) state = { state: 'clear', desktops: [] }; + } + ensureWatcher(); + if (!stopped) options.onScan(state); + } + + function scanNow(): Promise { + if (stopped) return Promise.resolve(); + if (running) { again = true; return running; } + running = (async () => { + do { again = false; await runScan(); } while (again && !stopped); + })().finally(() => { running = null; }); + return running; + } + + return { + start() { + if (interval !== null || stopped) return; + interval = timers.setInterval(() => { void scanNow(); }, options.intervalMs ?? COEXISTENCE_RESCAN_MS); + ensureWatcher(); + }, + scanNow, + state: (): CoexistenceState => state, + stop() { + stopped = true; + if (interval !== null) timers.clearInterval(interval); + if (debounce !== null) timers.clearTimeout(debounce); + interval = null; debounce = null; + watcher?.close(); watcher = null; + }, + }; +} + +interface ProfilePluginRuntime { + pauseForDesktop(message: string): void; + pluginPauseFailure(): unknown; + resumeAfterDesktop(): Promise; +} + +interface HostProfileCoexistenceOptions extends Omit { + message: string; + isCurrent(): boolean; + input: { + isHeldForDesktop(): boolean; + holdForDesktop(message: string): void; + releaseDesktopHold(): Promise; + }; + getPlugins(): ProfilePluginRuntime | null; + refreshPlugins(): Promise | undefined; + setState(state: { state: CoexistenceState['state'] | 'waiting-for-turns'; desktops: number[] }): void; + onInputReleased(): void; +} + +/** The input and plugin gates share the actual monitor's scan and rebuild boundaries. */ +export function createHostProfileCoexistenceMonitor(options: HostProfileCoexistenceOptions): CoexistenceMonitor { + const { input, log, isCurrent, getPlugins, setState } = options; + let releasingInput = false; + function resumePlugins() { + const plugins = getPlugins(); + if (!plugins?.pluginPauseFailure()) return; + void plugins.resumeAfterDesktop().then(resumed => { + if (resumed && isCurrent() && getPlugins() === plugins && !plugins.pluginPauseFailure()) return options.refreshPlugins(); + }).catch((error: unknown) => log.warn('resuming plugins after profile hold failed', { + error: error instanceof Error ? error.message : String(error), + })); + } + const monitor = createCoexistenceMonitor({ + ...options, + onScan: state => { + if (!isCurrent()) return; + if (state.state === 'desktop-running') { + if (!input.isHeldForDesktop()) log.warn('a desktop opened this profile; new sends are held', { pids: state.desktops }); + input.holdForDesktop(options.message); + getPlugins()?.pauseForDesktop(options.message); + setState({ ...state }); + return; + } + if (!input.isHeldForDesktop()) { + setState({ ...state }); + resumePlugins(); + return; + } + setState({ state: 'waiting-for-turns', desktops: [] }); + if (releasingInput) return; + releasingInput = true; + void input.releaseDesktopHold().then(released => { + if (!released || !isCurrent() || monitor.state().state !== 'clear' || input.isHeldForDesktop()) return; + setState({ state: 'clear', desktops: [] }); + resumePlugins(); + options.onInputReleased(); + }, (error: unknown) => log.warn('releasing the profile hold failed', { + error: error instanceof Error ? error.message : String(error), + })).finally(() => { releasingInput = false; }); + }, + }); + return monitor; +} + diff --git a/apps/host/src/agent/provider-config.ts b/apps/host/src/agent/provider-config.ts index 6dd932a63e0..0e936a82e97 100644 --- a/apps/host/src/agent/provider-config.ts +++ b/apps/host/src/agent/provider-config.ts @@ -17,6 +17,8 @@ import { withoutProviderHeaderCredentials } from '../../../desktop/src/main/make import { loadCatalogWithSource, storedCustomProviderId, type CatalogSourceConfig } from '@cindy/model-providers'; import { createGenericOAuthService, type GenericOAuthStorage } from '../../../desktop/src/main/maker-host/generic-oauth.js'; import { createGrokOAuthService } from '../../../desktop/src/main/maker-host/grok-oauth-login.js'; +import { holdGrokLoginWrites } from './xai-held-login.js'; +import { holdCredentialFetch, holdRecipeSecrets } from './held-credentials.js'; import { hostOutbound, resolveHostOutboundProxy } from '../outbound.mjs'; import { createClaudeNativeCli } from '../../../desktop/src/main/maker-host/claude-native-cli.js'; import { readClaudeCliLoginStatusBySpawn } from '@cindy/maker-core/claude-cli-login-status'; @@ -59,7 +61,9 @@ export function createHostCodexAccounts( /** Owner-bound configuration and the existing encrypted header migration. */ export function createHostProviderConfig(options: { profileDir: string; ownerId: string; openExternal(url: string): Promise; - gatewayConnected?(): boolean; getCodexBinary?(): string | null; getClaudeBinary?(): string | null; publish?(channel: string, payload: unknown): void; credentials: { + gatewayConnected?(): boolean; getCodexBinary?(): string | null; getClaudeBinary?(): string | null; publish?(channel: string, payload: unknown): void; + /** Coexistence plan A: whether a Cindy desktop app running on its own uses this profile (xai-held-login.ts). */ + isProfileHeld?(): boolean; credentials: { decrypt(value: string): string; read(key: string): string | null; write(key: string, value: string): void; remove(key: string): void; } }) { @@ -90,10 +94,18 @@ export function createHostProviderConfig(options: { profileDir: string; ownerId: set: (id, value) => { options.credentials.write(key(providerSecretStorageKey(id)), value); return true; }, remove: id => { options.credentials.remove(key(providerSecretStorageKey(id))); return { success: true }; }, }; - const oauth = createGenericOAuthService({ fetchImpl: hostOutbound.outboundFetch }); + // Custom provider OAuth renews through this fetch; while a desktop uses the profile it sends + // nothing, so no refresh token is spent and nothing is written back (held-credentials.ts). + const oauth = createGenericOAuthService({ fetchImpl: holdCredentialFetch(hostOutbound.outboundFetch, + () => options.isProfileHeld?.() === true, 'this provider sign-in is not renewed') }); oauth.configureGenericOAuth({ storage: oauthStorage, openExternal: options.openExternal }); - const grok = createGrokOAuthService({ outboundFetch: hostOutbound.outboundFetch, openExternal: options.openExternal, - genericOAuthSecretIo: oauthStorage, getProviderSecretStore: () => builtinStore }); + // Every Host consumer of the xAI login reads it through this one service; while a desktop uses + // the profile it neither renews nor signs out (xai-held-login.ts). + const grok = holdGrokLoginWrites(createGrokOAuthService({ outboundFetch: hostOutbound.outboundFetch, openExternal: options.openExternal, + genericOAuthSecretIo: oauthStorage, getProviderSecretStore: () => builtinStore }), { + isProfileHeld: () => options.isProfileHeld?.() === true, + readStoredLogin: id => (id === 'xai' ? builtinStore.get('xai') : oauthStorage.read(id)), + }); const claudeNative = createClaudeNativeCli({ binaryPath: () => { check(); return options.getClaudeBinary?.() ?? null; }, resolveOutboundProxy: resolveHostOutboundProxy, @@ -150,7 +162,9 @@ export function createHostProviderConfig(options: { profileDir: string; ownerId: await codexAccounts.close(); }; const api = { - list, readKey, oauth, grok, builtinStore, recipeSecretIo: oauthStorage, codexAccounts, claudeNative, cancelLogins, + list, readKey, oauth, grok, builtinStore, + // Browser recipes whose renewal rotates the refresh token are not read while held (held-credentials.ts). + recipeSecretIo: holdRecipeSecrets(oauthStorage, () => options.isProfileHeld?.() === true), codexAccounts, claudeNative, cancelLogins, async close() { closed = true; await cancelLogins(); diff --git a/apps/host/src/agent/provider-credentials.test.mjs b/apps/host/src/agent/provider-credentials.test.mjs index 0f83e228ea6..7e25a1385c5 100644 --- a/apps/host/src/agent/provider-credentials.test.mjs +++ b/apps/host/src/agent/provider-credentials.test.mjs @@ -207,3 +207,161 @@ test('failed refresh preserves executable models but drops stale payment adverti assert.ok(result.error); assert.ok(!JSON.stringify(result).includes('sensitive')); }); + +// ── Credential status and the XD model list (release table section 2, model list on credential status) ── +// 测试价值 +// - 生产入口:model-access.ts 的 createHostModelAccess(桌面 credentialsSync 的 Host 实例)把状态交给 +// providers.mjs 的 noteCredentialStatus,接法照 main.ts;模型写进本进程真实的 active-catalog +// (setXdGatewayModels,main.ts 的 applyModels 就是它),路由守卫用 Host 也用的 tombstoneGuardOptions。 +// - 规则:桌面 model-access/index.ts onStatusChange(433–441):failed 清掉模型、保留最近一次付费拒绝 +// (已有任务不能借此绕过路由守卫);disabled / unsupported / idle 清掉模型与拒绝、不回退内置嵌入模型; +// 这些状态下不发 /models,ok 之后的下一轮才把模型带回(桌面只在 ok 时发起,432)。 +// - 现有覆盖缺口:上面的用例用的是假快照,只测刷新失败与账号边界;之前 Host 不听凭据状态,模型和拒绝照旧, +// disabled 之后还用旧 Key 拉 /models。 +// - 最小失败输入:一次带付费拒绝的成功轮,再一次 failed(新 Key 存不下)或 disabled(503),再恢复到 ok。 +// tier:unit(临时 profile,无网络)。 +const { setXdGatewayModels, getXdGatewayModels, markXdGatewayModelAccessUnknown, getXdGatewayModelAccessSnapshot, getActiveCatalog } = + await import('../../../desktop/src/main/maker-host/active-catalog.ts'); +const { tombstoneGuardOptions } = await import('../../../desktop/src/main/maker-host/model-route-guard-catalog.ts'); +const { createHostModelAccess } = await import('./model-access.ts'); +const { configureHostOwner } = await import('./claude-auth.mjs'); +const fs = await import('node:fs'); +const os = await import('node:os'); +const path = await import('node:path'); + +const ROUND = [{ id: 'open-model', agents: ['claude-code'] }, { id: 'paid-model', agents: ['claude-code'], availability: 'requires_payment' }]; +const refusedByGuard = () => tombstoneGuardOptions(getActiveCatalog()).isPaymentRequiredTombstone('xd', 'paid-model', 'claude-code'); + +async function heldCatalog(t, ownerId) { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-model-hold-')); + configureHostOwner({ userDataDir: profile, ownerId }); + t.after(() => { setXdGatewayModels([]); configureHostOwner({ userDataDir: profile, ownerId: null }); fs.rmSync(profile, { recursive: true, force: true }); }); + const rounds = []; + const fetched = []; + const priced = []; + const catalog = createProviderCatalog({ + // The price projection's input (main.ts applyPricedModels): the models of each list it is fed. + applyPricedModels: models => priced.push(models.map(model => model.id)), + readProviders: async () => [], + // As main.ts: the shared active catalog of this process. + applyModels: (models, options) => setXdGatewayModels(models, options), + markModelsUnknown: () => markXdGatewayModelAccessUnknown(), + readModels: () => getXdGatewayModels(), + fetchModels: async gateway => { fetched.push(gateway.credential); const next = rounds.shift(); if (!next) throw new Error('no round'); return next; }, + }); + const endpoint = 'https://gateway.example.test'; + let key = 'fixture-key-a'; + let writable = true; + let respond = () => ({ endpoint, apiKey: key }); + const access = createHostModelAccess({ ownerId, region: 'global', + readKey: () => key, writeKey: value => { if (!writable) return false; key = value; return true; }, + request: async () => respond(), + publish: status => catalog.noteCredentialStatus(status), + onKeyChanged: () => {}, + }); + t.after(() => access.close()); + assert.equal((await access.start()).state, 'ok'); + const read = (force = false) => catalog({ gateway: { endpoint, credential: key }, ownerId, force }); + rounds.push(ROUND); + await read(); + assert.deepEqual(getXdGatewayModels().map(model => model.id), ['open-model', 'paid-model']); + assert.equal(refusedByGuard(), true, 'the paid route is refused before'); + return { + access, rounds, fetched, priced, read, + fail: () => { writable = false; respond = () => ({ endpoint, apiKey: 'fixture-key-b' }); }, + disable: () => { respond = () => { throw Object.assign(new Error('model access disabled'), { code: 'MODEL_ACCESS_DISABLED', statusCode: 503 }); }; }, + recover: () => { writable = true; respond = () => ({ endpoint, apiKey: key }); }, + }; +} + +test('credentials failed: the models go, the paid route stays refused, no /models round until ok', async t => { + const h = await heldCatalog(t, 'model-hold-failed'); + h.fail(); + assert.equal((await h.access.sync.retry()).state, 'failed'); + assert.deepEqual(getXdGatewayModels(), []); + assert.equal(getXdGatewayModelAccessSnapshot().authoritative, false); + assert.equal(refusedByGuard(), true, 'a task refused before cannot pass the route guard through the failure'); + h.rounds.push(ROUND); + await h.read(true); + assert.equal(h.fetched.length, 1, 'no /models round while failed, not even forced'); + assert.deepEqual(getXdGatewayModels(), []); + assert.equal(refusedByGuard(), true); + + h.recover(); + assert.equal((await h.access.sync.retry()).state, 'ok'); + await h.read(); + assert.equal(h.fetched.length, 2, 'the read after ok runs the round'); + assert.deepEqual(getXdGatewayModels().map(model => model.id), ['open-model', 'paid-model']); + assert.equal(getXdGatewayModelAccessSnapshot().authoritative, true); +}); + +test('credentials disabled: the models and refusals go, no embedding fallback, no /models with the old key', async t => { + const h = await heldCatalog(t, 'model-hold-disabled'); + // Let the bundled embedding fallback show again before the status, so its suppression is the status's. + setXdGatewayModels([], { authoritative: false }); + h.disable(); + assert.equal((await h.access.sync.retry()).state, 'disabled'); + assert.deepEqual(getXdGatewayModels(), []); + assert.equal(refusedByGuard(), false, 'the refusals are cleared with the models'); + assert.equal(getActiveCatalog().providers.find(provider => provider.id === 'xd')?.embeddingModels, undefined, + 'no fallback to the bundled embedding models'); + h.rounds.push(ROUND); + await h.read(true); + await h.read(); + assert.equal(h.fetched.length, 1, 'the old key is not used for /models after disabled'); + assert.deepEqual(getXdGatewayModels(), []); +}); + +test('a /models round in flight when the credentials fail is dropped: it writes neither the list nor the prices', async t => { + const h = await heldCatalog(t, 'model-hold-in-flight'); + let land; + h.rounds.push(new Promise(resolve => { land = resolve; })); + const inFlight = h.read(true); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(h.fetched.length, 2, 'the forced round is in flight'); + h.fail(); + assert.equal((await h.access.sync.retry()).state, 'failed'); + const pricedBefore = h.priced.length; + land(ROUND); + await inFlight; + assert.deepEqual(getXdGatewayModels(), [], 'the late round shows no models'); + assert.deepEqual(h.priced.slice(pricedBefore), [], 'and feeds no prices'); + // Not cached either: after ok the next read runs its own round instead of serving the dropped one. + h.recover(); + assert.equal((await h.access.sync.retry()).state, 'ok'); + h.rounds.push(ROUND); + await h.read(); + assert.equal(h.fetched.length, 3); + assert.deepEqual(getXdGatewayModels().map(model => model.id), ['open-model', 'paid-model']); +}); + +// 测试价值 +// - 生产入口:providers.mjs 的 createProviderCatalog(/api/providers 的读取),main.ts 给它 isProfileHeld。 +// - 规则:并存方案 A 后续(审核方 2026-11-17 定)。闸门关着时,读取不能写桌面也在用的 profile 文件:一轮成功的 +// /models 会写价格快照和账本币种(cache/model-pricing.json、cache/ledger-currency.json),所以不发 /models, +// 只用已有的列表作答;闸门打开后照常刷新。 +// - 现有覆盖缺口:上面的用例只走凭据状态;之前闸门关着时 force 读取照样拉 /models 并写价格。 +// - 最小失败输入:闸门关着时一次 force 读取。tier:unit(假快照,没有 IO)。 +test('while a desktop uses the profile, reading the providers runs no /models round and feeds no prices', async () => { + const snapshot = fakeSnapshot(); + let held = false; + let fetched = 0; + const priced = []; + const list = createProviderCatalog({ ...snapshot, + readProviders: async () => [], + fetchModels: async () => { fetched++; return [{ id: `round-${fetched}` }]; }, + applyPricedModels: models => priced.push(models.map(model => model.id)), + isProfileHeld: () => held, + }); + const gateway = { endpoint: 'https://gateway.example.test', credential: 'key' }; + await list({ gateway, ownerId: 'owner' }); + assert.deepEqual([fetched, priced], [1, [['round-1']]]); + held = true; + await list({ gateway, ownerId: 'owner', force: true }); + assert.equal(fetched, 1, 'no /models round while held, not even forced'); + assert.deepEqual(priced, [['round-1']], 'no price written'); + assert.deepEqual(snapshot.state.models.map(model => model.id), ['round-1'], 'the read answers from the list it has'); + held = false; + await list({ gateway, ownerId: 'owner', force: true }); + assert.deepEqual([fetched, priced.at(-1)], [2, ['round-2']], 'released, the next read refreshes'); +}); diff --git a/apps/host/src/agent/providers.mjs b/apps/host/src/agent/providers.mjs index 0ed4a25668e..4e044efe99c 100644 --- a/apps/host/src/agent/providers.mjs +++ b/apps/host/src/agent/providers.mjs @@ -2,15 +2,40 @@ import { modelsWithoutStalePaymentUpsell } from '../../../desktop/src/main/model const CACHE_MS = 5 * 60_000; +/** + * The XD model list while the credentials are held, as the desktop's onStatusChange applies it + * (model-access/index.ts 433–441, applyGatewayModels → setXdGatewayModels): failed clears the list but + * keeps the last payment refusals, so a task that was refused cannot pass the route guard through the + * failure; disabled, unsupported and idle clear both and do not fall back to the bundled embedding list. + */ +const HELD_MODELS = Object.freeze({ + failed: Object.freeze({ authoritative: false, preservePaymentRequiredRoutes: true }), + cleared: Object.freeze({ authoritative: false, suppressEmbeddingFallback: true }), +}); + /** Refresh account facts only. The shared catalog owns provider projection. - * @param {{ readProviders: (connected: boolean) => Promise, fetchModels: (gateway: {endpoint: string, credential: string}) => Promise, applyModels: (models: any[], options: {authoritative: boolean, preservePaymentRequiredRoutes?: boolean, suppressEmbeddingFallback?: boolean}) => void, readModels: () => readonly any[], markModelsUnknown?: () => void, readOwner?: () => { dataOwnerId: string | null, generation: number, pending: boolean } }} deps + * @param {{ readProviders: (connected: boolean) => Promise, fetchModels: (gateway: {endpoint: string, credential: string}) => Promise, applyModels: (models: any[], options: {authoritative: boolean, preservePaymentRequiredRoutes?: boolean, suppressEmbeddingFallback?: boolean}) => void, readModels: () => readonly any[], markModelsUnknown?: () => void, readOwner?: () => { dataOwnerId: string | null, generation: number, pending: boolean }, applyPricedModels?: (models: any[], ownerId: string | undefined) => void, trackModelsSync?: (sync: Promise) => void, isProfileHeld?: () => boolean }} deps + * + * `applyPricedModels` receives the XD price projection's input where the desktop's applyGatewayModels + * replaces it (model-access/index.ts): a successful /models round and an account boundary (an empty + * list). `applyModels` also runs on every read between rounds and after a failed round, where the + * desktop keeps its last prices. `trackModelsSync` gets each round in flight, as the desktop's + * trackGatewayModelPricingSync does, so billing waits briefly for it. + * + * The returned function also takes the account's credential status (`noteCredentialStatus`, fed by + * the Host model access as the desktop's credential sync feeds model-access/index.ts onStatusChange); + * while it holds them, reads apply its empty list instead of the cached one and start no round. */ -export function createProviderCatalog({ readProviders, fetchModels, applyModels, readModels, markModelsUnknown, readOwner }) { +export function createProviderCatalog({ readProviders, fetchModels, applyModels, readModels, markModelsUnknown, readOwner, applyPricedModels, trackModelsSync, isProfileHeld }) { let cached = null; let flight = null; let activeIdentity = null; let activeKey = null; - return async function listProviders(options) { + // The account's credentials, as the desktop's onStatusChange reads them (see noteCredentialStatus): + // null while usable; 'failed' for a temporary sync failure of the same account (it keeps its local + // key and its last payment refusals); 'cleared' for disabled, unsupported or idle (no model access). + let credentialHold = null; + async function listProviders(options) { const initial = readOwner?.(); const owner = { dataOwnerId: options.ownerId ?? null, ownerGeneration: initial?.generation ?? options.ownerGeneration ?? 0 }; // In-memory identity of this connection, only ever compared for equality. @@ -31,6 +56,7 @@ export function createProviderCatalog({ readProviders, fetchModels, applyModels, if (activeIdentity !== null) { cached = null; applyModels([], { authoritative: false, suppressEmbeddingFallback: true }); + applyPricedModels?.([], owner.dataOwnerId ?? undefined); } activeIdentity = identity; } @@ -45,7 +71,11 @@ export function createProviderCatalog({ readProviders, fetchModels, applyModels, if (activeKey !== key) throw new Error('PROVIDER_CONNECTION_CHANGED'); }; let error; - if (options.gateway && (!cached || Date.now() - cached.at >= CACHE_MS || options.force)) { + // No /models round while the credentials are held: the desktop starts one only on ok. Nor while a + // desktop that opens this profile runs (coexistence plan A): a round writes the price snapshot and + // ledger currency files the desktop shares, so the read answers from the list already held. + if (options.gateway && !credentialHold && !isProfileHeld?.() + && (!cached || Date.now() - cached.at >= CACHE_MS || options.force)) { if (flight?.key !== key) { // As the desktop's runModelsSync: once a new request starts, the last list still shows but // no longer proves that the account lacks a model; only this round's success restores that. @@ -53,9 +83,20 @@ export function createProviderCatalog({ readProviders, fetchModels, applyModels, const pending = { key, promise: null }; pending.promise = Promise.resolve().then(() => fetchModels(options.gateway)).then(models => { check(); + // A round that ends after the credentials were held proves nothing for them: it is dropped, + // and the round after ok replaces it. + if (credentialHold) return; + if (isProfileHeld?.()) { + // The request crossed into a desktop hold. Keep the last list for reads but make the + // next read after release fetch again, even if this was a forced refresh of a fresh list. + if (cached) cached = { ...cached, at: -Infinity }; + return; + } cached = { at: Date.now(), models }; + applyPricedModels?.(models, owner.dataOwnerId ?? undefined); }).finally(() => { if (flight === pending) flight = null; }); flight = pending; + trackModelsSync?.(pending.promise); } try { await flight.promise; } catch { @@ -67,7 +108,9 @@ export function createProviderCatalog({ readProviders, fetchModels, applyModels, } } check(); - if (error) { + if (credentialHold) { + applyModels([], HELD_MODELS[credentialHold]); + } else if (error) { // As the desktop's failed runModelsSync: the current list stays for display without stale // payment advertising, non-authoritative, with its payment refusals. applyModels(modelsWithoutStalePaymentUpsell(readModels()), { authoritative: false, preservePaymentRequiredRoutes: true }); @@ -78,5 +121,32 @@ export function createProviderCatalog({ readProviders, fetchModels, applyModels, const providers = await readProviders(Boolean(options.gateway)); check(); return { ...owner, providers, providerOrder: providers.map(provider => provider.id), ...(error ? { error } : {}) }; + } + /** + * As the desktop's credential status handler (model-access/index.ts getSync onStatusChange): failed, + * disabled, unsupported and idle clear the XD models (HELD_MODELS) and replace the XD prices with an + * empty list, so a failed account's models and prices no longer show; ok brings them back through the + * next /models round. Until ok no round starts (the key may be dead: disabled and unsupported never + * come back without a new sync), and a round already in flight is dropped. The desktop starts the + * round on ok itself (scheduleModelsSync); the Host's catalog is read on demand, so ok marks the last + * round stale and the next read fetches. The desktop also clears its account tier here; the Host + * keeps none (it reads only the models of a /models response). + * @param {{ state: string }} status + */ + listProviders.noteCredentialStatus = status => { + if (status.state === 'ok') { + if (!credentialHold) return; + credentialHold = null; + if (cached) cached = { ...cached, at: -Infinity }; + return; + } + const hold = status.state === 'failed' ? 'failed' + : ['disabled', 'unsupported', 'idle'].includes(status.state) ? 'cleared' : null; + if (!hold) return; + credentialHold = hold; + cached = null; + applyModels([], HELD_MODELS[hold]); + applyPricedModels?.([], undefined); }; + return listProviders; } diff --git a/apps/host/src/agent/runtime-selection.ts b/apps/host/src/agent/runtime-selection.ts new file mode 100644 index 00000000000..857e2e4393f --- /dev/null +++ b/apps/host/src/agent/runtime-selection.ts @@ -0,0 +1,1072 @@ +import type { AgentKind, Effort, Maker, Session } from '@cindy/maker-core'; +import type { ProviderView } from '@cindy/model-providers'; +import { + applyPendingAgentSwitchIfIdle, + createPendingAgentSwitchRegistry, + performSessionAgentSwitch, + projectPendingAgentSwitchIntent, + type MakerSessionAgentSwitchHandlerDeps, +} from '../../../desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts'; +import { + createSwitchedSessionBootstrap, + createAgentSwitchBoundaryInsert, + createAgentSwitchDbApply, + createRememberThinkingIntent, + readAgentSwitchSessionRow, +} from '../../../desktop/src/main/maker-ipc/agentSwitchDepsCore.ts'; +import { + applyAgentSwitchResumeFallbackAtomicallyWithPorts, + applyAgentSwitchToSessionRowWithPorts, + findParkedEngineSession, + rebroadcastAgentSwitchBoundaryWith, +} from '../../../desktop/src/main/localDb/agentSwitchRows.ts'; +import { getActiveCatalog } from '../../../desktop/src/main/maker-host/active-catalog.js'; +import { listMessagesForAgentHandoff } from '../../../desktop/src/main/localDb/agentHandoffHistory.ts'; +import { + createHandleSetModel, + type InternalRuntimeSelectionOptions, + type SessionRuntimeSelectionPorts, +} from '../../../desktop/src/main/maker-ipc/sessionRuntimeSelectionApply.ts'; +import { + createCanApplyAutomaticRuntimeSelection, + createReadSessionRuntimeProfiles, + createRecoverRenamedSessionModelOnSend, + createSelectSameAgentModel, +} from '../../../desktop/src/main/maker-ipc/sessionRuntimeSelectionLanding.ts'; +import { + createApplyPiPendingSelection, + createPendingCredentialSwitchRouteReader, + createPendingCredentialSwitchService, +} from '../../../desktop/src/main/maker-ipc/pendingCredentialSwitchAssembly.ts'; +import { + clearPendingCredentialSwitchWith, + getPendingCredentialSwitchTargetWith, + registerPendingCredentialSwitchWith, + wakeSessionInputAfterCredentialSwitchWith, + type PendingCredentialSwitchAccessPorts, +} from '../../../desktop/src/main/maker-ipc/pendingCredentialSwitchAccess.ts'; +import { createColdPiRehydrationBinding } from '../../../desktop/src/main/maker-ipc/coldPiRehydrationBinding.ts'; +import { createBotPermissionSync } from '../../../desktop/src/main/maker-ipc/botPermissionSyncCore.ts'; +import { + commitSessionPermissionModeWith, + createSetSessionPermissionMode, + createSetSessionPlanMode, + persistAgentPlanModeChangeWith, +} from '../../../desktop/src/main/maker-ipc/sessionPermissionSettings.ts'; +import { createDeferredRestartQueueGate } from '../../../desktop/src/main/maker-ipc/deferredRestartQueueWiring.ts'; +import { + createRecoverRemoteRuntimeAxisPersistence, + createSetSessionEffort, + createSetSessionFastMode, + createSetSessionThinkingEnabled, + createStagePendingUserRuntimeAxis, + createUpdateSavedScheduledAxis, + type ReadUsableAgentDeviceProviders, +} from '../../../desktop/src/main/maker-ipc/sessionRuntimeAxisSettings.ts'; +import { createSubscriptionFastPolicies } from '../../../desktop/src/main/maker-host/subscriptionFastPolicyCore.ts'; +import { directoryGrantsForRuntime } from '../../../desktop/src/main/maker-ipc/extraDirsValidator.ts'; +import { setPendingCredentialSwitchReader } from '../../../desktop/src/main/maker-host/provider-route.ts'; +import type { AgentInputCoordinator } from '../../../desktop/src/main/maker-ipc/agent-input-coordinator.desktop.ts'; +import { + createSessionRuntimeCleanup, + createSessionRuntimeProjection, + createSessionRuntimeProjector, + createUpdateScheduledPreference, +} from '../../../desktop/src/main/maker-ipc/sessionRuntimeProjection.ts'; +import { setSessionRuntimeProjector, type SessionRuntimeProjector } from '../../../desktop/src/main/localDb/mapper.ts'; +import { setSessionRuntimeCleanup } from '../../../desktop/src/main/localDb/sessionRuntimeCleanup.ts'; +import { createResolvePendingRuntimeAxisPatch } from '../../../desktop/src/main/maker-ipc/pendingRuntimeAxisPatch.ts'; +import { assertModelRouteUsableWith } from '../../../desktop/src/main/maker-ipc/modelRouteAdmission.ts'; +import { + pinExclusiveSessionProviderWithProviders, + resolveLenientSessionRouteWithProviders, + verdictForModelRouteWithProviders, +} from '../../../desktop/src/main/maker-host/model-route-guard-catalog.ts'; +import { createLocalRouteAdmission } from '../../../desktop/src/main/maker-ipc/localRouteAdmission.ts'; +import { hostManagedLocalModelNotReady } from './pi-native-providers.ts'; +import { persistSessionFieldsWith } from '../../../desktop/src/main/localDb/sessionFieldPersistence.ts'; +import { readSessionSource } from '../../../desktop/src/main/localDb/sessionDispatchSnapshot.ts'; +import { + clearOwnerScopedSessionRuntimeSelection, + getSessionRuntimeControlSnapshot, + recordUserSessionRuntimeMutation, +} from '../../../desktop/src/main/maker-ipc/sessionRuntimeControl.ts'; +import { createSharedTaskSettingGuard } from '../../../desktop/src/main/maker-ipc/sharedTaskSetting.ts'; +import { withSendToSessionLock } from '../../../desktop/src/main/maker-ipc/sendToSessionLock.ts'; +import { withRehydrateCloseSuppressed } from '../../../desktop/src/main/maker-host/rehydrateCloseSuppression.ts'; +import { clearSessionProvider, getSessionProvider, hasSessionProvider, setSessionProvider } from '../../../desktop/src/main/maker-host/session-provider-store.ts'; +import { getActiveAppSession, isAppSessionBoundaryPending, setAppSessionCommitBoundaryHook } from '../../../desktop/src/main/appSessionState.ts'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; +import * as broadcastTap from '../../../desktop/src/main/device-link/broadcast-tap.js'; +import type { Logger } from '../../../desktop/src/main/logger.ts'; +import { recordHostContextSnapshot } from './context-usage.ts'; +import { rememberSessionLastLiveUsage } from '../../../desktop/src/main/maker-ipc/sessionLastLiveUsage.ts'; +import { createSessionContextWindowBudgetReconcile, type SessionContextWindowBudgetReconcilePorts } from '../../../desktop/src/main/maker-ipc/sessionContextWindowBudgetReconcile.js'; +import { appliedContextWindowBudgets, pendingSessionContextWindowBudgetReconciles } from '../../../desktop/src/main/maker-ipc/sessionContextWindowBudgetState.js'; +import { createSessionRuntimeFallback } from '../../../desktop/src/main/maker-ipc/sessionRuntimeFallback.ts'; +import { createSessionRuntimeFallbackSettingsFile } from '../../../desktop/src/main/maker-host/sessionRuntimeFallbackSettingsCore.ts'; +import { getUserDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { createPendingSessionRuntimeControlSettlement } from '../../../desktop/src/main/maker-ipc/pendingSessionRuntimeControlSettlement.ts'; +import { publishAgentEvent } from './turn-executor.mjs'; +import { createHostTurnSettlement } from './turn-settlement.ts'; +import { getCurrentDbClientSnapshot } from '../../../desktop/src/main/localDb/client/current.js'; +import { getSessionEffort, getSessionFastMode, setSessionEffort as restoreEffort, setSessionFastMode as restoreFastMode } from '../../../desktop/src/main/maker-host/session-effort-store.js'; +import { readRuntimePluginSettings } from '../../../desktop/src/main/maker-host/runtime-plugin-settings.js'; +import { RuntimePluginControlError } from '../../../desktop/src/main/cindy-brain/runtimeControl.js'; +import { closeRejectedRuntimeAndRestoreControlStores } from '../../../desktop/src/main/maker-ipc/runtimeSetModel.js'; +import { createSessionControlRuntimeWriter } from '../../../desktop/src/main/maker-ipc/sessionControlRuntimeWriter.js'; +import { shouldApplyExclusiveProviderRerouteLive } from '../../../desktop/src/main/maker-host/model-route-guard-catalog.js'; +import type { GhostModelRoute } from '../../../desktop/src/shared/ghost.js'; +import { explicitPorts } from './explicit-ports.ts'; + +interface HostPendingSwitchOptions { + signal?: AbortSignal; + scheduled?: boolean; + clientId?: string; + nextInputChars?: number; + expectedPiModel?: string; + assertPreparationCurrent?: () => void; +} + +/** What the Host's runtime selection reads from the rest of the Host (main.ts binds it). */ +export interface HostRuntimeSelectionDeps { + getMaker(): Maker; + /** The Maker once the agent runtime is ready, else null (the desktop's getMakerIfReady). */ + getMakerIfReady(): Maker | null; + /** Publishes a Host event (the event hub). */ + publish(event: Record): void; + /** Writes a message row of a task (the Host's message store). */ + createDbMessage(sessionId: string, body: Record): Promise; + /** The pending handoff summary registry (one for the Host process). */ + pendingHandoff: { + set(sessionId: string, handoff: string, expectedGeneration?: number): void; + readGeneration(sessionId: string): number; + peek?(sessionId: string): Promise; + }; + /** The providers the Host can route to, as its model settings list them. */ + listProviderViews(): Promise; + /** The Host's profile directory (the desktop's app.getPath('userData')). */ + userDataDir: string; + /** A route's configured window with a task's window budget (start-options). */ + resolveConfiguredContextWindow: SessionRuntimeSelectionPorts['resolveConfiguredContextWindow']; + readStoredSessionContextWindowBudget: SessionRuntimeSelectionPorts['readStoredSessionContextWindowBudget']; + /** Whether a budget change changes a route's effective window (start-options, the budget core). */ + contextWindowBudgetChangesEffectiveWindow: SessionContextWindowBudgetReconcilePorts['contextWindowBudgetChangesEffectiveWindow']; + /** The Codex proxy's credential injection state (codex-runtime.ts). */ + codexProxyAuthInjectionState(): ReturnType; + /** The current owner runtime's input queue: its rollover, coordinator and executor facts. */ + inputQueue: { + contextRecoveryRollover(): SessionRuntimeSelectionPorts['contextOverflowRolloverHolder']; + sessionDbAgentKind(sessionId: string): 'cc' | 'codex' | 'pi' | null; + recordRuntimeControlError(sessionId: string, data: { message: string; reason: string }): void; + isTurnRunning(sessionId: string): boolean; + canSettleTurnControls(): boolean; + isHeldForDesktop(): boolean; + profileRouteStartupSignal(): AbortSignal; + retryTurnSettlement(sessionId: string): void; + wakeSession: AgentInputCoordinator['wakeSession']; + refreshQueuedRoute: AgentInputCoordinator['refreshQueuedRoute']; + cancelUsageLimitWait(sessionId: string): void; + /** Forgets a task's working-directory recovery (turn-executor.mjs discardWorkingDirectoryRecovery). */ + discardWorkingDirectoryRecovery(sessionId: string): void; + /** Starting a task's runtime outside a turn, as a send starts it (turn-executor.mjs startPorts). */ + startPorts(): HostRuntimeStartPorts; + }; + /** A task's provider group binding and a group (the Host's provider group stores, main.ts). */ + readProviderGroupBinding: Parameters[0]['readProviderGroupBinding']; + readProviderGroup: Parameters[0]['readProviderGroup']; + log: Logger; +} + +/** + * The input queue members the runtime selection calls. input-queue.mjs has no types, so main.ts casts + * its api to HostRuntimeSelectionDeps['inputQueue']; this list must name every one of those members + * (the type below fails to compile otherwise), and input-queue.test.mjs checks a real queue has each. + */ +export const HOST_RUNTIME_SELECTION_QUEUE_MEMBERS = [ + 'contextRecoveryRollover', 'sessionDbAgentKind', 'isTurnRunning', 'wakeSession', 'refreshQueuedRoute', + 'cancelUsageLimitWait', 'discardWorkingDirectoryRecovery', 'startPorts', 'recordRuntimeControlError', 'canSettleTurnControls', 'retryTurnSettlement', 'isHeldForDesktop', + 'profileRouteStartupSignal', +] as const satisfies readonly (keyof HostRuntimeSelectionDeps['inputQueue'])[]; +type UnlistedQueueMembers = Exclude; +const everyQueueMemberListed: [UnlistedQueueMembers] extends [never] ? true : never = true; +void everyQueueMemberListed; +/** The runtime start functions startPorts() returns (HostRuntimeStartPorts), checked the same way. */ +export const HOST_RUNTIME_START_PORTS = [ + 'buildCreateOptsWithStderr', 'checkWorkDirExists', 'synthesizeOrcaVendorOptionsFromDb', 'readSessionExtraDirsFromDb', + 'readSessionWritableDirsFromDb', 'ensureRemoteReadyForSessionStart', 'bootstrapSession', 'broadcastSessionCreated', +] as const satisfies readonly (keyof HostRuntimeStartPorts)[]; +type UnlistedStartPorts = Exclude; +const everyStartPortListed: [UnlistedStartPorts] extends [never] ? true : never = true; +void everyStartPortListed; + +/** The executor's runtime start functions (turn-executor.mjs startPorts), as the desktop's send transaction has them. */ +export interface HostRuntimeStartPorts { + /** Returns the options with the stderr capture (the desktop's CreateOpts, whose remoteHostId is optional). */ + buildCreateOptsWithStderr(opts: O): O & { remoteHostId?: string | null }; + checkWorkDirExists(sessionId: string, workingDir: string | undefined, agentKind: string, remoteHostId: string | null | undefined): Promise; + synthesizeOrcaVendorOptionsFromDb(sessionId: string, opts: object): Promise; + readSessionExtraDirsFromDb(sessionId: string): Promise; + readSessionWritableDirsFromDb(sessionId: string): Promise; + ensureRemoteReadyForSessionStart(params: { createOpts?: unknown }): Promise; + bootstrapSession(opts: object, assertAccess?: () => void, nativeHistoryResume?: boolean, routeStartupSignal?: AbortSignal): Promise<{ session: Session }>; + broadcastSessionCreated(sessionId: string): void; +} + +type OwnerScope = ReturnType | null; + +/** + * A model or engine change of a task on the Host, with the desktop's steps: the shared pending + * switch registry (an intent until the next send), the desktop's engine switch + * (performSessionAgentSwitch) and model change (handleSetModel, sessionRuntimeSelectionApply.ts), and + * the send-time landing in the shared send transaction. Ports are bound here; each binding that is + * not the desktop's own function names why (design: checkpoint 3 port table). + */ +export function createHostRuntimeSelection(deps: HostRuntimeSelectionDeps) { + const maker = () => deps.getMaker(); + const pendingSwitches = createPendingAgentSwitchRegistry(); + const settlement: ReturnType = createHostTurnSettlement({ + open: () => deps.inputQueue.canSettleTurnControls(), + busy: id => deps.inputQueue.isTurnRunning(id) || maker().getSession(id)?.isTurnRunning() === true, + retry: id => deps.inputQueue.retryTurnSettlement(id), + credentials: () => pendingCredentialSwitchService, + applyControl: id => settleRuntimeControl(id, 'host-turn-settled'), + onControlError: (sessionId, error) => deps.log.warn('runtime settlement delivery failed', { sessionId, error }), + }); + // As sessionSpendBroadcaster.ts and localDb/ipc/sessions.ts bind them: the same broadcast tap. + const captureOwnerScope = (): OwnerScope => broadcastTap.captureDataOwnerBroadcastScope?.() ?? null; + const isOwnerScopeCurrent = (scope: OwnerScope) => + scope === null || broadcastTap.isDataOwnerBroadcastScopeCurrent?.(scope) !== false; + const broadcastSessionPatched: SessionRuntimeSelectionPorts['broadcastSessionPatched'] = (sessionId, patch, ownerScope) => { + if (ownerScope !== undefined && !isOwnerScopeCurrent(ownerScope ?? null)) return; + deps.publish({ type: 'session_changed', sessionId, patch }); + }; + // The provider service's member the shared bodies call (listProviders), over the Host's listing. + const providerService: SessionRuntimeSelectionPorts['getDesktopProviderService'] = + () => ({ listProviders: () => deps.listProviderViews() }); + const verdictForModelRoute = (agent: AgentKind, model: string, providerId: string | null) => + verdictForModelRouteWithProviders(() => deps.listProviderViews(), agent, model, providerId); + const assertModelRouteUsable: SessionRuntimeSelectionPorts['assertModelRouteUsable'] = + (agent, model, providerId, remoteHostId, unavailableCode) => assertModelRouteUsableWith(explicitPorts[0]>({ + // The Host refuses SSH tasks before any of this runs (send-preflight.ts). + listSshCodexProviders: async () => throwIpcError('UNSUPPORTED_CAPABILITY', 'Host does not yet support remote execution'), + verdictForModelRoute, + }), agent, model, providerId, remoteHostId, unavailableCode); + // register.ts bootstrapSession's start admission of a runtime (localRouteAdmission.ts), with the + // route check above and the Host's provider listing. + const admitLocalRoute = createLocalRouteAdmission(explicitPorts[0]>({ + // The Host has no managed local model runtime (Ollama, llama.cpp): it answers as the desktop's + // preflight answers when that runtime is not ready (pi-native-providers.ts). + ensureManagedOllamaReadyForSession: input => + hostManagedLocalModelNotReady({ providerId: input.providerId ?? '', remoteHostId: input.remoteHostId ?? null }), + getUserDataDir: () => deps.userDataDir, + assertModelRouteUsable, + pinExclusiveSessionProvider: (agent, model, providerId) => + pinExclusiveSessionProviderWithProviders(() => deps.listProviderViews(), agent, model, providerId), + })); + const { broadcastSessionRuntimeProjection: publishProjection, projectScheduledPreferences } = createSessionRuntimeProjection(explicitPorts[0]>({ broadcastSessionPatched })); + const broadcastSessionRuntimeProjection: typeof publishProjection = (id, baseline) => { + settlement.observeControl(id); + return publishProjection(id, baseline); + }; + // The task read projector (register.ts setSessionRuntimeProjector), which bindHostSessionRuntimeHooks + // installs: every task read shows what the task runs on, an accepted runtime override included. + const sessionRuntimeProjector = createSessionRuntimeProjector(explicitPorts[0]>({ + projectScheduledPreferences, + runtimePluginsSelected: id => !!readRuntimePluginSettings(id), + })); + // The cleanup at a task's archive or delete (register.ts setSessionRuntimeCleanup), which + // bindHostSessionRuntimeHooks installs: the task's runtime override and axes do not outlive it. + const sessionRuntimeCleanup = createSessionRuntimeCleanup(explicitPorts[0]>({ + // The desktop stops a start still in progress on another computer; the Host starts no task on + // another computer (send-preflight.ts refuses remote tasks), so none is ever waiting. + cancelPendingRemoteStart: () => {}, + discardWorkingDirectoryRecovery: sessionId => deps.inputQueue.discardWorkingDirectoryRecovery(sessionId), + broadcastSessionRuntimeProjection, + log: deps.log, + })); + const updateScheduledPreference = createUpdateScheduledPreference(explicitPorts[0]>({ broadcastSessionRuntimeProjection })); + const resolvePendingRuntimeAxisPatch = createResolvePendingRuntimeAxisPatch(explicitPorts[0]>({ + getDesktopProviderService: providerService, + log: deps.log, + })); + // As register.ts: the same-engine pick an intent lands as, through applySessionRuntimeSelection + // (handleSetModel without a revision), read at call time because handleSetModel is assigned below. + const applySessionRuntimeSelection: Parameters[0]['applySessionRuntimeSelection'] = + (sessionId, model, providerId, selection, options) => + handleSetModel(sessionId, model, providerId, undefined, selection, options); + const canApplyAutomaticRuntimeSelection = createCanApplyAutomaticRuntimeSelection(explicitPorts[0]>({ agentSwitchPending: pendingSwitches })); + const coordinatorRoute: Pick = { + refreshQueuedRoute: (...args) => deps.inputQueue.refreshQueuedRoute(...args), + }; + const coordinatorWake: Pick = { + wakeSession: (...args) => deps.inputQueue.wakeSession(...args), + }; + // The Maker members the pending credential switch reads; the owner runtime's Maker at each call. + const pendingSwitchMaker = { + listActiveSessions: () => maker().listActiveSessions(), + closeSession: (sessionId: string, reason?: 'runtime-refresh') => maker().closeSession(sessionId, reason), + }; + // As register.ts: the pending credential switch service, assembled before handleSetModel exists; + // its Pi transaction is read at call time (createApplyPiPendingSelection below). + let applyPiPendingSelection: ReturnType | null = null; + const pendingCredentialSwitchService = createPendingCredentialSwitchService(explicitPorts[0]>({ + settlementPermit: settlement.permit, + maker: pendingSwitchMaker, + isSessionInTurn: sessionId => isSessionInTurn(sessionId), + applyPiPendingSelection: (sessionId, target, resolved, isCurrent) => { + if (!applyPiPendingSelection) throw new Error('Pi model selection is not ready'); + return applyPiPendingSelection(sessionId, target, resolved, isCurrent); + }, + // The desktop broadcasts these to its windows; the Host sends them on its event stream. + broadcastToAllWindows: (channel, payload) => deps.publish({ type: 'plugin_push', channel, payload }), + inputCoordinator: { + wakeSession(id, reason) { + coordinatorWake.wakeSession(id, reason); + settlement.credentialApplied(id); + }, + }, + resolveLenientSessionRoute: (agent, model, providerId, opts) => + resolveLenientSessionRouteWithProviders(() => deps.listProviderViews(), agent, model, providerId, opts), + getSessionDbAgentKind: sessionId => deps.inputQueue.sessionDbAgentKind(sessionId) ?? settlement.deferredDbKind(sessionId), + getDesktopProviderService: providerService, + resolveConfiguredContextWindow: deps.resolveConfiguredContextWindow, + agentInputCoordinatorHolder: coordinatorRoute, + broadcastSessionPatched, + log: deps.log, + })); + // As register.ts: the proxy's synchronous routing reads a task's pending switch. + setPendingCredentialSwitchReader(createPendingCredentialSwitchRouteReader(pendingCredentialSwitchService)); + // The shared register / clear / wake / read of a pending switch (register.ts pendingCredentialSwitchPorts). + const accessPorts = (): PendingCredentialSwitchAccessPorts => explicitPorts({ + pendingCredentialSwitchHolder: pendingCredentialSwitchService, + agentInputCoordinatorHolder: coordinatorWake, + getSessionDbAgentKind: sessionId => deps.inputQueue.sessionDbAgentKind(sessionId), + getMaker: maker, + }); + // Host also considers a runtime with an unacknowledged permission change busy. The desktop + // reads its foreground turn activity tracker here (release table, section 7). + const isSessionInTurn = (sessionId: string) => maker().getSession(sessionId)?.isTurnRunning?.() === true; + // register.ts's binding (createColdPiRehydrationBinding), with the Host's runtime start functions + // (the ones its send transaction uses) in place of the desktop's. + const bindColdPiRehydration = (onRehydrated?: (session: Session) => void, assertAccess?: () => void, signal?: AbortSignal) => createColdPiRehydrationBinding(explicitPorts[0]>({ + maker: { getSession: sessionId => maker().getSession(sessionId) }, + buildCreateOptsWithStderr: opts => deps.inputQueue.startPorts().buildCreateOptsWithStderr(opts), + checkWorkDirExists: (sessionId, workingDir, agentKind, remoteHostId) => + deps.inputQueue.startPorts().checkWorkDirExists(sessionId, workingDir, agentKind, remoteHostId), + synthesizeOrcaVendorOptionsFromDb: (sessionId, opts) => + deps.inputQueue.startPorts().synthesizeOrcaVendorOptionsFromDb(sessionId, opts), + readSessionExtraDirsFromDb: sessionId => deps.inputQueue.startPorts().readSessionExtraDirsFromDb(sessionId), + bootstrapSession: opts => { + const work = deps.inputQueue.startPorts().bootstrapSession(opts, assertAccess, false, signal); + return onRehydrated ? work.then(result => { + onRehydrated(result.session); + return result; + }) : work; + }, + })); + const rehydrateColdPiRuntimeForWindowVerification = bindColdPiRehydration(); + + const agentSwitchDeps: MakerSessionAgentSwitchHandlerDeps = explicitPorts({ + // Ports for moving a task to or between other computers (release table, B5): the Host refuses a + // switch with a non-empty agentDeviceId at its entry and refuses tasks running elsewhere at send, + // so these are never reached; written out so a new one is a decision (explicit-ports.ts). + resolveProviderGroupTarget: undefined, + assertAgentDeviceRouteUsable: undefined, + describeAgentDevice: undefined, + resolveHandoffWindow: async ({ sessionId, agent, model, providerId, agentDeviceId }) => { + if (agentDeviceId) return null; + const budget = await deps.readStoredSessionContextWindowBudget(sessionId); + return deps.resolveConfiguredContextWindow(getActiveCatalog(), agent, providerId, model, budget, 'required'); + }, + // Host does not assemble companion lanes for runtime handoffs. + listCompanionSessionIds: undefined, + relocateNativeHistory: undefined, + readOwnerGeneration: () => getActiveAppSession().generation, + peekPendingHandoff: deps.pendingHandoff.peek ? sessionId => deps.pendingHandoff.peek!(sessionId) : undefined, + withSessionLock: withSendToSessionLock, + // A task whose Agent runs on another computer is refused on the Host (send-preflight.ts). + assertModelRouteUsable: async (agent, model, providerId) => assertModelRouteUsable(agent, model, providerId), + getSessionRow: readAgentSwitchSessionRow, + getLiveSession: sessionId => maker().getSession(sessionId), + closeSession: sessionId => maker().closeSession(sessionId, 'agent-switch'), + listMessagesForHandoff: (sessionId, after) => listMessagesForAgentHandoff(sessionId, null, after, 'replay'), + findParkedEngineSession: (sessionId, targetDbKind, fromAgentDeviceId) => + findParkedEngineSession(sessionId, targetDbKind, fromAgentDeviceId), + applyAgentSwitchToDb: createAgentSwitchDbApply( + (sessionId, patch) => applyAgentSwitchToSessionRowWithPorts(sessionId, patch, + { captureOwnerScope, isOwnerScopeCurrent, broadcastSessionPatched }), + deps.resolveConfiguredContextWindow, + ), + setSessionProvider, + insertBoundaryMessage: createAgentSwitchBoundaryInsert((sessionId, body) => deps.createDbMessage(sessionId, body)), + applyResumeFallbackAtomically: (sessionId, boundaryClientId, content) => + applyAgentSwitchResumeFallbackAtomicallyWithPorts(sessionId, boundaryClientId, content, { + captureOwnerScope, isOwnerScopeCurrent, broadcastSessionPatched, + // The desktop's rebroadcastAgentSwitchBoundary (localDb/ipc/messages.ts): the boundary row + // as stored, shown only to the owner of the moment of the write, as the Host's message event. + rebroadcastAgentSwitchBoundary: (sessionId, boundaryClientId, ownerScope) => + rebroadcastAgentSwitchBoundaryWith(explicitPorts[0]>({ + isOwnerBroadcastScopeCurrent: scope => isOwnerScopeCurrent(scope ?? null), + broadcastMessageRow: (rowSessionId, message) => + deps.publish({ type: 'message_created', sessionId: rowSessionId, messageId: message.id, message }), + }), sessionId, boundaryClientId, ownerScope ?? null), + log: deps.log, + }), + setPendingHandoff: (sessionId, handoff, expectedGeneration) => + deps.pendingHandoff.set(sessionId, handoff, expectedGeneration), + readPendingHandoffGeneration: sessionId => deps.pendingHandoff.readGeneration(sessionId), + // As register.ts: the committed switch's runtime from its row. A landing at the send skips it + // (the send transaction starts the runtime), but a switch back to an engine with a parked native + // session starts it at once to see whether the resume holds (sessionAgentSwitchHandler.ts). The + // start functions are the executor's (its send transaction's); no IM channel resolves vendor + // options on the Host, as on a desktop without IM. + bootstrapSwitchedSession: createSwitchedSessionBootstrap(explicitPorts[0]>({ + getActiveAppSession, + buildCreateOptsWithStderr: opts => deps.inputQueue.startPorts().buildCreateOptsWithStderr(opts), + resolveSwitchedSessionVendorOptions: () => undefined, + synthesizeOrcaVendorOptionsFromDb: (sessionId, opts) => deps.inputQueue.startPorts().synthesizeOrcaVendorOptionsFromDb(sessionId, opts), + readSessionExtraDirsFromDb: sessionId => deps.inputQueue.startPorts().readSessionExtraDirsFromDb(sessionId), + directoryGrantsForRuntime, + readSessionWritableDirsFromDb: sessionId => deps.inputQueue.startPorts().readSessionWritableDirsFromDb(sessionId), + ensureRemoteReadyForSessionStart: params => deps.inputQueue.startPorts().ensureRemoteReadyForSessionStart(params), + bootstrapSession: (opts, assertAccess, nativeHistoryResume) => + deps.inputQueue.startPorts().bootstrapSession(opts, assertAccess, nativeHistoryResume), + broadcastSessionCreated: sessionId => deps.inputQueue.startPorts().broadcastSessionCreated(sessionId), + log: deps.log, + })), + // As register.ts: an engine pick replaces a credential switch registered before it. + supersedePendingCredentialSwitch: sessionId => clearPendingCredentialSwitchWith(accessPorts(), sessionId), + // As register.ts: a committed switch's thinking choice goes to the preference mirror the next + // runtime start reads (start-options.ts getThinkingEnabledFromMemory), and to the clients' memory. + rememberThinkingIntent: createRememberThinkingIntent(explicitPorts[0]>({ + broadcastToAllWindows: (channel, payload) => deps.publish({ type: 'plugin_push', channel, payload }), + })), + withCloseSuppressed: withRehydrateCloseSuppressed, + pendingSwitches, + selectSameAgentModel: createSelectSameAgentModel(explicitPorts[0]>({ applySessionRuntimeSelection })), + onPendingSwitchChanged: (sessionId, intent) => { + if (intent) recordUserSessionRuntimeMutation(sessionId); + broadcastSessionPatched(sessionId, { agentSwitchIntent: intent }); + }, + // The desktop also marks an IM task as detached from its channel default; the Host has no IM. + onUserRouteSelectionLanded: async sessionId => { await updateScheduledPreference(sessionId, null); }, + log: deps.log, + }); + + // As the desktop: a review task's settings follow its source task. Taking over a local Agent's + // visible session is the desktop's local-agent (release table, gap A 6); the Host has no such runtime. + const assertReviewSettingsUnlocked: SessionRuntimeSelectionPorts['assertReviewSettingsUnlocked'] = async sessionId => { + if ((await readSessionSource(sessionId)) === 'review') { + throwIpcError('UNSUPPORTED_CAPABILITY', 'Review task settings are fixed to the source task'); + } + }; + // The Host's entries are not a shared task's guest (no Device Link invoke context). + const captureSharedTaskSettingGuard: SessionRuntimeSelectionPorts['captureSharedTaskSettingGuard'] = + sessionId => createSharedTaskSettingGuard(undefined, sessionId, { admitted: false }); + // register.ts's budget reconcile, applier and replay (sessionContextWindowBudgetReconcile.ts), on the + // Host's ports: the runtime mutation dependencies are register.ts's runtimeMutationDeps, member for + // member. The applier takes the task's send lock itself; inside the Host's /sessions/update, which + // already holds it, it re-enters (sendToSessionLock.ts). + const contextWindowBudgetReconcile = createSessionContextWindowBudgetReconcile(explicitPorts[0]>({ + getMakerIfReady: deps.getMakerIfReady, + readStoredSessionContextWindowBudget: deps.readStoredSessionContextWindowBudget, + contextWindowBudgetChangesEffectiveWindow: deps.contextWindowBudgetChangesEffectiveWindow, + getPendingCredentialSwitchTarget: sessionId => getPendingCredentialSwitchTargetWith(accessPorts(), sessionId), + registerPendingCredentialSwitchForSession: (sessionId, target) => + registerPendingCredentialSwitchWith(accessPorts(), sessionId, target), + runtimeMutationDeps: () => ({ + maker: maker(), isSessionInTurn, + registerPendingCredentialSwitch: (sessionId, target) => registerPendingCredentialSwitchWith(accessPorts(), sessionId, target), + clearPendingCredentialSwitch: (sessionId, opts) => clearPendingCredentialSwitchWith(accessPorts(), sessionId, opts), + wakeSessionInputQueue: sessionId => wakeSessionInputAfterCredentialSwitchWith(accessPorts(), sessionId), + getPendingCredentialSwitch: sessionId => getPendingCredentialSwitchTargetWith(accessPorts(), sessionId), + codexAuthInjection: deps.codexProxyAuthInjectionState(), logger: deps.log, + }), + log: deps.log, + })); + const persistSessionFields: SessionRuntimeSelectionPorts['persistSessionFields'] = (sessionId, patch) => persistSessionFieldsWith(explicitPorts[0]>({ + captureOwnerScope, isOwnerScopeCurrent, broadcastSessionPatched, + // The session settings' budget hook, as the desktop registers it (bootstrap-electron.ts). + applyContextWindowBudget: () => contextWindowBudgetReconcile.sessionContextWindowBudgetApplier, + }), sessionId, patch); + const ports = (): SessionRuntimeSelectionPorts => explicitPorts({ + maker: maker(), + agentSwitchPending: pendingSwitches, + broadcastSessionRuntimeProjection, + assertReviewSettingsUnlocked, + canApplyAutomaticRuntimeSelection, + // Tasks whose Agent runs on another computer are refused on the Host (send-preflight.ts). + applyAgentDeviceRuntimeSelection: async () => throwIpcError('UNSUPPORTED_CAPABILITY', 'Host does not yet support remote execution'), + assertModelRouteUsable, + agentSwitchDeps, + resolvePendingRuntimeAxisPatch, + rehydrateColdPiRuntimeForWindowVerification, + updateScheduledPreference, + // A teammate's task is refused on the Host; the reconciler only acts on teammate tasks. + reconcileBotModelRoute: { acceptTaskChoice: async () => {} }, + log: deps.log, + // The Host's entries do not run inside a Device Link invoke (isDeviceLinkInvoke() is false). + localModelWindowSwitchErrorCode: code => code, + wakeSessionInputAfterCredentialSwitch: sessionId => wakeSessionInputAfterCredentialSwitchWith(accessPorts(), sessionId), + pendingCredentialSwitchHolder: pendingCredentialSwitchService, + clearPendingCredentialSwitchForSession: (sessionId, opts) => clearPendingCredentialSwitchWith(accessPorts(), sessionId, opts), + isSessionInTurn, + contextOverflowRolloverHolder: deps.inputQueue.contextRecoveryRollover(), + getPendingCredentialSwitchTarget: sessionId => getPendingCredentialSwitchTargetWith(accessPorts(), sessionId), + captureSharedTaskSettingGuard, + registerPendingCredentialSwitchForSession: (sessionId, target) => + registerPendingCredentialSwitchWith(accessPorts(), sessionId, target), + agentInputCoordinatorHolder: coordinatorRoute, + getSessionDbAgentKind: sessionId => deps.inputQueue.sessionDbAgentKind(sessionId), + broadcastSessionPatched, + persistSessionFields, + // A Device Link set-model's write-back marker: the Host has no Device Link set-model. + markRemoteSettingPersistedInsideHandler: () => {}, + getDesktopProviderService: providerService, + resolveConfiguredContextWindow: deps.resolveConfiguredContextWindow, + readStoredSessionContextWindowBudget: deps.readStoredSessionContextWindowBudget, + listSshCodexProviders: async () => throwIpcError('UNSUPPORTED_CAPABILITY', 'Host does not yet support remote execution'), + getCodexProxyAuthInjectionState: () => deps.codexProxyAuthInjectionState(), + recordSessionContextSnapshot: recordHostContextSnapshot, + }); + const handleSetModel = createHandleSetModel(ports); + + function captureRouteOwner() { + const generation = getActiveAppSession().generation; + const db = getCurrentDbClientSnapshot(); + return () => db === getCurrentDbClientSnapshot() && generation === getActiveAppSession().generation; + } + + class HostRouteAdmissionError extends Error {} + + // The plugin route guard checks again after Pi has acknowledged a live change. + // A rejected selection at that point has changed the runtime but not the task row. + // Restore the snapshot while this selection still holds the task's send lock. + async function recoverRejectedRoute( + id: string, + sameOwner: () => boolean, + assertTurnAdmission: () => void, + run: (bindRehydrated: (session: Session) => void) => Promise, + ): Promise { + return withSendToSessionLock(id, async () => { + // If admission changed while waiting for the lock, the live instance can + // already belong to another owner. There is nothing from this call to undo. + assertTurnAdmission(); + const ownerMaker = maker(); + const initialInstance = ownerMaker.getSession(id); + let instance = initialInstance; + const hadProvider = hasSessionProvider(id); + const provider = getSessionProvider(id); + const effort = getSessionEffort(id); + const fastMode = getSessionFastMode(id); + const pendingCredential = pendingCredentialSwitchService.get(id); + const generation = getSessionRuntimeControlSnapshot(id).generation; + let originalModel = instance?.model; + try { + return await run(session => { + // Window verification can create an instance within this same mutation. + // Capture its exact identity at bootstrap, before the engine accepts a route. + if (!instance) { + instance = session; + originalModel = session.model; + } + }); + } catch (error) { + if (!(error instanceof HostRouteAdmissionError)) throw error; + const ownsInstance = () => !!instance && ownerMaker.getSession(id) === instance; + const modelChanged = ownsInstance() && instance?.model !== originalModel; + const routeChanged = hadProvider !== hasSessionProvider(id) || provider !== getSessionProvider(id); + const axesChanged = effort !== getSessionEffort(id) || fastMode !== getSessionFastMode(id); + const credentialCleared = !!pendingCredential && !pendingCredentialSwitchService.has(id); + const accountChanged = !sameOwner() || isAppSessionBoundaryPending(); + if (modelChanged || instance !== initialInstance || routeChanged || axesChanged || credentialCleared || accountChanged) { + try { + await closeRejectedRuntimeAndRestoreControlStores({ + closeRuntime: async () => { + const rejected = instance; + if (!rejected || !ownsInstance()) return; + await withRehydrateCloseSuppressed(id, async () => { + await ownerMaker.closeSessionIfCurrent(rejected, 'runtime-refresh'); + }); + }, + restoreControlStores() { + // The Host's app-session commit hook clears providers, axes and runtime + // control state. Its outgoing runtime disposal clears credential registrations. + const live = ownerMaker.getSession(id); + if (!sameOwner() || isAppSessionBoundaryPending() || (live && live !== instance) || + getSessionRuntimeControlSnapshot(id).generation !== generation) return; + if (hadProvider) setSessionProvider(id, provider); + else clearSessionProvider(id); + restoreEffort(id, effort); + restoreFastMode(id, fastMode); + if (pendingCredential && !pendingCredentialSwitchService.has(id)) + pendingCredentialSwitchService.register(id, pendingCredential); + }, + reportCloseError: closeError => deps.log.warn('rejected Host route could not retire its runtime', { + sessionId: id, error: closeError instanceof Error ? closeError.message : String(closeError), + }), + assertRuntimeClosed() { + if (ownsInstance()) throw new Error('Rejected runtime is still registered'); + }, + }); + } catch (cleanupError) { + // An allow-on-failure plugin must never deliver through a runtime + // whose rejected route is still installed. + deps.log.error('rejected Host route left its runtime registered', { sessionId: id, error: cleanupError }); + throw new RuntimePluginControlError('block', '', true, 'rejected-route-still-live'); + } + } + throw error; + } + }); + } + async function applyPendingPick( + sessionId: string, + options: HostPendingSwitchOptions | undefined, + assertAdmission?: () => void, + expectedRevision?: number, + ) { + const sameOwner = captureRouteOwner(); + const routeSignal = deps.inputQueue.profileRouteStartupSignal(); + let rejected: HostRouteAdmissionError | undefined; + const check = () => { + if (rejected) throw rejected; + try { + routeSignal.throwIfAborted(); + assertAdmission?.(); + if (!sameOwner() || isAppSessionBoundaryPending()) { + throwIpcError('PRECONDITION_FAILED', 'Host account changed; runtime selection was not changed'); + } + } + catch (error) { + rejected = new HostRouteAdmissionError(error instanceof Error ? error.message : String(error), { cause: error }); + throw rejected; + } + }; + const selectionDeps: MakerSessionAgentSwitchHandlerDeps = { + ...agentSwitchDeps, + selectSameAgentModel: createSelectSameAgentModel({ + applySessionRuntimeSelection: (id, model, provider, selection, selectionOptions) => + recoverRejectedRoute(id, sameOwner, check, bindRehydrated => { + const select = createHandleSetModel(() => ({ + ...ports(), rehydrateColdPiRuntimeForWindowVerification: bindColdPiRehydration(bindRehydrated, check, routeSignal), + })); + return select(id, model, provider, undefined, selection, { + ...selectionOptions, + assertSelectionCurrent: () => { check(); selectionOptions?.assertSelectionCurrent?.(); }, + beforeMutation: async () => { await selectionOptions?.beforeMutation?.(); check(); }, + }); + }), + }), + closeSession: (...args) => { check(); return agentSwitchDeps.closeSession(...args); }, + applyAgentSwitchToDb: (...args) => { check(); return agentSwitchDeps.applyAgentSwitchToDb(...args); }, + }; + try { + await applyPendingAgentSwitchIfIdle(selectionDeps, sessionId, { + signal: options?.signal, nextInputChars: options?.nextInputChars, expectedRevision, + }); + } catch (error) { + if (!(error instanceof RuntimePluginControlError)) { + if (rejected) throw rejected.cause; + routeSignal.throwIfAborted(); + } + throw error; + } + // The shared cross-engine path can retain a failed pick and return normally. + if (rejected) throw rejected.cause; + } + + const settleRuntimeControl = createPendingSessionRuntimeControlSettlement(explicitPorts[0]>({ + canSettle: settlement.allowedControl, + onSettlementWork: settlement.onControlWork, + applySessionRuntimeSelection: (id, model, provider, selection, options) => { + const generation = options.applyingPendingGeneration!; + const check = () => settlement.assertControl(id, generation); + check(); + return applySessionRuntimeSelection(id, model, provider, selection, { ...options, assertSelectionCurrent: check }); + }, + runtimeSelectionRequiresModelWindowConfirmation: result => + result.contextWindowConfirmationRequired !== undefined || result.contextTokensForConfirmation !== undefined, + broadcastSessionRuntimeProjection, + getSessionDbAgentKind: id => deps.inputQueue.sessionDbAgentKind(id) ?? settlement.deferredDbKind(id), + onTurnErrorEvent: (id, error) => deps.inputQueue.recordRuntimeControlError(id, error), + broadcastToAllWindows: (_channel, { sessionId, event }) => publishAgentEvent({ publish: deps.publish }, sessionId, event, {}), + log: deps.log, + })); + applyPiPendingSelection = createApplyPiPendingSelection(explicitPorts[0]>({ handleSetModel })); + const readSessionRuntimeProfiles = createReadSessionRuntimeProfiles(explicitPorts[0]>({ + maker: { getSessionMeta: sessionId => maker().getSessionMeta(sessionId), getSession: sessionId => maker().getSession(sessionId) }, + agentSwitchPending: pendingSwitches, + log: deps.log, + })); + const recoverRenamedSessionModelOnSend = createRecoverRenamedSessionModelOnSend(explicitPorts[0]>({ + agentSwitchPending: pendingSwitches, getDesktopProviderService: providerService, readSessionRuntimeProfiles, handleSetModel, + })); + // The desktop's effort, Fast mode and thinking handlers (register.ts SET_EFFORT, SET_FAST_MODE, + // SET_THINKING_ENABLED) and the closures they use, from sessionRuntimeAxisSettings.ts. The desktop + // checks the IPC sender first; the Host's entries authenticate their caller themselves. + // An Agent on another computer: refused as the Host refuses remote execution (send-preflight.ts). + const readUsableAgentDeviceProviders: ReadUsableAgentDeviceProviders = async () => + throwIpcError('UNSUPPORTED_CAPABILITY', 'Host does not yet support remote execution'); + // The Maker members the handlers call; the owner runtime's Maker at each call. + const axisMaker = { + getSession: (sessionId: string) => maker().getSession(sessionId), + closeSession: (...args: Parameters) => maker().closeSession(...args), + closeSessionIfCurrent: (...args: Parameters) => maker().closeSessionIfCurrent(...args), + }; + const { createSubscriptionFastPolicy } = createSubscriptionFastPolicies(explicitPorts[0]>({ + readProviderGroupBinding: deps.readProviderGroupBinding, + readProviderGroup: deps.readProviderGroup, + })); + const updateSavedScheduledAxis = createUpdateSavedScheduledAxis(explicitPorts[0]>({ + readUsableAgentDeviceProviders, updateScheduledPreference, getDesktopProviderService: providerService, + })); + const recoverRemoteRuntimeAxisPersistence = createRecoverRemoteRuntimeAxisPersistence(explicitPorts[0]>({ + maker: axisMaker, broadcastSessionRuntimeProjection, log: deps.log, + })); + const stagePendingUserRuntimeAxis = createStagePendingUserRuntimeAxis(explicitPorts[0]>({ + agentSwitchDeps, readUsableAgentDeviceProviders, agentSwitchPending: pendingSwitches, + getDesktopProviderService: providerService, persistSessionFields, + wakeSessionInputAfterCredentialSwitch: sessionId => wakeSessionInputAfterCredentialSwitchWith(accessPorts(), sessionId), + })); + const axisPorts = { + maker: axisMaker, updateScheduledPreference, agentSwitchPending: pendingSwitches, stagePendingUserRuntimeAxis, + updateSavedScheduledAxis, resolvePendingRuntimeAxisPatch, readSessionRuntimeProfiles, recoverRemoteRuntimeAxisPersistence, + assertReviewSettingsUnlocked, broadcastSessionRuntimeProjection, captureSharedTaskSettingGuard, + // Called only inside a Device Link invoke (remoteResponse); the Host's entries are never one. + markRemoteSettingPersistedInsideHandler: () => {}, + persistSessionFields, + getPendingCredentialSwitchHolder: () => pendingCredentialSwitchService, + log: deps.log, + }; + const setSessionEffort = createSetSessionEffort(axisPorts); + const setSessionFastMode = createSetSessionFastMode(explicitPorts[0]>({ + ...axisPorts, readUsableAgentDeviceProviders, getDesktopProviderService: providerService, createSubscriptionFastPolicy, + })); + const setSessionThinkingEnabled = createSetSessionThinkingEnabled(explicitPorts[0]>({ + maker: axisMaker, assertReviewSettingsUnlocked, captureSharedTaskSettingGuard, + })); + // A task's permission mode and Plan mode (sessionPermissionSettings.ts): the desktop's commit with the + // Host's Maker, review-task check, patch broadcast and session field write. The entries run outside the + // task's send lock, as the desktop's do: the permission queues come first, the send lock after. + const permissionMaker = { getSession: (sessionId: string) => maker().getSession(sessionId) }; + // botPermissionSync.ts's lane sync: a Bot's other lanes follow a permission save. + const botPermissionSync = createBotPermissionSync(explicitPorts[0]>({ + getMakerIfReady: () => deps.getMakerIfReady(), + broadcastSessionPatched: (sessionId, patch) => broadcastSessionPatched(sessionId, patch), + })); + const commitSessionPermissionMode = (sessionId: string, mode: string, remote = false, beforeMutation?: () => Promise) => + commitSessionPermissionModeWith(explicitPorts[0]>({ + maker: permissionMaker, assertReviewSettingsUnlocked, + broadcastSessionPatched: (patchedSessionId, patch) => broadcastSessionPatched(patchedSessionId, patch), + syncBotLinkedLanePermissions: botPermissionSync.syncBotLinkedLanePermissions, + // Called only inside a Device Link invoke (remote); the Host's entries are never one. + markRemoteSettingPersistedInsideHandler: () => {}, + log: deps.log, + }), sessionId, mode, remote, beforeMutation); + const setSessionPermissionMode = createSetSessionPermissionMode(explicitPorts[0]>({ commitSessionPermissionMode })); + const setSessionPlanMode = createSetSessionPlanMode(explicitPorts[0]>({ + maker: permissionMaker, assertReviewSettingsUnlocked, persistSessionFields, + markRemoteSettingPersistedInsideHandler: () => {}, log: deps.log, + })); + /** + * A runtime of a task closed (the Maker's session:closed, from the session's own close), finalized + * in the desktop's order: finalizeClosedSession keeps its last live usage for a cold Pi model + * change's window check (sessionLastLiveUsage.ts), read from the closed session as the desktop reads + * it; then cleanupClosedSessionRuntime settles its pending credential switch. + */ + const onSessionClosed = (sessionId: string, session: Pick) => { + rememberSessionLastLiveUsage(sessionId, session.getUsageSnapshot()); + if (deps.inputQueue.canSettleTurnControls()) pendingCredentialSwitchService.onSessionClosed(sessionId); + // As the desktop's cleanupClosedSessionRuntime (register.ts), after the pending switch: a closed + // runtime's budget bookkeeping goes, so its replacement starts from the stored budget. + appliedContextWindowBudgets.delete(sessionId); + pendingSessionContextWindowBudgetReconciles.delete(sessionId); + }; + + // The route change an interrupted-turn auto-resume tries first (sessionRuntimeFallback.ts), as + // register.ts assembles it: a task with the user's fallback setting on moves to another provider's + // candidate on its second attempt. The rebuild leases it marks are the auto-resume's own (read on an + // unexpected close on the desktop; the Host does not tear a resume down when a runtime closes). + const pendingSessionRuntimeFallbackRebuilds = new WeakMap(); + const fallbackSettings = createSessionRuntimeFallbackSettingsFile(() => getUserDataDir()); + const maybeApplySessionRuntimeFallback = createSessionRuntimeFallback(explicitPorts>[0]>({ + maker: { getSession: sessionId => maker().getSession(sessionId), closeSession: sessionId => maker().closeSession(sessionId) }, + readSessionRuntimeProfiles, canApplyAutomaticRuntimeSelection, + // Teammate tasks are refused at Host admission: no task has a Teammate route to fall back along. + readBotFallbackCandidate: async () => ({ isBot: false, candidate: null }), + // The Host does not bind model groups to its dispatched inputs. + readModelGroupFallbackCandidate: undefined, + // Agents on another computer are refused at Host admission (send-preflight.ts): every task runs here. + readSessionAgentDeviceId: async () => null, + readSessionRuntimeFallbackSettings: () => fallbackSettings.read(), + getDesktopProviderService: providerService as Parameters>[0]['getDesktopProviderService'], + pendingSessionRuntimeFallbackRebuilds, + applySessionRuntimeSelection, + getPendingCredentialSwitchTarget: sessionId => getPendingCredentialSwitchTargetWith(accessPorts(), sessionId), + clearPendingCredentialSwitchForSession: (sessionId, options) => clearPendingCredentialSwitchWith(accessPorts(), sessionId, options), + broadcastSessionRuntimeProjection, + agentSwitchDeps, + performSessionAgentSwitch, + // As register.ts (runtimeSelectionRequiresModelWindowConfirmation): a pick that needs the user to + // confirm a smaller context window is not applied automatically. + runtimeSelectionRequiresModelWindowConfirmation: result => + result.contextWindowConfirmationRequired !== undefined || result.contextTokensForConfirmation !== undefined, + log: deps.log, + })); + + return { + readSessionRuntimeProfiles, + assertReviewSettingsUnlocked, + async applyPluginRoute(id: string, route: GhostModelRoute, assertVerdict: () => void, assertTurn: () => void) { + const sameOwner = captureRouteOwner(); + const check = () => { + try { assertTurn(); } + catch (error) { throw new HostRouteAdmissionError('The originating Host turn changed', { cause: error }); } + if (!sameOwner() || isAppSessionBoundaryPending() || deps.inputQueue.isHeldForDesktop()) + throw new HostRouteAdmissionError('The Host cannot persist a route for this turn'); + assertVerdict(); + }; + check(); + if (route.agentDeviceId) throw new Error('Host does not support remote execution'); + const generation = getSessionRuntimeControlSnapshot(id).generation; + const profiles = await readSessionRuntimeProfiles(id); + if (!profiles) throw new Error('Task runtime unavailable'); + check(); + const effective = profiles.pendingMutation?.profile ?? profiles.effective; + const targetAgent = route.agentKind === 'cc' ? 'claude-code' : route.agentKind; + const selectHarness = targetAgent !== effective.agentKind || !!effective.agentDeviceId; + await recoverRejectedRoute(id, sameOwner, check, async bindRehydrated => { + const applyPluginModel = createHandleSetModel(() => ({ + ...ports(), rehydrateColdPiRuntimeForWindowVerification: bindColdPiRehydration(bindRehydrated), + })); + const write = createSessionControlRuntimeWriter(explicitPorts[0]>({ + agentSwitchPending: pendingSwitches, agentSwitchDeps, assertModelRouteUsable, getDesktopProviderService: providerService, + reconcileBotModelRoute: { acceptTaskChoice: async () => {} }, updateScheduledPreference, readSessionRuntimeProfiles, + readUsableAgentDeviceProviders, shouldApplyExclusiveProviderRerouteLive, + applySessionRuntimeSelection: async (sessionId, model, provider, selection, options) => { + const result = await applyPluginModel(sessionId, model, provider, undefined, selection, { ...options, assertSelectionCurrent: check }); + if (result.superseded && !sameOwner()) throw new HostRouteAdmissionError('Host account changed during plugin route selection'); + return result; + }, + runtimeSelectionRequiresModelWindowConfirmation: result => + result.contextWindowConfirmationRequired !== undefined || result.contextTokensForConfirmation !== undefined, + })); + const result = await write({ targetSessionId: id, expectedGeneration: generation, + beforeMutation: async () => check(), + patch: { ...(selectHarness ? { harness: targetAgent, agentDeviceId: null } : {}), + model: route.model, providerId: route.providerId, + ...(route.effort !== undefined ? { effort: route.effort as Effort } : {}), + ...(route.fastMode !== undefined ? { fastMode: route.fastMode } : {}), + }, + }); + if (!result.ok) throw new Error(result.errorCode); + }); + }, + pendingSwitches, + agentSwitchDeps, + /** The task read projector and the archive/delete cleanup (bindHostSessionRuntimeHooks installs them, as register.ts). */ + sessionRuntimeProjector, + sessionRuntimeCleanup, + /** The interrupted-turn auto-resume's route change (auto-resume.ts), and the rebuild leases it marks. */ + maybeApplySessionRuntimeFallback, + pendingSessionRuntimeFallbackRebuilds, + /** + * The start admission of a task runtime (register.ts bootstrapSession's admitLocalRoute): a start + * that is not a verified resume of the task's stored route is refused on a disabled, retired or + * payment-required route, or rerouted to an enabled copy; it changes `providerId` in place. + */ + admitLocalRoute, + /** The intent of a task as clients see it (session_changed, the task snapshot). */ + projectIntent: (sessionId: string) => projectPendingAgentSwitchIntent(pendingSwitches.get(sessionId)), + /** The desktop's set-effort (an effort change of a task, live or staged into a pending pick). */ + setEffort: (sessionId: unknown, effort: unknown) => setSessionEffort(sessionId, effort), + /** The desktop's set-fast-mode. */ + setFastMode: (sessionId: unknown, requestedSpeed: unknown) => setSessionFastMode(sessionId, requestedSpeed), + /** The desktop's set-thinking-enabled. */ + setThinkingEnabled: (sessionId: unknown, enabled: unknown) => setSessionThinkingEnabled(sessionId, enabled), + /** The desktop's set-permission-mode (its arguments checked, then the commit). */ + setPermissionMode: (sessionId: unknown, mode: unknown) => setSessionPermissionMode(sessionId, mode), + /** The desktop's set-plan-mode. */ + setPlanMode: (sessionId: unknown, enabled: unknown) => setSessionPlanMode(sessionId, enabled), + /** + * A Plan mode a runtime changed itself (its plan_mode_changed event), saved as the desktop's + * emitWiredSessionEvent saves it; the executor gives the owner it wired the runtime under and its + * session bindings. + */ + persistAgentPlanModeChange: ( + ports: Pick[0], 'ownerDb' | 'sessionBindings'>, + session: Parameters[1], + event: Parameters[2], + ) => persistAgentPlanModeChangeWith(explicitPorts[0]>({ ...ports, persistSessionFields, log: deps.log }), session, event), + /** A model change a client asks for: the desktop's set-model (source 'user'). */ + setModel(sessionId: string, model: unknown, providerId: unknown, revision: unknown, selection: unknown) { + deps.inputQueue.cancelUsageLimitWait(sessionId); + const options: InternalRuntimeSelectionOptions = { source: 'user' }; + return handleSetModel(sessionId, model, providerId, revision, selection, options); + }, + /** An engine change a client asks for: the desktop's switch-session-agent, under the task's lock. */ + switchAgent(params: Parameters[1]) { + // As the desktop's handler: the shared task guard of this entry (no Device Link guest on the + // Host), and the task's lock when the session id is a string. + const guard = createSharedTaskSettingGuard(undefined, String(params.sessionId), { admitted: false }); + const run = () => performSessionAgentSwitch(agentSwitchDeps, { ...params, assertSelectionCurrent: guard.admit }); + return typeof params.sessionId === 'string' && params.sessionId ? withSendToSessionLock(params.sessionId, run) : run(); + }, + /** + * The send transaction's landing of a picked model or engine, with the steps of the desktop's + * transaction binding (register.ts, createMakerSendTransaction's applyPendingAgentSwitch) in its + * order: the landing (with the send's signal and next input size), then, for a send + * that is not scheduled, the recovery of a renamed model, then the replay of a window budget rebuild + * still owed (under the send lock the transaction holds). The desktop's other steps are not on the + * Host yet (release table: the scheduled model scope, the Orca pending check, the provider group + * check). + */ + async applyPendingAgentSwitch(sessionId: string, options?: HostPendingSwitchOptions) { + // A context recovery can replay its interrupted input while a desktop owns the profile. + // Leave independent user selections and model-renaming writes for the next normal send. + const intent = pendingSwitches.get(sessionId); + const assertPreparation = options?.assertPreparationCurrent; + if (options && assertPreparation) { + assertPreparation(); + if (!intent || intent.targetAgentKind !== 'pi' || intent.model !== options.expectedPiModel || intent.targetAgentDeviceId) { + throwIpcError('PRECONDITION_FAILED', 'The selected Pi route is not ready'); + } + const originalRuntime = maker().getSession(sessionId); + await applyPendingPick(sessionId, options, assertPreparation, pendingSwitches.revision?.(sessionId)); + assertPreparation(); + if (pendingSwitches.get(sessionId)) { + throwIpcError('PRECONDITION_FAILED', 'The selected Pi route is not ready'); + } + // The shared switch normally retires the old engine. A non-owner pick + // can take a local landing path, so confirm the old runtime is gone. + const live = maker().getSession(sessionId); + if (intent.deviceLinkModelSelectionOrigin !== 'owner' && live && live === originalRuntime && live.agentKind !== 'pi') { + await maker().closeSessionIfCurrent(live, 'runtime-refresh'); + assertPreparation(); + } + return; + } + if (intent && !deps.inputQueue.isHeldForDesktop()) { + await applyPendingPick(sessionId, options); + } + if (!deps.inputQueue.isHeldForDesktop() && !options?.scheduled) await recoverRenamedSessionModelOnSend(sessionId); + await contextWindowBudgetReconcile.replayPendingSessionContextWindowBudgetUnderLock(sessionId); + }, + /** The session settings write with the budget hook (persistSessionFieldsWith): /sessions/update's budget. */ + persistSessionFields, + onTurnSettled: settlement.settle, + disposeTurnSettlements: settlement.dispose, + holdTurnSettlements: settlement.hold, + deferredTurnSettlements: settlement.pendingIds, + /** + * register.ts registerPendingCredentialSwitchForSession: a credential switch that waits for the task's + * turn to end. The Agent, system, IM card and scheduled model changes register through it on the + * desktop; on the Host they are not wired yet (release table, B2), so only tests call it today. + */ + registerPendingCredentialSwitch: ( + sessionId: string, + target: Parameters[2], + ) => registerPendingCredentialSwitchWith(accessPorts(), sessionId, target), + /** Whether a credential switch waits for this task's turn to end (the coordinator and idle-release gates). */ + hasPendingCredentialSwitch: (sessionId: string) => pendingCredentialSwitchService.has(sessionId), + clearIntent(sessionId: string) { + pendingSwitches.clear(sessionId); + }, + onSessionClosed, + /** Subscribes to a Maker's session-closed events (each session's own close); returns the unsubscribe. */ + /** register.ts's cold Pi window check (createColdPiRehydrationBinding); the context rollover binds it too. */ + rehydrateColdPiRuntimeForWindowVerification, + attachMaker(target: Pick): () => void { + return target.on(event => { + if (event.type === 'session:closed') onSessionClosed(event.sessionId, event.session); + }); + }, + }; +} + +type HostRuntimeSelection = ReturnType; + +/** + * The process-wide runtime selection slots the desktop fills at startup, filled for the Host: main.ts + * calls this once, after the runtime selection is built and before the first owner commit + * (configureHostOwner in ensureRuntime). Returns the undo, for tests. + * + * The task read projector (mapper.ts setSessionRuntimeProjector; the desktop's, register.ts): every task + * read (the task list, a single task) shows the route the task runs on, an accepted runtime override + * (an automatic fallback) included, with runtimeEffective, runtimePending and runtimeGeneration, as the + * route change pushes already do. + * + * The cleanup at a task's archive or delete (sessionRuntimeCleanup.ts setSessionRuntimeCleanup; the + * desktop's, register.ts): the status writers call cleanupSessionRuntimeForTerminalStatus, which runs it, + * so a task archived after an automatic fallback starts on its saved route once restored. + * + * The app session commit boundary (appSessionState.ts setAppSessionCommitBoundaryHook; the desktop's + * hook, bootstrap-electron.ts): when the owner changes, before the new owner is visible, every task's + * provider, runtime axes and runtime control state go (clearOwnerScopedSessionRuntimeSelection, which + * also advances the owner epoch). The desktop's other steps of that hook, on the Host: + * - local Agent confirmations (cancelLocalAgentConfirmations): the Host runs no local Agent service + * (release table row 29); its own tool confirmations close in disposeOwnerRuntime (main.ts), which + * every owner commit follows; + * - a Claude Code login in progress (cancelClaudeCliLogin): disposeOwnerRuntime closes the provider + * configuration, whose cancelLogins aborts it and kills the CLI child; every commit of another owner + * follows that dispose (ensureRuntime refuses an owner switch while an owner runtime is up); + * - task attention badges, remote desktop viewers, popped-out tab windows: window state, which the + * Host does not have. + */ +export function bindHostSessionRuntimeHooks(selection: { + sessionRuntimeProjector: SessionRuntimeProjector; + sessionRuntimeCleanup(sessionId: string): void; +}): () => void { + setAppSessionCommitBoundaryHook(() => clearOwnerScopedSessionRuntimeSelection()); + setSessionRuntimeProjector(selection.sessionRuntimeProjector); + setSessionRuntimeCleanup(selection.sessionRuntimeCleanup); + return () => { + setAppSessionCommitBoundaryHook(null); + setSessionRuntimeProjector(null); + setSessionRuntimeCleanup(null); + }; +} + +/** + * The input queue's hooks the runtime selection answers (main.ts passes them to createInputQueue; the + * input-queue tests use the same function): a pick lands at the send, the coordinator and idle-release + * gates of a pending credential switch (with the gateway restart, deferredRestartQueueWiring.ts), a + * turn's end landing that switch before the rest of the settle work, a runtime's own Plan change, and + * the start admission of a runtime. + * The selection is read at call time: main.ts creates it after the queue. + */ +export function hostRuntimeSelectionQueueHooks( + getSelection: () => Pick, + ports: { isSessionRestarting(sessionId: string): boolean; afterTurnSettled?(sessionId: string): void }, +) { + return { + applyPendingAgentSwitch: (sessionId: string, options?: HostPendingSwitchOptions) => + getSelection().applyPendingAgentSwitch(sessionId, options), + hasPendingCredentialSwitch: createDeferredRestartQueueGate(explicitPorts[0]>({ + hasPendingCredentialSwitchEntry: (sessionId: string) => getSelection().hasPendingCredentialSwitch(sessionId), + isSessionRestarting: (sessionId: string) => ports.isSessionRestarting(sessionId), + })), + hasPendingCredentialSwitchEntry: (sessionId: string) => getSelection().hasPendingCredentialSwitch(sessionId), + disposeTurnSettlements: () => getSelection().disposeTurnSettlements(), + holdTurnSettlements: (tasks: Iterable) => getSelection().holdTurnSettlements(tasks), + deferredTurnSettlements: () => getSelection().deferredTurnSettlements(), + onSessionSettled: (sessionId: string) => getSelection().onTurnSettled(sessionId), + afterTurnSettled: ports.afterTurnSettled, + persistAgentPlanModeChange: (...args: Parameters) => + getSelection().persistAgentPlanModeChange(...args), + // The interrupted-turn auto-resume's route change and its rebuild leases (auto-resume.ts). + maybeApplySessionRuntimeFallback: (...args: Parameters) => + getSelection().maybeApplySessionRuntimeFallback(...args), + pendingSessionRuntimeFallbackRebuilds: { + set: (session: Session, attemptToken: number) => getSelection().pendingSessionRuntimeFallbackRebuilds.set(session, attemptToken), + delete: (session: Session) => getSelection().pendingSessionRuntimeFallbackRebuilds.delete(session), + }, + /** Every runtime start of the executor takes this admission before its runtime is created. */ + admitLocalRoute: (...args: Parameters) => getSelection().admitLocalRoute(...args), + }; +} + diff --git a/apps/host/src/agent/runtime.ts b/apps/host/src/agent/runtime.ts index dc0d5b00ad3..2183a76c7ef 100644 --- a/apps/host/src/agent/runtime.ts +++ b/apps/host/src/agent/runtime.ts @@ -15,11 +15,16 @@ import { existsSync } from 'node:fs'; import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../../desktop/src/main/appSessionState.js'; import { ClaudeCodeAgent } from '@cindy/maker-core/agents/claude-code'; import { CodexAgent } from '@cindy/maker-core/agents/codex'; +import { hasProxyEnvConfig } from '@cindy/anthropic-compat-proxy'; import { Maker, PiAgent } from '@cindy/maker-core'; import type { AgentDeps, AgentKind, AuthAdapter, AuthAdapterOptions, AuthLoginOptions, AuthState, MakerDeps, MakerMemoryManager } from '@cindy/maker-core'; import { hasClaudeNativeLogin } from '../../../desktop/src/main/maker-host/claude-native-auth.ts'; +import { peekClaudeCliLoginStatus } from '../../../desktop/src/main/maker-host/claude-native-cli-status.js'; +import { ensureCliProxyBridge } from '../../../desktop/src/main/maker-host/cli-proxy-bridge.js'; +import { HOST_PROFILE_IN_USE_BY_DESKTOP } from './profile-coexistence.js'; import { createMakerLogger } from '../../../desktop/src/main/maker-host/logger-adapter.js'; +import { getHostOutboundPathSnapshotFor, resolveHostOutboundProxy } from '../outbound-proxy.ts'; import { readCodexLocalAuthState } from '../../../desktop/src/main/maker-host/codex-local-auth-state.js'; import { codexSharedAuthLinkUnavailableReason } from '../../../desktop/src/shared/codexAuthReason.js'; import { commitHostCodexDisconnectBoundary, readHostCodexInvalidation, readHostCodexRecoveryRequirement } from './codex-invalidation.js'; @@ -32,6 +37,7 @@ import { CLAUDE_ACCOUNT_RETIRED_REASON, subscriptionAccountKind } from '../../.. import { getActiveCatalog, getLocalCatalogOverridesSnapshot } from '../../../desktop/src/main/maker-host/active-catalog.js'; import { resolvePiCindyGatewayModelApi, resolvePiCindyGatewayModelSpec } from '../../../desktop/src/main/maker-host/piNativeProvidersCore.js'; import { createHostPiNativeProviders } from './pi-native-providers.js'; +import type { HostSharedGlobalSkills } from './shared-global-skills.js'; import { spawnHostPiSubagentRunner } from './pi-subagent-runner.js'; import { createHostPiPackages } from './pi-packages.js'; import { deriveAvailableModels, refreshCatalogDerivedModels, resolveModelContextProviderId, resolvePiGatewayDescriptorProviderId, resolvePiRuntimeModelDescriptor } from '../../../desktop/src/main/maker-host/catalog-to-descriptors.js'; @@ -66,6 +72,12 @@ import { createHostAutoReview } from './auto-review.js'; import { createClaudeAutoPermissionFallbackCoordinator, setClaudeAutoClassifierUnavailableListener } from '../../../desktop/src/main/maker-host/claude-auto-permission-fallback.js'; import { registerAgentProcess, registerCodexProcessRole } from '../../../desktop/src/main/process-monitor/codex-process-registry.js'; import { resolveSessionCcDebugFile, trackSessionCcDebugFile } from '../../../desktop/src/main/logger.js'; +import { readCodexCompactionState } from '../../../desktop/src/main/maker-host/compaction-settings-store.js'; +import { explicitPorts } from './explicit-ports.js'; +import { + PORTS_ONLY_CLAUDE_AND_CODEX_READ, PORTS_ONLY_CLAUDE_AND_PI_READ, PORTS_ONLY_CLAUDE_READS, PORTS_ONLY_CODEX_READS, + PORTS_ONLY_PI_READS, +} from './agent-deps-engines.js'; type HostProviderConfig = ReturnType; @@ -91,7 +103,7 @@ export interface HostAgentGraphOptions { piBinaryPath?: string; makerMemory?: MakerMemoryManager; mcpProviders?: NonNullable; - onSessionClose?: (id: string) => unknown; + onSessionClose?: (id: string, close: { reason: string; transient: boolean }) => unknown; isSessionInTurn?: (id: string) => boolean; /** The window's MCP duplicate choices for Claude (mcp-duplicate-choices.ts), as the desktop constructor. */ resolveLocalMcpDuplicateChoices?: AgentDeps['resolveLocalMcpDuplicateChoices']; @@ -100,6 +112,7 @@ export interface HostAgentGraphOptions { ensureProviderCatalog?: () => Promise; /** The plugin roster section from the Host plugin gateway. */ getGhostRosterPrompt?: AgentDeps['getGhostRosterPrompt']; + toolLifecycleControl?: AgentDeps['toolLifecycleControl']; /** Built-in and approved plugin Skills (Desktop listCindyManagedSkills). All three engines get * it as on the desktop; Codex only reads it to switch off its own copy when the computer that * runs the task supplies managed Skills. Codex's Skill projection itself is release row 25. */ @@ -110,11 +123,34 @@ export interface HostAgentGraphOptions { reportGatewayKeyRejected?: (key: string) => void; /** The account realm (main.ts), as the desktop's getActiveAuthRealm for the Codex token reader. */ readAuthRealm?: () => string | null; + /** Coexistence plan A: whether a desktop uses this profile. While it does, reading a login state + * writes nothing the desktop shares and starts no CLI: Codex skips its reconciliation with the + * system login, Claude answers from the CLI status already read. */ + isProfileHeld?: () => boolean; + /** Shared global Skill preparation (agent/shared-global-skills.ts, release table row 25): before + * each Claude CLI start (the desktop's Claude getAuthEnv) and before local Pi (piNativeProviders). */ + sharedGlobalSkills?: Pick | null; +} + +/** The desktop's Claude getAuthEnv opens with the shared Skill preparation; the Host adapter keeps its own body. */ +function withClaudeSkillPreparation(adapter: T, skills: HostAgentGraphOptions['sharedGlobalSkills']): T { + if (!skills) return adapter; + return { + ...adapter, + async getAuthEnv(options?: AuthAdapterOptions) { + options?.nativeSubscriptionAccount?.assertCurrent(); + await skills.beforeClaudeLaunch(); + return adapter.getAuthEnv(options); + }, + }; } export const LOGGER = createMakerLogger('maker'); const missingRouteResolver: HostProviderRouteResolver = async () => { throw new Error('Provider credential resolver is unavailable'); }; +const notHeld = () => false; +/** A login state that cannot be read while a desktop uses this profile: unknown, not "not signed in". */ +const LOGIN_STATE_UNKNOWN_WHILE_HELD: AuthState = Object.freeze({ authenticated: false, errorReason: HOST_PROFILE_IN_USE_BY_DESKTOP }); /** A credential adapter retained by an outgoing task cannot authenticate a new owner. */ function bindAuthOwner(adapter: T): T { @@ -141,7 +177,8 @@ function bindAuthOwner(adapter: T): T { * Subscription-only view: state comes from the shared verdict, and the lane * injects no credentials because the CLI authenticates itself. */ -export function createClaudeSubscriptionAuth(gateway: HostGateway | null | undefined, resolveRoute: HostProviderRouteResolver = missingRouteResolver, cli?: HostProviderConfig['claudeNative']) { +export function createClaudeSubscriptionAuth(gateway: HostGateway | null | undefined, resolveRoute: HostProviderRouteResolver = missingRouteResolver, cli?: HostProviderConfig['claudeNative'], + isProfileHeld: () => boolean = notHeld) { const owner = activeOwnerScopeKey(); const current = () => owner === activeOwnerScopeKey() && !isAppSessionBoundaryPending(); return bindAuthOwner({ @@ -150,7 +187,13 @@ export function createClaudeSubscriptionAuth(gateway: HostGateway | null | undef try { await resolveRoute(opts.providerId, 'claude-code'); return { authenticated: true, authSource: 'api-key', identity: opts.providerId }; } catch { return { authenticated: false, errorReason: 'not_connected' }; } } - if (cli && isNativeProviderAuthBound('anthropic')) await cli.readClaudeCliLoginStatus({ maxAgeMs: 30_000 }); + if (cli && isNativeProviderAuthBound('anthropic')) { + // While a desktop uses this profile no `claude auth status` runs: whether that CLI call + // refreshes and writes back its own login cannot be read from this repository, so it is + // treated as a write. The status read before answers; with none, the state is unknown. + if (!isProfileHeld()) await cli.readClaudeCliLoginStatus({ maxAgeMs: 30_000 }); + else if (!peekClaudeCliLoginStatus()) return { ...LOGIN_STATE_UNKNOWN_WHILE_HELD }; + } return hasClaudeNativeLogin() ? { authenticated: true, authSource: 'oauth', identity: 'Claude subscription' } : { authenticated: false, errorReason: 'not_connected' }; @@ -199,7 +242,7 @@ type GrokLoginView = Pick, - proxy: ClaudeProxyAuthView, cli?: HostProviderConfig['claudeNative'], grok?: GrokLoginView) { + proxy: ClaudeProxyAuthView, cli?: HostProviderConfig['claudeNative'], grok?: GrokLoginView, isProfileHeld: () => boolean = notHeld) { const gatewayKey = () => gateway?.credential || null; // A proxy secret travels only with the loopback address it was read with, so it can never be // sent to the upstream. While the proxy is not ready (getClaudeEndpoint falls back to the @@ -211,8 +254,11 @@ function createClaudeProxyAuth(gateway: HostGateway | null | undefined, native: // Explicit sources: the proxy routes the secret as the desktop routes the provider placeholder. const providerEnv = () => viaProxy(proxy.inboundSecret()) ?? { ANTHROPIC_API_KEY: CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY }; // The desktop's claudeNativeLoginState (CLAUDE_CLI_STATUS_MAX_AGE_MS = 60 s). + // While a desktop uses this profile, the status read before (as the subscription adapter above). const nativeLoginState = async (): Promise => { - const login = cli && isNativeProviderAuthBound('anthropic') ? await cli.readClaudeCliLoginStatus({ maxAgeMs: 60_000 }) : null; + const bound = Boolean(cli) && isNativeProviderAuthBound('anthropic'); + if (bound && isProfileHeld() && !peekClaudeCliLoginStatus()) return { ...LOGIN_STATE_UNKNOWN_WHILE_HELD }; + const login = !bound ? null : isProfileHeld() ? peekClaudeCliLoginStatus() : await cli!.readClaudeCliLoginStatus({ maxAgeMs: 60_000 }); return login?.loggedIn ? { authenticated: true, identity: 'Claude.ai · OAuth', authSource: 'oauth' } : { authenticated: false, errorReason: 'no_oauth' }; @@ -244,6 +290,7 @@ function createClaudeProxyAuth(gateway: HostGateway | null | undefined, native: if (opts?.credentialMode === 'oauth-bearer') return nativeLoginState(); if (gatewayKey()) return { authenticated: true }; const login = await nativeLoginState(); + if (login.errorReason === HOST_PROFILE_IN_USE_BY_DESKTOP) return login; if (!login.authenticated) return { authenticated: false, errorReason: 'no_key' }; return servesModel(opts?.model) ? login : { authenticated: true }; }, @@ -292,9 +339,9 @@ function createClaudeProxyAuth(gateway: HostGateway | null | undefined, native: /** Gateway-key lane: the key is injected as ANTHROPIC_API_KEY for the CLI spawn. */ export function createClaudeGatewayAuth(gateway: HostGateway | null | undefined, resolveRoute: HostProviderRouteResolver = missingRouteResolver, cli?: HostProviderConfig['claudeNative'], proxy?: ClaudeProxyAuthView | null, - grok?: GrokLoginView) { - const native = createClaudeSubscriptionAuth(null, resolveRoute, cli); - if (proxy) return createClaudeProxyAuth(gateway, native, proxy, cli, grok); + grok?: GrokLoginView, isProfileHeld: () => boolean = notHeld) { + const native = createClaudeSubscriptionAuth(null, resolveRoute, cli, isProfileHeld); + if (proxy) return createClaudeProxyAuth(gateway, native, proxy, cli, grok, isProfileHeld); return bindAuthOwner({ async getState(opts?: AuthAdapterOptions) { if (opts?.providerId === 'anthropic' || opts?.credentialMode === 'oauth-bearer') return native.getState(opts); @@ -339,8 +386,13 @@ export function createCodexLocalCliAuth(gateway: HostGateway | null | undefined, afterLogout?: () => Promise; /** The runtime's reconciliation with the system Codex login (codex-system-login.ts). */ systemLogin?: ReturnType; + /** Coexistence plan A: while a desktop uses this profile, reading the state does not reconcile. */ + isProfileHeld?: () => boolean; + /** Before a spawn on the default login: a rejection remembered while held (codex-runtime.ts). */ + assertNativeLoginUsable?: () => void; }) { const invalidate = native?.invalidate; + const isProfileHeld = native?.isProfileHeld ?? notHeld; if (!codexHome || !path.isAbsolute(codexHome)) throw new Error('Codex requires an explicit isolated profile'); const owner = activeOwnerScopeKey(); const current = () => owner === activeOwnerScopeKey() && !isAppSessionBoundaryPending(); @@ -406,7 +458,11 @@ export function createCodexLocalCliAuth(gateway: HostGateway | null | undefined, const invalidated = readHostCodexInvalidation(codexHome, systemAuthPath); if (invalidated) return { authenticated: false, errorReason: invalidated.reason, credentialScope: invalidated.credentialScope }; // Then the reconciliation with the system login, as readState does before reading auth.json. - await systemLogin.reconcile(); + // Not while a desktop uses this profile: it can relink codex-home/auth.json and bind the login + // to the account (codex-system-login.ts), both shared with that desktop. The state then comes + // from the files as they are. + const held = isProfileHeld(); + if (!held) await systemLogin.reconcile(); // The desktop's codexSharedAuthLinkUnavailableReason: the system login is signed in but // this runtime could not link to it, so the credential is unreachable, not absent. const sharedLinkReason = codexSharedAuthLinkUnavailableReason({ @@ -417,7 +473,7 @@ export function createCodexLocalCliAuth(gateway: HostGateway | null | undefined, const local = await readCodexLocalAuthState(codexHome); // The desktop reads the token through getAccessToken, which reconciles again before its // binding check, so a claim the first pass abandoned is made for the current session. - if (local.authenticated && local.authSource === 'oauth') await systemLogin.reconcile(); + if (!held && local.authenticated && local.authSource === 'oauth') await systemLogin.reconcile(); const native = isNativeProviderAuthBound('openai') ? local : null; if (native?.authenticated && native.authSource === 'oauth') { const scoped = { ...native, credentialScope: detectHostCodexCredentialScope(codexHome, systemAuthPath) }; @@ -512,8 +568,14 @@ export function createCodexLocalCliAuth(gateway: HostGateway | null | undefined, // gateway-key and provider-oauth spawns and independent accounts, which it never reconciles for. const reconcileForSpawn = opts?.credentialMode !== 'gateway-key' && opts?.credentialMode !== 'provider-oauth' && !(opts?.providerId && accounts?.isCodexAccountProvider(opts.providerId)); - if (reconcileForSpawn && !readHostCodexInvalidation(codexHome, systemAuthPath)) await systemLogin.reconcile(); - if (opts?.providerId === 'openai' || opts?.credentialMode === 'oauth-bearer') return { CODEX_HOME: codexHome }; + // Coexistence plan A: not while a desktop uses this profile (the reconciliation can relink + // auth.json and bind the login, both that desktop's too); the spawn uses the files as they are. + if (reconcileForSpawn && !isProfileHeld() && !readHostCodexInvalidation(codexHome, systemAuthPath)) await systemLogin.reconcile(); + if (opts?.providerId === 'openai' || opts?.credentialMode === 'oauth-bearer') { + // Coexistence plan A: a login the upstream rejected while held fails with that reason. + native?.assertNativeLoginUsable?.(); + return { CODEX_HOME: codexHome }; + } if (opts?.providerId && !['xd', 'cindy', 'openai'].includes(opts.providerId)) { // The proxy injects the selected provider's exact credential and headers. // Do not place a different provider's key into the shared native process. @@ -535,7 +597,9 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { afterLogin: () => options.codexRuntime!.authBoundary.afterLogin(), afterLogout: () => options.codexRuntime!.authBoundary.afterLogout(), systemLogin: options.codexRuntime!.systemLogin, - } : undefined); + isProfileHeld: options.isProfileHeld, + assertNativeLoginUsable: () => options.codexRuntime!.assertNativeLoginUsable(), + } : { isProfileHeld: options.isProfileHeld }); // Match Desktop: default-auth invalidation preserves separately selected subscription accounts. options.codexRuntime?.setLocalHostRetirement(async (reason, preserveSubscriptionAccounts) => { await codex?.forceDisposeLocalHostForAuthChange(reason, { preserveExternalAuth: true, preserveSubscriptionAccounts }); @@ -621,10 +685,15 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { // As the desktop's getPluginRegistry(): the owner's registry, read at each check. createDesktopInputShellGuardHooks(() => createPluginRegistry().isEnabled('computer'), LOGGER), ); - const agent = options.binaryPath ? new ClaudeCodeAgent({ - ...(options.resolveLocalMcpDuplicateChoices ? { resolveLocalMcpDuplicateChoices: options.resolveLocalMcpDuplicateChoices } : {}), + const agent = options.binaryPath ? new ClaudeCodeAgent(explicitPorts({ + ...PORTS_ONLY_CODEX_READS, + ...PORTS_ONLY_PI_READS, + resolveLocalMcpDuplicateChoices: options.resolveLocalMcpDuplicateChoices, claudeHooks, - auth: createClaudeGatewayAuth(options.gateway, options.resolveProviderRoute, config.claudeNative, options.claudeProxy, config.grok), + auth: withClaudeSkillPreparation( + createClaudeGatewayAuth(options.gateway, options.resolveProviderRoute, config.claudeNative, options.claudeProxy, config.grok, + options.isProfileHeld), + options.sharedGlobalSkills), runtimeConfig: runtimeConfigs.buildClaudeRuntimeConfig(engineEndpoint, claudeProxy ? () => claudeProxy.resolveAgentEndpoint() : undefined), binaryPath: options.binaryPath, logger: LOGGER, @@ -645,10 +714,16 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { }), // Skills the user disabled in Cindy, from the profile's activation preferences. getDisabledSkillPaths: readDisabledSkillPaths, - ...(options.getGhostRosterPrompt ? { getGhostRosterPrompt: options.getGhostRosterPrompt } : {}), - ...(options.getManagedSkills ? { getManagedSkills: options.getManagedSkills } : {}), + // The native recovery topic is only published by the Desktop assembly. + nativeRecoveryObserver: undefined, + getGhostRosterPrompt: options.getGhostRosterPrompt, + getManagedSkills: options.getManagedSkills, capabilityRouting: DESKTOP_CAPABILITY_ROUTING_POLICY, capabilityAdditions: availableModels('claude-code'), + // Plugin tool interception (will-tool-call / did-tool-result; the desktop passes + // ghostToolLifecycleControl): not connected on the Host yet (release table row 33, 8i, 甲). Unset, + // the agent adds no tool lifecycle hooks: every tool call goes ahead without asking a plugin. + toolLifecycleControl: options.toolLifecycleControl, // The turn change record the desktop keeps for Claude and Pi (turn-change-set/store.ts). turnChangeCapture: { beforeKnownFileWrite: captureKnownFileBefore, noteOpaqueWrite: noteOpaqueTurnChange }, // As the desktop: the process registry (read by the quit-time Codex reaper and, from M2, the @@ -658,14 +733,35 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { resolveCcDebugFile: resolveSessionCcDebugFile, trackCcDebugFile: trackSessionCcDebugFile, ...claudeModelResolvers, - ...(mcpProviders.length > 0 ? { mcpProviders } : {}), - ...(options.makerMemory ? { makerMemory: options.makerMemory } : {}), - }) : null; - const codex = options.codexBinaryPath - ? new CodexAgent({ + mcpProviders: mcpProviders.length > 0 ? mcpProviders : undefined, + makerMemory: options.makerMemory, + // Remote execution: send-preflight refuses tasks with a remote host or device (release table section 7, row 18). + getRemoteAgentFileOps: undefined, + remoteCcQueryFactory: undefined, + resolveRemoteClaudeRoute: undefined, + // Teammate tasks are refused here too; their session environment comes with them (section 4, M3). + resolveSessionEnvironment: undefined, + // SkillHub discovery isolation is M2 (section 4); without it the agent scans the native locations. + scanLocalCustomizations: undefined, + })) : null; + // main.ts builds the Codex runtime whenever it has the Codex binary; only test graphs build Codex + // without it, and then these ports stay unbound. + const codexRuntimePorts = options.codexRuntime?.deps ?? { + prepareCodexResumeSession: undefined, resolveCodexThreadStorage: undefined, recordCodexThreadLocation: undefined, + prepareCodexExtraSpawnConfig: undefined, disableCodexPluginRuntime: undefined, onCodexLocalModelsListed: undefined, + resolveCodexSubagentRoutingSignature: undefined, resolveCodexLocalAuthPolicy: undefined, isCodexAccountProvider: undefined, + isolateCodexAccountSessions: undefined, registerCodexTextOnlyPolicy: undefined, registerCodexSystemPromptForThread: undefined, + getCodexSubagentIdentity: undefined, armCodexHttpRecovery: undefined, registerCodexChildThreadForParent: undefined, + } satisfies { [K in keyof AgentDeps]?: undefined }; + // codexModelResolvers exists exactly when there is a Codex binary (above). + const codex = codexBinaryPath && codexModelResolvers + ? new CodexAgent(explicitPorts({ + ...PORTS_ONLY_CLAUDE_READS, + ...PORTS_ONLY_PI_READS, + ...PORTS_ONLY_CLAUDE_AND_PI_READ, auth: codexAuth, ...options.mcpRuntime.codexDeps, - ...options.codexRuntime?.deps, + ...codexRuntimePorts, // As the desktop (maker-host/index.ts): each read is fenced to the owner, the realm and // this agent's runtime, and takes the login's own credentials only from an authenticated // oauth-bearer state of this agent's auth adapter. @@ -677,14 +773,15 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { }), ...codexModelResolvers, getDisabledSkillPaths: readDisabledSkillPaths, - ...(options.getManagedSkills ? { getManagedSkills: options.getManagedSkills } : {}), + getManagedSkills: options.getManagedSkills, // A getter, as on the desktop: evaluated after the MCP bridge is prepared. get capabilityRouting() { return codexCapabilityRouting.capabilityRouting(); }, resolveCapabilityRouting: codexCapabilityRouting.resolveCapabilityRouting, capabilityAdditions: availableModels('codex'), - ...(options.getGhostRosterPrompt ? { getGhostRosterPrompt: options.getGhostRosterPrompt } : {}), + nativeRecoveryObserver: undefined, + getGhostRosterPrompt: options.getGhostRosterPrompt, runtimeConfig: runtimeConfigs.buildCodexRuntimeConfig(), - binaryPath: options.codexBinaryPath, + binaryPath: codexBinaryPath, logger: LOGGER, // As the desktop: Host exit reaps the tool trees below these app-servers (main.ts stop). registerLocalCodexAppServerProcess: ({ pid, role }) => registerCodexProcessRole(pid, role), @@ -703,8 +800,31 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { }, reviewAutoPermissionAction: autoReview.reviewAutoPermissionAction, mcpProviders, - ...(options.makerMemory ? { makerMemory: options.makerMemory } : {}), - }) + makerMemory: options.makerMemory, + // As the desktop (maker-host/index.ts): the user's Codex server-compaction choice, from the same + // file in this owner's profile; null keeps the native policy. + getCodexServerCompactionPreference: () => readCodexCompactionState().value.serverEnabled, + // As the desktop (maker-host/index.ts): the exit origin the Codex proxy recorded for this + // thread, then the outbound resolver's judgement for that origin (outbound-proxy.ts). Without + // a recorded origin (no Codex proxy, or Codex reaching the upstream directly) the generic + // error text stays (release table section 7). + getOutboundPathFact: ({ threadId }) => { + if (!threadId) return null; + const origin = options.codexRuntime?.proxy.getCodexThreadUpstreamOrigin(threadId); + return origin ? getHostOutboundPathSnapshotFor([origin]) : null; + }, + // Remote execution: send-preflight refuses tasks with a remote host or device (release table section 7, row 18). + getRemoteAgentFileOps: undefined, + getRemoteCodexTransport: undefined, + // Only for the local-agent service's host-tools-only sessions, which the Host does not have (row 29). + prepareCodexHostToolCatalog: undefined, + // Cindy Skill projection into the Codex home is not on the Host yet (row 25). + prepareCodexSkills: undefined, + // Teammate tasks are refused here too (section 4, M3). + resolveSessionEnvironment: undefined, + // SkillHub discovery isolation is M2 (section 4). + scanLocalCustomizations: undefined, + })) : null; // The desktop's learned Pi cache compatibility (pi-native-compat-overrides-store.ts), on this // profile; the Pi bridge writes the file and the runtime reads it back. @@ -714,13 +834,20 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { const piNativeProviders = createHostPiNativeProviders({ userDataDir: options.userDataDir, piBinaryPath: options.piBinaryPath ?? null, endpoint: engineEndpoint, claudeProxy, providerConfig: config, + ensureSharedGlobalSkills: () => options.sharedGlobalSkills?.ensureSharedGlobalSkills() ?? Promise.resolve(), }); // The desktop's main-process strings (i18n.desktop.ts) in the system language, as // plugins/authorization.ts does; the window's language choice does not reach the Host. const { t } = createMainI18n(() => [Intl.DateTimeFormat().resolvedOptions().locale]); const pi = options.piBinaryPath - ? new PiAgent({ + ? new PiAgent(explicitPorts({ + ...PORTS_ONLY_CLAUDE_READS, + ...PORTS_ONLY_CODEX_READS, + ...PORTS_ONLY_CLAUDE_AND_CODEX_READ, auth: piAuth, + getLocalPiHttpsProxy: async env => hasProxyEnvConfig(env) + ? undefined + : ensureCliProxyBridge(resolveHostOutboundProxy), ...options.mcpRuntime.piDeps, runtimeConfig: buildPiRuntimeConfig({ ripgrepPath: runtimeConfigs.getRipgrepBinaryPath(), @@ -761,7 +888,7 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { ); }, // Pi's loopback requests carry a per-session token the proxy checks (pi-host.ts). - ...(claudeProxy ? { registerPiProxySession: claudeProxy.registerPiProxySession } : {}), + registerPiProxySession: claudeProxy?.registerPiProxySession, // As the desktop (pi-host.ts): 执行端动态学习;SSH 独立存储,避免把本机线路结论带到远端。 resolvePiNativeCompatStorePath: remoteHostId => remoteHostId ? '$HOME/.xdt-server/v1/pi-agent-home/pi-native-compat-overrides.json' @@ -782,12 +909,15 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { ...piModelResolvers, getDisabledSkillPaths: readDisabledSkillPaths, capabilityAdditions: availableModels('pi'), - ...(options.getManagedSkills ? { getManagedSkills: options.getManagedSkills } : {}), + getManagedSkills: options.getManagedSkills, turnChangeCapture: { beforeKnownFileWrite: captureKnownFileBefore, noteOpaqueWrite: noteOpaqueTurnChange }, registerLocalAgentProcess: ({ pid, kind, role, sessionId }) => registerAgentProcess(pid, kind, role, sessionId), - ...(options.getGhostRosterPrompt ? { getGhostRosterPrompt: options.getGhostRosterPrompt } : {}), - ...(options.makerMemory ? { makerMemory: options.makerMemory } : {}), + // Plugin tool interception: not connected yet (as the Claude bag above; row 33, 8i, 甲). + toolLifecycleControl: options.toolLifecycleControl, + nativeRecoveryObserver: undefined, + getGhostRosterPrompt: options.getGhostRosterPrompt, + makerMemory: options.makerMemory, // As the desktop (pi-host.ts): the cloud-file startup hint and the extension dialog strings. formatPiStartupCloudFileHint: (file) => t('logic.errors.piStartupCloudFile').replace('{{path}}', () => file), getPiExtensionUiStrings: () => ({ @@ -808,7 +938,23 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { remove: t('settings.piPackages.success.remove'), }, }), - }) + // Remote execution: send-preflight refuses tasks with a remote host or device (release table section 7, row 18). The derived proxy token is for + // remote Pi sessions only; local ones take a fresh random token. + derivePiProxySessionToken: undefined, + getRemoteAgentFileOps: undefined, + getRemotePiAgentProxyEnv: undefined, + getRemotePiFileOps: undefined, + getRemotePiTransport: undefined, + remotePiSkipMcpBridge: undefined, + resolveRemotePiBinaryPath: undefined, + // Not bound on the desktop either (pi-host.ts takes it as an option, maker-host/index.ts passes none): + // approved project resources stay unavailable to Pi on both. + resolvePiProjectTrustInput: undefined, + // Teammate tasks are refused here too (section 4, M3). + resolveSessionEnvironment: undefined, + // SkillHub discovery isolation is M2 (section 4). + scanLocalCustomizations: undefined, + })) : null; const agents = { ...(agent ? { 'claude-code': agent } : {}), @@ -822,11 +968,13 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { const capabilitiesByAgent = Object.fromEntries( Object.entries(agents).map(([kind, instance]) => [kind, instance.capabilities]), ); - const maker = new Maker({ + const maker = new Maker(explicitPorts({ createOneShotUsageRecorder, agents, storage: options.storage, - lifecycleHooks: { + // Starting the agent on another computer of the account (B5): the Host refuses device tasks at entry. + startDeviceAgentSession: undefined, + lifecycleHooks: explicitPorts({ beforeTurn: applyProjectDirectoriesForTurn, prepareStartOptions: startOptions.prepareStartOptions, onBeforeStart: startOptions.onBeforeStart, @@ -837,17 +985,25 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { onCodexProductPromptDelivery: async ({ sessionId, historyHasProductPrompt }) => { await writeCodexHistoryHasProductPrompt(sessionId, historyHasProductPrompt); }, - onClose: async (id, closeOptions) => { - await startOptions.onClose(id, closeOptions); - options.claudeProxy?.closeSession(id); - try { await options.codexRuntime?.closeSession(id); } - finally { await options.onSessionClose?.(id); } - } }, + onClose: async (id, startOptionsSnapshot, close) => { + await startOptions.onClose(id, startOptionsSnapshot); + options.claudeProxy?.closeSession(id); + try { await options.codexRuntime?.closeSession(id); } + finally { await options.onSessionClose?.(id, close); } + }, + // The desktop marks Orca MCP hydration and Orca workers and settles a teammate's runtime snapshot + // here; the Host runs neither (send-preflight). + onStartSucceeded: undefined, + // Lets onClose skip what a transient rebuild must keep (temporary attachments, the worktree pool); + // the Host's onClose has none of those (it clears pricing and releases the lease, which the desktop + // also does on every close), and those rebuilds still close with the reason runtime-refresh. + isTransientCloseRequest: undefined, + }), logger: LOGGER, // Pi and Codex sessions read the tool-loop reviewer from Maker, as on the desktop. toolLoopReviewer: autoReview.toolLoopReviewer, - ...(options.makerMemory ? { makerMemory: options.makerMemory } : {}), - }); + makerMemory: options.makerMemory, + })); // As the desktop (register.ts): when the loopback proxy sees Claude's native Auto classifier // fail, the task stays on Auto and its later approvals go to the Cindy reviewer above. // The latest graph owns the process-wide listener. @@ -894,12 +1050,12 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { }, codexHistory: options.codexRuntime?.codexHistory ?? null, }; - // A model change's window gate (model-window-gate.ts): a route's configured window with the task's - // window budget, as the desktop's change of model reads it (register.ts resolveWindowForRoute). + // What a model change reads of windows (runtime-selection.ts, handleSetModel's ports): the desktop's + // model-context-settings functions, through start-options as the runtime's own start reads them. const modelWindow = { - resolveRouteWindow: (agentKind: string, modelId: string, providerId: string | null, budget: number | null, verification?: 'required') => - startOptions.resolveConfiguredContextWindow(getActiveCatalog(), agentKind as AgentKind, providerId, modelId, budget, verification), - readSessionBudget: (sessionId: string) => startOptions.readStoredSessionContextWindowBudget(sessionId), + resolveConfiguredContextWindow: startOptions.resolveConfiguredContextWindow, + readStoredSessionContextWindowBudget: startOptions.readStoredSessionContextWindowBudget, + contextWindowBudgetChangesEffectiveWindow: startOptions.contextWindowBudgetChangesEffectiveWindow, }; return { maker, agent, codex, pi, gatewayRestart, capabilitiesByAgent, instances: agents, autoReview, piPackages, contextRecovery, modelWindow, diff --git a/apps/host/src/agent/send-preflight.ts b/apps/host/src/agent/send-preflight.ts index fc9c77ad722..c49691d09fe 100644 --- a/apps/host/src/agent/send-preflight.ts +++ b/apps/host/src/agent/send-preflight.ts @@ -22,6 +22,24 @@ export function assertHostTaskExecutionSupported(facts: HostTaskExecutionFacts): if (unsupported) throwIpcError('UNSUPPORTED_CAPABILITY', `Host does not yet support ${unsupported}`); } +/** + * The provider group refusal of a task start (moved verbatim out of main.ts, where the input queue's + * assertProviderExecutionSupported was bound): the Host has no provider group assignment service, so a + * task bound to a group, or routed to a group provider, is refused before its runtime starts. The send + * path (turn-executor.mjs readExecutionSession) and the Device Link create entry take the same check. + */ +export function createHostProviderExecutionCheck({ hostProviderBindings, hostProviderGroups }: { + hostProviderBindings: { readProviderGroupBinding(sessionId: string): unknown }; + hostProviderGroups: { readProviderGroup(providerId: string): unknown }; +}) { + return (id: string, providerId?: string | null) => { + if (hostProviderBindings.readProviderGroupBinding(id) + || (providerId && hostProviderGroups.readProviderGroup(providerId))) { + throw new Error('[UNSUPPORTED_CAPABILITY] Host does not yet support provider groups'); + } + }; +} + /** Preserve Host's existing text/mention/local-file input. Desktop cache and * transfer references need the shared materializer before they can reach core; * never pass them as a local file or quietly drop an attachment. */ diff --git a/apps/host/src/agent/session-activity.ts b/apps/host/src/agent/session-activity.ts new file mode 100644 index 00000000000..bc64c75eab3 --- /dev/null +++ b/apps/host/src/agent/session-activity.ts @@ -0,0 +1,34 @@ +import { writeSessionListActivity } from '../../../desktop/src/main/localDb/sessionActivityWrite.js'; +import { isEndedWriteSuppressed } from '../../../desktop/src/main/localDb/sessionActiveTurn.js'; +import type { CurrentDbClientSnapshot } from '../../../desktop/src/main/localDb/client/current.js'; +import { createLogger } from '../../../desktop/src/main/logger.js'; + +const log = createLogger('localDb/sessions'); + +/** + * The task list's activity time, as the desktop's touchSessionActivityInDb (localDb/ipc/sessions.ts): the + * same write (localDb/sessionActivityWrite.ts, only forward), skipped while ended writes are suppressed, + * owned by the account that started it, and the same patch to the clients ({ lastActivityAt, updatedAt }, + * as broadcastSessionPatched sends it). A failure is logged and swallowed, as there. + */ +export function createHostSessionActivity(deps: { + getOwner: () => CurrentDbClientSnapshot | null; + publish: (event: { type: 'session_changed'; sessionId: string; patch: Record }) => void; +}): (sessionId: string, atMs?: number, skipActiveGoal?: boolean) => Promise { + return async (id, atMs = Date.now(), skipActiveGoal = false) => { + if (isEndedWriteSuppressed()) return; + const owner = deps.getOwner(); + if (!owner) return; + try { + const updated = await writeSessionListActivity(owner.client, id, atMs, skipActiveGoal); + if (updated[0]?.lastActivityAt != null && deps.getOwner() === owner) { + deps.publish({ type: 'session_changed', sessionId: id, patch: { + lastActivityAt: new Date(updated[0].lastActivityAt).toISOString(), + updatedAt: new Date(updated[0].updatedAt).toISOString(), + } }); + } + } catch (error) { + log.warn('Failed to persist session list activity', { sessionId: id, error: String(error) }); + } + }; +} diff --git a/apps/host/src/agent/session-move.ts b/apps/host/src/agent/session-move.ts new file mode 100644 index 00000000000..0361f8bab57 --- /dev/null +++ b/apps/host/src/agent/session-move.ts @@ -0,0 +1,119 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import type { LiveCcSessionBridge } from '../../../desktop/src/main/maker-host/claude-transcript-relocation.ts'; +import type { SessionWorktreeBindingLookup } from '../../../desktop/src/main/localDb/ipc/sessionWorkingDirMove.ts'; +import { withRehydrateCloseSuppressed } from '../../../desktop/src/main/maker-host/rehydrateCloseSuppression.ts'; + +/** + * The Host's ports for the desktop's working-directory move (sessionWorkingDirMove.ts), which + * /sessions/update runs (session-update.ts). + */ + +/** The desktop's worktree registry (worktree/worktreeStore.ts): electron-store `worktrees` in the profile root. */ +const WORKTREE_REGISTRY_FILE = 'worktrees.json'; + +const isPlainObject = (value: unknown): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value); + +/** + * A task's live worktree binding, read from the desktop's registry; the Host only reads it (it creates + * no worktrees). The file is `{ "worktrees": { "": { "path": … } } }`, plain JSON written + * atomically (electron-store over conf). The desktop answers `worktreeStore.get(id)?.path ?? null` + * (bootstrap-electron.ts) and reads the file on every call, as this does. + * - No file: no binding (the desktop's store starts from `{ worktrees: {} }`). + * - A file the desktop cannot read (unreadable, not JSON, not the registry's shape) fails the move: the + * desktop's store throws there too, and "no binding" would let a worktree task move out of it. + */ +export function createHostWorktreeBindingLookup(profileDir: string): SessionWorktreeBindingLookup { + const file = path.join(profileDir, WORKTREE_REGISTRY_FILE); + return sessionId => { + if (!sessionId) return null; + let text: string; + try { + text = fs.readFileSync(file, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw error; + } + const registry: unknown = JSON.parse(text); + if (!isPlainObject(registry)) throw new Error('invalid worktree registry'); + if (!Object.hasOwn(registry, 'worktrees')) return null; + const worktrees = registry.worktrees; + if (!isPlainObject(worktrees)) throw new Error('invalid worktree registry'); + if (!Object.hasOwn(worktrees, sessionId)) return null; + const entry = worktrees[sessionId]; + if (!isPlainObject(entry) || typeof entry.path !== 'string' || entry.path.length === 0) { + throw new Error('invalid worktree registry entry'); + } + return entry.path; + }; +} + +/** The desktop's local-db:recent-workdirs:changed (sessions.ts broadcastRecentWorkdirsChanged), a channel its renderer listens on. */ +export const RECENT_WORKDIRS_CHANGED_CHANNEL = 'local-db:recent-workdirs:changed'; + +/** + * The desktop's recent projects push, with its `{ path }`: the Host's clients take it from the event + * stream (apps/web/shim.js; the desktop window in client mode, host-delegation.ts), as the desktop's own + * windows take it from IPC. A move and a send both announce through it. + */ +export function createRecentWorkdirsChangedPush(publish: (event: Record) => void): (path: string) => void { + return path => publish({ type: 'plugin_push', channel: RECENT_WORKDIRS_CHANGED_CHANNEL, payload: { path } }); +} + +interface MoveMaker { + getSession(sessionId: string): { isTurnRunning(): boolean } | null | undefined; + listActiveSessions(): readonly { id: string; sdkSessionId?: string | null }[]; + closeSession(sessionId: string): Promise; +} + +/** + * The Host's bindings of the move's ports, as the desktop's composition root binds them + * (bootstrap-electron.ts closeIdleSessionForMove and lookupSessionWorktreeBinding, register.ts + * setLiveCcSessionBridge, sessions.ts broadcastRecentWorkdirsChanged). + */ +export function createHostSessionMovePorts(deps: { + /** The profile root, where the desktop keeps worktrees.json. */ + profileDir: string; + getMakerIfReady(): MoveMaker | null; + /** The executor's turn, which stays running while its rows settle after the terminal. */ + isTurnRunning(sessionId: string): boolean; + /** The executor's close of an idle runtime (turn-executor.mjs closeRuntime). */ + closeRuntime(sessionId: string): Promise; + publish(event: Record): void; +}): { + move: { + lookupSessionWorktreeBinding: SessionWorktreeBindingLookup; + closeIdleSessionForMove(sessionId: string): Promise; + broadcastRecentWorkdirsChanged(path: string): void; + }; + liveCcSessionBridge: LiveCcSessionBridge; +} { + return { + move: { + lookupSessionWorktreeBinding: createHostWorktreeBindingLookup(deps.profileDir), + // As bootstrap-electron.ts: a runtime in a turn is not moved; an idle one is closed with its rebuild + // suppressed. The Host also counts a turn whose rows are still settling (the desktop reads the + // runtime only): closing then could race those writes. The idle runtime closes through the + // executor, which lets go of the instance (interactions, binding, environment notes) first. + closeIdleSessionForMove: async sessionId => { + const maker = deps.getMakerIfReady(); + if (deps.isTurnRunning(sessionId) || maker?.getSession(sessionId)?.isTurnRunning()) return false; + if (maker) await withRehydrateCloseSuppressed(sessionId, () => deps.closeRuntime(sessionId)); + return true; + }, + broadcastRecentWorkdirsChanged: createRecentWorkdirsChangedPush(deps.publish), + }, + // As register.ts setLiveCcSessionBridge: a Claude task's resume id in memory, and Maker closing its + // runtime so the old directory's CLI stops writing the transcript being copied. The desktop does not + // check for a running turn here; Maker's close settles an unfinished turn with its terminal before it + // drops its listeners, so this goes to Maker itself and the executor still sees that terminal. + liveCcSessionBridge: { + resolveSdkSessionId: sessionId => + deps.getMakerIfReady()?.listActiveSessions().find(session => session.id === sessionId)?.sdkSessionId ?? null, + closeSession: async sessionId => { + await deps.getMakerIfReady()?.closeSession(sessionId); + }, + }, + }; +} diff --git a/apps/host/src/agent/session-route-lock.mjs b/apps/host/src/agent/session-route-lock.mjs index 111df64e687..fea0c53e87f 100644 --- a/apps/host/src/agent/session-route-lock.mjs +++ b/apps/host/src/agent/session-route-lock.mjs @@ -4,9 +4,9 @@ import { withSendToSessionLock } from '../../../desktop/src/main/maker-ipc/sendT * The Host entries that change a task's runtime or route run under the task's send lock, as their * desktop counterparts do (register.ts: model, effort and runtime changes, discarding an unsent * task, closing a task, restoring a plugin page's task). A send of the same task, and context - * recovery, cannot interleave with them. Switching engines only records an intent, applied by - * `updateSession` when the next input is queued; reading that intent and stopping a turn do not - * take the lock (a stop must interrupt whoever holds it). + * recovery, cannot interleave with them. Switching engines only records an intent, applied when the + * next input is queued (the send transaction's applyPendingAgentSwitch); reading that intent and + * stopping a turn do not take the lock (a stop must interrupt whoever holds it). * * None of these is called from inside an input-queue command, and no command takes this lock: a * holder may wait for a task's command chain (deletion stops the task), never the reverse. diff --git a/apps/host/src/agent/session-update.test.mjs b/apps/host/src/agent/session-update.test.mjs index aaae62886e3..8acea859f72 100644 --- a/apps/host/src/agent/session-update.test.mjs +++ b/apps/host/src/agent/session-update.test.mjs @@ -1,21 +1,23 @@ /** - * The Host's /sessions/update with the model-switch window gate (session-update.ts, - * model-window-gate.ts). - * - Rule: a model change from a client is gated as the desktop gates one from a Device Link client - * (register.ts applySessionRuntimeSelection, `isRemote`): a verified shrink whose usage is at - * danger or overflow is refused with PRECONDITION_FAILED and the desktop's text, before anything - * changes; anything unverified goes through. The Host applies a change during a turn at once - * (no deferred selection), so it is gated as if idle. - * - Gap: Host model changes had no window gate at all, and /sessions/update had no test. - * - Tier: unit, through the real entry over a migrated profile database; windows come from a fake - * route resolver. + * The Host's /sessions/update with the desktop's set-model (session-update.ts, runtime-selection.ts). + * - Rule: a user's model or provider pick is the desktop's (sessionRuntimeSelectionApply.ts, the user + * branch of handleSetModel): an intent until the next send, returned as + * { deferred: true, superseded: false, pendingUntilSend: true } and published as the task's + * agentSwitchIntent; the task row and the running Agent keep their route. Picking the current + * model again replaces the intent with one for the current route, as the desktop registers it. The window gate and a rebuild run when the intent lands at the + * send (input-queue.test.mjs, model change at send). + * - Gap: the Host applied a model change at once and refused a shrink at danger outright (its own + * window gate), where the desktop rebuilds at the send. + * - Tier: unit, through the real entries over a migrated profile database; providers and windows come + * from fixture ports. */ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { eq } from 'drizzle-orm'; +import { INDEFINITE_SNOOZE_UNTIL } from '@cindy/maker-shared/live-task-priority'; import { randomUUID } from 'node:crypto'; import { createContextOverflowRollover } from '../../../desktop/src/main/maker-ipc/contextOverflowRollover.ts'; import { commitContextRebuildWithPorts } from '../../../desktop/src/main/localDb/contextRebuildPersistence.ts'; @@ -29,13 +31,35 @@ import { OwnerSessionStorage } from '../../../desktop/src/main/localDb/sessionSt import { sessions, messages } from '../../../desktop/src/main/localDb/schema.ts'; import { estimateHandoffTokens } from '../../../desktop/src/main/maker-ipc/agentHandoff.ts'; import { setSessionProvider, getSessionProvider, clearSessionProvider } from '../../../desktop/src/main/maker-host/session-provider-store.ts'; -import { planUserRuntimeModelSwitch } from '../../../desktop/src/shared/runtimeModelSwitchGate.ts'; import { createHostSessionUpdate } from './session-update.ts'; -import { createInputQueue } from './input-queue.mjs'; -import { MODEL_WINDOW_REBUILD_UNSUPPORTED } from './model-window-gate.ts'; +import { createHostService } from '../service.mjs'; +import { lockSessionRoute } from './session-route-lock.mjs'; +import { createHostSessionMovePorts, createRecentWorkdirsChangedPush } from './session-move.ts'; +import { createHostTouchUserSend } from './touch-user-send.ts'; +import { setLiveCcSessionBridge } from '../../../desktop/src/main/maker-host/claude-transcript-relocation.ts'; +import { listRecentWorkdirs, upsertRecentWorkdir } from '../../../desktop/src/main/localDb/ipc/recentWorkdirsCore.ts'; +import { readSessionContextWindowBudget } from '../../../desktop/src/main/maker-host/session-context-budget-store.js'; +import { createSessionContextBudget } from '../../../desktop/src/main/maker-host/sessionContextBudgetCore.ts'; +import { ownerScopedPath } from '../../../desktop/src/main/ownerContext.ts'; +import { appliedContextWindowBudgets, pendingSessionContextWindowBudgetReconciles } from '../../../desktop/src/main/maker-ipc/sessionContextWindowBudgetState.js'; +import { setModelWithWindowConfirmation } from '../../../desktop/src/renderer/features/cc-agent/lib/modelWindowConfirmation.ts'; +import { bindTaskRestoreRetention, createHostTaskRestore } from './task-restore.ts'; +import { taskManagementStore } from '../../../desktop/src/main/task-management/store.ts'; +import { ARCHIVE_CANDIDATE_SELECT, taskArchiveKeepReason } from '../../../desktop/src/main/task-management/eligibility.ts'; +import { setSessionRouteLockImplementation } from '../../../desktop/src/main/localDb/sessionRouteLock.ts'; +import { withSendToSessionLock, withSessionRestartLock } from '../../../desktop/src/main/maker-ipc/sendToSessionLock.ts'; +import { botProfiles, botSessionLinks } from '../../../desktop/src/main/localDb/schema.ts'; +import { createHostRuntimeSelection } from './runtime-selection.ts'; +import { Maker } from '@cindy/maker-core'; +import { getSessionLastLiveUsage, _resetSessionLastLiveUsageForTests } from '../../../desktop/src/main/maker-ipc/sessionLastLiveUsage.ts'; -// Route windows of the fixture catalog; a model it does not know has no verified window. +// Route windows of the fixture providers; a model they do not list has no verified window. const WINDOWS = { big: 200_000, small: 100_000, huge: 300_000 }; +// Each model offers two efforts, so an effort change has a value to keep (resolveSessionRuntimeAxes). +const model = id => ({ id, efforts: ['low', 'high'], defaultEffort: 'high', supportsFastMode: false }); +const VIEWS = ['prov-a', 'prov-b'].map(id => ({ id, connected: true, agents: ['claude-code'], source: 'user', + routing: { 'claude-code': {} }, models: { 'claude-code': Object.keys(WINDOWS).map(model) } })); +const quiet = { debug() {}, info() {}, warn() {}, error() {} }; async function fixture(t) { // The development build refuses to migrate what it takes for the official shared profile @@ -62,23 +86,62 @@ async function fixture(t) { const live = new Map(); const events = []; const budgets = new Map(); + const taskRestore = createHostTaskRestore({ getOwner: () => database, publish: event => events.push(event) }); + const restoreCalls = []; + const restoreTaskToActive = (id, options) => { restoreCalls.push(['task list', id]); return taskRestore.restoreTaskToActive(id, options); }; + const maker = { + getSession: id => live.get(id) ?? null, + getSessionMeta: id => live.get(id) ? { id, agentKind: live.get(id).agentKind } : null, + closeSession: async id => { live.delete(id); }, + // As Maker (maker.ts): the runtimes it holds; a budget rebuild reads them. + listActiveSessions: () => [...live.values()], + }; + const selection = createHostRuntimeSelection({ + getMaker: () => maker, getMakerIfReady: () => maker, + publish: event => events.push(event), + createDbMessage: async () => {}, + pendingHandoff: { set() {}, readGeneration: () => 0 }, + listProviderViews: async () => VIEWS, + resolveConfiguredContextWindow: (_catalog, _agentKind, _providerId, modelId, budget) => { + const window = WINDOWS[modelId] ?? null; + return window !== null && budget ? Math.min(window, budget) : window; + }, + // The fixture's budgets first, then the task's stored preference (what /sessions/update writes). + readStoredSessionContextWindowBudget: async id => budgets.has(id) ? budgets.get(id) : readSessionContextWindowBudget(id), + // As the budget core: a change matters when the route's configured window differs. + contextWindowBudgetChangesEffectiveWindow: ({ modelId, previous, next }) => { + const window = budget => (WINDOWS[modelId] ?? null) !== null && budget ? Math.min(WINDOWS[modelId], budget) : WINDOWS[modelId] ?? null; + return window(previous) !== window(next); + }, + codexProxyAuthInjectionState: () => null, + inputQueue: { contextRecoveryRollover: () => null, sessionDbAgentKind: () => 'cc', isTurnRunning: () => false, + wakeSession() {}, refreshQueuedRoute() {}, cancelUsageLimitWait() {} }, + log: quiet, + }); + // The move's ports as main.ts binds them; the executor is the fixture's: its turns still settling, and + // its close of an idle runtime (recorded). + const settling = new Set(); + const closedByExecutor = []; + const closeGate = { current: null }; + const sessionMove = createHostSessionMovePorts({ + profileDir: profile, + getMakerIfReady: () => maker, + isTurnRunning: id => settling.has(id), + closeRuntime: async id => { closedByExecutor.push(id); await closeGate.current; live.delete(id); }, + publish: event => events.push(event), + }); + setLiveCcSessionBridge(sessionMove.liveCcSessionBridge); + t.after(() => setLiveCcSessionBridge(null)); const update = createHostSessionUpdate({ - getLiveSession: id => live.get(id), - closeRejectedPiRuntime: async (id, expected) => { if (live.get(id) === expected) live.delete(id); }, - readSessionForRun: async id => (await database.drizzle.select().from(sessions).where(eq(sessions.id, id)))[0], + restoreTaskToActive, + persistSessionFields: (...args) => selection.persistSessionFields(...args), publish: event => events.push(event), - modelWindow: () => ({ - resolveRouteWindow: (_agentKind, modelId, _providerId, budget, verification) => { - if (modelId === 'display-only') return verification ? null : 100_000; - const window = WINDOWS[modelId] ?? null; - return window !== null && budget ? Math.min(window, budget) : window; - }, - readSessionBudget: async id => budgets.get(id) ?? null, - }), + setModel: (...args) => selection.setModel(...args), + move: sessionMove.move, }); - const task = async (id, { agentKind = 'claude-code', model = 'big', contextTokens = 0, sdkSessionId } = {}) => { - await storage.create({ id, title: 'Window fixture', agentKind, model, workDir: root, providerId: 'prov-a' }); - await database.drizzle.update(sessions).set({ contextTokens, ...(sdkSessionId ? { sdkSessionId } : {}) }).where(eq(sessions.id, id)); + const task = async (id, { agentKind = 'claude-code', model = 'big', contextTokens = 0, workDir = root } = {}) => { + await storage.create({ id, title: 'Window fixture', agentKind, model, workDir, providerId: 'prov-a' }); + await database.drizzle.update(sessions).set({ contextTokens }).where(eq(sessions.id, id)); setSessionProvider(id, 'prov-a'); t.after(() => clearSessionProvider(id)); }; @@ -96,185 +159,868 @@ async function fixture(t) { return session; }; const row = async id => (await database.drizzle.select().from(sessions).where(eq(sessions.id, id)))[0]; - const handoffs = new Map(); - const history = new Map(); - const listMessages = id => database.drizzle.select().from(messages).where(eq(messages.sessionId, id)); - const rollover = createContextOverflowRollover({ - getSessionRow: row, getLiveSession: id => live.get(id), - drainPersistQueue: async () => {}, - closeSession: async id => { live.delete(id); }, - listMessages: async id => [{ role: 'user', content: 'Preserve the previous request.', clientId: 'source', createdAt: 1 }, ...(history.get(id) ?? [])], - findLatestRebuildMeta: async () => null, - commitRebuild: (id, handoff, meta) => commitContextRebuildWithPorts({ - now: Date.now, createId: randomUUID, tx: (name, args) => database.tx(name, args), - }, id, handoff, meta), - setPendingHandoff: (id, handoff) => handoffs.set(id, handoff), - withCloseSuppressed: (_id, run) => run(), - log: { warn() {}, info() {}, debug() {} }, + const liveSession = id => live.get(id); + const closeRuntime = async id => { live.delete(id); }; + return { update, task, runtime, row, events, budgets, database, taskRestore, restoreCalls, selection, liveSession, closeRuntime, + root, profile, settling, closedByExecutor, closeGate }; +} + +const intentOf = f => f.events.filter(event => event.type === 'session_changed' + && Object.hasOwn(event.patch ?? {}, 'agentSwitchIntent')).at(-1)?.patch.agentSwitchIntent; + +for (const inTurn of [false, true]) { + test(`model change ${inTurn ? 'during a turn' : 'while idle'}: a user's pick is an intent until the next send`, { timeout: 30_000 }, async t => { + const f = await fixture(t); + const id = `intent-${inTurn ? 'turn' : 'idle'}`; + // Usage at danger for the smaller window: the gate runs at the send, not here. + await f.task(id, { contextTokens: 95_000 }); + const session = f.runtime(id, { inTurn }); + const answer = await f.update(id, { model: 'small' }); + assert.deepEqual(answer.runtimeSelection, { deferred: true, superseded: false, pendingUntilSend: true }); + assert.equal((await f.row(id)).model, 'big', 'the task row keeps its model'); + assert.deepEqual(session.setModelCalls, [], 'the running Agent keeps its model'); + assert.equal(getSessionProvider(id), 'prov-a', 'the provider registration is unchanged'); + assert.equal(intentOf(f)?.model, 'small', 'the intent is published'); + assert.equal(f.selection.projectIntent(id)?.model, 'small', 'and shown to a reconnecting client'); }); - return { update, task, runtime, row, events, budgets, handoffs, history, listMessages, live, rollover }; } -// #11352 / DB tier: prewarm must use the same window gate as dispatch before opening Pi. -// Existing dispatch coverage misses this entry. A single display-only window must leave -// both the saved model and the native binding intact and prevent a preparation receipt. -test('remote Pi skill preparation refuses an owner route with an unverified window', { timeout: 30_000 }, async t => { +// As the desktop's user branch (sessionRuntimeSelectionApply.ts, the picker records intent only): a +// pick of the task's current model is an intent too, replacing the earlier one; it lands at the send +// with no route change. +test('model change: picking the current model again replaces the intent with the current route', { timeout: 30_000 }, async t => { const f = await fixture(t); - const id = 'pi-prewarm-unverified'; - const sdkSessionId = 'pi-native-before-prewarm'; - await f.task(id, { agentKind: 'pi', contextTokens: 95_000, sdkSessionId }); - const saved = await f.row(id); - const live = f.runtime(id, { agentKind: 'pi', usage: { contextWindow: 200_000, contextTokens: 95_000 } }); - live.workDir = saved.workingDir; - live.abort = async () => {}; - const queue = createInputQueue({ - getMaker: () => ({ getSession: () => live }), - hub: { publish() {} }, - readSession: f.row, - applyPendingAgentSwitch: (sessionId, prepare) => f.update(sessionId, { model: 'display-only' }, { - ...prepare, assertCurrent() {}, - }), - }); - try { - await assert.rejects(queue.preparePiSkillRuntime(id, saved.workingDir, { applyPendingOwnerSelection: true }), - /target context window or current usage could not be verified/); - const after = await f.row(id); - assert.equal(after.model, saved.model); - assert.equal(after.sdkSessionId, sdkSessionId); - assert.deepEqual(live.setModelCalls, []); - } finally { await queue.dispose(); } -}); - -// Each cell: the task's usage and the change it asks for. `refused`: the Host's verdict. -const CELLS = [ - { name: 'a verified shrink at danger', contextTokens: 95_000, target: 'small', refused: true }, - { name: 'a verified shrink at overflow', contextTokens: 150_000, target: 'small', refused: true }, - { name: 'a verified shrink with low usage', contextTokens: 50_000, target: 'small', refused: false }, - { name: 'a larger window', contextTokens: 150_000, target: 'huge', refused: false }, - { name: 'an unverified target window', contextTokens: 150_000, target: 'unlisted', refused: false }, - { name: 'an unverified current window', contextTokens: 150_000, current: 'unlisted', target: 'small', refused: false }, - { name: 'Codex, which compacts natively', agentKind: 'codex', contextTokens: 150_000, target: 'small', refused: false }, -]; + await f.task('intent-back'); + f.runtime('intent-back'); + await f.update('intent-back', { model: 'small' }); + const back = await f.update('intent-back', { model: 'big' }); + assert.equal(back.runtimeSelection.pendingUntilSend, true); + assert.equal(intentOf(f)?.model, 'big'); + assert.equal(f.selection.projectIntent('intent-back')?.model, 'big'); + assert.equal((await f.row('intent-back')).model, 'big'); +}); + +test('model change: other fields are written at once, and a provider-only pick is an intent too', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('intent-other'); + f.runtime('intent-other'); + await f.update('intent-other', { title: 'Renamed' }); + assert.equal((await f.row('intent-other')).title, 'Renamed'); + const answer = await f.update('intent-other', { providerId: 'prov-b' }); + assert.equal(answer.runtimeSelection.pendingUntilSend, true); + assert.equal((await f.row('intent-other')).providerId, 'prov-a', 'the row keeps its provider until the send'); + assert.equal(intentOf(f)?.providerId, 'prov-b'); +}); + +// A missing task is NOT_FOUND, typed as updateSessionInDb answers it (it was a plain error, HTTP 500). +const notFound = { code: 'NOT_FOUND', message: '[NOT_FOUND] Session 不存在' }; +test('model change: a task that does not exist is NOT_FOUND, and a runtime left without its row is not changed', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await assert.rejects(f.update('window-missing', { model: 'small' }), notFound); + await assert.rejects(f.update('window-missing', { title: 'Renamed' }), notFound); + // Before the gate, the running Agent was switched and then the missing row reported. + const orphan = f.runtime('window-orphan'); + await assert.rejects(f.update('window-orphan', { model: 'small' }), notFound); + assert.deepEqual(orphan.setModelCalls, []); +}); + +/** + * The old path for runtime settings (A8): /sessions/update refuses them and names their entry. + * - Rule: effort, fast mode, permission mode and Plan mode each have an entry that runs the desktop's + * handler (runtime-selection.ts); a second path here would be a second implementation. Refused as + * the desktop's updateSessionInDb refuses directory grants: UNSUPPORTED_CAPABILITY naming the entry. + * A field this entry does not write (an engine switch included) is INVALID_PARAMS naming it. The + * patch is checked before anything is read or changed, and refused whole. + * - Gap: the Host wrote these fields to the row and the running Agent directly, beside their entries, + * and an unknown field answered a plain error (500). + * - Minimal failing input: one field each; a field with a user's pick pending; a mixed patch. + * - Tier: unit, through the real entries over a migrated profile database. + */ +const DEDICATED = [['effort', 'low', /set-effort/], ['fastMode', true, /set-fast-mode/], + ['permissionMode', 'bypassPermissions', /set-permission-mode/], ['planModeEnabled', true, /set-plan-mode/]]; +const sessionPatchEvents = (f, id) => f.events.filter(event => event.type === 'session_changed' && event.sessionId === id); +// A runtime that records every setting call made on it. +function recordingRuntime(f, id) { + const session = f.runtime(id); + session.calls = []; + for (const name of ['setEffort', 'setFastMode', 'setPermissionMode', 'setPlanMode']) { + session[name] = async value => { session.calls.push([name, value]); }; + } + return session; +} + +test('runtime settings: /sessions/update refuses each one, naming its entry, and changes nothing', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('old-path'); + const session = recordingRuntime(f, 'old-path'); + const before = await f.row('old-path'); + for (const [field, value, entry] of DEDICATED) { + await assert.rejects(f.update('old-path', { [field]: value }), error => + error.code === 'UNSUPPORTED_CAPABILITY' && entry.test(error.message) && error.message.includes(field), field); + } + assert.deepEqual(session.calls, [], 'the running Agent is not touched'); + assert.deepEqual(await f.row('old-path'), before, 'the task row is not written'); + assert.deepEqual(sessionPatchEvents(f, 'old-path'), []); +}); + +test('runtime settings: with a user\'s pick pending, an effort through /sessions/update is refused and the pick keeps its effort', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('old-path-pending'); + const session = recordingRuntime(f, 'old-path-pending'); + await f.update('old-path-pending', { model: 'small' }); + const intent = f.selection.projectIntent('old-path-pending'); + await assert.rejects(f.update('old-path-pending', { effort: 'low' }), { code: 'UNSUPPORTED_CAPABILITY' }); + assert.deepEqual(f.selection.projectIntent('old-path-pending'), intent); + assert.equal(intent.model, 'small'); + assert.deepEqual(session.calls, []); + assert.equal((await f.row('old-path-pending')).effort, 'high'); +}); + +test('/sessions/update: an engine switch or an unknown field is INVALID_PARAMS naming the fields', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('old-path-unknown'); + const before = await f.row('old-path-unknown'); + await assert.rejects(f.update('old-path-unknown', { agentKind: 'codex' }), error => + error.code === 'INVALID_PARAMS' && /agentKind/.test(error.message)); + // The working directory is written here since A5 (the move tests below); only the unknown field is named. + await assert.rejects(f.update('old-path-unknown', { title: 'Renamed', workingDir: '/tmp', colour: 'red' }), error => + error.code === 'INVALID_PARAMS' && /: colour$/.test(error.message)); + assert.deepEqual(await f.row('old-path-unknown'), before); + assert.deepEqual(sessionPatchEvents(f, 'old-path-unknown'), []); +}); +test('/sessions/update: a mixed patch is refused whole, before any read or model pick', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('old-path-mixed'); + const session = recordingRuntime(f, 'old-path-mixed'); + const before = await f.row('old-path-mixed'); + await assert.rejects(f.update('old-path-mixed', { title: 'Renamed', permissionMode: 'bypassPermissions' }), + { code: 'UNSUPPORTED_CAPABILITY' }); + await assert.rejects(f.update('old-path-mixed', { model: 'small', effort: 'low' }), { code: 'UNSUPPORTED_CAPABILITY' }); + assert.deepEqual(await f.row('old-path-mixed'), before, 'the title is not written'); + assert.equal(f.selection.projectIntent('old-path-mixed'), null, 'no model pick is registered'); + assert.equal(intentOf(f), undefined); + assert.deepEqual(session.calls, []); + assert.deepEqual(sessionPatchEvents(f, 'old-path-mixed'), []); + // Nothing is read first either: a task that does not exist is refused for its fields, not "not found". + await assert.rejects(f.update('old-path-missing', { model: 'small', effort: 'low' }), { code: 'UNSUPPORTED_CAPABILITY' }); +}); + +// The renderer's switch to the Claude subscription (CCAgentSessionView handleSwitchToClaudeSubscription) +// writes the route with sessionService.update({ model, providerId }) only when the switch answers +// 'applied' (setModelWithWindowConfirmation). On the Host a user's pick always answers pendingUntilSend +// (or superseded, or an error), so that write never runs and no second intent follows; were it called, +// /sessions/update would register the pick again (the "picking the current model again" test above). +// This pins today's answer, in and out of a turn, through the renderer's own helper. for (const inTurn of [false, true]) { - for (const cell of CELLS) { - test(`model change ${inTurn ? 'during a turn' : 'while idle'}: ${cell.name} is ${cell.refused ? 'refused' : 'applied'}`, { timeout: 30_000 }, async t => { - const f = await fixture(t); - const id = `window-${inTurn ? 'turn' : 'idle'}-${CELLS.indexOf(cell)}`; - const current = cell.current ?? 'big'; - await f.task(id, { agentKind: cell.agentKind, model: current, contextTokens: cell.contextTokens }); - const session = f.runtime(id, { model: current, inTurn, agentKind: cell.agentKind }); - const change = f.update(id, { model: cell.target }); - if (cell.refused) { - await assert.rejects(change, error => error.code === 'PRECONDITION_FAILED' - && error.message === `[PRECONDITION_FAILED] ${MODEL_WINDOW_REBUILD_UNSUPPORTED}`); - assert.equal((await f.row(id)).model, current, 'the task row keeps its model'); - assert.deepEqual(session.setModelCalls, [], 'the running Agent keeps its model'); - assert.equal(getSessionProvider(id), 'prov-a', 'the provider registration is unchanged'); - assert.equal(f.events.length, 0, 'nothing is published'); - } else { - await change; - assert.equal((await f.row(id)).model, cell.target); - assert.deepEqual(session.setModelCalls.map(([model]) => model), [cell.target]); - } - // The desktop's Device Link path on the same facts: idle, the same verdict; during a turn the - // desktop defers the change to the next send (no deferred selection on the Host). - const plan = planUserRuntimeModelSwitch({ agentKind: cell.agentKind ?? 'claude-code', model: cell.target, - providerId: 'prov-a', currentFastMode: false, selection: { effort: null, fastMode: false }, - gate: { inTurn, isRemote: true, agentKind: cell.agentKind ?? 'claude-code', runtimeRouteChanged: true, - verifiedTargetWindow: WINDOWS[cell.target] ?? null, verifiedCurrentWindow: WINDOWS[current], - contextTokensKnown: true, contextTokens: cell.contextTokens } }); - assert.equal(plan.outcome, inTurn ? 'defer' : cell.refused ? 'reject' : 'hot-apply'); + test(`model change: the Claude subscription switch answers 'pending' on the Host ${inTurn ? 'during a turn' : 'while idle'}, so the renderer writes no route`, { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('subscription-switch'); + f.runtime('subscription-switch', { inTurn }); + const answer = await setModelWithWindowConfirmation({ + invoke: () => f.selection.setModel('subscription-switch', 'big', 'prov-b', undefined, undefined), + confirm: async () => { throw new Error('no window confirmation for a pick'); }, }); + assert.equal(answer, 'pending'); + assert.equal(f.selection.projectIntent('subscription-switch')?.providerId, 'prov-b'); + assert.equal((await f.row('subscription-switch')).providerId, 'prov-a', 'the row keeps its route until the send'); + }); +} + +/** + * A task's context window budget through /sessions/update (checkpoint 3b-2). + * - Rule: the desktop's budget chip saves through local-db:sessions:update (updateSessionInDb): the same + * range check (assertSessionContextWindowBudgetPatch, INVALID_PARAMS with the desktop's text), a missing + * task NOT_FOUND before anything is written, the budget kept in the task's preference file (no row + * write), broadcast, and handed to the runtime hook (the shared budget reconcile). A budget that cannot + * be saved fails a budget-only update and is dropped from a mixed one. + * - Gap: the field was not accepted (a plain error, then INVALID_PARAMS after A8): the web client's + * budget never saved on the Host. + * - Minimal failing input: one budget; each refused value; a missing task; an unreadable preference + * file alone and beside a title; a restart waiting on the task. + * - Tier: unit, through the real entry over a migrated profile database and the real preference store. + */ +const budgetEvents = (f, id) => f.events.filter(event => event.type === 'session_changed' && event.sessionId === id); + +test('window budget: /sessions/update keeps it in the preference file and broadcasts it, writing no row', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('budget-set'); + const before = await f.row('budget-set'); + const answer = await f.update('budget-set', { contextWindowBudget: 100_000 }); + assert.equal(answer.id, 'budget-set'); + assert.equal(readSessionContextWindowBudget('budget-set'), 100_000); + assert.deepEqual(await f.row('budget-set'), before, 'the row is not written (no updatedAt bump)'); + assert.deepEqual(budgetEvents(f, 'budget-set').map(event => event.patch), [{ contextWindowBudget: 100_000 }]); + await f.update('budget-set', { contextWindowBudget: null }); + assert.equal(readSessionContextWindowBudget('budget-set'), null); + assert.deepEqual(budgetEvents(f, 'budget-set').map(event => event.patch).at(-1), { contextWindowBudget: null }); +}); + +test('window budget: an idle live runtime is rebuilt for a budget that changes its window', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('budget-live'); + const live = f.runtime('budget-live'); + t.after(() => { appliedContextWindowBudgets.delete('budget-live'); pendingSessionContextWindowBudgetReconciles.delete('budget-live'); }); + await withSendToSessionLock('budget-live', () => f.update('budget-live', { contextWindowBudget: 100_000 })); + // The applier re-entered the send lock /sessions/update holds and rebuilt the runtime (closed it). + assert.equal(f.selection.pendingSwitches.get('budget-live'), undefined); + assert.notEqual(f.liveSession('budget-live'), live, 'the runtime is closed for its rebuild'); + assert.equal(appliedContextWindowBudgets.get('budget-live'), 100_000); +}); + +test('window budget: an out-of-range value is INVALID_PARAMS with the desktop\'s text, and nothing changes', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('budget-range'); + const before = await f.row('budget-range'); + for (const value of [999, 100_000_001, 300_000.5, '300000']) { + await assert.rejects(f.update('budget-range', { contextWindowBudget: value }), error => + error.code === 'INVALID_PARAMS' && error.message === + '[INVALID_PARAMS] contextWindowBudget must be null or an integer within [1000, 100000000]', String(value)); + } + assert.equal(readSessionContextWindowBudget('budget-range'), null); + assert.deepEqual(await f.row('budget-range'), before); + assert.deepEqual(budgetEvents(f, 'budget-range'), []); +}); + +test('window budget: a task that does not exist is NOT_FOUND and its preference is not written', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await assert.rejects(f.update('budget-missing', { contextWindowBudget: 300_000 }), notFound); + assert.equal(readSessionContextWindowBudget('budget-missing'), null); + assert.deepEqual(budgetEvents(f, 'budget-missing'), []); +}); + +test('window budget: an unreadable preference file fails a budget-only update and spares the title of a mixed one', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('budget-unreadable'); + // The store refuses to write over a preference file it cannot read (it keeps it for a person to fix). + const prefs = ownerScopedPath('session-context-budget-prefs.json'); + mkdirSync(path.dirname(prefs), { recursive: true }); + writeFileSync(prefs, '{ not json'); + await assert.rejects(f.update('budget-unreadable', { contextWindowBudget: 300_000 }), /unreadable|parse|JSON/i); + assert.deepEqual(budgetEvents(f, 'budget-unreadable'), [], 'nothing is broadcast for a budget that was not saved'); + await f.update('budget-unreadable', { title: 'Renamed', contextWindowBudget: 300_000 }); + assert.equal((await f.row('budget-unreadable')).title, 'Renamed'); + assert.deepEqual(budgetEvents(f, 'budget-unreadable').map(event => event.patch), [{ title: 'Renamed' }], + 'the title is broadcast, the unsaved budget is not'); +}); + +test('window budget: with a restart waiting on the task, the budget is saved without an error and the next start reads it', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('budget-restart'); + f.runtime('budget-restart'); + t.after(() => { appliedContextWindowBudgets.delete('budget-restart'); pendingSessionContextWindowBudgetReconciles.delete('budget-restart'); }); + let restart; + await withSendToSessionLock('budget-restart', async () => { + // A restart registers its fence, then waits for the lock /sessions/update holds (as main.ts wraps it). + restart = withSessionRestartLock('budget-restart', async () => { await f.closeRuntime('budget-restart'); }); + await f.update('budget-restart', { contextWindowBudget: 100_000 }); + }); + await restart; + assert.equal(readSessionContextWindowBudget('budget-restart'), 100_000, 'the budget is saved'); + assert.equal(appliedContextWindowBudgets.has('budget-restart'), false, 'not recorded as applied to the old runtime'); + // The next start reads the task's stored budget (start-options, the budget core's reader). + const budget = createSessionContextBudget({ resolveContextProviderId: () => null, readSessionContextWindowBudget, logger: quiet }); + assert.equal(await budget.readStoredSessionContextWindowBudget('budget-restart'), 100_000); +}); + +/** + * Making an archived task active (task-restore.ts): the task list's restore and a send to the task + * go through the same writer, the shared transaction `sessions.setStatus`. + * - Rule: the desktop restores through patchSessionMetaInDb's active branch, whose result is decided + * by that transaction: a deleted task stays deleted, a teammate's own task is managed by the + * teammate, a group lane is detached in the same transaction. A send also refuses a managed task + * the desktop's send refuses (archivedTaskRestore.ts). + * - Gap: the Host wrote the status column directly, and a send left an archived task archived. + * - Tier: unit, through the real entries over a migrated profile database. + */ +async function archivedTask(f, id, { status = 'archived', source, lane } = {}) { + await f.task(id); + await f.database.drizzle.update(sessions).set({ status, ...(source ? { source } : {}), updatedAt: 1 }) + .where(eq(sessions.id, id)); + if (lane) { + await f.database.drizzle.insert(botProfiles).values({ id: `bot-${id}`, displayName: 'Teammate', createdAt: 1, updatedAt: 1 }); + await f.database.drizzle.insert(botSessionLinks).values({ id: `link-${id}`, botId: `bot-${id}`, sessionId: id, role: lane, createdAt: 1 }); } } +const linkOf = async (f, id) => (await f.database.drizzle.select().from(botSessionLinks).where(eq(botSessionLinks.sessionId, id)))[0]; -test('model change: the running Agent\'s usage counts over the stored usage, and the task\'s window budget caps both windows', { timeout: 30_000 }, async t => { +test('restore: the task list and a send make an archived task active through the same transaction', { timeout: 30_000 }, async t => { const f = await fixture(t); - // Stored usage 0, the runtime reports 95k: refused against the 100k target. - await f.task('window-live'); - f.runtime('window-live', { usage: { contextTokens: 95_000, contextWindow: 200_000 } }); - await assert.rejects(f.update('window-live', { model: 'small' }), { code: 'PRECONDITION_FAILED' }); - // 300k to 200k at 195k is refused; with a 150k budget both windows are 150k, not a shrink. - await f.task('window-unbudgeted', { model: 'huge', contextTokens: 195_000 }); - f.runtime('window-unbudgeted', { model: 'huge' }); - await assert.rejects(f.update('window-unbudgeted', { model: 'big' }), { code: 'PRECONDITION_FAILED' }); - await f.task('window-budget', { model: 'huge', contextTokens: 195_000 }); - f.budgets.set('window-budget', 150_000); - f.runtime('window-budget', { model: 'huge' }); - await f.update('window-budget', { model: 'big' }); - assert.equal((await f.row('window-budget')).model, 'big'); -}); - -test('model change: a provider-only change is gated on the same model, and other fields never are', { timeout: 30_000 }, async t => { + await archivedTask(f, 'restore-list'); + await archivedTask(f, 'restore-send'); + const updated = await f.update('restore-list', { status: 'active', title: 'Back' }); + assert.equal(updated.status, 'active'); + assert.equal(updated.title, 'Back'); + await f.taskRestore.restoreArchivedSessionForSend('restore-send'); + for (const id of ['restore-list', 'restore-send']) { + const row = await f.row(id); + assert.equal(row.status, 'active'); + assert.ok(row.updatedAt > 1, 'the transaction stamps updated_at'); + } + // One event per route: the task list's carries its whole patch, a send's the new status. + assert.deepEqual(f.events.map(e => [e.sessionId, e.patch]), [ + ['restore-list', { status: 'active', title: 'Back', snoozedUntil: null, snoozedAt: null }], + ['restore-send', { status: 'active', snoozedUntil: null, snoozedAt: null }], + ]); + assert.deepEqual(f.restoreCalls, [['task list', 'restore-list']]); + // An active task is left as it is by a send. + await f.taskRestore.restoreArchivedSessionForSend('restore-send'); + assert.equal(f.events.length, 2); +}); + +/** + * The restore is recorded for idle archiving (task-restore.ts bindTaskRestoreRetention). + * - Rule: the desktop's task management installs the restore observer (task-management/service.ts): + * a restored task is kept for its retention days ('restored', eligibility.ts) before idle archiving + * may archive it again (release table 甲 22). + * - Gap: the Host installed none, so a task restored on the Host carried no restoredAt. The Host runs + * no idle archiving; the desktop does when it opens the same profile itself, and archived the task + * straight away. + * - Minimal failing input: an archived, long-unused task restored through the task list or a send. + * - Tier: unit, through the Host's restore entries over a migrated profile database, then the + * desktop's own retention decision on the row the desktop's archiving reads. + */ +test('restore: both routes record the restore, so later idle archiving keeps the task', { timeout: 30_000 }, async t => { const f = await fixture(t); - await f.task('window-other', { contextTokens: 150_000 }); - f.runtime('window-other'); - await f.update('window-other', { title: 'Renamed', effort: 'high' }); - assert.equal((await f.row('window-other')).title, 'Renamed'); - // Same model on another provider: the windows are the same, the change goes through. - await f.update('window-other', { providerId: 'prov-b' }); - assert.equal((await f.row('window-other')).providerId, 'prov-b'); + t.after(bindTaskRestoreRetention()); + await archivedTask(f, 'restore-kept-list'); + await archivedTask(f, 'restore-kept-send'); + await f.update('restore-kept-list', { status: 'active' }); + await f.taskRestore.restoreArchivedSessionForSend('restore-kept-send'); + const restoredAt = taskManagementStore.restoredAt(); + const idle = { ready: true, viewed: new Set(), drafts: new Set(), remoteUnknown: false }; + for (const id of ['restore-kept-list', 'restore-kept-send']) { + assert.ok(restoredAt[id] > Date.now() - 60_000, `${id} has its restore time`); + // Unused for a long time: without the record the desktop's archiving would pick it at once. + await f.database.drizzle.update(sessions).set({ lastActivityAt: 1, userSendAt: null, updatedAt: 1 }) + .where(eq(sessions.id, id)); + const row = await f.database.queryOne(`${ARCHIVE_CANDIDATE_SELECT} WHERE s.id = ?`, [id]); + const decide = at => taskArchiveKeepReason(row, { now: Date.now(), days: 7, restoredAt: at, protection: idle, busy: false }); + assert.equal(decide(restoredAt[id]), 'restored'); + assert.equal(decide(undefined), null, 'the same row without the record is archived'); + } }); -test('model change: a cold task (no running Agent) is gated on its stored model and usage', { timeout: 30_000 }, async t => { +test('restore: a deleted task stays deleted on both routes', { timeout: 30_000 }, async t => { const f = await fixture(t); - await f.task('window-cold', { contextTokens: 150_000 }); - await assert.rejects(f.update('window-cold', { model: 'small' }), { code: 'PRECONDITION_FAILED' }); - await f.update('window-cold', { model: 'huge' }); - assert.equal((await f.row('window-cold')).model, 'huge'); - // A cold Pi task's current window is only what its runtime reports: unverified, so it goes through. - await f.task('window-cold-pi', { agentKind: 'pi', contextTokens: 150_000 }); - await f.update('window-cold-pi', { model: 'small' }); - assert.equal((await f.row('window-cold-pi')).model, 'small'); + await archivedTask(f, 'restore-deleted', { status: 'deleted' }); + await assert.rejects(f.update('restore-deleted', { status: 'active' }), { code: 'PRECONDITION_FAILED' }); + await assert.rejects(f.taskRestore.restoreArchivedSessionForSend('restore-deleted'), { code: 'NOT_FOUND' }); + assert.equal((await f.row('restore-deleted')).status, 'deleted'); }); -test('model change: a task that does not exist is "session not found", as before the gate, and a runtime left without its row is not changed', { timeout: 30_000 }, async t => { +test('restore: a teammate\'s own task is refused, a group lane is restored and detached', { timeout: 30_000 }, async t => { const f = await fixture(t); - await assert.rejects(f.update('window-missing', { model: 'small' }), { message: 'session not found' }); - await assert.rejects(f.update('window-missing', { title: 'Renamed' }), { message: 'session not found' }); - // Before the gate, the running Agent was switched and then the missing row reported. - const orphan = f.runtime('window-orphan'); - await assert.rejects(f.update('window-orphan', { model: 'small' }), { message: 'session not found' }); - assert.deepEqual(orphan.setModelCalls, []); + await archivedTask(f, 'restore-teammate', { source: 'bot', lane: 'canonical' }); + await assert.rejects(f.update('restore-teammate', { status: 'active' }), { code: 'PRECONDITION_FAILED' }); + await assert.rejects(f.taskRestore.restoreArchivedSessionForSend('restore-teammate'), { code: 'PRECONDITION_FAILED' }); + assert.equal((await f.row('restore-teammate')).status, 'archived'); + + for (const [id, route] of [['restore-group-list', 'list'], ['restore-group-send', 'send']]) { + await archivedTask(f, id, { source: 'bot', lane: 'group' }); + if (route === 'list') await f.update(id, { status: 'active' }); + else await f.taskRestore.restoreArchivedSessionForSend(id); + assert.equal((await f.row(id)).status, 'active'); + assert.ok((await linkOf(f, id)).archivedAt > 0, 'restored history is never the live group receiver again'); + } }); -// 2026-11-18 owner Device Link decision. The old service-level tests reject 95k/100k; -// at the scheduled application boundary, the real recovery transaction must move the route and -// native binding together. Use the existing migrated SQLite fixture and real rollover (DB tier). -test('owner dispatch rebuilds Claude and hot Pi on the host-verified window and keeps an unverifiable Pi route', { timeout: 30_000 }, async t => { +// Unit: the route lock a restore takes. The Host installs the task's send lock as the shared route +// lock bridge (main.ts, as the desktop's registerAll does). Rule: a send already holding the lock +// restores re-entrantly; a restore from outside it (context recovery's replay) waits for the holder. +test('restore: a send holding the task lock restores re-entrantly, and a restore outside it waits for the lock', { timeout: 30_000 }, async t => { const f = await fixture(t); - const apply = { prepareModelWindowSwitch: f.rollover.prepareModelWindowSwitch, assertCurrent() {}, nextInputChars: 45_000 }; - const cases = [ - { id: 'owner-claude', agentKind: 'claude-code', model: 'small', expectedModel: 'small' }, - // The target catalog is larger than the source. The final native Pi window is smaller. - { id: 'owner-pi', agentKind: 'pi', model: 'huge', finalPiWindow: 100_000, expectedModel: 'huge' }, - { id: 'owner-pi-unverified', agentKind: 'pi', model: 'small', finalPiWindow: 0, expectedModel: 'big' }, - { id: 'owner-unverified-catalog', agentKind: 'claude-code', model: 'display-only', expectedModel: 'big' }, - ]; - for (const { id, agentKind, model, finalPiWindow, expectedModel } of cases) { - await f.task(id, { agentKind, contextTokens: 95_000, sdkSessionId: `native-${id}` }); - f.runtime(id, { agentKind, finalPiWindow, usage: { contextTokens: 95_000, contextWindow: 200_000 } }); - if (expectedModel !== 'big') { - f.history.set(id, [{ role: 'assistant', content: 'Prior output '.repeat(6_000), clientId: 'reply', createdAt: 2 }]); - } - const result = f.update(id, { model }, apply); - if (expectedModel === 'big') { - await assert.rejects(result, { code: 'PRECONDITION_FAILED' }); - assert.equal((await f.row(id)).sdkSessionId, `native-${id}`); - assert.equal(f.handoffs.has(id), false); + setSessionRouteLockImplementation(withSendToSessionLock); + t.after(() => setSessionRouteLockImplementation(null)); + await archivedTask(f, 'restore-locked'); + // Re-entrant: the send path already holds the task's lock. + await withSendToSessionLock('restore-locked', () => f.taskRestore.restoreArchivedSessionForSend('restore-locked')); + assert.equal((await f.row('restore-locked')).status, 'active'); + + await f.database.drizzle.update(sessions).set({ status: 'archived' }).where(eq(sessions.id, 'restore-locked')); + let release; + const held = withSendToSessionLock('restore-locked', () => new Promise(resolve => { release = resolve; })); + await new Promise(resolve => setImmediate(resolve)); + let restored = false; + const restoring = f.taskRestore.restoreArchivedSessionForSend('restore-locked').then(() => { restored = true; }); + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + assert.equal(restored, false, 'waits while another holder has the task lock'); + assert.equal((await f.row('restore-locked')).status, 'archived'); + release(); + await held; + await restoring; + assert.equal((await f.row('restore-locked')).status, 'active'); +}); + +// Close convergence (runtime-selection.ts attachMaker): +// - Rule: as the desktop's per-session status listener finalizes every closed runtime +// (sessionBindingLifecycle.ts → finalizeClosedSession → rememberSessionLastLiveUsage), each close of a +// task's runtime is seen exactly once, whichever path closed it, and its usage is read from the closed +// session at that moment (a cold Pi model change's window check reads it, sessionLastLiveUsage.ts). +// - Gap: the Host kept no last live usage. +// - Tier: unit, through a real Maker and its sessions; the agent is a fixture handle. Each Host path +// reaches the Maker through the entry named in its test. +const closeAgent = handles => ({ + capabilities: Object.fromEntries(['switchModel', 'effort', 'setPermissionModeMidSession', 'rewind', 'memory'] + .map(key => [key, { supported: false, reason: 'not-implemented' }]).concat([['permissionModes', []]])), + startSession: async opts => { + let usage = { tokenUsage: 0, contextTokens: 80_000, contextWindow: 200_000, costUsd: 0 }; + let closing = false; + const handle = { id: `native-${handles.length}`, agentKind: 'claude-code', model: opts.model, closedReads: 0, + send: async () => {}, steer: async () => {}, abort: async () => {}, + // The usage is gone one macrotask after the close: only a read at the close itself sees it. + close: async () => { closing = true; setImmediate(() => { usage = undefined; }); }, + events: async function* () { await new Promise(() => {}); }, + // Maker reads no usage on a close; each read after it began is the convergence's. + getUsageSnapshot: () => { if (closing) handle.closedReads += 1; return usage; }, + setInteractionResolver: () => {} }; + handles.push(handle); + return handle; + }, + dispose: async () => {}, +}); +function closeFixture(t) { + _resetSessionLastLiveUsageForTests(); + const rows = new Map(); + const storage = { + create: async meta => { const row = { ...meta, createdAt: Date.now(), updatedAt: Date.now() }; rows.set(row.id, row); return row; }, + get: async id => rows.get(id) ?? null, + list: async () => [...rows.values()], + update: async (id, patch) => { const next = { ...rows.get(id), ...patch, updatedAt: Date.now() }; rows.set(id, next); return next; }, + compareAndClearSdkSessionId: async () => false, + delete: async id => { rows.delete(id); }, + }; + const silent = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return silent; } }; + const handles = []; + const maker = new Maker({ agents: { 'claude-code': closeAgent(handles) }, storage, logger: silent }); + const selection = createHostRuntimeSelection({ + getMaker: () => maker, getMakerIfReady: () => maker, publish: () => {}, createDbMessage: async () => {}, + pendingHandoff: { set() {}, readGeneration: () => 0 }, listProviderViews: async () => VIEWS, + resolveConfiguredContextWindow: () => null, readStoredSessionContextWindowBudget: () => null, + contextWindowBudgetChangesEffectiveWindow: () => false, + codexProxyAuthInjectionState: () => null, + inputQueue: { contextRecoveryRollover: () => null, sessionDbAgentKind: () => 'cc', isTurnRunning: () => false, + wakeSession() {}, refreshQueuedRoute() {}, cancelUsageLimitWait() {} }, + log: quiet, + }); + // Called detached, as a caller may destructure it: the subscription does not depend on `this`. + const { attachMaker } = selection; + const off = attachMaker(maker); + t.after(async () => { off(); await maker.shutdown(); _resetSessionLastLiveUsageForTests(); }); + // Which task each fixture runtime belongs to, in start order. + const runtimes = []; + const start = async id => { + const session = await maker.createSession({ id, agentKind: 'claude-code', model: 'big', providerId: 'prov-a', workingDir: os.tmpdir() }); + runtimes.push([id, handles.at(-1)]); + return session; + }; + // The closes the convergence saw: one entry per read of a closing runtime's usage. + const seen = () => runtimes.flatMap(([id, handle]) => Array(handle.closedReads).fill(id)); + const settle = async () => { for (let i = 0; i < 5; i += 1) await new Promise(resolve => setImmediate(resolve)); }; + const remembered = id => { + const usage = getSessionLastLiveUsage(id); + return usage && { contextTokens: usage.contextTokens, contextWindow: usage.contextWindow }; + }; + return { maker, start, seen, settle, remembered, off }; +} + +const CLOSE_PATHS = [ + // turn-executor.mjs closeRuntime: an idle release, and a refresh of the runtime it still holds. + ['idle release', (maker, id) => maker.closeSession(id)], + ['idle release of the current runtime', (maker, id, session) => maker.closeSessionIfCurrent(session, 'runtime-refresh')], + // runtime-selection.ts agentSwitchDeps.closeSession (performSessionAgentSwitch). + ['engine switch', (maker, id) => maker.closeSession(id, 'agent-switch')], + // context-recovery-assembly.ts rollover closeSession (a context rebuild). + ['rebuild', (maker, id) => maker.closeSession(id, 'runtime-refresh')], + // main.ts deleteSession → inputQueue.disposeSession → executor.close → closeRuntime. + ['delete', (maker, id) => maker.closeSession(id)], + // main.ts disposeOwnerRuntime: inputQueue.dispose closes each runtime, then maker.shutdown. + ['shutdown', (maker, id) => maker.shutdown()], +]; +for (const [name, close] of CLOSE_PATHS) { + test(`close convergence: ${name} is seen once, with the usage the runtime had at its close`, { timeout: 30_000 }, async t => { + const f = closeFixture(t); + const session = await f.start(`close-${name}`); + await close(f.maker, session.id, session); + await f.settle(); + assert.deepEqual(f.seen(), [session.id]); + assert.deepEqual(f.remembered(session.id), { contextTokens: 80_000, contextWindow: 200_000 }); + assert.equal(session.getUsageSnapshot(), undefined, 'the fixture runtime has dropped its usage since'); + }); +} + +test('close convergence: a runtime closed twice, or closed and then shut down, is seen once; the task\'s next runtime once more', { timeout: 30_000 }, async t => { + const f = closeFixture(t); + const first = await f.start('close-twice'); + await Promise.all([f.maker.closeSession(first.id), f.maker.closeSession(first.id)]); + await f.settle(); + assert.deepEqual(f.seen(), ['close-twice']); + const next = await f.start('close-twice'); + assert.notEqual(next, first); + const other = await f.start('close-then-shutdown'); + await f.maker.closeSession(other.id); + await f.maker.shutdown(); + await f.settle(); + assert.deepEqual(f.seen().sort(), ['close-then-shutdown', 'close-twice', 'close-twice']); +}); + +test('close convergence: after the owner runtime unsubscribes, a close is not seen', { timeout: 30_000 }, async t => { + const f = closeFixture(t); + const session = await f.start('close-after-off'); + f.off(); + await f.maker.closeSession(session.id); + await f.settle(); + assert.deepEqual(f.seen(), []); + assert.equal(f.remembered(session.id), undefined); +}); + +// Rule: the Host refuses a task whose Agent runs on another computer with its remote execution refusal +// (send-preflight.ts assertHostTaskExecutionSupported: UNSUPPORTED_CAPABILITY), where the desktop hands +// the change to that computer (handleSetModel → applyAgentDeviceRuntimeSelection). Gap: the Host's +// binding threw a plain error, answered as an untyped 500. Such a row reaches the Host by migration. +test('model change: a task whose Agent runs on another computer is refused as remote execution, with nothing changed', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('on-device'); + await f.database.drizzle.update(sessions).set({ agentDeviceId: 'other-computer' }).where(eq(sessions.id, 'on-device')); + await assert.rejects(f.update('on-device', { model: 'small' }), error => + error.code === 'UNSUPPORTED_CAPABILITY' && /remote execution/.test(error.message)); + assert.equal((await f.row('on-device')).model, 'big'); + assert.equal(intentOf(f), undefined); +}); + +// Effort and thinking changes (checkpoint 3b, the desktop's SET_EFFORT and SET_THINKING_ENABLED bodies +// from sessionRuntimeAxisSettings.ts): +// - Rule: with no pick pending, an effort change applies to the task's runtime and row at once; with a +// user's pick pending, it goes into that pick (stagePendingUserRuntimeAxis) and the running model is +// left alone. A thinking change applies to the runtime, after the Review check. +// - Gap: the Host applied an effort change to the running model and row even with a pick pending, and +// had no thinking entry. +test('effort: with no pick pending, the change applies to the task\'s runtime and row at once', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('effort-live'); + const live = f.runtime('effort-live'); + const applied = []; + live.setEffort = async effort => { applied.push(effort); }; + await f.selection.setEffort('effort-live', 'low'); + assert.deepEqual(applied, ['low']); + assert.equal((await f.row('effort-live')).effort, 'low'); +}); + +test('effort: with a user\'s pick pending, the change goes into the pick and the running model is left alone', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('effort-pending'); + const live = f.runtime('effort-pending'); + const applied = []; + live.setEffort = async effort => { applied.push(effort); }; + await f.update('effort-pending', { model: 'small' }); + const answer = await f.selection.setEffort('effort-pending', 'low'); + assert.deepEqual(answer, { deferred: true, superseded: false, pendingUntilSend: true }); + assert.deepEqual(applied, [], 'the running model keeps its effort'); + assert.equal((await f.row('effort-pending')).effort, 'high', 'the task row keeps its effort until the pick lands'); + assert.equal(f.selection.projectIntent('effort-pending')?.effort, 'low', 'the pick carries the new effort'); + assert.equal(f.selection.projectIntent('effort-pending')?.model, 'small'); +}); + +test('thinking: a change applies to the runtime, and a Review task is refused before it', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('thinking-live'); + const live = f.runtime('thinking-live'); + const changes = []; + live.setThinkingEnabled = async enabled => { changes.push(enabled); }; + await f.selection.setThinkingEnabled('thinking-live', false); + assert.deepEqual(changes, [false]); + await f.database.drizzle.update(sessions).set({ source: 'review' }).where(eq(sessions.id, 'thinking-live')); + await assert.rejects(f.selection.setThinkingEnabled('thinking-live', true), + error => error.code === 'UNSUPPORTED_CAPABILITY' && /Review task settings/.test(error.message)); + assert.deepEqual(changes, [false], 'the Review task\'s runtime is not touched'); +}); + +// Working-directory move (A5: session-update.ts with the desktop's move steps, sessionWorkingDirMove.ts; +// the Host's ports, session-move.ts): +// - Rule: moving a task to another directory or a dialogue is the desktop's updateSessionInDb (its move +// steps run as they were moved): the stored form of the directory, the mapper dropping the explicit +// project, the worktree ownership guard (the desktop's registry, worktrees.json in the profile root), +// an idle Pi/Codex runtime closed and a running one refused, a Claude task's transcripts copied to the +// new directory's key, the recent project record, and the patch the steps changed in place published. +// - Gap: /sessions/update refused workingDir and workspaceKind (INVALID_PARAMS): the web client's "move +// to project" failed and its folder pick changed nothing. +// - Minimal failing input: one move of each kind below; the lock's holder; each registry state. +// - Tier: unit, through the real entry over a migrated profile database, the real registry file and the +// real transcript copy in an isolated Claude config directory; the runtime is a fixture. +const moveDir = (f, name) => { const dir = path.join(f.root, name); mkdirSync(dir, { recursive: true }); return dir; }; +// Host rows and events use forward slashes even when the caller supplies a native Windows path. +const storedDir = dir => dir.split(path.sep).join('/'); +const movedEvents = (f, id) => f.events.filter(event => event.type === 'session_changed' && event.sessionId === id); +const recentPushes = f => f.events.filter(event => event.type === 'plugin_push' && event.channel === 'local-db:recent-workdirs:changed'); + +test('move: an idle Codex task moves to a project; its runtime is closed, and the row, the event and the recent projects follow', { timeout: 30_000 }, async t => { + const f = await fixture(t); + const from = moveDir(f, 'from'); + const to = moveDir(f, 'to'); + // df520e3564: moving a task advances an existing project's usage time. + await upsertRecentWorkdir(to, 1_000); + await f.task('move-codex', { agentKind: 'codex', workDir: from }); + await f.database.drizzle.update(sessions).set({ projectDir: from }).where(eq(sessions.id, 'move-codex')); + f.runtime('move-codex', { agentKind: 'codex' }); + const moved = await f.update('move-codex', { workingDir: `${to}/`, workspaceKind: 'project' }); + assert.equal(moved.workingDir, storedDir(to)); + const row = await f.row('move-codex'); + assert.deepEqual([row.workingDir, row.workspaceKind, row.projectDir], [storedDir(to), 'project', null]); + assert.deepEqual(f.closedByExecutor, ['move-codex'], 'the idle runtime is closed before the new directory is written'); + assert.equal(f.liveSession('move-codex'), undefined); + assert.deepEqual(movedEvents(f, 'move-codex').at(-1).patch, { workingDir: storedDir(to), workspaceKind: 'project', projectDir: null }); + // Protocol: the desktop's own push (sessions.ts broadcastRecentWorkdirsChanged sends this channel with + // { path }); its renderer listens on it (preload localDb.recentWorkdirs.onChanged), reached here through + // the web shim and the client-mode window. Another channel or payload and the recent list goes stale. + assert.deepEqual(recentPushes(f), [{ type: 'plugin_push', channel: 'local-db:recent-workdirs:changed', payload: { path: storedDir(to) } }]); + assert.ok((await listRecentWorkdirs()).find(entry => entry.path === storedDir(to))?.lastUsedAt > new Date(1_000).toISOString()); +}); + +test('move: a Claude task\'s transcripts follow it, and the resume id the move persisted is in the row and the published patch', { timeout: 30_000 }, async t => { + const f = await fixture(t); + const claudeConfig = path.join(f.root, 'claude-config'); + const previous = process.env.CLAUDE_CONFIG_DIR; + process.env.CLAUDE_CONFIG_DIR = claudeConfig; + t.after(() => { if (previous === undefined) delete process.env.CLAUDE_CONFIG_DIR; else process.env.CLAUDE_CONFIG_DIR = previous; }); + const from = moveDir(f, 'claude-from'); + const to = moveDir(f, 'claude-to'); + const storedId = '11111111-1111-4111-8111-111111111111'; + const liveId = '22222222-2222-4222-8222-222222222222'; + await f.task('move-claude', { workDir: from }); + await f.database.drizzle.update(sessions).set({ sdkSessionId: storedId }).where(eq(sessions.id, 'move-claude')); + // The live runtime is ahead of the row (a fork whose rows are not written yet); its transcript is on disk. + const session = f.runtime('move-claude'); + session.sdkSessionId = liveId; + const source = path.join(claudeConfig, 'projects', 'old-key'); + mkdirSync(source, { recursive: true }); + writeFileSync(path.join(source, `${liveId}.jsonl`), '{"type":"user"}\n'); + await f.update('move-claude', { workingDir: `${to}/`, workspaceKind: 'project' }); + const row = await f.row('move-claude'); + assert.deepEqual([row.workingDir, row.sdkSessionId], [storedDir(to), liveId]); + assert.deepEqual(movedEvents(f, 'move-claude').at(-1).patch, + { workingDir: storedDir(to), workspaceKind: 'project', sdkSessionId: liveId, projectDir: null }); + assert.equal(f.liveSession('move-claude'), undefined, 'the Claude runtime in the old directory is closed'); + const copies = readdirSync(path.join(claudeConfig, 'projects')) + .filter(key => key !== 'old-key' && existsSync(path.join(claudeConfig, 'projects', key, `${liveId}.jsonl`))); + assert.equal(copies.length, 1, 'the transcript is copied under the new directory\'s key'); +}); + +test('move: inside the task lock the move re-enters it; another holder of the lock waits until the move is done', { timeout: 30_000 }, async t => { + const f = await fixture(t); + setSessionRouteLockImplementation(withSendToSessionLock); + t.after(() => setSessionRouteLockImplementation(null)); + const to = moveDir(f, 'locked-to'); + await f.task('move-locked', { agentKind: 'codex', workDir: moveDir(f, 'locked-from') }); + // As main.ts: the entry runs in the task's send lock, and the move takes the route lock again. + await lockSessionRoute(f.update)('move-locked', { workingDir: to, workspaceKind: 'project' }); + assert.equal((await f.row('move-locked')).workingDir, storedDir(to)); + + // The move holds the lock while it closes the runtime; another holder (a send) waits behind it. + f.runtime('move-locked', { agentKind: 'codex' }); + f.closedByExecutor.length = 0; + let open; + f.closeGate.current = new Promise(resolve => { open = resolve; }); + const back = moveDir(f, 'locked-back'); + const moving = lockSessionRoute(f.update)('move-locked', { workingDir: back, workspaceKind: 'project' }); + for (let i = 0; i < 200 && !f.closedByExecutor.includes('move-locked'); i += 1) await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(f.closedByExecutor, ['move-locked'], 'the move is closing the runtime'); + let ran = false; + const other = withSendToSessionLock('move-locked', async () => { ran = true; return (await f.row('move-locked')).workingDir; }); + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + assert.equal(ran, false, 'waits while the move holds the task lock'); + open(); + await moving; + assert.equal(await other, storedDir(back), 'runs after the move and reads the moved directory'); +}); + +// The desktop's registry: `{ worktrees: { : { path } } }` in the profile root (worktreeStore.ts). +const writeRegistry = (f, text) => writeFileSync(path.join(f.profile, 'worktrees.json'), text); + +test('move: the worktree registry decides ownership; no registry is no binding, an unreadable one refuses the move', { timeout: 30_000 }, async t => { + const f = await fixture(t); + const worktree = moveDir(f, path.join('repo', '.cindy-worktrees', 'feature')); + const elsewhere = moveDir(f, 'elsewhere'); + const unchanged = async (id, patch, check) => { + const before = await f.row(id); + await assert.rejects(f.update(id, patch), check); + assert.deepEqual(await f.row(id), before, 'nothing is written'); + }; + for (const [name, registry, outcome] of [ + ['bound', JSON.stringify({ worktrees: { 'wt-bound': { path: worktree } } }), 'blocked'], + ['no registry', null, 'moved'], + ['registry without the task', JSON.stringify({ worktrees: {} }), 'moved'], + ['not JSON', '{"worktrees":', 'failed'], + ['not the registry\'s shape', JSON.stringify({ worktrees: [] }), 'failed'], + ['an entry without a path', JSON.stringify({ worktrees: { 'wt-entry': {} } }), 'failed'], + ]) { + const id = { bound: 'wt-bound', 'an entry without a path': 'wt-entry' }[name] ?? `wt-${name.replaceAll(/\W+/g, '-')}`; + // The task's directory is a managed worktree path either way: a recycled worktree keeps it (no binding). + await f.task(id, { agentKind: 'codex', workDir: worktree }); + rmSync(path.join(f.profile, 'worktrees.json'), { force: true }); + if (registry !== null) writeRegistry(f, registry); + const patch = { workingDir: elsewhere, workspaceKind: 'project' }; + if (outcome === 'moved') { + await f.update(id, patch); + assert.equal((await f.row(id)).workingDir, storedDir(elsewhere), name); + } else if (outcome === 'blocked') { + await unchanged(id, patch, error => error.code === 'PRECONDITION_FAILED' + && error.message.includes('A worktree session cannot be moved outside its worktree')); } else { - await result; - assert.equal((await f.row(id)).sdkSessionId, null); - assert.equal((await f.row(id)).contextTokens, 0); - const handoff = f.handoffs.get(id); - assert.match(handoff, /Preserve the previous request/); - assert.ok(handoff.length > 16_000); - assert.ok(estimateHandoffTokens(handoff) <= 20_000); - const marker = (await f.listMessages(id)).find(message => message.role === 'context_rebuild'); - assert.equal(JSON.parse(marker.content).handoffCoverage, 'condensed'); + await unchanged(id, patch, error => error instanceof Error && !error.message.includes('cannot be moved outside')); } - assert.equal((await f.row(id)).model, expectedModel); - assert.equal(f.live.has(id), id === 'owner-unverified-catalog'); } + // A move inside the bound worktree, and a move to a dialogue, stay allowed. + writeRegistry(f, JSON.stringify({ worktrees: { 'wt-bound': { path: worktree } } })); + await f.update('wt-bound', { workingDir: moveDir(f, path.join('repo', '.cindy-worktrees', 'feature', 'sub')) }); + await f.update('wt-bound', { workspaceKind: 'dialogue' }); + assert.equal((await f.row('wt-bound')).workspaceKind, 'dialogue'); +}); + +test('move: a task in a turn, or whose turn is still settling, is not moved and its runtime is not closed', { timeout: 30_000 }, async t => { + const f = await fixture(t); + const to = moveDir(f, 'busy-to'); + for (const [id, state] of [['busy-turn', 'in a turn'], ['busy-settling', 'settling']]) { + await f.task(id, { agentKind: 'pi', workDir: moveDir(f, `${id}-from`) }); + f.runtime(id, { agentKind: 'pi', inTurn: state === 'in a turn' }); + if (state === 'settling') f.settling.add(id); + const before = await f.row(id); + await assert.rejects(f.update(id, { workingDir: to, workspaceKind: 'project' }), + error => error.code === 'PRECONDITION_FAILED' && error.message.includes('运行中的任务不能移动'), state); + assert.deepEqual(await f.row(id), before, state); + assert.ok(f.liveSession(id), `${state}: the runtime is kept`); + } + assert.deepEqual(f.closedByExecutor, []); +}); + +test('move and window budget: a Review task refuses both, before anything is written', { timeout: 30_000 }, async t => { + const f = await fixture(t); + await f.task('review-move', { workDir: moveDir(f, 'review-from') }); + await f.database.drizzle.update(sessions).set({ source: 'review' }).where(eq(sessions.id, 'review-move')); + const before = await f.row('review-move'); + for (const patch of [{ workingDir: moveDir(f, 'review-to'), workspaceKind: 'project' }, { contextWindowBudget: 100_000 }]) { + await assert.rejects(f.update('review-move', patch), + error => error.code === 'UNSUPPORTED_CAPABILITY' && /Review task settings/.test(error.message), Object.keys(patch).join()); + } + assert.deepEqual(await f.row('review-move'), before); + assert.equal(readSessionContextWindowBudget('review-move'), null, 'the budget preference is not written'); + assert.deepEqual(movedEvents(f, 'review-move'), []); +}); + +// updatedAt and the send's recent project (A18, A19: the desktop's isSessionSettingsOnlyPatch and +// recordRecentWorkdirForSend, moved out of updateSessionInDb and touchUserSendInDb): +// - Rule: a patch of settings only (title, pin, mute, move) leaves updatedAt alone and a status change +// moves it (the sidebar orders by it); a user's send records the project it was made in as recent, +// announced while the owner holds; a stamp that changes nothing records and announces nothing. +// - Gap: the Host bumped updatedAt on every /sessions/update, and its send recorded no recent project. +// - Minimal failing input: each patch below on a task stamped updatedAt = 1; one send, the same send +// again, a send after the owner changed. +// - Tier: unit, through the real entries over a migrated profile database. +test('updatedAt: settings-only patches leave it, a status change moves it', { timeout: 30_000 }, async t => { + const f = await fixture(t); + const to = moveDir(f, 'stamp-to'); + for (const [name, patch, moves] of [ + ['a title', { title: 'Renamed' }, false], + ['a pin', { pinnedAt: new Date().toISOString() }, false], + ['a mute', { notificationsMuted: true }, false], + ['a move', { workingDir: to, workspaceKind: 'project' }, false], + ['an archive', { status: 'archived' }, true], + ]) { + const id = `stamp-${name.replaceAll(' ', '-')}`; + await f.task(id, { agentKind: 'codex', workDir: moveDir(f, `${id}-from`) }); + await f.database.drizzle.update(sessions).set({ updatedAt: 1 }).where(eq(sessions.id, id)); + await f.update(id, patch); + const row = await f.row(id); + if (moves) assert.ok(row.updatedAt > 1, name); + else assert.equal(row.updatedAt, 1, name); + assert.ok(movedEvents(f, id).length > 0, `${name}: still published`); + } +}); + +// §3.2 DB: the upstream Inbox writes through /api/sessions/update in client mode. +// This entry rejected snoozedUntil. A valid future deadline must save and publish both +// timestamps without changing the task status or activity. ccda86c776 also reserves +// one ISO value past the one-year limit. A regular date alone misses that branch. +// Minimal failing input: the reserved value through the same service, with no other patch. +// Invalid input must still write nothing. This DB case reuses the existing migrated fixture. +test('task snooze: the Host update saves, rejects and clears the date like the desktop', { timeout: 30_000 }, async t => { + const f = await fixture(t); + const id = 'snoozed-task'; + await f.task(id); + await f.database.drizzle.update(sessions).set({ updatedAt: 1 }).where(eq(sessions.id, id)); + const invoke = createHostService({ updateSession: lockSessionRoute(f.update) }); + const update = patch => invoke('/api/sessions/update', { sessionId: id, patch }); + const snoozedUntil = new Date(Date.now() + 3_600_000).toISOString(); + const { status, body: saved } = await update({ snoozedUntil }); + assert.equal(status, 200); + assert.equal(saved.status, 'active'); + assert.equal(saved.snoozedUntil, snoozedUntil); + const row = await f.row(id); + assert.equal(row.updatedAt, 1); + assert.equal(row.snoozedUntil, Date.parse(snoozedUntil)); + assert.equal(row.snoozedAt, Date.parse(saved.snoozedAt)); + assert.ok(row.snoozedAt > 0); + assert.deepEqual(movedEvents(f, id).at(-1).patch, { snoozedUntil, snoozedAt: saved.snoozedAt }); + + const pushes = f.events.length; + for (const invalid of [123, 'not-a-date', '2000-01-01T00:00:00.000Z', new Date(Date.now() + 367 * 86_400_000).toISOString()]) { + await assert.rejects(update({ title: 'Do not apply', snoozedUntil: invalid }), { + code: 'INVALID_PARAMS', + message: '[INVALID_PARAMS] snoozedUntil must be a future ISO timestamp within one year', + }); + } + assert.deepEqual(await f.row(id), row); + assert.equal(f.events.length, pushes); + + const { status: indefiniteStatus, body: indefinite } = await update({ snoozedUntil: INDEFINITE_SNOOZE_UNTIL }); + assert.equal(indefiniteStatus, 200); + assert.equal(indefinite.snoozedUntil, INDEFINITE_SNOOZE_UNTIL); + const indefiniteRow = await f.row(id); + assert.equal(indefiniteRow.snoozedUntil, Date.parse(INDEFINITE_SNOOZE_UNTIL)); + assert.equal(indefiniteRow.updatedAt, 1); + assert.deepEqual(movedEvents(f, id).at(-1).patch, + { snoozedUntil: INDEFINITE_SNOOZE_UNTIL, snoozedAt: indefinite.snoozedAt }); + + const { body: cancelled } = await update({ snoozedUntil: null }); + assert.deepEqual([cancelled.snoozedUntil, cancelled.snoozedAt], [null, null]); + assert.deepEqual(movedEvents(f, id).at(-1).patch, { snoozedUntil: null, snoozedAt: null }); + await update({ snoozedUntil }); + const { body: archived } = await update({ status: 'archived' }); + assert.deepEqual([archived.status, archived.snoozedUntil, archived.snoozedAt], ['archived', null, null]); + const archivedRow = await f.row(id); + assert.deepEqual([archivedRow.snoozedUntil, archivedRow.snoozedAt], [null, null]); + assert.deepEqual(movedEvents(f, id).at(-1).patch, { status: 'archived', snoozedUntil: null, snoozedAt: null }); +}); + +// df520e3564: a send in an unregistered directory must neither add a project nor push a project refresh. +// The existing fixture covered recency and owner checks, but not the registered/unregistered boundary. +test('send: only a registered project becomes recent and is announced; an unchanged stamp or another owner announces nothing', { timeout: 30_000 }, async t => { + const f = await fixture(t); + const project = moveDir(f, 'sent-project'); + await f.task('sent', { workDir: project }); + const owner = { client: f.database }; + // The owner the entry reads first, then the one current when it announces (an account switch during + // the write when they differ). + let after = owner; + let reads = 0; + const touch = createHostTouchUserSend({ getOwner: () => (reads++ === 0 ? owner : after), publish: event => f.events.push(event), + broadcastRecentWorkdirsChanged: createRecentWorkdirsChangedPush(event => f.events.push(event)) }); + await touch('sent', 4_000); + assert.equal((await listRecentWorkdirs()).some(entry => entry.path === storedDir(project)), false); + assert.deepEqual(recentPushes(f), []); + await upsertRecentWorkdir(project, 1_000); + + reads = 0; + await touch('sent', 5_000); + assert.equal((await listRecentWorkdirs()).find(entry => entry.path === storedDir(project))?.lastUsedAt, new Date(5_000).toISOString()); + assert.deepEqual(recentPushes(f), [{ type: 'plugin_push', channel: 'local-db:recent-workdirs:changed', payload: { path: storedDir(project) } }]); + assert.equal(movedEvents(f, 'sent').at(-1).patch.userSendAt, new Date(5_000).toISOString()); + const events = f.events.length; + reads = 0; + await touch('sent', 5_000); + assert.equal(f.events.length, events, 'the same stamp again changes nothing'); + reads = 0; + after = { client: f.database }; + await touch('sent', 6_000); + assert.equal(f.events.length, events, 'nothing is announced once the owner changed during the send'); + assert.equal((await f.row('sent')).userSendAt, 6_000, 'the entry\'s own database is still stamped'); }); diff --git a/apps/host/src/agent/session-update.ts b/apps/host/src/agent/session-update.ts index 2b76794d26f..302439c7b08 100644 --- a/apps/host/src/agent/session-update.ts +++ b/apps/host/src/agent/session-update.ts @@ -1,174 +1,216 @@ import { eq } from 'drizzle-orm'; +import { INDEFINITE_SNOOZE_UNTIL } from '@cindy/maker-shared/live-task-priority'; import { getDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; import { sessions as sessionTable } from '../../../desktop/src/main/localDb/schema.ts'; -import { sessionToCamel } from '../../../desktop/src/main/localDb/mapper.ts'; -import { dbToMakerAgentKind } from '../../../desktop/src/shared/agentKindConversion.js'; -import { applyLiveSessionSettings } from './session-settings.mjs'; -import { assessRuntimeModelSwitchGate } from '../../../desktop/src/shared/runtimeModelSwitchGate.ts'; -import { shouldRebuildForModelWindowSwitch, type createContextOverflowRollover } from '../../../desktop/src/main/maker-ipc/contextOverflowRollover.ts'; +import { sessionPatchToRow, sessionToCamel } from '../../../desktop/src/main/localDb/mapper.ts'; +import type { DbClient } from '../../../desktop/src/main/localDb/client/DbClient.ts'; import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; -import { MODEL_WINDOW_REBUILD_UNSUPPORTED, modelSwitchGateInput, type ModelSwitchLiveRuntime } from './model-window-gate.ts'; +import { assertSessionContextWindowBudgetPatch } from '../../../desktop/src/main/localDb/sessionContextWindowBudgetPatch.js'; +import { isSessionSettingsOnlyPatch } from '../../../desktop/src/main/localDb/sessionSettingsOnlyPatch.ts'; +import { touchRecentWorkdir } from '../../../desktop/src/main/localDb/ipc/recentWorkdirsCore.ts'; +import { cleanupSessionRuntimeForTerminalStatus } from '../../../desktop/src/main/localDb/sessionRuntimeCleanup.ts'; +import { + assertReviewSessionPatchAllowed, + assertSessionWorkspaceKindPatch, + normalizeSessionWorkingDirPatch, + prepareSessionWorkingDirMove, + recordRecentWorkdirForMove, + relocateClaudeTranscriptsForMove, + withSessionWorkingDirMoveLocks, + type SessionWorktreeBindingLookup, +} from '../../../desktop/src/main/localDb/ipc/sessionWorkingDirMove.ts'; +import { explicitPorts } from './explicit-ports.ts'; -type ModelWindowPreparation = ReturnType['prepareModelWindowSwitch']; - -export interface HostModelSelectionApply { - prepareModelWindowSwitch: ModelWindowPreparation; - assertCurrent(): void; - signal?: AbortSignal; - nextInputChars?: number; -} - -type LiveSession = ModelSwitchLiveRuntime & Parameters[0]; +/** The fields this entry writes; anything else is INVALID_PARAMS, naming the fields. */ +const UPDATABLE_FIELDS = new Set(['title', 'status', 'pinnedAt', 'notificationsMuted', 'model', 'providerId', 'contextWindowBudget', + 'workingDir', 'workspaceKind', 'snoozedUntil']); +/** + * Runtime settings with their own entry, which runs the desktop's handler (runtime-selection.ts). This + * entry refuses them, as the desktop's updateSessionInDb refuses directory grants (UNSUPPORTED_CAPABILITY + * naming the entry): a second path here would be a second implementation of the same setting (release + * table, section 2). + */ +const DEDICATED_ENTRIES: Record = { + effort: '/api/sessions/set-effort (maker:set-effort)', + fastMode: '/api/sessions/set-fast-mode (maker:set-fast-mode)', + permissionMode: '/api/sessions/set-permission-mode (maker:set-permission-mode)', + planModeEnabled: '/api/sessions/set-plan-mode (maker:set-plan-mode)', +}; /** - * The Host's session update under the task's route lock. Only the send path can pass an - * owner selection for application. Ordinary HTTP updates keep the original window gate. + * The Host's /sessions/update (main.ts wraps it in the task's route lock). The patch is checked before + * anything is read or changed, and refused whole: a field this entry does not write is INVALID_PARAMS, + * a runtime setting with its own entry is UNSUPPORTED_CAPABILITY naming that entry. A model or provider + * change is the desktop's set-model (runtime-selection.ts, handleSetModel): a user's pick is an intent + * until the next send, so the task row and the running Agent keep their route here, and the answer + * carries the selection's result. A task's context window budget is the desktop's own path (its budget + * chip saves through local-db:sessions:update, updateSessionInDb): the same range check, then + * persistSessionFields (persistSessionFieldsWith with the budget hook). As updateSessionInDb, a missing + * task is NOT_FOUND before anything is written, and a budget that cannot be saved fails a budget-only + * update but only drops the budget from a mixed one. Moving a task to another working directory or to a + * dialogue runs the desktop's own move steps (sessionWorkingDirMove.ts, moved from updateSessionInDb) at + * the places updateSessionInDb runs them: the route and worktree locks around everything (inside the + * route lock main.ts already holds, re-entered), the workspaceKind check, the stored form of the + * directory, the Review task check (for the whole patch, as the desktop), the worktree ownership guard + * and closing an idle Pi/Codex runtime, the Claude transcript move, and the recent project record. The + * patch they change in place (the stored directory, a resume id the transcript move persisted) is the + * one published. The other fields are written here. */ export function createHostSessionUpdate(deps: { - getLiveSession(sessionId: string): LiveSession | null | undefined; - closeRejectedPiRuntime?(sessionId: string, runtime: LiveSession): Promise; - readSessionForRun(sessionId: string): Promise<{ model?: string | null }>; + /** The session settings write with the budget hook (runtime-selection.ts persistSessionFields). */ + persistSessionFields(sessionId: string, patch: Record): Promise; publish(event: Record): void; - /** The configured window of a route, with the task's window budget (agent graph). */ - modelWindow?(): { - resolveRouteWindow(agentKind: string, modelId: string, providerId: string | null, budget: number | null, verification?: 'required'): number | null; - readSessionBudget(sessionId: string): Promise; - } | null; + /** Making the task active again (task-restore.ts), the one Host route for it; it also serves sends. */ + restoreTaskToActive(sessionId: string, options?: { publish?: boolean }): Promise; + /** A model or provider change: the desktop's set-model, with the desktop IPC's arguments. */ + setModel(sessionId: string, model: unknown, providerId: unknown, revision: unknown, selection: unknown): Promise; + /** The working-directory move's ports (session-move.ts). */ + move: { + /** The desktop's worktree registry, read only. */ + lookupSessionWorktreeBinding: SessionWorktreeBindingLookup; + /** False when the task's turn is running; otherwise its runtime is closed (or there is none). */ + closeIdleSessionForMove(sessionId: string): Promise; + /** The desktop's local-db:recent-workdirs:changed. */ + broadcastRecentWorkdirsChanged(path: string): void; + }; }) { - return async ( - sessionId: string, - patch: Record, - apply?: HostModelSelectionApply, - assertCurrent = apply?.assertCurrent, - ) => { - const allowed: Record = { - title: true, status: true, pinnedAt: true, notificationsMuted: true, model: true, - effort: true, permissionMode: true, fastMode: true, planModeEnabled: true, - providerId: true, agentKind: true, - }; - if (Object.keys(patch).some((key) => allowed[key] !== true)) { - throw new Error('unsupported session field'); + // Runs inside the move locks (below), as updateSessionInDb's `update`. + const applyUpdate = async (sessionId: string, patch: Record, fields: string[], dbClient: DbClient) => { + const db = dbClient.drizzle; + assertSessionWorkspaceKindPatch(patch); + assertSessionContextWindowBudgetPatch(patch); + normalizeSessionWorkingDirPatch(patch); + await assertReviewSessionPatchAllowed({ db, sid: sessionId, p: patch }); + const beforeMove = await prepareSessionWorkingDirMove(explicitPorts[0]>({ + db, sid: sessionId, p: patch, + moveGuard: undefined, // see the entry below + opts: explicitPorts[0]['opts']>({ + closeIdleSessionForMove: deps.move.closeIdleSessionForMove, + }), + sessionWorktreeBindingLookup: deps.move.lookupSessionWorktreeBinding, + })); + // As updateSessionInDb, at the same place: a patch of settings only (a title, a pin, a mute, a move, a + // model) leaves updatedAt alone; a status change moves it. + const isSettingsOnly = isSessionSettingsOnlyPatch(patch); + const hasBudget = patch.contextWindowBudget !== undefined; + const budgetOnly = fields.length > 0 && fields.every(key => key === 'contextWindowBudget'); + if (hasBudget) { + // updateSessionInDb answers a missing task NOT_FOUND before it writes the budget; persistSessionFields + // alone would write the preference (the known difference, release table section 2). + const [target] = await getDbClient().drizzle.select({ id: sessionTable.id }).from(sessionTable) + .where(eq(sessionTable.id, sessionId)).limit(1); + if (!target) throwIpcError('NOT_FOUND', 'Session 不存在'); } - // A live Session keeps its own permission mode and model route. Apply the - // change there first so the stored value and the running Agent cannot - // disagree (a tighter mode must bind the very next tool call). An engine - // switch is left to the input queue, which recreates the Session. - const live = patch.agentKind === undefined ? deps.getLiveSession(sessionId) : undefined; - let routeRebuilt = false; - let liveModelApplied = false; - if (patch.agentKind === undefined && (typeof patch.model === 'string' || Object.hasOwn(patch, 'providerId'))) { - const [before] = await getDbClient().drizzle.select().from(sessionTable) + // A model or provider change: the desktop's set-model. The row keeps its route; the selection + // lands at the next send. + let runtimeSelection: unknown; + const routeChange = typeof patch.model === 'string' || Object.hasOwn(patch, 'providerId'); + if (routeChange) { + const [before] = await getDbClient().drizzle.select({ model: sessionTable.model }).from(sessionTable) .where(eq(sessionTable.id, sessionId)).limit(1); - if (!before) throw new Error('session not found'); - const window = deps.modelWindow?.() ?? null; - const budget = window ? await window.readSessionBudget(sessionId) : null; - const target = { - model: typeof patch.model === 'string' ? patch.model : (live?.model ?? before.model ?? ''), - providerId: Object.hasOwn(patch, 'providerId') ? (patch.providerId as string | null) : before.providerId, - }; - const windowInput = await modelSwitchGateInput({ - agentKind: dbToMakerAgentKind(before.agentKind), - live: live ?? null, - stored: { model: before.model, providerId: before.providerId, contextTokens: before.contextTokens }, - target, - ...(window ? { - resolveRouteWindow: (agentKind: string, modelId: string, providerId: string | null) => - window.resolveRouteWindow(agentKind, modelId, providerId, budget, apply ? 'required' : undefined), - } : {}), - }); - assertCurrent?.(); - const legacyGate = assessRuntimeModelSwitchGate(windowInput); - if (apply && before.sdkSessionId && windowInput.runtimeRouteChanged && windowInput.agentKind !== 'codex') { - if (before.remoteHostId) throwIpcError('PRECONDITION_FAILED', MODEL_WINDOW_REBUILD_UNSUPPORTED); - if (live?.isTurnRunning?.()) throwIpcError('PRECONDITION_FAILED', 'the agent is still working; change the model after this turn'); - let contextWindow = windowInput.verifiedTargetWindow; - const currentContextWindow = windowInput.verifiedCurrentWindow; - const needsProtection = !windowInput.contextTokensKnown || windowInput.contextTokens > 0; - const piNeedsFinalWindow = windowInput.agentKind === 'pi' && needsProtection; - if (piNeedsFinalWindow && (!windowInput.piCanVerifyLiveWindow || !live || !deps.closeRejectedPiRuntime)) { - throwIpcError('PRECONDITION_FAILED', 'Pi final context window could not be verified; runtime selection was not changed'); - } - if (needsProtection && (!windowInput.contextTokensKnown || !currentContextWindow || !contextWindow)) { - throwIpcError('PRECONDITION_FAILED', 'target context window or current usage could not be verified; runtime selection was not changed'); - } - try { - if (piNeedsFinalWindow && live) { - // Pi's preview never certifies a different route. setModel reads native get_state - // before resolving. Keep the old DB route until that final window is checked. - liveModelApplied = true; - await applyLiveSessionSettings(live, patch, before); - apply.assertCurrent(); - const finalWindow = live.getUsageSnapshot?.()?.contextWindow; - if (!finalWindow || !Number.isFinite(finalWindow) || finalWindow <= 0) { - throwIpcError('PRECONDITION_FAILED', 'Pi final context window could not be verified; runtime selection was not changed'); - } - contextWindow = contextWindow ? Math.min(contextWindow, finalWindow) : finalWindow; - } - if (contextWindow && currentContextWindow && shouldRebuildForModelWindowSwitch({ - contextTokens: windowInput.contextTokens, - currentContextWindow, - targetContextWindow: contextWindow, - })) { - const prepared = await apply.prepareModelWindowSwitch(sessionId, { - contextWindow, - verifiedHandoffWindow: contextWindow, - nextInputChars: apply.nextInputChars, - recheckTargetPressure: true, - confirmedTargetPressure: true, - replacementRoute: { - ...target, - effort: typeof patch.effort === 'string' ? patch.effort : before.effort, - fastMode: patch.fastMode === true || patch.fastMode === false || patch.fastMode === 'ultrafast' - ? patch.fastMode : (before.fastMode ?? false), - }, - signal: apply.signal, - assertCanCommit: apply.assertCurrent, - }); - if (prepared !== 'not-needed' && prepared !== 'rebuilt') { - throwIpcError('PRECONDITION_FAILED', `model window preparation failed (${prepared}); runtime selection was not changed`); - } - routeRebuilt = prepared === 'rebuilt'; - } - } catch (error) { - if (liveModelApplied && live) await deps.closeRejectedPiRuntime?.(sessionId, live); - throw error; - } - } else if (legacyGate.reject === 'remote-shrink-rebuild') { - throwIpcError('PRECONDITION_FAILED', MODEL_WINDOW_REBUILD_UNSUPPORTED); - } + if (!before) throwIpcError('NOT_FOUND', 'Session 不存在'); + runtimeSelection = await deps.setModel(sessionId, typeof patch.model === 'string' ? patch.model : before.model, + Object.hasOwn(patch, 'providerId') ? patch.providerId : undefined, undefined, undefined); + patch = { ...patch }; + delete patch.model; + delete patch.providerId; + } + const budget = hasBudget ? patch.contextWindowBudget : undefined; + if (hasBudget) { + patch = { ...patch }; + delete patch.contextWindowBudget; } - const stored = live && patch.model === undefined && Object.hasOwn(patch, 'providerId') - ? await deps.readSessionForRun(sessionId) : null; - assertCurrent?.(); - if (!routeRebuilt && !liveModelApplied) await applyLiveSessionSettings(live, patch, stored); - const update: Record = { updatedAt: Date.now() }; + // A budget-only update writes no row (the budget is a preference, not a column), as updateSessionInDb. + if (budgetOnly) { + await deps.persistSessionFields(sessionId, { contextWindowBudget: budget }); + const [row] = await getDbClient().drizzle.select().from(sessionTable).where(eq(sessionTable.id, sessionId)).limit(1); + if (!row) throwIpcError('NOT_FOUND', 'Session 不存在'); + return sessionToCamel({ ...row, messageCount: 0 }); + } + // The moved fields through the desktop's mapper (a move to a project or a dialogue drops the explicit + // project), with a resume id the Claude transcript move persisted. + const setObj = sessionPatchToRow({ + workingDir: patch.workingDir, + workspaceKind: patch.workspaceKind, + snoozedUntil: patch.status === 'active' ? undefined : patch.snoozedUntil, + // The shared mapper clears both snooze fields on archive. Restore uses the transaction below. + status: patch.status === 'archived' ? 'archived' : undefined, + } as Parameters[0], { bumpUpdatedAt: false }); + await relocateClaudeTranscriptsForMove(explicitPorts[0]>({ + sid: sessionId, p: patch, beforeMove, + moveGuard: undefined, // see the entry below + dbClient, setObj, + })); + const update: Record = { ...(isSettingsOnly ? {} : { updatedAt: Date.now() }), ...setObj }; if (typeof patch.title === 'string') update.title = patch.title; - if (patch.status === 'active' || patch.status === 'archived') update.status = patch.status; if (patch.pinnedAt === null) update.pinnedAt = null; else if (typeof patch.pinnedAt === 'string') update.pinnedAt = Date.parse(patch.pinnedAt) || null; if (typeof patch.notificationsMuted === 'boolean') update.notificationsMuted = patch.notificationsMuted; - if (typeof patch.model === 'string') update.model = patch.model; - if (typeof patch.effort === 'string') update.effort = patch.effort; - if (typeof patch.permissionMode === 'string') update.permissionMode = patch.permissionMode; - if (typeof patch.fastMode === 'boolean' || patch.fastMode === 'ultrafast') update.fastMode = patch.fastMode; - if (typeof patch.planModeEnabled === 'boolean') update.planModeEnabled = patch.planModeEnabled; - if (patch.providerId === null || typeof patch.providerId === 'string') update.providerId = patch.providerId; - if (typeof patch.agentKind === 'string') update.agentKind = patch.agentKind === 'claude-code' ? 'cc' : patch.agentKind; - // Context recovery committed the entire replacement route in context.rebuild. - if (!routeRebuilt) { - try { - assertCurrent?.(); - await getDbClient().drizzle.update(sessionTable).set(update).where(eq(sessionTable.id, sessionId)); - } catch (error) { - if (liveModelApplied && live) await deps.closeRejectedPiRuntime?.(sessionId, live); - throw error; - } + // As writeSessionPatch: nothing to write is no write (a model pick alone is an intent, not a column). + if (Object.keys(update).length > 0) { + await getDbClient().drizzle.update(sessionTable).set(update).where(eq(sessionTable.id, sessionId)); } + // As the desktop's patchSessionMetaInDb: the other fields first, then the status transaction. The + // event below carries the whole patch, so the restore does not publish its own. + if (patch.status === 'active') await deps.restoreTaskToActive(sessionId, { publish: false }); const rows = await getDbClient().drizzle.select().from(sessionTable) .where(eq(sessionTable.id, sessionId)).limit(1); const row = rows[0]; - if (!row) throw new Error('session not found'); - deps.publish({ type: 'session_changed', action: 'update', sessionId, patch, status: row.status }); - return sessionToCamel({ ...row, messageCount: 0 }); + if (!row) throwIpcError('NOT_FOUND', 'Session 不存在'); + // As patchSessionMetaInDb, under the task's route lock (main.ts): an archive clears the task's runtime + // override and axes (the runtime cleanup bindHostSessionRuntimeHooks installs); other statuses do nothing. + cleanupSessionRuntimeForTerminalStatus(sessionId, patch.status); + await recordRecentWorkdirForMove({ + projectTargetChanged: patch.workspaceKind !== undefined || patch.workingDir !== undefined, + row, dbClient, ownerScope: null, + touchRecentWorkdir, + broadcastRecentWorkdirsChanged: path => deps.move.broadcastRecentWorkdirsChanged(path), + }); + // As updateSessionInDb's broadcast: the project the mapper dropped goes out with the move. + const published = setObj.projectDir !== undefined ? { ...patch, projectDir: row.projectDir } : patch; + const result = sessionToCamel({ ...row, messageCount: 0 }); + const snooze = patch.snoozedUntil !== undefined || patch.status === 'active' || patch.status === 'archived' + ? { snoozedUntil: result.snoozedUntil, snoozedAt: result.snoozedAt } : {}; + deps.publish({ type: 'session_changed', action: 'update', sessionId, patch: { ...published, ...snooze }, status: row.status }); + if (hasBudget) { + // A mixed update keeps its other fields when the budget cannot be saved (updateSessionInDb). + try { + await deps.persistSessionFields(sessionId, { contextWindowBudget: budget }); + } catch (error) { + console.warn('[sessions] write context window budget failed; row update already applied', { + sessionId, error: error instanceof Error ? error.message : String(error), + }); + } + } + return { ...result, ...(routeChange ? { runtimeSelection } : {}) }; + }; + return async (sessionId: string, patch: Record) => { + const fields = Object.keys(patch); + const unknown = fields.filter(key => !UPDATABLE_FIELDS.has(key) && !Object.hasOwn(DEDICATED_ENTRIES, key)); + if (unknown.length > 0) throwIpcError('INVALID_PARAMS', `unsupported session field: ${unknown.join(', ')}`); + const dedicated = fields.filter(key => Object.hasOwn(DEDICATED_ENTRIES, key)); + if (dedicated.length > 0) { + throwIpcError('UNSUPPORTED_CAPABILITY', dedicated + .map(key => `${key} must be changed through ${DEDICATED_ENTRIES[key]}`).join('; ')); + } + // The same date validation as desktop updateSessionInDb, before any row or other setting changes. + const snoozedUntil = patch.snoozedUntil; + if (snoozedUntil !== undefined && snoozedUntil !== null && snoozedUntil !== INDEFINITE_SNOOZE_UNTIL) { + const ms = typeof snoozedUntil === 'string' ? Date.parse(snoozedUntil) : NaN; + if (!Number.isFinite(ms) || ms <= Date.now() || ms > Date.now() + 366 * 86_400_000) { + throwIpcError('INVALID_PARAMS', 'snoozedUntil must be a future ISO timestamp within one year'); + } + } + const dbClient = getDbClient(); + // As updateSessionInDb: a working-directory change runs under the task's route lock and its worktree + // locks (re-entering the route lock main.ts holds); anything else runs at once. + return withSessionWorkingDirMoveLocks(explicitPorts[0]>({ + sid: sessionId, p: patch, + // The desktop's MCP move tool's guard (updateSessionInDb's moveGuard); the Host has no MCP move tool + // (host-tools.ts creates the MCP providers without moveSession). + moveGuard: undefined, + db: dbClient.drizzle, + update: () => applyUpdate(sessionId, patch, fields, dbClient), + })); }; } diff --git a/apps/host/src/agent/shared-global-skills.ts b/apps/host/src/agent/shared-global-skills.ts new file mode 100644 index 00000000000..5d50a61a7ef --- /dev/null +++ b/apps/host/src/agent/shared-global-skills.ts @@ -0,0 +1,54 @@ +/** + * The desktop's shared global Skill preparation on the Host (release table row 25, 25b): the built-in + * Skill bundle this Host carries (user decision: the personal Host ships its own copy), the legacy + * built-in link migration and the shared home-level Skill links, through the same core + * (maker-host/sharedGlobalSkillsPreparationCore.ts) and the same stable-owner boundary. The Host + * binds the desktop's own preparation scope, its configured profile and app-data roots, and the + * bundle root of its layout. + * + * While a desktop that opens this profile's database is running (coexistence plan A, the input + * queue's hold), the shared projections belong to that desktop: preparation is skipped, nothing is + * written, and callers carry on with what is already there (reviewer decision, 2026-11-17). + */ +import { + createSharedGlobalSkillsPreparation, + preparationScope, + type SharedGlobalSkillsPreparationPorts, +} from '../../../desktop/src/main/maker-host/sharedGlobalSkillsPreparationCore.ts'; +import { markClaudeSessionObserved } from '../../../desktop/src/main/maker-host/shared-global-skills.ts'; +import { getAppDataDir, getUserDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { explicitPorts } from './explicit-ports.ts'; + +export interface HostSharedGlobalSkills { + /** Refresh unless a desktop holds the profile; resolves either way (failures are logged by the core). */ + ensureSharedGlobalSkills(): Promise; + /** The desktop's Claude getAuthEnv step: a Claude CLI is about to start, then refresh. */ + beforeClaudeLaunch(): Promise; +} + +export function createHostSharedGlobalSkills(ports: { + /** The input queue's desktop hold (main.ts profileHold); true while a desktop uses the profile. */ + isProfileHeld(): boolean; + /** The built-in Skill bundle of this Host (runtime-layout.mjs systemSkillsDir). */ + bundledSystemSkillsRoot(): string; +}): HostSharedGlobalSkills { + const preparation = createSharedGlobalSkillsPreparation(explicitPorts({ + preparationScope, + bundledSystemSkillsRoot: () => ports.bundledSystemSkillsRoot(), + userDataDir: () => getUserDataDir(), + appDataDir: () => getAppDataDir(), + })); + const ensureSharedGlobalSkills = async () => { + if (ports.isProfileHeld()) return; + await preparation.ensureSharedGlobalSkills(); + }; + return { + ensureSharedGlobalSkills, + async beforeClaudeLaunch() { + // As the desktop's DesktopClaudeAuthAdapter.getAuthEnv: opening the ~/.claude/skills projection + // gate (#9282) comes first, even for a session whose ~/.claude does not exist yet. + markClaudeSessionObserved(); + await ensureSharedGlobalSkills(); + }, + }; +} diff --git a/apps/host/src/agent/silent-stop.ts b/apps/host/src/agent/silent-stop.ts new file mode 100644 index 00000000000..288b5a8883a --- /dev/null +++ b/apps/host/src/agent/silent-stop.ts @@ -0,0 +1,214 @@ +import type { AgentEvent, Session } from '@cindy/maker-core'; +import { SilentStopTurnLeaseGate } from '../../../desktop/src/main/maker-ipc/sessionTurnLease.ts'; +import { handleSilentStopTurnEndWithPorts, type SilentStopTurnEndPorts } from '../../../desktop/src/main/maker-ipc/silentStopTurnEnd.ts'; +import { + settleSilentStopDoneWithPorts, + type SilentStopSettlePorts, + type SilentStopSettleReason, +} from '../../../desktop/src/main/maker-ipc/silentStopSettle.ts'; +import { surfaceSilentStopFailureWithPorts } from '../../../desktop/src/main/maker-ipc/silentStopFailure.ts'; +import { SILENT_STOP_DECISION_DELAY_MS, type SilentStopAutoResumeGuard } from '../../../desktop/src/main/maker-ipc/silentStopAutoResume.ts'; +import type { SessionListActivityTracker } from '../../../desktop/src/main/maker-ipc/sessionTurnActivityTracker.ts'; +import { noteClaudeSessionTurnState } from '../../../desktop/src/main/maker-host/claude-session-background-activity.ts'; +import { explicitPorts } from './explicit-ports.ts'; +import type { HostUsageRecording } from './usage-recording.ts'; + +export interface HostSilentStopPorts { + /** The task's input coordinator (input-queue.mjs); read when the decision runs. */ + coordinator: { + hasPendingQueuedWork(sessionId: string): boolean; + noteHostTurnContinuation(sessionId: string, vendorTurnGeneration: number): void; + noteHostTurnContinuationFailed(sessionId: string, adoptedVendorTurnGeneration: number): void; + }; + /** The silent-stop guard of this owner runtime (auto-resume.ts); without it nothing is scheduled. */ + guard(): SilentStopAutoResumeGuard | null; + /** The task list's activity tracker (product-turn.ts), if the runtime has one. */ + listActivity(): Pick | null; + /** Coexistence plan A (input-queue.mjs holdForDesktop): the profile is the desktop's while held. */ + isProfileHeld(): boolean; + /** The owner runtime is stopping: an account boundary or the Host's shutdown began (input-queue.mjs beginStop). */ + isStopping(): boolean; + /** A row of the task (the continuation's user row, the exhausted marker), behind its reply rows. */ + writeRow: SilentStopTurnEndPorts['createDbMessage']; + /** The exhausted banner's error event, to the task's clients (the window and /api/chat). */ + publishFailure(sessionId: string, turn: Turn, data: object): void; + /** The executor still runs this turn record for the task (no newer turn replaced it). */ + isTurnCurrent(sessionId: string, turn: Turn): boolean; + /** This turn record is the task's and still waits for its silent-stop decision (not continued, not ended). */ + isAwaitingDecision(sessionId: string, turn: Turn): boolean; + /** The continuation reserved a new generation for this turn: its events are this turn's from now on. */ + adoptGeneration(turn: Turn, generation: number): void; + /** The continuation was not dispatched: the turn goes back to the generation it had. */ + rollbackGeneration(turn: Turn, generation: number): void; + /** The turn's change record ends (turn-change-set/store.ts, complete). */ + finalizeChangeSet(sessionId: string, turn: Turn): void; + /** The turn ends without a continuation (turn-executor.mjs finish, which hands the coordinator its done). */ + endTurn(sessionId: string, turn: Turn, reason: SilentStopSettleReason): void; + /** The usage records' product-turn trackers (usage-recording.ts), when the Host records usage. */ + usageTrackers(): Pick | null; + log: SilentStopTurnEndPorts['log']; +} + +/** + * The desktop's silent-stop continuation on the Node Host. A turn the engine ended with an empty reply + * (its done carries `silentStop`, the Claude Code and Pi translators) is not over yet. As the desktop's + * turn observer (sessionTurnObserver.ts onTerminal), its terminal is scheduled once and the runtime keeps + * its generation for the continuation (claimHostTurnContinuation, so neither retirement nor idle release + * closes it meanwhile). As the desktop's preparation (sessionEventPreparation.ts), the decision comes + * SILENT_STOP_DECISION_DELAY_MS later, through the shared silentStopTurnEnd.ts. A hidden "继续" continues + * the same turn on a new generation, or the turn settles (silentStopSettle.ts): skipped when work is + * queued or the guard declines, or exhausted with the "继续" banner (silentStopFailure.ts). + * + * The desktop's settle also idles its turn tracker, wakes the coordinator, lands a pending credential + * switch and runtime control, and notifies its Codex restart services. On the Host one step does all of + * that: the turn's finish, which hands the coordinator its done once the rows settle and then runs the + * Host's settled-turn hooks (input-queue.mjs onTerminal, onSessionSettled). Those ports are bound empty + * here with that reason. + */ +export function createHostSilentStop(ports: HostSilentStopPorts) { + const gate = new SilentStopTurnLeaseGate(); + + function settlePorts(sessionId: string, turn: Turn, reason: SilentStopSettleReason): SilentStopSettlePorts { + return explicitPorts({ + silentStopTurnLeaseGate: gate, + // The desktop's turn lease (sessionTurnLease.ts) answers whether a newer turn of the task started; + // on the Host that is the executor's turn record. The runtime's claim is released either way. + sessionTurnLeaseTracker: { + markTurnEndedAndCheckIdle: async (_sessionId, _turnLeaseId, onSettled) => { + try { + return ports.isTurnCurrent(sessionId, turn); + } finally { + onSettled?.(); + } + }, + }, + finalizeTurnChangeSet: async () => { ports.finalizeChangeSet(sessionId, turn); }, + sessionListActivityTracker: { commit: id => ports.listActivity()?.commit(id) }, + // The product turn's wall clock and usage target of the Host's usage records (usage-recording.ts). + productTurnWallClockTracker: { clear: id => ports.usageTrackers()?.productTurnWallClockTracker.clear(id) }, + productTurnUsageTargetTracker: { clear: id => ports.usageTrackers()?.productTurnUsageTargetTracker.clear(id) }, + // The turn's finish below (endTurn). + sessionTurnActivityTracker: { scheduleIdleAfterTerminalBroadcast: () => {} }, + noteClaudeSessionTurnState, + agentInputCoordinatorHolder: { + onTurnEvent: () => ports.endTurn(sessionId, turn, reason), + // endTurn wakes the other tasks' credential waiters after this turn's writes settle. + onExternalTurnSettled: () => {}, + }, + // The turn's finish (endTurn) runs the Host's settled-turn hooks: these happen there. + settlePendingCredentialSwitch: () => {}, + settlePendingSessionRuntimeControlHolder: undefined, + deferredCodexRestartHolder: undefined, + gatewayCodexRestartHolder: undefined, + // The Host runs no remote Codex tasks. + refreshRemoteCodexMcpOnTurnSettledHolder: undefined, + // No in-process runner (scheduler, hook, IM) waits on a silent stop on the Host. + fireSilentStopSettled: () => {}, + log: ports.log, + }); + } + + function turnEndPorts(sessionId: string, turn: Turn, guard: SilentStopAutoResumeGuard): SilentStopTurnEndPorts { + return explicitPorts({ + silentStopTurnLeaseGate: gate, + agentInputCoordinatorHolder: { + // While the profile is held, its writes are the desktop's; once an account boundary or the shutdown + // began, a continuation would be a write torn down at once. Either way none is sent, as no queued + // input would be, and the turn settles as one that had queued work (as an interruption once stopping). + hasPendingQueuedWork: id => ports.isProfileHeld() || ports.isStopping() || ports.coordinator.hasPendingQueuedWork(id), + noteHostTurnContinuation: (id, generation) => { + ports.adoptGeneration(turn, generation); + ports.coordinator.noteHostTurnContinuation(id, generation); + }, + noteHostTurnContinuationFailed: (id, generation) => { + ports.rollbackGeneration(turn, generation); + ports.coordinator.noteHostTurnContinuationFailed(id, generation); + }, + }, + silentStopAutoResumeGuard: guard, + sessionListActivityTracker: { + captureContinuation: id => ports.listActivity()?.captureContinuation(id) ?? (() => {}), + }, + // The product turn's wall clock of the Host's usage records (usage-recording.ts). + productTurnWallClockTracker: { + preserveForContinuation: id => ports.usageTrackers()?.productTurnWallClockTracker.preserveForContinuation(id), + }, + // The IM runtime-recovery notice: the Host has no IM channels. + advanceRuntimeRecoveryNotice: () => {}, + createDbMessage: ports.writeRow, + settleSilentStopDone: (id, reason, turnLeaseId, runtime, generation) => + settleSilentStopDoneWithPorts(id, reason, turnLeaseId, runtime, generation, settlePorts(sessionId, turn, reason)), + surfaceSilentStopExhaustedBanner: (id, cause) => surfaceSilentStopFailureWithPorts(id, cause, { + createDbMessage: ports.writeRow, + broadcast: data => ports.publishFailure(id, turn, data), + log: ports.log, + }), + log: ports.log, + }); + } + + // Host protection; the desktop has none (there the same failure only leaves its idle unsent, the release + // table's desktop items). A decision that fails before its settle (a step of the shared code throws) would + // leave the turn open, and the task's next inputs queued, until a restart. A turn still waiting for its + // decision ends here as the shared settle ends one whose continuation failed: each step on its own. + function failClosed(session: Session, turn: Turn, turnLeaseId: string, generation: number): void { + if (!ports.isAwaitingDecision(session.id, turn)) return; + gate.settle(session.id, turnLeaseId); + const steps = [ + () => session.settleHostTurnContinuation(generation), + () => ports.finalizeChangeSet(session.id, turn), + () => ports.listActivity()?.commit(session.id), + () => noteClaudeSessionTurnState(session.id, false), + () => ports.endTurn(session.id, turn, 'send-failed'), + ]; + for (const step of steps) { + try { + step(); + } catch (error) { + ports.log.warn('silent-stop fail-closed step failed', { + sessionId: session.id, error: error instanceof Error ? error.name : typeof error, + }); + } + } + } + + return { + /** + * At a silent-stop done of the task's current turn, before anything else handles it: 'scheduled' + * (one decision for this terminal, the runtime keeps its generation), 'duplicate' (the desktop drops + * a second terminal of the same generation), or null (not a silent stop, or no guard). + */ + schedule(session: Session, event: AgentEvent): 'scheduled' | 'duplicate' | null { + if (event.type !== 'done' || (event.data as { silentStop?: unknown } | null | undefined)?.silentStop !== true + || !ports.guard()) return null; + const generation = typeof event.sessionTurnGeneration === 'number' ? event.sessionTurnGeneration : session.getTurnGeneration(); + if (!gate.schedule(session.id, event, `${session.instanceId}:${generation}`)) return 'duplicate'; + session.claimHostTurnContinuation(generation); + return 'scheduled'; + }, + /** This event is the silent-stop done a decision was scheduled for. */ + isScheduled: (event: AgentEvent) => gate.turnLeaseIdForEvent(event) !== undefined, + /** The decision, SILENT_STOP_DECISION_DELAY_MS after the done (sessionEventPreparation.ts). */ + decideLater(session: Session, turn: Turn, event: AgentEvent): void { + const turnLeaseId = gate.turnLeaseIdForEvent(event); + const guard = ports.guard(); + if (!turnLeaseId || !guard) return; + const doneAt = Date.now(); + const turnOrigin = event.turnOrigin; + const generation = typeof event.sessionTurnGeneration === 'number' ? event.sessionTurnGeneration : session.getTurnGeneration(); + setTimeout(() => { + void handleSilentStopTurnEndWithPorts(session, doneAt, turnLeaseId, turnOrigin, turnEndPorts(session.id, turn, guard)) + .catch(error => { + ports.log.warn('silent-stop decision failed', { + sessionId: session.id, error: error instanceof Error ? error.name : typeof error, + }); + failClosed(session, turn, turnLeaseId, generation); + }); + }, SILENT_STOP_DECISION_DELAY_MS); + }, + /** A newer provider turn of the task, or a terminal that is not a silent stop (sessionTurnObserver.ts). */ + supersede: (sessionId: string) => gate.supersede(sessionId), + /** The runtime is no longer the task's (sessionTurnObserver.ts teardown). */ + released: (sessionId: string, instanceId: string) => gate.supersedeOwnedBy(sessionId, `${instanceId}:`), + }; +} diff --git a/apps/host/src/agent/skill-projection-boundary.ts b/apps/host/src/agent/skill-projection-boundary.ts new file mode 100644 index 00000000000..2a57485c180 --- /dev/null +++ b/apps/host/src/agent/skill-projection-boundary.ts @@ -0,0 +1,71 @@ +/** + * Read-only view of the Skill projection owner boundary for this Host profile (release table row 25, + * step 25a). + * + * The boundary module is the desktop's own (`authBoundaryQuarantine.ts`). It reads the profile from + * `getUserDataDir()`, which the Host pins at startup, and its passive check defaults to "not + * passive": a Host never joins another process's shared dev profile. Under option A the window + * commits the owner and the Host only joins it, so nothing here writes or takes the boundary lock. + * The real decision still happens under the lock in each mutation (shared Skill projection, Codex + * home preparation), and a stale read here cannot authorize anything. + */ +import { + isGhostSkillProjectionBoundaryStableForOwner, + readGhostSkillProjectionBoundaryState, +} from '../../../desktop/src/main/authBoundaryQuarantine.ts'; + +/** + * A category only: no owner id (another account's id must not reach the status interface). + * A state file that exists but cannot be read is `missing-or-invalid`, as the boundary itself + * treats it (fail closed, logged by the module); `unreadable` means the check itself threw, for + * example the profile is not configured. + */ +export type SkillProjectionBoundaryStatus = + | 'stable' + | 'other-owner' + | 'pending' + | 'quarantined' + | 'missing-or-invalid' + | 'unreadable'; + +export function readSkillProjectionBoundaryStatus(ownerId: string): SkillProjectionBoundaryStatus { + try { + // State first, then the stability check: the window may commit between the two reads, and a + // commit that lands in between then reads as `stable` rather than as a stale category. + const state = readGhostSkillProjectionBoundaryState(); + if (isGhostSkillProjectionBoundaryStableForOwner(ownerId)) return 'stable'; + if (!state) return 'missing-or-invalid'; + // Stable for this owner and still refused: the durable quarantine marker (the Host commits + // nothing, so its in-process quarantine flag never turns on). Trimmed as the module compares. + if (state.phase === 'stable') return state.ownerId === ownerId.trim() ? 'quarantined' : 'other-owner'; + return state.phase; + } catch { + return 'unreadable'; + } +} + +/** The one log call the observer makes; main.ts binds createLogger('host-skill-projection'). */ +export interface SkillProjectionBoundaryLog { + warn(message: string, fields: { boundary: SkillProjectionBoundaryStatus }): void; +} + +/** + * Reads the status for each caller (startup and every authorized /health) and logs a warning when + * it turns to a non-stable category. The log carries the category only, no owner id or path. + */ +export function createSkillProjectionBoundaryObserver( + log: SkillProjectionBoundaryLog, +): (ownerId: string) => SkillProjectionBoundaryStatus { + let lastLogged: SkillProjectionBoundaryStatus | null = null; + return (ownerId) => { + const boundary = readSkillProjectionBoundaryStatus(ownerId); + if (boundary === 'stable') { + lastLogged = null; + } else if (boundary !== lastLogged) { + lastLogged = boundary; + // Until the window commits this account here, the boundary's mutations refuse to run for it. + log.warn('skill projection boundary is not stable for this Host owner', { boundary }); + } + return boundary; + }; +} diff --git a/apps/host/src/agent/skill-projection-owner.ts b/apps/host/src/agent/skill-projection-owner.ts new file mode 100644 index 00000000000..a95fcdb7610 --- /dev/null +++ b/apps/host/src/agent/skill-projection-owner.ts @@ -0,0 +1,145 @@ +/** + * Who publishes the Skill projection owner on a Host profile (release table row 25, 25b; reviewer + * decision (a)). + * + * Under option A the window commits the owner and the Host joins it. A Host on its own profile has + * no window, so `cindy-host login` commits there, as the desktop's sign-in does, and the resident + * process (serve) never does: serve injects a refusal before it loads anything that reads the + * boundary (guarded, so the injection cannot go missing), login injects the allowance. + * + * The owner transition's disk part is the desktop's: before a different owner becomes visible, the + * Ghost Skill links of every owner projection root are revoked (desktop suspendAllGhosts: + * removeGhostSkillLinksForRoots over listGhostOwnerProjectionRoots, with the shared-roots lock), and + * a blocker aborts. The runtime part of the desktop's teardown has no counterpart: login requires + * that no account runtime of another owner is running (login-cli.mjs), and Pi durable Subagent + * runners end with the Host (release table, m1-cp18c2). + */ +import path from 'node:path'; + +import { + configureProjectionBoundaryOwnerCommit, + isGhostSkillProjectionBoundaryStableForOwner, + withSharedSkillRootsLock, + withStableOwnerBoundaryMutation, +} from '../../../desktop/src/main/authBoundaryQuarantine.ts'; +import { ghostSkillPluginRoot, removeGhostSkillLinksForRoots } from '../../../desktop/src/main/cindy-brain/skillSlot.ts'; +import { ownerScopedPath } from '../../../desktop/src/main/dataOwnerPath.ts'; +import { listLegacyOwnerProjectionRoots } from '../../../desktop/src/main/ownerProjectionRoots.ts'; + +/** serve: this process never publishes the projection owner. */ +export function refuseSkillProjectionOwnerCommit(): void { + configureProjectionBoundaryOwnerCommit(() => false); +} + +/** `cindy-host login`: the one party that publishes the owner of a Host's own profile. */ +export function allowSkillProjectionOwnerCommit(): void { + configureProjectionBoundaryOwnerCommit(() => true); +} + +/** + * The desktop's listGhostOwnerProjectionRoots (cindy-brain/index.ts) for an explicit owner: that + * owner's brain, cindy-brain and ghost-install-state, plus every legacy and per-owner root. + */ +export function ghostOwnerProjectionRoots(userDataDir: string, ownerId: string | null): string[] { + return [...new Set([ + ...(ownerId ? ['brain', 'cindy-brain', 'ghost-install-state'].map(part => ownerScopedPath(userDataDir, ownerId, part)) : []), + ...listLegacyOwnerProjectionRoots(userDataDir), + ])]; +} + +/** + * Revoke the Ghost Skill links of an outgoing owner, as the desktop's suspendAllGhosts does. + * Throws when a link could not be inspected or removed (the account boundary must not proceed). + */ +export async function revokeOwnerSkillProjections(userDataDir: string, ownerId: string | null): Promise<{ warnings: string[] }> { + const roots = ghostOwnerProjectionRoots(userDataDir, ownerId); + const cleanup = await removeGhostSkillLinksForRoots(roots, undefined, + roots.map(root => path.join(ghostSkillPluginRoot(root), 'skills')), + withSharedSkillRootsLock); + if (cleanup.blockers.length > 0) throw new Error(`ghost owner skill cleanup incomplete (${cleanup.blockers.length})`); + return { warnings: cleanup.warnings }; +} + +export type LogoutSkillSweep = 'revoked' | 'skipped-profile-held' | 'skipped-not-stable' | 'failed'; + +/** + * serve's logout (reviewer decision (ii)): the desktop clears an outgoing owner's projections when it + * signs out; serve cannot commit, so it runs the same disk sweep inside a stable-owner mutation + * instead, and the boundary stays stable(owner) until the next `cindy-host login` transitions it. + * + * - A desktop that opens this profile's database is running (the input queue's hold): the shared + * projections are that desktop's; nothing is swept and the logout itself still succeeds. + * - The boundary is no longer stable for this owner: in client mode the window signed out first and + * its own transition already swept, so serve does nothing (each side acts only on stable(owner), + * under the same owner lock; a second sweep finds nothing to remove). + * Never throws: logout must not be refused by this step. + */ +export async function sweepOwnerSkillProjectionsAtLogout(input: { + userDataDir: string; + ownerId: string; + isProfileHeld(): boolean; + warn(message: string, fields: { outcome: LogoutSkillSweep }): void; +}): Promise { + if (input.isProfileHeld()) { + input.warn('skill projection sweep skipped at logout: a desktop is using this profile', { outcome: 'skipped-profile-held' }); + return 'skipped-profile-held'; + } + if (!isGhostSkillProjectionBoundaryStableForOwner(input.ownerId)) { + input.warn('skill projection sweep skipped at logout: the boundary is no longer this owner\'s', { outcome: 'skipped-not-stable' }); + return 'skipped-not-stable'; + } + try { + await withStableOwnerBoundaryMutation(input.ownerId, () => revokeOwnerSkillProjections(input.userDataDir, input.ownerId)); + return 'revoked'; + } catch { + // Includes the boundary changing between the check above and the locked re-check. + input.warn('skill projection sweep at logout did not run to completion', { outcome: 'failed' }); + return 'failed'; + } +} + +/** + * `cindy-host login`'s session save and owner commit, in the desktop's order (authManager + * completeLogin → commitDesktopLoginSessions): under the account vault's cross-process lock, save the + * session, then publish the owner through the boundary's transition; if the commit fails, put the + * previous session record back (or remove the new one) before the lock is released. + * + * The transition's teardown is the disk part of the desktop's (revokeOwnerSkillProjections for the + * outgoing owner); the boundary module writes quarantine and pending first and keeps them on failure. + * previousOwnerId is the owner the boundary last published, else the profile's single account + * database, else none; a wrong guess still forces a transition (the boundary compares it). + */ +export async function commitLoginSessionAndOwner(input: { + userDataDir: string; + record: string; + nextOwnerId: string; + store: { read(key: string): string | null; write(key: string, value: string): void; remove(key: string): void }; + sessionKey: string; + previousOwnerId: string | null; + withVaultLock(task: () => Promise): Promise; + commitOwner(options: { + previousOwnerId: string | null; + nextOwnerId: string; + prepareTransition(context: { ownerChanged: boolean }): Promise; + commit(): void; + }): Promise; +}): Promise { + await input.withVaultLock(async () => { + const previousRecord = input.store.read(input.sessionKey); + input.store.write(input.sessionKey, input.record); + try { + await input.commitOwner({ + previousOwnerId: input.previousOwnerId, + nextOwnerId: input.nextOwnerId, + // Revoke every owner projection root's Ghost Skill links, outgoing owner included, as the + // desktop's suspendAllGhosts at an account boundary (also on a same-owner repair). + prepareTransition: async () => { await revokeOwnerSkillProjections(input.userDataDir, input.previousOwnerId); }, + commit: () => undefined, + }); + } catch (error) { + if (previousRecord === null) input.store.remove(input.sessionKey); + else input.store.write(input.sessionKey, previousRecord); + throw error; + } + }); +} diff --git a/apps/host/src/agent/start-options.ts b/apps/host/src/agent/start-options.ts index d55a3758350..c375e64757f 100644 --- a/apps/host/src/agent/start-options.ts +++ b/apps/host/src/agent/start-options.ts @@ -181,6 +181,8 @@ export function createHostStartOptions(ports: HostStartOptionsPorts) { resolveConfiguredContextWindow: budget.resolveConfiguredContextWindow, /** The task's window budget the user set (null: the route's default). */ readStoredSessionContextWindowBudget: budget.readStoredSessionContextWindowBudget, + /** Whether a budget change changes a route's effective window (the budget core, as the desktop's). */ + contextWindowBudgetChangesEffectiveWindow: budget.contextWindowBudgetChangesEffectiveWindow, prepareStartOptions, onBeforeStart, async onStartFailed({ sessionId, options, runtimeMayBeAlive }: SessionStartFailureContext): Promise { diff --git a/apps/host/src/agent/task-restore.ts b/apps/host/src/agent/task-restore.ts new file mode 100644 index 00000000000..0c8a2b9df3b --- /dev/null +++ b/apps/host/src/agent/task-restore.ts @@ -0,0 +1,87 @@ +import { eq } from 'drizzle-orm'; +import { sessions } from '../../../desktop/src/main/localDb/schema.ts'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; +import { getDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { noteSessionsRestoring, setSessionRestoreObserver } from '../../../desktop/src/main/localDb/sessionRestoreRetention.ts'; +import { recordTaskArchiveRestores } from '../../../desktop/src/main/task-management/restoreObserver.ts'; +import { restoreArchivedTaskForSend } from '../../../desktop/src/main/localDb/archivedTaskRestore.ts'; + +type Publish = (event: Record) => void; + +/** + * Making an archived task active again, on the Host. The desktop restores through the active branch + * of `patchSessionMetaInDb` (localDb/ipc/sessions.ts); the Host keeps its three steps that decide + * the result: + * 1. `noteSessionsRestoring`: the shared retention observer records when the task came back + * (bindTaskRestoreRetention, installed by main.ts as the desktop's task management does); + * 2. the database transaction `sessions.setStatus` to active, which refuses a deleted task and a + * teammate's own lane and detaches a group lane, as on the desktop; + * 3. the change is published to clients. + * Agent Island and the native thread archive sync are not on the Host. + * + * Both Host routes to an active task use it: sending to an archived task (the send transaction's + * `restoreArchivedSessionForSend`) and the task list's restore (`/sessions/update`). + */ +/** + * The restore observer the desktop's task management installs (task-management/service.ts): before a + * task is made active, record when, in the owner's task management file the desktop reads. The Host runs + * no idle archiving; the desktop does when it opens this profile itself, and keeps a task restored here + * for its retention days instead of archiving it again. Returns the uninstall. + */ +export function bindTaskRestoreRetention(): () => void { + setSessionRestoreObserver(recordTaskArchiveRestores); + return () => setSessionRestoreObserver(null); +} + +export function createHostTaskRestore(deps: { getOwner(): unknown; publish: Publish; isHeldForDesktop?(): boolean }) { + async function restoreTaskToActive( + sessionId: string, + options: { signal?: AbortSignal; publish?: boolean } = {}, + ): Promise { + const owner = deps.getOwner(); + const database = getDbClient(); + const assertCurrent = () => { + if (deps.getOwner() !== owner || getDbClient() !== database) { + throw Object.assign(new Error('Task owner changed'), { code: 'PRECONDITION_FAILED' }); + } + if (options.signal?.aborted) { + throw Object.assign(new Error('Session send aborted'), { code: 'PRECONDITION_FAILED' }); + } + }; + await noteSessionsRestoring([sessionId], database.drizzle); + assertCurrent(); + await database.tx('sessions.setStatus', { sessionIds: [sessionId], status: 'active' }); + if (options.publish !== false && deps.getOwner() === owner) { + deps.publish({ type: 'session_changed', action: 'update', sessionId, + patch: { status: 'active', snoozedUntil: null, snoozedAt: null }, status: 'active' }); + } + } + + function requireActiveDuringHold(id: string): boolean { + if (!deps.isHeldForDesktop?.()) return false; + const row = getDbClient().drizzle.select({ status: sessions.status }).from(sessions).where(eq(sessions.id, id)).get(); + if (row?.status !== 'active') { + throwIpcError('PRECONDITION_FAILED', 'The interrupted turn cannot resume while its task is inactive and the profile is held'); + } + return true; + } + + return { + restoreTaskToActive, + /** + * The send transaction's port, as the desktop passes it: the restore takes the task's route lock + * (the Host installs the send lock as that bridge in main.ts, as the desktop's registerAll does), + * re-entrantly when the send already holds it; context recovery's replay does not hold it. + */ + async restoreArchivedSessionForSend(sessionId: string) { + if (requireActiveDuringHold(sessionId)) return; + await restoreArchivedTaskForSend(sessionId, {}, { + async patchSessionMetaInDb(id, _patch, options) { + if (!requireActiveDuringHold(id)) await restoreTaskToActive(id, { signal: options.signal }); + }, + captureOwnerScope: () => deps.getOwner(), + isOwnerScopeCurrent: owner => owner === deps.getOwner(), + }); + }, + }; +} diff --git a/apps/host/src/agent/task-runtime-plugins.ts b/apps/host/src/agent/task-runtime-plugins.ts new file mode 100644 index 00000000000..6d46df89f74 --- /dev/null +++ b/apps/host/src/agent/task-runtime-plugins.ts @@ -0,0 +1,95 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { Maker } from '@cindy/maker-core'; +import type { createRuntimePluginHost } from '../../../desktop/src/main/cindy-brain/runtimePluginHostCore.js'; +import { + createPrepareTaskRuntimePluginTurn, createRuntimePluginInputHooks, createRuntimePluginSettingsHandler, createRuntimePluginTaskPrompt, +} from '../../../desktop/src/main/maker-ipc/runtimePluginTaskBindings.js'; +import { revokeTrustedDesktopQueuedOrigin } from '../../../desktop/src/main/maker-ipc/queuedInputOrigin.js'; +import { writeRuntimePluginSettings } from '../../../desktop/src/main/maker-host/runtime-plugin-settings.js'; +import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from '../../../desktop/src/main/device-link/broadcast-tap.js'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; +import type { Logger } from '../../../desktop/src/main/logger.js'; +import type { createHostRuntimeSelection } from './runtime-selection.js'; + +type PluginHost = ReturnType; +type RuntimeSelection = ReturnType; + +export function createHostTaskRuntimePlugins({ + getMaker, pluginHost, selection, publish, log, +}: { + getMaker(): Pick; + pluginHost: PluginHost; + selection: Pick; + publish(event: Record): void; + log: Pick; +}) { + const maker: ReturnType = { + getSession: id => getMaker().getSession(id), + createSession: (opts, signal) => getMaker().createSession(opts, signal), + closeSession: (id, reason) => getMaker().closeSession(id, reason), + }; + const runtimePluginControl = pluginHost.getGhostRuntimePluginControl(); + const turnGuard = new AsyncLocalStorage<() => void>(); + const prepare = createPrepareTaskRuntimePluginTurn({ + maker, runtimePluginControl, readSessionRuntimeProfiles: selection.readSessionRuntimeProfiles, + isPluginModelRouteAvailableNow: pluginHost.isPluginModelRouteAvailableNow, log, + applyRoute(id, route, assertVerdict) { + const assertTurn = turnGuard.getStore(); + if (!assertTurn) throw new Error('Plugin route has no originating Host turn'); + return selection.applyPluginRoute(id, route, assertVerdict, assertTurn); + }, + }); + return { + ...createRuntimePluginTaskPrompt({ + maker, ghostTaskSystemPrompt: pluginHost.ghostTaskSystemPrompt, + readSessionRuntimeProfiles: selection.readSessionRuntimeProfiles, + }), + ...createRuntimePluginInputHooks({ + getStableSessionForTurnBoundary: maker.getSession, + screenGhostUserMessage: pluginHost.screenGhostUserMessage, + // Agent Island only previews input on the desktop. A rewritten steer can + // still carry a previously restored local command receipt, so revoke it. + rollbackAgentIslandUserPrompt() {}, revokeTrustedDesktopQueueOrigin: revokeTrustedDesktopQueuedOrigin, + broadcastGhostMessageBlocked: payload => publish({ type: 'plugin_push', channel: 'ghosts:user-message-blocked', payload }), + broadcastGhostMessageRewritten: payload => publish({ type: 'plugin_push', channel: 'ghosts:user-message-rewritten', payload }), + }), + forgetSession: runtimePluginControl.forgetSession, + composeRuntimeContext: pluginHost.composeGhostRuntimeContext, + prepareRuntimeTurn(id: string, message: unknown, signal: AbortSignal | undefined, assertTurn: () => void) { + return turnGuard.run(assertTurn, () => prepare(id, message, signal)); + }, + }; +} + +export function createHostRuntimePluginSettings(deps: { + maker: Pick; + selection: Pick; + resolveGhostControlPointPlugin: PluginHost['resolveGhostControlPointPlugin']; + profileHold(): string | null; + holdGeneration(): number; + publish(event: Record): void; +}) { + return (sessionId: unknown, value: unknown) => { + const hold = deps.holdGeneration(); + const owner = captureDataOwnerBroadcastScope(); + const assertCurrent = () => { + const held = deps.profileHold(); + if (held || hold !== deps.holdGeneration()) + throwIpcError('PRECONDITION_FAILED', held ?? 'HOST_PROFILE_IN_USE_BY_DESKTOP: Profile ownership changed'); + if (!isDataOwnerBroadcastScopeCurrent(owner)) throwIpcError('PRECONDITION_FAILED', 'Account changed'); + }; + return createRuntimePluginSettingsHandler({ + maker: deps.maker, + assertCaller: assertCurrent, + captureDataOwnerBroadcastScope: () => owner, + isDataOwnerBroadcastScopeCurrent: scope => { + assertCurrent(); + return isDataOwnerBroadcastScopeCurrent(scope); + }, + assertReviewSettingsUnlocked: deps.selection.assertReviewSettingsUnlocked, + resolveGhostControlPointPlugin: deps.resolveGhostControlPointPlugin, + writeRuntimePluginSettings: (id, settings) => writeRuntimePluginSettings(id, settings, assertCurrent), + broadcastSessionPatched: (id, patch) => deps.publish({ type: 'session_changed', sessionId: id, patch }), + })(undefined, sessionId, value); + }; +} diff --git a/apps/host/src/agent/touch-user-send.ts b/apps/host/src/agent/touch-user-send.ts new file mode 100644 index 00000000000..c76b329eee2 --- /dev/null +++ b/apps/host/src/agent/touch-user-send.ts @@ -0,0 +1,36 @@ +import type { DbClient } from '../../../desktop/src/main/localDb/client/DbClient.ts'; +import { touchUserSendRow } from '../../../desktop/src/main/localDb/sessionQueries.ts'; +import { touchRecentWorkdir } from '../../../desktop/src/main/localDb/ipc/recentWorkdirsCore.ts'; +import { recordRecentWorkdirForSend } from '../../../desktop/src/main/localDb/ipc/touchUserSendRecentWorkdir.ts'; + +/** + * A user's send stamps the task (the desktop's touchUserSendInDb, localDb/ipc/sessions.ts): the row's send + * and activity times in one guarded update, a `session_changed` with them while the owner holds, and the + * desktop's own record of the project the send was made in (recordRecentWorkdirForSend), in the entry's + * database, announced only while that owner still holds (the desktop's owner scope). + */ +export function createHostTouchUserSend(deps: { + getOwner(): Owner | null; + publish(event: Record): void; + /** The recent projects push (session-move.ts createRecentWorkdirsChangedPush). */ + broadcastRecentWorkdirsChanged(path: string): void; +}) { + return async (sessionId: string, atMs?: number) => { + const owner = deps.getOwner(); + if (!owner) throw new Error('DbClient not ready'); + const ts = typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0 ? Math.floor(atMs) : Date.now(); + const updated = await touchUserSendRow(owner.client.drizzle, sessionId, ts); + // As touchUserSendInDb: an older or repeated stamp changes nothing and announces nothing. + if (updated.length === 0) return; + const [row] = updated; + if (deps.getOwner() === owner) deps.publish({ type: 'session_changed', sessionId, + patch: { userSendAt: new Date(row.userSendAt!).toISOString(), + lastActivityAt: new Date(row.lastActivityAt!).toISOString(), updatedAt: new Date(row.updatedAt).toISOString() } }); + await recordRecentWorkdirForSend({ + updated, ts, dbClient: owner.client, ownerScope: owner, touchRecentWorkdir, + broadcastRecentWorkdirsChanged: (path, scope) => { + if (deps.getOwner() === scope) deps.broadcastRecentWorkdirsChanged(path); + }, + }); + }; +} diff --git a/apps/host/src/agent/turn-executor.mjs b/apps/host/src/agent/turn-executor.mjs index fc17041f91c..86048f87785 100644 --- a/apps/host/src/agent/turn-executor.mjs +++ b/apps/host/src/agent/turn-executor.mjs @@ -1,10 +1,9 @@ -import fs from 'node:fs/promises'; +import { getActiveAppSession } from '../../../desktop/src/main/appSessionState.js'; import { createMakerSteerTransaction } from '../../../desktop/src/main/maker-ipc/makerSteerTransaction.ts'; import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '../../../desktop/src/main/maker-ipc/autoReviewUserIntent.ts'; import { readBotDmThreadContextNote } from '../../../desktop/src/main/maker-ipc/botDmThreadContext.ts'; import { readReplyQuoteNote } from '../../../desktop/src/main/maker-ipc/chatReplyQuoteNote.ts'; import { publishUiSessionIntervention } from '../../../desktop/src/main/maker-ipc/uiContinuationSignal.ts'; -import { extractPlainText } from '../../../desktop/src/main/maker-ipc/agentHandoff.ts'; import { listMessagesForAgentHandoff } from '../../../desktop/src/main/localDb/agentHandoffHistory.ts'; import { createSessionOptionsReconciler } from '../../../desktop/src/main/maker-ipc/sessionOptionsReconciler.ts'; import { createMakerSendTransaction, prepareDirectoryGrantsForBootstrap } from '../../../desktop/src/main/maker-ipc/makerSendTransaction.ts'; @@ -18,16 +17,44 @@ import { assertHostTaskExecutionSupported, prepareHostUserMessage } from './send import { createHostLearnInvocationCapture } from './learn-capture.ts'; import { createHostEventPersistence } from './event-persistence.ts'; import { createHostContextRecovery } from './context-recovery.ts'; +import { createHostSilentStop } from './silent-stop.ts'; +import { createHostWorkingDirectory } from './working-directory.ts'; +import { clearSealedCodexPlanState, readCodexPlanState } from '../../../desktop/src/main/localDb/codexPlanState.ts'; +import { buildCompletedPlanGuardNote, buildPlanReconcileNote } from '../../../desktop/src/main/maker-ipc/planReconcile.ts'; +import { peekGoalInactiveNote } from '../../../desktop/src/main/goal-host/inactiveNote.ts'; +import { createTurnModelAttribution } from '../../../desktop/src/main/maker-ipc/turnModelAttribution.ts'; +import { patchMessageAgentMetaWithResultRow } from '../../../desktop/src/main/localDb/messageMutations.ts'; +import { getDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { latestVisiblePreview } from '../../../desktop/src/main/localDb/latestMessageText.ts'; +import { sessionListPreviewPatch } from '../../../desktop/src/main/sessionTaskSummary.logic.ts'; +import { sessions } from '../../../desktop/src/main/localDb/schema.ts'; +import { persistAndHydrateSessionProvider } from '../../../desktop/src/main/maker-ipc/sessionProviderBootstrap.ts'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.ts'; +import { eq } from 'drizzle-orm'; +import { isPiPromptRpcTimeoutError } from '../../../desktop/src/shared/inputError.ts'; import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continuation'; import { isTerminalTurnErrorEvent } from '../../../desktop/src/main/maker-ipc/sessionTurnActivityTracker.ts'; +import { noteClaudeSessionTurnState } from '../../../desktop/src/main/maker-host/claude-session-background-activity.ts'; +import { syncBackgroundCommandWork } from '../../../desktop/src/main/maker-host/claude-background-command-work-sync.ts'; import { clearPendingTurnChangeSets, finalizeTurnChangeSet, noteTurnDiffEvent } from '../../../desktop/src/main/turn-change-set/store.ts'; import { beginTurnChangeSetAtDispatch } from '../../../desktop/src/main/turn-change-set/dispatchBoundary.ts'; -import { setSessionProvider, clearSessionProvider, getSessionProvider } from '../../../desktop/src/main/maker-host/session-provider-store.ts'; +import { setSessionProvider, clearSessionProvider, getSessionProvider, hydrateSessionProvider } from '../../../desktop/src/main/maker-host/session-provider-store.ts'; import { setSessionEffort } from '../../../desktop/src/main/maker-host/session-effort-store.ts'; import { applyQueuedSessionSettings, rememberLiveSessionSettings } from './session-settings.mjs'; import { MCP_APP_MESSAGE_GUARD } from '../../../desktop/src/main/mcp-apps/message.ts'; import { redactEventForRenderer } from '../../../desktop/src/main/maker-ipc/rendererEventRedaction.ts'; +import { isQuietScheduledOutput } from '../../../desktop/src/main/scheduler-host/silent-output.ts'; +import { claudeOpusPlanTerminalErrorData, defaultDecisionForPending, handleInteractionDismissedEvent, localizeRuntimeRecoveryEvent, routeStandaloneTextEvent } from '../../../desktop/src/main/maker-ipc/sessionEventPreparationSteps.ts'; +import { uiText } from '../../../desktop/src/main/uiText.ts'; +import { MAKER_PUSH } from '../../../desktop/src/main/maker-ipc/channels.ts'; import { isGatewayProxyTokenRecoveryErrorEventForProvider } from '../../../desktop/src/main/maker-ipc/gatewayProxyTokenRecovery.ts'; +import { contextSnapshotForStatus, isContextCompactionSnapshot } from '../../../desktop/src/main/maker-ipc/sessionContextSnapshot.ts'; +import { recordHostContextSnapshot } from './context-usage.ts'; +import { readTerminalTurnErrorSignals } from '../../../desktop/src/main/maker-ipc/terminalTurnErrorSignals.ts'; +import { isForegroundRunningStatus, noteAutoResumeProgress, noteForegroundTurnStarted, settleAutoResumeAttemptOnDone, + settleAutoResumeAttemptOnTerminalError } from '../../../desktop/src/main/maker-ipc/sessionEventAutoResumeSteps.ts'; +import { applySessionRuntimeOverrideForStart } from '../../../desktop/src/main/maker-ipc/sessionRuntimeControl.ts'; +import { isSuccessfulAssistantReplyDoneData } from '../../../desktop/src/main/cindy-brain/assistantReplyHook.ts'; const makerKind = kind => kind === 'cc' ? 'claude-code' : kind; const dbKind = kind => kind === 'claude-code' ? 'cc' : kind; @@ -36,13 +63,18 @@ const errorText = error => error instanceof Error ? error.message : String(error /** * Node platform adapter for one maker-core turn. Queue order, recovery and * dispatch ownership belong to AgentInputCoordinator, never to this adapter. - * A terminal is handed back only after all visible reply rows have settled. + * The coordinator receives a turn's terminal when it arrives, as on the desktop; the next input + * still waits until all visible reply rows have settled, because the turn counts as running + * (isRunning, the coordinator's dispatch boundary) until then. */ /** * Publishes an agent event to the Host's clients (the event stream and the device link read the * hub). As on the desktop (sessionEventPreparation.ts broadcastEvent), what leaves is the * renderer-boundary projection of the event; persistence and bookkeeping keep the original. */ +// The English of settings.piPackages.failure.runtimeRetirementFailed, for a main i18n that lacks it (ui-text.ts). +const RUNTIME_RETIREMENT_FAILED_EN = 'Pi extensions could not be refreshed. Restart Cindy before using Pi again.'; + export function publishAgentEvent(hub, sessionId, event, fields) { const clientEvent = redactEventForRenderer(event); hub.publish({ ...clientEvent, sessionId, event: clientEvent, ...fields }); @@ -58,8 +90,53 @@ export function createTurnExecutor(deps) { // Context recovery of a terminal error (context-recovery.ts); without a recovery factory the // listener behaves as before. const recovery = deps.getRecoveryRollover ? createHostContextRecovery({ getRollover: deps.getRecoveryRollover, - isRecoverable: deps.isContextRecoveryOpen, + isRecoverable: deps.isContextRecoveryOpen, isErrorSuppressed: deps.isSessionErrorSuppressed, publish: (id, event, fields) => publishAgentEvent(deps.hub, id, event, fields), log }) : null; + // The desktop's silent-stop continuation (silent-stop.ts), with the input coordinator's ports; an + // executor without them (a unit fixture) ends a silent-stop done as any done. + const silentStop = deps.silentStopCoordinator ? createHostSilentStop({ + coordinator: deps.silentStopCoordinator, + guard: () => deps.getAutoResume?.()?.silentStopAutoResumeGuard ?? null, + listActivity: () => deps.productTurn?.listActivity ?? null, + isProfileHeld: () => deps.isProfileHeld?.() === true, + isStopping: () => deps.isStoppingRuntime() === true, + writeRow: (id, message, options) => behindDurableWrites(id, `silent-stop-row:${id}`, () => deps.persistMessage(id, message, options)), + // As the desktop broadcasts the banner (register.ts surfaceSilentStopExhaustedBanner, source as there), + // with the turn's input so /api/chat ends on it. + publishFailure: (id, turn, data) => publishAgentEvent(deps.hub, id, { type: 'error', data, source: 'claude-code' }, turnStreamFields(turn)), + isTurnCurrent: (id, turn) => turns.get(id) === turn, + isAwaitingDecision: (id, turn) => turns.get(id) === turn && turn.silentStopPending === true && !turn.terminal, + // The listener keeps only the turn's own generation (listen): the continuation's events carry the new one. + adoptGeneration: (turn, generation) => { + turn.preContinuationGeneration = turn.generation; + turn.generation = generation; + turn.continuedSilentStopDoneAt = turn.silentStopDoneAt; + turn.silentStopDoneAt = undefined; + turn.silentStopPending = false; + }, + rollbackGeneration: (turn, generation) => { + if (turn.generation !== generation) return; + turn.generation = turn.preContinuationGeneration; + turn.silentStopDoneAt = turn.continuedSilentStopDoneAt; + turn.silentStopPending = true; + }, + finalizeChangeSet: (id, turn) => { if (turn.changeRecordStarted) void finalizeTurnChangeSet(id, null, 'complete'); }, + endTurn: (id, turn, reason) => endSilentStopTurn(id, turn, reason), + usageTrackers: () => deps.usage ?? null, + log, + }) : null; + // The fields a turn's events carry for its clients: its input, and the input an automatic resume continues. + const turnStreamFields = turn => ({ inputClientId: turn.clientId, ...(turn.resumeOf ? { autoResumeOf: turn.resumeOf } : {}) }); + // The auto-resume bookkeeping steps of the desktop's event preparation (sessionEventAutoResumeSteps.ts), + // over the auto-resume runtime (auto-resume.ts). The failed-turn assistant pairing map is the + // desktop's; the Host only keeps it so a new turn drops a stale entry, as there. + const pendingFailedTurnAssistantPersistId = new Map(); + function autoResumeStepDeps() { + const autoResume = deps.getAutoResume?.(); + return autoResume ? { autoResumeBookkeeping: autoResume.autoResumeBookkeeping, pendingFailedTurnAssistantPersistId, + silentStopAutoResumeGuard: autoResume.silentStopAutoResumeGuard, + interruptedTurnAutoResumeGuard: autoResume.interruptedTurnAutoResumeGuard, usageLimitAutoResume: undefined } : null; + } function historyFor(id) { let history = histories.get(id); if (!history) { @@ -110,19 +187,93 @@ export function createTurnExecutor(deps) { return prepareSnapshot ? prepareSnapshot(snapshot) : snapshot.onTurnStart(sessionId, signal); } + // The desktop's list preview refresh after a done (sessionTaskSummary.ts refreshSessionListPreview, called + // by sessionEventTerminal.ts once the write queue has drained): the latest visible message goes to the task + // list, whatever the pinned section shows. A failure is logged and swallowed, as there. + async function refreshListPreview(sessionId) { + const owner = deps.getOwner?.(); + try { + const preview = await latestVisiblePreview(sessionId); + if (!deps.isCurrent() || (deps.getOwner && deps.getOwner() !== owner)) return; + deps.hub.publish({ type: 'session_changed', sessionId, patch: sessionListPreviewPatch(preview) }); + } catch (error) { + log.warn('refresh session list preview failed (swallowed)', { sessionId, error: String(error) }); + } + } + + // As the desktop's terminal stage (sessionEventTerminal.ts), in the same write queue and before an + // error row: the last top-level reply since the previous seal gets its seal. A successful done (for + // Codex, also requiring raw status completed) seals it completed, with the native fork anchor. A + // terminal error or an unsuccessful done seals it failed, so later history reads neither take a + // progress note for the final answer nor a stopped plan for a finished one. Teammate result ids are not + // passed: the Host refuses teammate tasks. Without a terminal event nothing is sealed; the id is + // consumed either way so it cannot seal a later turn. A paused write queue keeps the seal for its retry + // and reports the failure itself (onPersistenceError); the rejected promise only says so. + function sealLastReply(sessionId, history, failed, event) { + const sealId = history.consumeLastTopLevelAssistantPersistId(sessionId); + if (!sealId || (!failed && !event)) return; + const succeeded = !failed && event?.type === 'done' + && isSuccessfulAssistantReplyDoneData(event.data) + && (event.source !== 'codex' || history.isSuccessfulCodexDoneEventData(event.data)); + const nativeForkAnchor = succeeded ? event.agentMeta?.nativeForkAnchor : undefined; + void (succeeded + ? history.markAssistantTurnCompleted(sessionId, sealId, nativeForkAnchor ? { nativeForkAnchor } : undefined) + : history.markAssistantTurnFailed(sessionId, sealId)).catch(() => {}); + } + + // The desktop's terminal stage runs on every done and terminal error, also those that do not end the + // Host's turn: a continuation boundary of the foreground turn, and a background turn's terminal. There it + // writes the reply block (with the event's agent meta), the orphan tool results, seals the last reply, + // and resets the per-turn persistence state (keeping what a late background result still needs), so + // the segments before and after a continuation stay two replies with a seal each. + function settleTurnBoundary(sessionId, history, event, usageSlot = null) { + const agentMeta = event.agentMeta ?? null; + history.flushAssistantBlock(sessionId, agentMeta); + // The usage target the desktop's terminal stage consumes after the reply block (sessionEventTerminal.ts). + const consumed = history.consumeLastAssistantPersistId(sessionId); + if (usageSlot) usageSlot.consumed = consumed; + history.flushOrphanToolResults(sessionId, agentMeta); + sealLastReply(sessionId, history, event.type !== 'done', event); + history.preserveTurnPersistStateForBackground(sessionId); + history.resetTurnPersistState(sessionId); + // The desktop refreshes the list preview after every done that is not a continuation boundary + // (sessionEventTerminal.ts), a background turn's done included, once the writes have drained. + if (event.type === 'done' && !isTurnContinuationBoundaryEvent(event)) { + void history.drain().then(() => { if (deps.isCurrent()) return refreshListPreview(sessionId); }, () => {}); + } + } + // recoveryOwnsError: context recovery claimed this terminal error and writes its row if it fails. - function finish(sessionId, turn, error, event, recoveryOwnsError = false) { + function finish(sessionId, turn, error, event, recoveryOwnsError = false, usageSlot = null) { if (turn.terminal) return turn.settlement; turn.terminal = true; // A stop the engine acknowledged without a terminal event: the engines' stop paths end in a // done on the desktop, which takes the after-edit savepoint there. if (!event && !error && turn.abortRequested && !deps.isStoppingRuntime()) settleGitBaseline(sessionId, turn, 'stopped'); - turn.endedAt = Date.now(); + // A silent stop that did not continue ended at its done (silent-stop.ts), as the desktop marks it there. + turn.endedAt = turn.silentStopDoneAt ?? Date.now(); turn.interruptedByShutdown = deps.isStoppingRuntime(); const history = historyFor(sessionId); history.flushAssistantBlock(sessionId); + // As the desktop's terminal stage and stop (sessionEventTerminal.ts, register.ts abort): the usage target + // is consumed with the seal, so it cannot attach a later turn's usage to this turn's reply. + const consumed = history.consumeLastAssistantPersistId(sessionId); + if (usageSlot) usageSlot.consumed = consumed; history.flushOrphanToolResults(sessionId, event?.agentMeta ?? null); - if (error && !recoveryOwnsError) history.onTurnErrorEvent(sessionId, { ...event?.data, message: error }, event?.agentMeta ?? null); + sealLastReply(sessionId, history, Boolean(error), event); + if (error && !recoveryOwnsError) { + // As the desktop's terminal stage (sessionEventTerminal.ts): while an automatic resume holds this + // error (pending or deferred, sessionErrorSuppression.ts), its row is not written; the bookkeeping + // keeps it, with the turn's start for the clear cap, and writes it once if the resume gives up. + if (event && deps.isSessionErrorSuppressed?.(sessionId, event) === true && deps.holdSuppressedError) { + history.saveTurnStartedAtForDeferred(sessionId); + deps.holdSuppressedError(sessionId, { ...event.data, message: error }); + } else { + history.onTurnErrorEvent(sessionId, { ...event?.data, message: error }, event?.agentMeta ?? null); + // A new terminal replaces an older interruption's replacement (sessionEventTerminal.ts). + if (event && isTerminalTurnErrorEvent(event)) autoResumeStepDeps()?.autoResumeBookkeeping.discardReplacementProvenByProviderEvent(sessionId); + } + } if (error) history.persistCodexPlanOnTerminalError(sessionId); else if (event) history.persistCodexPlanOnDone(sessionId, event.data); history.preserveTurnPersistStateForBackground(sessionId); @@ -132,6 +283,9 @@ export function createTurnExecutor(deps) { try { await deps.markEnded?.(sessionId, turn.endedAt); } catch (failure) { turn.persistenceError = errorText(failure); deps.onPersistenceError(sessionId, turn.persistenceError); } } + // Only after a done, as the desktop; not awaited, so the turn's end is not held by the read. The + // pinned card summary that follows it there is not generated on the Host (release table 甲 13). + if (event?.type === 'done' && deps.isCurrent()) void refreshListPreview(sessionId); turn.running = false; if (turns.get(sessionId) === turn) { // Some providers become idle after abort without emitting done. Publish @@ -142,7 +296,8 @@ export function createTurnExecutor(deps) { deps.hub.publish({ type: 'input_receipt', sessionId, inputClientId: turn.clientId, clientId: turn.clientId, status: 'interrupted' }); } - deps.onTerminal(sessionId, error ? 'error' : 'done', error, turn.terminalMeta, turn.direct === true); + deps.onTerminal(sessionId, error ? 'error' : 'done', error, turn.terminalMeta, turn.direct === true, + turn.terminalHandedOver === true); } }); return turn.settlement; @@ -156,6 +311,219 @@ export function createTurnExecutor(deps) { if (!bindings.has(sessionId)) return; deps.getGitSnapshot?.()?.onSessionClosed(sessionId); clearPendingTurnChangeSets(sessionId); + // As the desktop's close (sessionBindingLifecycle.ts teardown, finalizeClosedSession): the closed + // runtime's deferred failures and the task's list activity record go. + deps.productTurn?.closed(sessionId, bindings.get(sessionId).session); + listActivityInTurn.delete(sessionId); + // As the desktop's session close (register.ts :6064–6070, sessionBindingLifecycle.ts): the task's usage + // tables and its failed-turn usage handoff go with the runtime. + deps.usage?.clear(sessionId); + pendingFailedTurnAssistantPersistId.delete(sessionId); + // As the desktop's turn observer teardown: the closed runtime's silent-stop decision goes. Its turn + // cannot continue on it and no terminal will come (the runtime already sent its done): it ends here. + const bound = bindings.get(sessionId).session; + silentStop?.released(sessionId, bound.instanceId); + const turn = turns.get(sessionId); + if (turn?.silentStopPending && !turn.terminal && turn.session === bound) { + turn.silentStopPending = false; + void finish(sessionId, turn); + } + } + + // A silent-stop done closes its segment's rows as the desktop's terminal stage does for it (the reply + // block, its seal and the list preview: settleTurnBoundary). The Host's turn stays open for the decision + // (silent-stop.ts): the coordinator does not get this done (handTerminalToCoordinator), and the next input + // waits. The turn's end is not marked here: the desktop marks it at this done (markTurnEndedAfterPersistDrain), + // so a crash or an account boundary during the decision or the continuation leaves it looking finished. + // On the Host it stays a running turn until it really ends (review item 2): a settle without a continuation + // marks the end at the done's time (finish), a continuation at its own end, and an interruption marks none. + function settleSilentStopSegment(sessionId, turn, session, history, event, usageSlot = null) { + turn.silentStopPending = true; + turn.silentStopDoneAt = Date.now(); + settleTurnBoundary(sessionId, history, event, usageSlot); + silentStop.decideLater(session, turn, event); + } + + // A silent stop that does not continue ends its turn as a done (silentStopSettle.ts): the turn's finish + // hands the coordinator its done and runs the settled-turn hooks. Host-only (/api/chat, chat.mjs): a + // stream that followed the silent stop ends with the recorded receipt (skipped, or its decision failed); + // an exhausted one already ended on its banner's error, a stopped one on its interrupted receipt. + function endSilentStopTurn(sessionId, turn, reason) { + turn.silentStopPending = false; + if (turn.resumeOf !== undefined) deps.resumeAnswered?.(sessionId, turn.resumeOf); + void finish(sessionId, turn).then(() => { + // A turn the owner boundary interrupted gets no receipt from here (/api/chat ends on the boundary's). + if (reason === 'exhausted' || turn.abortRequested || turn.interruptedByShutdown + || typeof turn.clientId !== 'string' || !deps.isCurrent()) return; + deps.hub.publish({ type: 'input_receipt', sessionId, ...turnStreamFields(turn), clientId: turn.clientId, status: 'recorded' }); + }, () => {}); + } + + // The task list activity of the desktop (SessionListActivityTracker, product-turn.ts), at the desktop's + // points: a foreground running status starts it (sessionEventPreparation.ts), a foreground not-running + // status ends it once the event batch is over (sessionEventDelivery.ts, statusOnly), a turn's done or + // terminal error ends it (sessionEventTerminal.ts), held while an automatic resume or a context recovery + // owns the turn, which commits it later through the product-turn failure gate. Goal turns write none. + const listActivityInTurn = new Set(); + const activityIdentity = (session, event) => event.sessionTurnGeneration === undefined ? undefined + : `${event.sessionInstanceId ?? session.instanceId}:${event.sessionTurnGeneration}`; + + // Claude's background-activity detection (claude-session-background-activity.ts) reads the logical + // turn's start and end at the desktop's points: a running status of the foreground turn starts it + // (sessionEventPreparation.ts); a done, a terminal error or a foreground running=false status ends + // it, refreshing the background command work (sessionEventDelivery.ts); a task update refreshes + // that work. Idle release reads the result (idle-release.ts). A silent-stop done whose decision is + // pending keeps the logical turn going, as the desktop's preparation notes it; its settle ends it. + function noteBackgroundActivity(session, event) { + if (silentStop?.isScheduled(event)) { + noteClaudeSessionTurnState(session.id, true); + return; + } + const continuation = isTurnContinuationBoundaryEvent(event); + if (event.type === 'status' && event.data?.isRunning === true && event.turnScope !== 'background') { + noteClaudeSessionTurnState(session.id, true); + } else if ((event.type === 'done' && !continuation) || isTerminalTurnErrorEvent(event) + || (event.type === 'status' && event.data?.isRunning === false && !continuation && event.turnScope !== 'background')) { + syncBackgroundCommandWork(session); + noteClaudeSessionTurnState(session.id, false); + } else if (event.type === 'agent_task_update') { + syncBackgroundCommandWork(session); + } + } + + // As the desktop's event preparation (sessionEventPreparation.ts) hands a terminal to the input + // coordinator: a product done (not a continuation boundary, not a silent-stop done, which the + // desktop decides on later) and a terminal error with its message and structured signals. The + // desktop leaves out the planned close of a remote daemon; the Host runs no remote tasks. + // Whether the terminal is this input's and current is the coordinator's own decision + // (shouldIgnoreUnownedTerminal, isFencedStaleTerminal). + function handTerminalToCoordinator(sessionId, event) { + if (!deps.handTerminal) return false; + const meta = { sessionTurnGeneration: event.sessionTurnGeneration, sessionInstanceId: event.sessionInstanceId }; + if (event.type === 'done') { + if (isTurnContinuationBoundaryEvent(event) || event.data?.silentStop === true) return false; + deps.handTerminal(sessionId, 'done', undefined, undefined, meta); + return true; + } + if (!isTerminalTurnErrorEvent(event)) return false; + const { message, signals } = readTerminalTurnErrorSignals(event, redactEventForRenderer(event)); + deps.handTerminal(sessionId, 'error', message, signals, meta); + return true; + } + + // The desktop's preparation steps that come before it hands a terminal to the coordinator + // (sessionEventPreparation.ts :219, :363, :409, :483): the first event of a resume's attempt, a + // foreground running status starting a new attempt, a done or terminal error settling it. + function noteAutoResumeEventBeforeTerminal(session, event) { + const steps = autoResumeStepDeps(); + if (!steps) return; + if (typeof event.turnAttemptToken === 'number') steps.interruptedTurnAutoResumeGuard.noteAttemptEvent(session.id, event.turnAttemptToken); + if (event.type === 'status' && event.data && isForegroundRunningStatus(event.data, event)) { + // The turn's start for the clear cap is noted by the Host at dispatch (beginHostTurn, the send + // transaction); subagent observation is the desktop's renderer feature. + noteForegroundTurnStarted(steps, session, event, { noteTurnStarted: () => {}, noteSubagentObservationTurnStarted: () => {} }); + } + if (event.type === 'done') settleAutoResumeAttemptOnDone(steps, session, event, isTurnContinuationBoundaryEvent(event)); + if (isTerminalTurnErrorEvent(event)) settleAutoResumeAttemptOnTerminalError(steps, session, event); + } + + // The desktop's ports of these steps (register.ts), as the Host has them. The accepted input of the + // notice is this turn's; its provenance only tells a bot's private reply, and the Host refuses bot + // inputs at admission. + function standaloneTextPorts(session) { + return { redactEventForRenderer, agentInputCoordinatorHolder: { + getActiveInputClientId(id, generation) { + const turn = turns.get(id); + if (!turn || turn.session !== session || turn.terminal || !turn.clientId) return null; + return typeof generation === 'number' && typeof turn.generation === 'number' && generation !== turn.generation + ? null : turn.clientId; + }, + getAcceptedInputProvenance: () => null, + } }; + } + // The pending card leaves the Host's broker (interactions.mjs) as the desktop's clearPendingInteraction; + // the decision of a question or plan is saved, as the desktop's persistInteractionDecision; the + // floating island is a desktop window. + function interactionDismissedPorts(sessionId, history) { + return { + handleAgentIslandInteractionDismissed: () => {}, + clearPendingInteraction: requestId => deps.interactions?.clearPending(requestId, sessionId) ?? null, + defaultDecisionForPending, + persistInteractionDecision: (id, persistId, kind, request, decision) => { + if (kind === 'ask_user_question' || kind === 'plan_review') history.onInteractionResolved(id, persistId, kind, request, decision); + }, + broadcastToAllWindows: (channel, payload) => { + if (channel === MAKER_PUSH.INTERACTION_DISMISSED) deps.hub.publish({ type: 'interaction_dismissed', ...payload }); + }, + }; + } + + // The product-turn bookkeeping runs inside the event callback, before the turn's finish: a throw there + // would leave the turn without its end. The desktop has no such guard; the Host adds one, so a failure + // costs at most this turn's activity time and is logged (task id and error name only). + function guardProductTurn(sessionId, step) { + try { + return step() ?? null; + } catch (error) { + // deps.productTurnLog: a test reads the warning there; the Host itself logs as the executor does. + (deps.productTurnLog ?? log).warn('product turn bookkeeping failed', { sessionId, error: error instanceof Error ? error.name : typeof error }); + return null; + } + } + + // The desktop's terminal stage for the product turn (sessionEventTerminal.ts), in its order. A + // terminal an automatic resume holds (its error row suppressed) defers its owner, as the shared + // deferContextRecoveryTerminal does; a context recovery that claimed it deferred it already (its + // claim). The turn's list activity then ends, held while either owns it or a resume is pending or + // deferred. A successful reply's done clears the owner; an unsuccessful terminal that nothing holds + // goes through the finalizer at once. The Host writes the error row of a gateway key recovery and of + // a planned close at once (it has no deferred persist to settle them later), so those are not held. + function settleProductTurn(session, event, owner, claim) { + const sessionId = session.id; + const productTurn = deps.productTurn; + const suppressed = deps.isSessionErrorSuppressed?.(sessionId, event) === true; + const recoveryOwns = claim !== 'idle'; + if (suppressed) productTurn.defer(owner); + listActivityInTurn.delete(sessionId); + const resumeHeld = deps.isAutoResumeHeld?.(sessionId) === true; + if (event.turnOrigin?.kind !== 'goal') { + // The desktop also holds a silent-stop done's end (sessionEventTerminal.ts): the continuation drops + // it, a settle without one commits it (silent-stop.ts). + productTurn.listActivity.end(sessionId, { identity: activityIdentity(session, event), + hold: suppressed || recoveryOwns || resumeHeld || silentStop?.isScheduled(event) === true }); + } + const successfulReply = event.type === 'done' && isSuccessfulAssistantReplyDoneData(event.data); + if (successfulReply && !recoveryOwns && !resumeHeld + && deps.getAutoResume?.()?.autoResumeBookkeeping.hasSuppressedError(sessionId) !== true) productTurn.finish(owner); + if (!successfulReply && !recoveryOwns && !suppressed) productTurn.interrupt(sessionId, owner); + } + + // The turn usage recorders (usage-recording.ts) where the desktop's pipeline runs them: after the terminal + // stage, for every event its preparation keeps (sessionEventPipeline.ts :61–71). A done or terminal error + // takes its usage target from that stage (`consumed`); a late one (after the Host's turn ended, or of + // another generation) takes only a failed turn's handed-over id (release table row 13). + function recordTurnUsage(session, event, history, consumed) { + const usage = deps.usage; + if (!usage) return; + const terminalError = isTerminalTurnErrorEvent(event); + const target = event.type === 'done' || terminalError + ? usage.usageTarget(session.id, event, consumed, pendingFailedTurnAssistantPersistId, terminalError) : undefined; + // The owner the input runtime was bound to when its turns started (input-queue.mjs assertCurrent). + usage.record(session, event, target, history, deps.runtimeOwner?.()); + } + // The usage steps of the desktop's preparation for the foreground turn (sessionEventPreparation.ts): a + // running status starts the turn's usage state, a terminal error drops its model (:391–395), and its end + // (a final done, a terminal error, a not-running status) is noted for the next start. + function noteUsageTurnState(session, event) { + const usage = deps.usage; + if (!usage || event.turnScope === 'background') return; + const boundary = isTurnContinuationBoundaryEvent(event); + if (event.type === 'status' && event.data && isForegroundRunningStatus(event.data, event)) usage.noteRunningStatus(session, event); + else if (event.type === 'status' && event.data?.isRunning === false && !boundary) usage.noteTurnEnded(session.id); + if (isTerminalTurnErrorEvent(event)) { + usage.noteTerminalError(event, session.id); + usage.noteTurnEnded(session.id); + } else if (event.type === 'done' && !boundary && event.data?.silentStop !== true) usage.noteTurnEnded(session.id); } function listen(sessionId, session) { @@ -163,68 +531,196 @@ export function createTurnExecutor(deps) { if (bindings.has(sessionId)) clearPendingTurnChangeSets(sessionId); bindings.get(sessionId)?.unsubscribe(); const history = historyFor(sessionId); + const standalonePorts = standaloneTextPorts(session); + const dismissedPorts = interactionDismissedPorts(sessionId, history); history.noteSessionAgentKind(sessionId, dbKind(session.agentKind ?? turns.get(sessionId)?.dbKind)); deps.interactions?.attach(session, sessionId, { history, isCurrent: deps.isCurrent, isPaused: () => deps.isExecutionPaused?.(sessionId) === true }); + // As the desktop wires a runtime (register.ts): the owner it was wired under, which a runtime's own + // Plan change is saved for. + const ownerDb = deps.getOwner?.() ?? null; const unsubscribe = session.onEvent(event => { + // As the desktop's emitWiredSessionEvent: a Plan mode the runtime changed itself is saved (behind + // the task's permission queue, only while the owner, this binding and the runtime's value hold), in + // or out of a turn, and is not delivered as a turn event. + if (event.type === 'plan_mode_changed') { + deps.persistAgentPlanModeChange?.({ ownerDb, sessionBindings: { getSession: id => bindings.get(id)?.session } }, session, event); + return; + } + // The coordinator gets a terminal before the Host's own turn filters below, which only keep the + // Host's records, publishing and rows: a follow-up of Session.holdEventStream was handled by the + // host that held it (as the desktop), and an owner that is not current has its coordinator closing. + const prepared = !event.hostProjection && deps.isCurrent(); + // As the desktop's preparation (sessionEventPreparation.ts and its shared steps), in or out of a + // turn and in its order: a standalone notice is its own row, not a reply nor a client event; a + // Claude Opus plan-mode terminal error carries its normalized reason before the coordinator and the + // records see it; then, after the attempt's bookkeeping, a card the runtime closed itself leaves the + // pending cards with its decision saved, and a Codex generated image is stored and delivered as its + // imagegen tool rows (agent/generated-images.ts), which the stream waits for + // (Session.holdEventStream); the raw image event, with its bytes, is neither history nor sent. + if (prepared) { + if (routeStandaloneTextEvent(standalonePorts, session, event, history.onStandaloneTextEvent)) return; + const opusPlanErrorData = claudeOpusPlanTerminalErrorData({ log }, session, event); + if (opusPlanErrorData) event = { ...event, data: opusPlanErrorData }; + } + if (prepared) noteAutoResumeEventBeforeTerminal(session, event); + const handedOver = prepared && handTerminalToCoordinator(sessionId, event); + if (prepared) { + if (handleInteractionDismissedEvent(dismissedPorts, session, event)) return; + if (event.type === 'image' && event.source === 'codex' && deps.deliverCodexGeneratedImage) { + if (!isQuietScheduledOutput(event)) session.holdEventStream(deps.deliverCodexGeneratedImage(sessionId, event)); + return; + } + } const turn = turns.get(sessionId); if (!turn || turn.session !== session || !deps.isCurrent()) return; + // The context usage a status event carries, decided as the desktop decides it + // (sessionEventPreparation.ts: before its turn bookkeeping, from the shared rules) and written + // once the event is delivered, as the desktop writes it (sessionEventSnapshots.ts). The + // `event.data` check is the Host's own guard (the desktop reads a status event's data as + // present); a status without data carries no snapshot either way. + const contextSnapshot = event.type === 'status' && event.data + ? contextSnapshotForStatus(isContextCompactionSnapshot(session, event, event.data), event.data) + : null; + const recordContextSnapshot = () => { + if (contextSnapshot) void recordHostContextSnapshot(sessionId, contextSnapshot.contextTokens, contextSnapshot.contextWindow); + }; if (event.turnScope !== 'background') { if (event.hostProjection) return; if (typeof event.sessionTurnGeneration === 'number' && (typeof turn.generation === 'number' - ? event.sessionTurnGeneration !== turn.generation : event.sessionTurnGeneration === turn.previousGeneration)) return; + ? event.sessionTurnGeneration !== turn.generation : event.sessionTurnGeneration === turn.previousGeneration)) { + // Another generation's event is not this turn's; its usage is still recorded, once (release table row 13). + recordTurnUsage(session, event, history, undefined); + return; + } + // A silent-stop done of this turn gets one decision (silent-stop.ts); a second one is dropped, as the + // desktop's preparation drops it. + if (!turn.terminal && silentStop?.schedule(session, event) === 'duplicate') return; + noteBackgroundActivity(session, event); + noteUsageTurnState(session, event); + if (deps.productTurn && event.type === 'status' && event.data && isForegroundRunningStatus(event.data, event)) { + if (!listActivityInTurn.has(sessionId) || event.sessionTurnGeneration !== undefined) { + deps.productTurn.listActivity.start(sessionId, activityIdentity(session, event)); + } + listActivityInTurn.add(sessionId); + } if (turn.terminal) { + recordContextSnapshot(); // The turn has ended for the Host; only its Git baseline still listens. if (event.type === 'done' && !isTurnContinuationBoundaryEvent(event)) settleGitBaseline(sessionId, turn, 'end'); else if (isTerminalTurnErrorEvent(event)) settleGitBaseline(sessionId, turn, 'abort'); + // Usage that arrives after the turn ended (a failed turn's paired done) is still recorded, once, + // without rows or client events, as on the desktop (release table row 13). + recordTurnUsage(session, event, history, undefined); return; } } + if (event.turnScope === 'background') noteBackgroundActivity(session, event); if (event.type === 'compact_boundary') wireNotes.reset(sessionId); // Desktop records Codex's native turn diff from the event stream (register.ts) // and closes the turn change record at the turn's end (sessionEventPreparation.ts). noteTurnDiffEvent(sessionId, event, session.remoteHostId !== null); + // As the desktop (sessionEventPreparation.ts): the diff is kept by the change record only; it is + // not saved as history or sent to clients (it can be several megabytes). + if (event.type === 'turn_diff') return; if (turn.changeRecordStarted && event.type === 'done' && !isTurnContinuationBoundaryEvent(event)) { const rawTurn = event.data?.raw; - // Desktop settles a silent-stop done once its guard declines to resume - // (settleSilentStopDone); the Host has no auto-resume, so it settles now. - if (event.data?.silentStop === true) void finalizeTurnChangeSet(sessionId, null, 'complete'); + // Desktop settles a silent-stop done once its guard declines to resume (settleSilentStopDone, + // silent-stop.ts); an executor without the continuation settles it now. + if (event.data?.silentStop === true) { if (!silentStop?.isScheduled(event)) void finalizeTurnChangeSet(sessionId, null, 'complete'); } else void finalizeTurnChangeSet(sessionId, typeof rawTurn?.id === 'string' ? rawTurn.id : null, rawTurn && rawTurn.status !== 'completed' ? 'partial' : 'complete'); } if (turn.changeRecordStarted && isTerminalTurnErrorEvent(event)) void finalizeTurnChangeSet(sessionId, null, 'partial'); const stream = history.event(session, event); + // As the desktop's preparation, after the event's bookkeeping: substantive output proves a resume. + const steps = autoResumeStepDeps(); + if (steps) noteAutoResumeProgress(steps, session, event); // As the desktop (sessionEventDelivery.ts): a turn that ended on a rejected Cindy AI Key // reports the current key, which resynchronizes the credentials. const gatewayKeyRejected = isGatewayProxyTokenRecoveryErrorEventForProvider(getSessionProvider(sessionId), event); if (gatewayKeyRejected) deps.reportAgentCindyGatewayKeyRejected?.(); - const fields = { ...stream, inputClientId: turn.clientId }; - // Recovery claims a turn's terminal error synchronously, before finish hands it to the - // coordinator (the desktop's coordinator receives it first; the order differs, release table). + const fields = { ...stream, ...turnStreamFields(turn) }; + // Host-only (/api/chat, chat.mjs): a silent-stop done whose decision is pending does not end the + // stream; the continuation, the banner or the recorded receipt does. + if (silentStop?.isScheduled(event)) fields.silentStopPending = true; + // A terminal error the coordinator took over for an automatic resume (handed over above): its + // clients see it with the takeover, as the desktop's window sees the error and the activity row, + // and a stream that waits for this input follows the resume instead of ending here. + if (handedOver && event.turnScope !== 'background' && isTerminalTurnErrorEvent(event)) { + const pending = deps.autoResumePendingOf?.(sessionId, turn.resumeOf ?? turn.clientId); + if (pending) fields.autoResumePending = pending; + } + // Recovery claims a turn's terminal error synchronously, after the coordinator has it (above), as on + // the desktop: its preparation hands it over first, its delivery and terminal stages claim it. + // The product turn's owner (task, runtime instance, turn generation) at its terminal, captured before + // anything can start the next turn (sessionEventTerminal.ts terminalOwner). + const productOwner = deps.productTurn && (event.type === 'done' || isTerminalTurnErrorEvent(event)) + && event.turnScope !== 'background' && !isTurnContinuationBoundaryEvent(event) + ? guardProductTurn(sessionId, () => deps.productTurn.capture(session, event)) : null; const recoveryTerminal = recovery && event.type === 'error' && isTerminalTurnErrorEvent(event) && event.turnScope !== 'background' - ? { session, event, history, fields, isStopping: deps.isStoppingRuntime(), isGatewayProxyTokenRecovery: gatewayKeyRejected } + ? { session, event, history, fields, isStopping: deps.isStoppingRuntime(), isGatewayProxyTokenRecovery: gatewayKeyRejected, + // A recovery that claims the terminal holds its failure; its final failure settles it. + deferProductTurn: () => { if (productOwner) deps.productTurn.defer(productOwner); }, + notifyProductTurn: () => { if (productOwner) deps.productTurn.interrupt(sessionId, productOwner); } } : null; const claim = recoveryTerminal ? recovery.claim(recoveryTerminal) : 'idle'; if (claim === 'idle') publishAgentEvent(deps.hub, sessionId, event, fields); + recordContextSnapshot(); + if (deps.productTurn && event.type === 'status' && event.data?.isRunning === false && event.turnScope !== 'background' + && !isTurnContinuationBoundaryEvent(event) && listActivityInTurn.delete(sessionId) && event.turnOrigin?.kind !== 'goal') { + deps.productTurn.listActivity.end(sessionId, { identity: activityIdentity(session, event), statusOnly: true, + hold: deps.isAutoResumeHeld?.(sessionId) === true }); + } // Desktop takes the after-edit savepoint once the event is delivered (sessionEventDelivery.ts). if (event.type === 'done' && !isTurnContinuationBoundaryEvent(event)) settleGitBaseline(sessionId, turn, 'end'); if (isTerminalTurnErrorEvent(event)) settleGitBaseline(sessionId, turn, 'abort'); + // The terminal stage's usage target (finish, settleTurnBoundary), for the recorders below. + const usageSlot = { consumed: undefined }; + if ((event.type === 'done' || isTerminalTurnErrorEvent(event)) + && (event.turnScope === 'background' || isTurnContinuationBoundaryEvent(event))) settleTurnBoundary(sessionId, history, event, usageSlot); if ((event.type === 'done' || isTerminalTurnErrorEvent(event)) && event.turnScope !== 'background' && !isTurnContinuationBoundaryEvent(event)) { + if (silentStop?.isScheduled(event)) { + if (productOwner) guardProductTurn(sessionId, () => settleProductTurn(session, event, productOwner, claim)); + settleSilentStopSegment(sessionId, turn, session, history, event, usageSlot); + recordTurnUsage(session, event, history, usageSlot.consumed); + return; + } + // As the desktop's turn observer: a terminal that is not a silent stop ends a pending decision. + silentStop?.supersede(sessionId); turn.terminalMeta = { sessionTurnGeneration: event.sessionTurnGeneration, sessionInstanceId: event.sessionInstanceId }; + // A resumed turn that ended without another takeover answered the input it continued. + if (turn.resumeOf !== undefined && !fields.autoResumePending) deps.resumeAnswered?.(sessionId, turn.resumeOf); const error = event.type === 'error' ? event.data?.message || event.message || (typeof event.data === 'string' ? event.data : 'Agent error') : undefined; - void finish(sessionId, turn, error, event, claim !== 'idle'); + // The coordinator has this terminal already; finish then only wakes it once the rows settle. + if (handedOver) turn.terminalHandedOver = true; + if (productOwner) guardProductTurn(sessionId, () => settleProductTurn(session, event, productOwner, claim)); + void finish(sessionId, turn, error, event, claim !== 'idle', usageSlot); if (claim !== 'idle') recovery.settle(recoveryTerminal, claim, () => turn.settlement); } + recordTurnUsage(session, event, history, usageSlot.consumed); }); const unsubscribeStatus = session.onStatusChange?.(status => { if (status === 'closed' && bindings.get(sessionId)?.session === session) releaseBinding(sessionId); }); - bindings.set(sessionId, { session, unsubscribe: () => { unsubscribe(); unsubscribeStatus?.(); } }); + // As the desktop (register.ts passes session.onRuntimeRecovery to its event pipeline): the receipt of + // a runtime retirement that failed after its turn (agent/pi-packages.ts retires Pi runtimes) becomes + // the localized notice of sessionEventPreparationSteps.ts, saved and published outside any turn, for + // the owner and runtime it was wired under only. Its copy is the main i18n (ui-text.ts). + const unsubscribeRecovery = session.onRuntimeRecovery?.(event => { + if (!deps.isCurrent() || bindings.get(sessionId)?.session !== session) return; + const localized = localizeRuntimeRecoveryEvent(event, key => uiText(key, RUNTIME_RETIREMENT_FAILED_EN)); + const stream = history.event(session, localized); + publishAgentEvent(deps.hub, sessionId, localized, stream); + }); + bindings.set(sessionId, { session, unsubscribe: () => { unsubscribe(); unsubscribeStatus?.(); unsubscribeRecovery?.(); } }); + // A runtime that replaces this task's runtime takes over its held failures (register.ts onBind). + deps.productTurn?.rebind(sessionId, session); } async function readExecutionSession(id) { @@ -236,6 +732,59 @@ export function createTurnExecutor(deps) { return row; } + async function assertPiSkillPreparationReady(id, dir, assertCurrent, maySwitchHarness = false) { + assertCurrent(); + const row = await deps.readSession(id); + assertCurrent(); + if (row.source === 'review' || row.workingDir !== dir || row.remoteHostId || row.agentDeviceId || row.orcaRole || + (!maySwitchHarness && makerKind(row.agentKind) !== 'pi') || + turns.get(id)?.running || deps.getMaker()?.getSession(id)?.isTurnRunning?.()) { + throwIpcError('PRECONDITION_FAILED', maySwitchHarness ? 'The selected Pi route is not ready' : 'Pi session is unavailable'); + } + assertHostTaskExecutionSupported(row); + deps.assertProviderExecutionSupported?.(id, row.providerId); + } + + // As the desktop's bootstrapSession (register.ts) once the runtime has started: the task row takes the + // start's provider (a route the start admission rerouted or pinned included), and a failed write + // refuses the start. A start on an accepted runtime override keeps the saved provider baseline, as the + // desktop's `providerId: runtimeOverride ? undefined : o.providerId`. + async function persistStartedSessionProvider(session, opts, assertAccess, runtimeOverride = null) { + try { + const db = getDbClient().drizzle; + await persistAndHydrateSessionProvider({ + sessionId: session.id, + providerId: runtimeOverride ? undefined : opts.providerId, + updateProviderId: async (targetSessionId, providerId) => { + deps.assertCurrent(); + assertAccess?.(); + await db.update(sessions).set({ providerId }).where(eq(sessions.id, targetSessionId)); + }, + readProviderId: async (targetSessionId) => { + const [pRow] = await db + .select({ providerId: sessions.providerId }) + .from(sessions) + .where(eq(sessions.id, targetSessionId)) + .limit(1); + return pRow?.providerId; + }, + hydrateSessionProvider: (...args) => { assertAccess?.(); hydrateSessionProvider(...args); }, + }); + } catch (err) { + log.warn('session provider persistence failed; refusing task startup', { + sessionId: session.id, + error: err instanceof Error ? err.message : String(err), + }); + // A duplicate create can reuse a running Session; do not interrupt its turn. + await deps.getMaker().closeSessionIfCurrent(session, 'requested', { onlyIfIdle: true }).catch((closeError) => { + log.warn('failed to close task after provider persistence failure', { + sessionId: session.id, error: String(closeError), + }); + }); + throwIpcError('PRECONDITION_FAILED', 'Could not save the selected model provider. Retry the task.'); + } + } + async function readAutoReviewHistory(id) { deps.assertCurrent(); await historyFor(id).drain(); @@ -269,9 +818,40 @@ export function createTurnExecutor(deps) { listen(id, session); } + // The desktop's write FIFO does not pause on a failed write (messagePersistBroadcaster.ts + // enqueueDurableWrite pauses only when given onPersistenceError, which the desktop never passes); + // the Host's pauses the task's reply writes after one, until it is retried. Used for two reads (the + // plan snapshot, the goal note) and two best-effort writes (clearing a sealed plan, recording the + // turn's model and its model-change card): they wait behind the task's writes, as on the desktop, + // and their failure goes back to the caller (which skips the note or logs) without pausing the task. + function behindDurableWrites(id, label, fn) { + return historyFor(id).enqueueDurableWrite(label, () => Promise.resolve().then(fn) + .then(value => ({ value }), error => ({ error }))) + .then(result => { if ('error' in result) throw result.error; return result.value; }); + } + const reconcileCreateOptsWithDb = createSessionOptionsReconciler({ log, readSession: readExecutionSession }); - const statDirectory = deps.statDirectory ?? fs.stat; - const transaction = createMakerSendTransaction({ + // The desktop's working-directory check and recovery (working-directory.ts). + const workingDirectory = createHostWorkingDirectory({ + stat: deps.statDirectory, + readBoundWorkingDir: async id => [deps.getMaker().getSession(id)?.workDir || null, + await readExecutionSession(id).then(row => row.workingDir ?? null, () => null)], + listActiveSessions: () => deps.getMaker().listActiveSessions?.() ?? [], + log, + }); + const statDirectory = workingDirectory.statDirectory; + const transactionDeps = { + // A model or engine the user picked lands when the message is sent, before the runtime is read + // (makerSendTransaction.ts), with the desktop's steps (runtime-selection.ts). + applyPendingAgentSwitch: deps.applyPendingAgentSwitch, + prepareUnhealthySession: deps.prepareUnhealthySession, + prepareRuntimeTurn(id, message, signal) { + const turn = turns.get(id); + if (!turn) return; + return deps.getTaskRuntimePlugins?.()?.prepareRuntimeTurn(id, message, signal, turn.check); + }, + prepareRuntimePrompt: id => deps.getTaskRuntimePlugins?.()?.prepareTaskPromptForSend(id), + composeRuntimeContext: (id, text, signal) => deps.getTaskRuntimePlugins?.()?.composeRuntimeContext(id, text, signal), // A server's OS language is not the remote user's interface preference. getResolvedMainLocale: deps.getResolvedMainLocale ?? (() => null), getMainClassicalStyle: deps.getMainClassicalStyle ?? (() => DEFAULT_CLASSICAL_REPLY_STYLE), @@ -286,15 +866,14 @@ export function createTurnExecutor(deps) { if (session) assertHostTaskExecutionSupported(session); if (createOpts) assertHostTaskExecutionSupported(createOpts); }, - checkWorkDirExists: async (id, dir) => { + checkWorkDirExists: async (id, ...args) => { await readExecutionSession(id); - if (!dir) return true; - try { return (await statDirectory(dir)).isDirectory(); } - catch (error) { - if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return false; - throw error; - } + return workingDirectory.checkWorkDirExists(id, ...args); }, + resolveRecoveredWorkingDir: workingDirectory.resolveRecoveredWorkingDir, + isPersistedWorktreeFallback: workingDirectory.isPersistedWorktreeFallback, + peekWorkingDirectoryRecoveryNote: workingDirectory.peekWorkingDirectoryRecoveryNote, + consumeWorkingDirectoryRecoveryNote: workingDirectory.consumeWorkingDirectoryRecoveryNote, statDirectory, readSessionWorkingDirFromDb: async id => (await readExecutionSession(id)).workingDir ?? null, readSessionWorkingDirState: async id => ({ exists: true, workingDir: (await readExecutionSession(id)).workingDir ?? null }), @@ -310,10 +889,16 @@ export function createTurnExecutor(deps) { readSessionExtraDirsFromDb: deps.readSessionExtraDirs ?? (async () => []), readSessionWritableDirsFromDb: deps.readSessionWritableDirs ?? (async () => []), withRehydrateCloseSuppressed, - bootstrapSession: async (opts, assertStartupCurrent) => { + // assertAccess and nativeHistoryResume as the desktop's bootstrapSession (register.ts) takes them + // from a committed engine switch (agentSwitchDepsCore.ts createSwitchedSessionBootstrap): the owner + // check before the start, and a parked native session that must resume or fail (the switch then + // handles the failure; no fresh start here). + bootstrapSession: async (opts, assertAccess, nativeHistoryResume = false, routeStartupSignal) => { const previous = turns.get(opts.id); const turn = previous?.running ? previous : undefined; turn?.check(); + assertAccess?.(); + if (nativeHistoryResume) opts.vendorOptions = { ...opts.vendorOptions, _cindyRequireNativeResume: true }; const preparing = (async () => { const stored = await readExecutionSession(opts.id); assertHostTaskExecutionSupported(opts); @@ -325,13 +910,34 @@ export function createTurnExecutor(deps) { persistExistingSession: async () => { throw new Error('Host must not rewrite directory grants at startup'); }, }); deps.assertCurrent(); - assertStartupCurrent?.(); + assertAccess?.(); + turn?.check(); + // The resume id is known before the start admission reads it: a verified resume of the task's + // stored route keeps that route (register.ts admitLocalRoute). The admission may reroute + // `providerId` before createSession freezes it (start-options.ts). + // Kept for the flow of o.resumeSessionId in the desktop's bootstrapSession, which the admission + // reads already set. Every current caller brings the task row's id (the shared options + // reconciler, the cold Pi check, the engine switch, storedSessionOptions), so the fallback to + // stored.sdkSessionId takes no different value; for that reason no test covers this step alone. + opts.resumeSessionId = opts.resumeSessionId ?? (opts.agentKind === makerKind(stored.agentKind) ? stored.sdkSessionId || undefined : undefined); + // The accepted runtime mutation (an automatic route fallback) wins over the stored route, + // before the start admission, through the desktop's own step. The Host refuses provider-group + // tasks at admission (send-preflight.ts), so a provider group never decides the source. + const runtimeOverride = applySessionRuntimeOverrideForStart(opts, false); + await deps.admitLocalRoute(opts); + assertAccess?.(); turn?.check(); - const session = await deps.getMaker().createSession({ ...opts, - resumeSessionId: opts.resumeSessionId ?? (opts.agentKind === makerKind(stored.agentKind) ? stored.sdkSessionId || undefined : undefined), - }, turn?.sendOpts.signal); + const turnSignal = turn?.sendOpts.signal; + const signal = routeStartupSignal && turnSignal ? AbortSignal.any([routeStartupSignal, turnSignal]) + : routeStartupSignal ?? turnSignal; + const taskPlugins = deps.getTaskRuntimePlugins?.(); + const session = await (taskPlugins + ? taskPlugins.createSessionWithRuntimePlugins({ ...opts }, signal) + : deps.getMaker().createSession({ ...opts }, signal)); deps.assertCurrent(); turn?.check(); + await persistStartedSessionProvider(session, opts, assertAccess, runtimeOverride); + turn?.check(); rememberLiveSessionSettings(session, opts); setSessionProvider(opts.id, opts.providerId ?? null); wireNotes.reset(opts.id); @@ -349,14 +955,20 @@ export function createTurnExecutor(deps) { prepareSendUserMessage: deps.prepareUserMessage ?? prepareHostUserMessage, // The trusted /learn Skill of a persisted user turn, as on the desktop (learn-capture.ts). captureCindyLearnInvocation: deps.captureCindyLearnInvocation ?? createHostLearnInvocationCapture({ getMaker: deps.getMaker }), + // The turn's user row, through the one entry the desktop writes it from (register.ts:17811, + // createUserMessageDurably): it recharges the resume budgets for a person's message, registers an + // auto-resume's pending outcome, and writes the row behind the task's reply rows with its + // transcript anchor. A failed write goes back to the transaction, as on the desktop: it does not + // pause the task's reply writes and is not written later (auto-resume.ts). As on the desktop, the + // turn is checked once, before the row queues behind the reply rows; a turn cancelled while it + // waits still gets its row, as register.ts:17811 passes createUserMessageDurably unwrapped. There is + // no other path: an executor without the auto-resume runtime refuses to write a user row. createDbMessage: async (id, message, options) => { - const history = historyFor(id); - await history.drain(); const turn = turns.get(id); turn?.check(); - const transcriptParentUuid = history.getLastAssistantTranscriptUuid(id); - return deps.persistMessage(id, { ...message, agentKind: turn?.dbKind, - agentMeta: { ...message.agentMeta, ...(transcriptParentUuid ? { transcriptParentUuid } : {}) } }, options); + const autoResume = deps.getAutoResume?.(); + if (!autoResume) throw new Error('user row write requires the auto-resume runtime (input-queue.mjs)'); + return autoResume.createUserMessage(id, { ...message, agentKind: turn?.dbKind }, options); }, isSessionRunningError, reconcileCreateOptsWithDb, @@ -375,6 +987,7 @@ export function createTurnExecutor(deps) { }, assertScheduledDispatchRoute: async id => { await readExecutionSession(id); }, beforeProviderStart: async id => { + deps.getTaskRuntimePlugins?.()?.assertTaskPromptCurrent(id); const turn = turns.get(id); turn.check(); await turn.sendOpts.beforeProviderStart?.(); @@ -418,14 +1031,41 @@ export function createTurnExecutor(deps) { } }) : undefined, readTaskSource: async id => (await readExecutionSession(id)).source ?? null, + // Sending to an archived task makes it active first (task-restore.ts), as on the desktop. + restoreArchivedSessionForSend: deps.restoreArchivedSessionForSend, // Desktop register.ts: a direct (non-queued) user turn takes the Git baseline // before dispatch and drops it when the turn is not dispatched. beforeDispatchDirectUserTurn: startGitBaseline, onUndispatchedDirectUserTurn: id => { const turn = turns.get(id); if (turn) settleGitBaseline(id, turn, 'abort'); }, readHostDeviceIdentity: deps.readHostDeviceIdentity, planRepeatableWireNotes: (id, notes, options) => wireNotes.plan(id, notes, options), + // The plan reconciliation and goal notes, read behind the task's durable writes, as register.ts + // reads them behind its write FIFO (so a reply still being stored is not missed). + peekPlanReconcileNote: async id => { + const snapshot = await behindDurableWrites(id, `plan-reconcile-read:${id}`, () => readCodexPlanState(id)); + if (!snapshot) return null; + if (snapshot.state === 'sealed') return { note: buildCompletedPlanGuardNote(), sealedTurnId: snapshot.turnId }; + const openSteps = snapshot.plan.filter(item => item.status !== 'completed').map(item => item.step); + if (openSteps.length === 0 && snapshot.state !== 'interrupted') return null; + return { note: buildPlanReconcileNote({ openSteps, totalSteps: snapshot.plan.length }) }; + }, + consumeSealedPlanReconcileNote: (id, turnId) => + behindDurableWrites(id, `plan-seal-consume:${id}:${turnId}`, () => clearSealedCodexPlanState(id, turnId)), + peekGoalInactiveNote: id => behindDurableWrites(id, `goal-inactive-read:${id}`, () => peekGoalInactiveNote(id)), + // Which model ran a dispatched user turn, and a model-change card when it changed (turnModelAttribution.ts). + onModelDispatched: (id, clientId) => createTurnModelAttribution({ + maker: deps.getMaker(), getSessionProvider, + captureDataOwnerBroadcastScope: () => deps.getOwner?.() ?? null, + isDataOwnerBroadcastScopeCurrent: owner => (deps.getOwner?.() ?? null) === owner && deps.isCurrent(), + enqueueDurableWrite: (label, write) => behindDurableWrites(id, label, write), + patchMessageAgentMeta: async (sessionId, messageClientId, patch) => + (await patchMessageAgentMetaWithResultRow(getDbClient(), sessionId, messageClientId, patch)) !== null, + createDbMessage: (sessionId, body) => deps.persistMessage(sessionId, body), + log, + })(id, clientId), log, - }); + }; + const transaction = createMakerSendTransaction(transactionDeps); function assertSteerCurrent(id, opts) { deps.assertCurrent(); @@ -499,7 +1139,9 @@ export function createTurnExecutor(deps) { const turn = { running: true, terminal: false, dbKind: dbKind(createOpts.agentKind), createOpts, sendOpts, clientId, previousGeneration: turns.get(sessionId)?.generation }; turns.set(sessionId, turn); + const ownerGeneration = getActiveAppSession().generation; turn.check = () => { + if (getActiveAppSession().generation !== ownerGeneration) throw new Error('input runtime owner changed'); deps.assertCurrent(); sendOpts.signal?.throwIfAborted(); if (turns.get(sessionId) !== turn) throw new Error('input runtime was replaced'); @@ -519,6 +1161,8 @@ export function createTurnExecutor(deps) { onVendorTurnReserved: generation => { turn.check(); bindTurnSession(sessionId, deps.getMaker().getSession(sessionId)); + // As the desktop's provider start (sessionTurnObserver.ts): a newer turn ends a pending silent-stop decision. + silentStop?.supersede(sessionId); turn.generation = generation; turn.sendOpts.onVendorTurnReserved?.(generation); }, @@ -539,15 +1183,12 @@ export function createTurnExecutor(deps) { async function sendUnlocked(sessionId, message, createOpts, sendOpts) { createOpts = { ...createOpts }; const turn = openTurn(sessionId, createOpts, sendOpts, sendOpts.persistUserMessage?.clientId); + // An automatic resume continues an earlier input whose stream (/api/chat) still waits for it. + if (sendOpts.persistUserMessage?.autoResume === true) turn.resumeOf = deps.resumeOriginOf?.(sessionId); const check = turn.check; turn.preparing = (async () => { await sendOpts[MCP_APP_MESSAGE_GUARD]?.(); check(); - // The send lock is held. Read the committed route and native identity below. - const nextInput = typeof message === 'string' ? message : message?.content; - const nextInputChars = (typeof nextInput === 'string' ? nextInput : extractPlainText(nextInput)).length; - await deps.applyPendingAgentSwitch?.(sessionId, sendOpts.signal, nextInputChars); - check(); const stored = await readExecutionSession(sessionId); const queuedPlan = createOpts.planMode; await reconcileCreateOptsWithDb(sessionId, createOpts); @@ -622,6 +1263,30 @@ export function createTurnExecutor(deps) { return { send, + /** + * What starting a task's runtime outside a turn reads, as the desktop binds the same functions + * for the send transaction and for a cold Pi runtime's window check (register.ts + * createColdPiRehydrationForWindowVerification): the start options with the stderr capture, the + * working directory check, the Orca and directory option preparation, and the bootstrap, which + * creates the runtime and listens to it as a send does. + */ + startPorts: { + buildCreateOptsWithStderr: transactionDeps.buildCreateOptsWithStderr, + checkWorkDirExists: transactionDeps.checkWorkDirExists, + synthesizeOrcaVendorOptionsFromDb: transactionDeps.synthesizeOrcaVendorOptionsFromDb, + readSessionExtraDirsFromDb: transactionDeps.readSessionExtraDirsFromDb, + readSessionWritableDirsFromDb: transactionDeps.readSessionWritableDirsFromDb, + ensureRemoteReadyForSessionStart: transactionDeps.ensureRemoteReadyForSessionStart, + bootstrapSession: transactionDeps.bootstrapSession, + broadcastSessionCreated: transactionDeps.broadcastSessionCreated, + }, + /** Forgets a task's working-directory recovery at its archive or delete (working-directory.ts). */ + discardWorkingDirectoryRecovery: id => workingDirectory.discardWorkingDirectoryRecovery(id), + /** The engine of a task as its message persistence knows it (the desktop's getSessionDbAgentKind). */ + sessionDbAgentKind: id => histories.get(id)?.getSessionDbAgentKind(id) ?? null, + /** Rows of a task's turn not in the database yet, as the history view shows them (the desktop's + * getSessionThinkingSnapshots, which its history view reads, bootstrap-electron.ts readHistoryLiveMessages). */ + liveHistory: id => histories.get(id)?.getSessionThinkingSnapshots(id) ?? [], /** On shutdown, before stopping tasks: waits (bounded) for context recoveries in flight to end. */ drainRecoveriesForShutdown: () => recovery?.drainForShutdown(), /** A recovery's replay was accepted (the recovery factory's onRebuilt). */ @@ -631,6 +1296,14 @@ export function createTurnExecutor(deps) { async drainHistories() { await Promise.all([...histories.values()].map(history => history.drain())); }, /** A rebuilt native context has seen no environment notes (contextRecoveryRebuilt). */ resetWireNotes: id => wireNotes.reset(id), + /** + * Closes a task's runtime outside a turn, as a runtime refresh does: the executor lets go of the + * instance (interactions, binding, environment notes) before Maker closes it. A working-directory + * move closes an idle runtime this way (session-move.ts). + */ + closeRuntime: id => closeRuntime(id), + /** The runtime the Host binds for a task (the product-turn failure gate's current-owner check). */ + boundSession: id => bindings.get(id)?.session, async beforeDispatchUserTurn(id, item, signal, prepareSnapshot) { const turn = turns.get(id); const live = deps.getMaker()?.getSession(id); @@ -677,13 +1350,24 @@ export function createTurnExecutor(deps) { steer, readExecutionSession, readAutoReviewHistory, + assertPiSkillPreparationReady, async preparePiSkillRuntime(id, dir, assertStartupCurrent) { - const row = await readExecutionSession(id); + await assertPiSkillPreparationReady(id, dir, assertStartupCurrent); assertStartupCurrent(); - if (row.source === 'review' || makerKind(row.agentKind) !== 'pi' || row.workingDir !== dir) - throw new Error('[PRECONDITION_FAILED] Pi session is unavailable'); - await transaction.preparePiSkillRuntime(id, dir, {}, assertStartupCurrent); - deps.assertCurrent(); + const maker = deps.getMaker(); + const initial = maker.getSession(id); + try { + await transaction.preparePiSkillRuntime(id, dir, {}, assertStartupCurrent); + assertStartupCurrent(); + } catch (error) { + try { assertStartupCurrent(); } + catch (admissionError) { + const started = maker.getSession(id); + if (started && started !== initial) await maker.closeSessionIfCurrent(started, 'runtime-refresh', { onlyIfIdle: true }); + throw admissionError; + } + throw error; + } }, async restoreSession(id, options, assertCurrent) { deps.assertCurrent(); await assertCurrent(); @@ -694,21 +1378,65 @@ export function createTurnExecutor(deps) { const maker = deps.getMaker(); let session = maker.getSession(id); if (!session) { - session = await maker.createSession({ ...options, id }); - rememberLiveSessionSettings(session, options); + // As every runtime start (the bootstrap above): the start admission, then the start's provider + // on the task row. + const start = { ...options, id }; + // As the bootstrap above (the desktop restores through bootstrapSession too). + const runtimeOverride = applySessionRuntimeOverrideForStart(start, false); + await deps.admitLocalRoute(start); + deps.assertCurrent(); await assertCurrent(); + session = await maker.createSession({ ...start }); + await persistStartedSessionProvider(session, start, undefined, runtimeOverride); + rememberLiveSessionSettings(session, start); } deps.assertCurrent(); await assertCurrent(); listen(id, session); return session; }, enqueueDurableWrite(id, label, fn) { return historyFor(id).enqueueDurableWrite(label, fn); }, + /** A task's event persistence, for the auto-resume runtime (auto-resume.ts) and the reply anchor. */ + autoResumeHistory: id => historyFor(id), + // The coordinator's hooks for a user turn stored but not dispatched, as register.ts passes them: + // a retryable error row (the desktop's onTurnErrorEvent with the Pi prompt-timeout reason), and + // for a Pi prompt timeout, closing the stuck native process (no replay; the user retries). + // Host-only: the input's interrupted receipt once its error row is stored. /api/chat (chat.mjs) + // ends a message's stream on it; without it a stream for this input waited for a terminal event + // that never comes. Only this path sends it: an error claimed by context recovery (or, later, + // held by an automatic continuation) stores no row here, so that stream stays open. + persistTerminalSendError(id, message, inputClientId) { + const history = historyFor(id); + history.onTurnErrorEvent(id, { + message, ...(isPiPromptRpcTimeoutError({ message }) ? { reason: 'pi-prompt-timeout' } : {}), + }, null); + if (typeof inputClientId !== 'string') return; + void history.drain().then(() => { + if (history.hasFailedWrites() || !deps.isCurrent()) return; + deps.hub.publish({ type: 'input_receipt', sessionId: id, inputClientId, clientId: inputClientId, status: 'interrupted' }); + }); + }, + onPersistedSendRejected(id, message) { + if (!isPiPromptRpcTimeoutError({ message })) return; + void closeRuntime(id).catch(error => { + log.warn('failed to close unhealthy PI session after prompt timeout', { sessionId: id, error: errorText(error) }); + }); + }, + recordRuntimeControlError(id, data) { historyFor(id).onTurnErrorEvent(id, data, null); }, isRunning(id) { return turns.get(id)?.running === true; }, + // The turn has its terminal and its rows are still settling: still running for dispatch (isRunning). + isSettling(id) { const turn = turns.get(id); return turn?.terminal === true && turn.running === true; }, isInputRunning(id, clientId) { const turn = turns.get(id); return turn?.clientId === clientId && turn.running; }, + // Context recovery has claimed this input's terminal error and is rebuilding before its replay: + // the input is still being answered (the replay carries its client id). + isInputRecovering(id, clientId) { return recovery?.replayClientId(id) === clientId; }, + /** A context recovery of the task is running: part of its turn (input-queue.mjs releaseDesktopHold). */ + isRecovering(id) { return recovery?.isRecovering(id) === true; }, reconcileIdle(id) { const turn = turns.get(id); if (!turn?.abortRequested || turn.terminal || turn.session?.isTurnRunning?.() !== false) return false; - // finish owns the durable terminal. Its asynchronous settlement releases - // the coordinator; returning true here would let the next input overtake it. + // finish owns the durable terminal and its asynchronous settlement wakes the coordinator. What + // holds the next input until the rows settle is isRunning (the coordinator rechecks it before any + // dispatch; input-queue.test.mjs 'the next input is not dispatched before the reply rows settle'); + // this only reports that the turn has not been reconciled, so no idle is claimed while it writes. void finish(id, turn); return false; }, diff --git a/apps/host/src/agent/turn-settlement.ts b/apps/host/src/agent/turn-settlement.ts new file mode 100644 index 00000000000..6453cfa8b0e --- /dev/null +++ b/apps/host/src/agent/turn-settlement.ts @@ -0,0 +1,215 @@ +// A profile hold spans two input runtimes. Keep acceptance evidence with the +// pending choice, outside either queue. The Host uses an in-process SQLite DB. +import { eq } from 'drizzle-orm'; +import { getActiveAppSession } from '../../../desktop/src/main/appSessionState.ts'; +import { getCurrentDbClientSnapshot } from '../../../desktop/src/main/localDb/client/current.ts'; +import { sessions } from '../../../desktop/src/main/localDb/schema.ts'; +import type { CredentialSettlementPermit, PendingCredentialSwitch, PendingCredentialSwitchService } from '../../../desktop/src/main/maker-ipc/pendingCredentialSwitch.ts'; +import { cancelPendingSessionRuntimeMutation, getPendingSessionRuntimeMutation } from '../../../desktop/src/main/maker-ipc/sessionRuntimeControl.ts'; + +function readRoute(id: string) { + // The desktop's runtime route key identifies the engine, model, provider and + // device. Include the saved remote host as well when comparing the task row. + const db = getCurrentDbClientSnapshot(); + return db?.client.drizzle.select({ + engine: sessions.agentKind, model: sessions.model, provider: sessions.providerId, + device: sessions.agentDeviceId, host: sessions.remoteHostId, + }).from(sessions).where(eq(sessions.id, id)).get(); +} + +function captureOwner() { + return { db: getCurrentDbClientSnapshot(), account: getActiveAppSession().generation }; +} +type Owner = ReturnType; +function capture(id: string) { + return { ...captureOwner(), route: readRoute(id) }; +} +type Acceptance = ReturnType; +const sameOwner = (accepted: Owner | undefined) => !!accepted?.db && + accepted.db === getCurrentDbClientSnapshot() && accepted.account === getActiveAppSession().generation; +function sameRoute(id: string, accepted: Acceptance | undefined) { + const then = accepted?.route; + const now = readRoute(id); + return !!now && !!then && now.engine === then.engine && now.model === then.model && + now.provider === then.provider && now.device === then.device && now.host === then.host; +} + +interface Deferred { + owner: Owner; + unobservedGeneration?: number; + credential?: PendingCredentialSwitch; + runtime?: number; + staleRuntime?: boolean; +} + +export function createHostTurnSettlement(ports: { + open(): boolean; + busy(id: string): boolean; + retry(id: string): void; + credentials(): PendingCredentialSwitchService; + applyControl(id: string): void; + onControlError(id: string, error: unknown): void; +}) { + const credentialAcceptance = new WeakMap(); + const controls = new Map(); + const deferred = new Map(); + const active = new Map }>(); + const applyingControl = new Map[] }>(); + let holdOwner: Owner | undefined; + const waitingForCredentials = new Set(); + const retryScheduled = new Set(); + + function retryIfIdle(id: string) { + if (active.has(id) || retryScheduled.has(id) || !ports.open()) return; + retryScheduled.add(id); + queueMicrotask(() => { + retryScheduled.delete(id); + if (ports.open() && !ports.busy(id)) ports.retry(id); + }); + } + + function defer(id: string) { + const pending = getPendingSessionRuntimeMutation(id); + deferred.set(id, { + owner: deferred.get(id)?.owner ?? holdOwner ?? captureOwner(), + unobservedGeneration: pending && pending.generation !== controls.get(id)?.generation ? pending.generation : undefined, + }); + } + + const permit: CredentialSettlementPermit = { + registered(id, target) { + credentialAcceptance.set(target, capture(id)); + if (!ports.open()) defer(id); + }, + allows(id, target) { + if (!ports.open()) return false; + if (deferred.has(id) && ports.busy(id)) return false; + if (deferred.has(id) && deferred.get(id)?.credential !== target) { + // A retry after rebuild must pass the same ordered checks as the terminal. + retryIfIdle(id); + return false; + } + return sameOwner(credentialAcceptance.get(target)); + }, + }; + function observeControl(id: string) { + const pending = getPendingSessionRuntimeMutation(id); + if (!pending) { controls.delete(id); return; } + if (controls.get(id)?.generation === pending.generation) return; + // A projection arriving after a hold cannot vouch for the earlier acceptance. + if (!ports.open()) { defer(id); return; } + if (deferred.get(id)?.unobservedGeneration === pending.generation) return; + controls.set(id, { generation: pending.generation, accepted: capture(id) }); + } + function hold(knownTasks: Iterable) { + holdOwner = captureOwner(); + // Revoke any in-flight admission before either the timer or a late DB read resumes. + const ids = new Set([...deferred.keys(), ...active.keys(), ...controls.keys()]); + for (const id of knownTasks) if (getPendingSessionRuntimeMutation(id)) ids.add(id); + for (const [id] of ports.credentials().entries()) ids.add(id); + for (const id of ids) defer(id); + } + const allowedControl = (id: string, generation: number) => + ports.open() && sameOwner(applyingControl.get(id)?.owner) && (!deferred.has(id) || (!ports.busy(id) && deferred.get(id)?.runtime === generation)); + + async function run(id: string): Promise { + if (!ports.open()) { defer(id); return false; } + const admission = deferred.get(id); + const ownerAtStart = captureOwner(); + const current = () => ports.open() && admission === deferred.get(id) && !ports.busy(id) && + ownerAtStart.db === getCurrentDbClientSnapshot() && ownerAtStart.account === getActiveAppSession().generation; + if (!current()) return false; + const service = ports.credentials(); + const previous = service.waitForIdle(id); + if (previous) await previous; + if (!current()) return false; + const credential = service.get(id); + if (credential) { + const accepted = credentialAcceptance.get(credential); + const ownerCurrent = sameOwner(accepted); + if (!ownerCurrent || (admission && !sameRoute(id, accepted))) { + // The desktop owns its new route. Never restore the old row on invalidation. + service.discard(id, credential, ownerCurrent); + } else { + if (admission) admission.credential = credential; + waitingForCredentials.add(id); + await service.onTurnSettled(id); + } + } + if (!current() || service.has(id)) return false; + waitingForCredentials.delete(id); + const control = getPendingSessionRuntimeMutation(id); + if (control) { + // The producer can yield between accepting a mutation and publishing it. + // With uninterrupted ownership the terminal can complete its registration. + let saved = controls.get(id); + if ((admission && !sameOwner(admission.owner)) || (saved && !sameOwner(saved.accepted))) { + cancelPendingSessionRuntimeMutation(id, control.generation); + } else { + if (!admission && saved?.generation !== control.generation) { + observeControl(id); + saved = controls.get(id); + } + if (admission) { + admission.runtime = control.generation; + admission.staleRuntime = saved?.generation !== control.generation || !sameRoute(id, saved.accepted); + } + const work: Promise[] = []; + applyingControl.set(id, { owner: saved?.accepted ?? ownerAtStart, work }); + try { + ports.applyControl(id); + // A finally can start the next generation before this one completes. + for (const generation of work) await generation; + } finally { applyingControl.delete(id); } + const latest = getPendingSessionRuntimeMutation(id); + if (current() && latest && latest.generation !== control.generation) return run(id); + } + } + if (!current() || getPendingSessionRuntimeMutation(id)) return false; + deferred.delete(id); + controls.delete(id); + return true; + } + function settle(id: string): Promise { + const running = active.get(id); + if (running) { + // A terminal started before the hold. After its outstanding I/O drains, + // the rebuilt runtime still owes a fresh comparison against the stored row. + if (running.admission !== deferred.get(id) && ports.open()) return running.work.then(() => settle(id)); + return running.work; + } + const admission = deferred.get(id); + const work = run(id).finally(() => active.delete(id)); + active.set(id, { admission, work }); + return work; + } + return { + permit, hold, observeControl, settle, allowedControl, + onControlWork(id: string, generation: Promise) { + const handled = generation.catch(error => ports.onControlError(id, error)); + applyingControl.get(id)?.work.push(handled); + }, + pendingIds: () => [...deferred.keys()], + deferredDbKind(id: string) { + // The rebuilt executor has no live history yet. The credential write must + // still reconcile effort/window against the stored task's engine. + if (!deferred.has(id)) return null; + const kind = readRoute(id)?.engine; + return kind === 'cc' || kind === 'pi' || kind === 'codex' ? kind : null; + }, + credentialApplied(id: string) { + if (waitingForCredentials.has(id)) retryIfIdle(id); + }, + dispose() { + holdOwner = undefined; + for (const [id] of ports.credentials().entries()) ports.credentials().clear(id); + deferred.clear(); + controls.clear(); + applyingControl.clear(); + waitingForCredentials.clear(); + }, + assertControl(id: string, generation: number) { + if (!allowedControl(id, generation) || deferred.get(id)?.staleRuntime) throw new Error('pending runtime route changed or settlement deferred'); + }, + }; +} diff --git a/apps/host/src/agent/usage-pricing.test.mjs b/apps/host/src/agent/usage-pricing.test.mjs new file mode 100644 index 00000000000..8c1710d97ca --- /dev/null +++ b/apps/host/src/agent/usage-pricing.test.mjs @@ -0,0 +1,309 @@ +/* + * 测试价值 + * - 生产入口:providers.mjs 的 createProviderCatalog(Host 唯一的 /models 轮次)加 + * usage-pricing.ts 的 createHostUsagePricing(桌面 modelPricingCore 的 Host 实例),接法与 + * main.ts 相同:applyPricedModels → replaceGatewayModelPricing,trackModelsSync → + * trackGatewayModelPricingSync。 + * - 规则:放行表第 13 行 3a。桌面只在一次 /models 成功和账号边界替换 XD 报价 + * (model-access/index.ts applyGatewayModels);Host 的 applyModels 在两轮之间的每次读取和 + * 失败轮也会调用,若把价格挂在那里,会每次重写缓存、失败时用旧列表重算。Host 原来 + * /api/usage/model-pricing 恒为 null。 + * - 覆盖缺口:桌面 modelPricing.test.ts 只测桌面壳与 mock 端口;Host 没有任何定价测试。 + * - 最小输入:一个带价格的 XD 模型、一次失败轮、一次账号代际变化、一次 Key 文件替换。 + * tier:unit,无网络、无子进程、无真实等待。 + * + * 凭据状态(最后两条用例,审核方 2026-11-17 定对齐桌面): + * - 生产入口:model-access.ts 的 createHostModelAccess(桌面 credentialsSync 的 Host 实例),它的 + * publish 照 main.ts 交给 listProviders.noteCredentialStatus。 + * - 规则:桌面 model-access/index.ts 的 onStatusChange 在 failed(437–439)与 + * disabled / unsupported / idle(440–441)时传空列表,清掉 XD 报价;ok 时才发起下一轮 /models + * (432)。继续显示已失效账号的价格,用户会以为还能按那个价格用。 + * - 覆盖缺口:上面三条用例只走 /models 轮次与账号边界;Host 原来不听凭据状态,凭据失败后旧报价照旧答复。 + * - 最小失败输入:一次成功同步后,一次 failed(新 Key 存不下,SAFE_STORAGE_UNAVAILABLE)或一次 + * disabled(503),再一次恢复到 ok。tier:unit。 + * - 实测:Host 的 node --import tsx --import ./src/loaders/register-raw.mjs --test 单文件, + * 见交付记录。 + * + * 清理(集成分支负载下偶发 ENOTEMPTY):价格快照(modelPricingCore writeDiskCache)和账本币种 + * (accountCurrencyStore 的写链:读、mkdir cache、写临时文件、改名)都是不等待的写入。测试结束时它们 + * 可能还在线程池里,与 t.after 的 rmSync 交错,就会在已清空的 profile 里重建 cache/。每个 profile 上的 + * 异步 fs 调用在这里登记,清理前等它们全部落完(不是重试 rm,也不是固定延时)。 + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { createProviderCatalog } from './providers.mjs'; +import { createHostUsagePricing } from './usage-pricing.ts'; +import { configureHostOwner } from './claude-auth.mjs'; +import { createHostModelAccess } from './model-access.ts'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../../desktop/src/main/localDb/client/current.ts'; +import { resolveOwnerScopedSecretStorageKey } from '../../../desktop/src/main/secrets/providerSecretOwnerKey.ts'; +import { providerSecretStorageKey } from '../../../desktop/src/shared/providerSecrets.ts'; +import { commitVolatileAppSession } from '../../../desktop/src/main/appSessionState.ts'; + +const profileWrites = new Map(); +/** Every async fs call the production code makes under a test profile, so cleanup can wait for them. */ +for (const name of ['mkdir', 'writeFile', 'rename', 'readFile', 'rm', 'lstat', 'stat']) { + const original = fs.promises[name]; + fs.promises[name] = function (target, ...rest) { + const result = original.call(this, target, ...rest); + const file = String(target); + for (const [root, pending] of profileWrites) { + if (file.startsWith(root)) { + pending.add(result); + result.then(() => pending.delete(result), () => pending.delete(result)); + } + } + return result; + }; +} + +/** Until no fs call on the profile is in flight, including those a landing one starts (the currency write chain). */ +async function settleProfile(root) { + const pending = profileWrites.get(root); + while (pending?.size) { + await Promise.allSettled([...pending]); + await new Promise(resolve => setImmediate(resolve)); + } +} + +const PRICED = [{ id: 'claude-sonnet-4', currency: 'USD', inputCostPerToken: 0.000003, outputCostPerToken: 0.000015 }]; + +/** A Host profile with one owner, its DB slot, a gateway key file and the two production pieces. */ +function setup(t, ownerId) { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-pricing-')); + profileWrites.set(profile, new Set()); + configureHostOwner({ userDataDir: profile, ownerId }); + const client = {}; + setCurrentDbClient(client, ownerId); + const keyFile = path.join(profile, 'safe-storage', `${resolveOwnerScopedSecretStorageKey(providerSecretStorageKey('xd'))}.enc`); + fs.mkdirSync(path.dirname(keyFile), { recursive: true }); + fs.writeFileSync(keyFile, 'encrypted-key-a'); + t.after(async () => { + // The price snapshot and the ledger currency are written without waiting: let them land first. + await settleProfile(profile); + profileWrites.delete(profile); + clearCurrentDbClient(client); + fs.rmSync(profile, { recursive: true, force: true }); + }); + const pricing = () => createHostUsagePricing({ profileDir: profile, modelAccessApiBaseUrl: () => 'https://model-access.example.test' }); + const rounds = []; + const fed = []; + let generation = 1; + const catalog = (usagePricing, isProfileHeld) => createProviderCatalog({ + readProviders: async () => [], + applyModels: () => {}, + readModels: () => [], + fetchModels: async () => { const next = rounds.shift(); if (next instanceof Error) throw next; return next; }, + readOwner: () => ({ dataOwnerId: ownerId, generation, pending: false }), + applyPricedModels: (models, owner) => { fed.push(models.length); usagePricing.replaceGatewayModelPricing(models, owner); }, + trackModelsSync: sync => usagePricing.trackGatewayModelPricingSync(sync), + isProfileHeld, + }); + const list = (listProviders, force = false) => + listProviders({ gateway: { endpoint: 'https://gateway.example.test', credential: 'key-a' }, ownerId, force }); + return { profile, keyFile, pricing, catalog, rounds, fed, list, cacheFile: path.join(profile, 'cache', 'model-pricing.json'), + settle: () => settleProfile(profile), + nextGeneration: () => { generation += 1; } }; +} + +test('a successful /models round feeds the Host prices; reads between rounds and a failed round keep them', async t => { + const env = setup(t, 'pricing-owner-rounds'); + const usagePricing = env.pricing(); + const listProviders = env.catalog(usagePricing); + env.rounds.push(PRICED); + await env.list(listProviders); + const first = await usagePricing.getGatewayModelPricing(); + assert.equal(first?.xd?.['claude-sonnet-4']?.inputPerMtok, 3); + assert.equal(first?.xd?.['claude-sonnet-4']?.currency, 'USD'); + await env.settle(); + assert.ok(fs.existsSync(env.cacheFile), 'the price snapshot reaches the profile'); + const written = fs.readFileSync(env.cacheFile, 'utf8'); + const writtenAt = fs.statSync(env.cacheFile).mtimeMs; + + // Between rounds and after a failed round the catalog re-applies its list; the prices stay. + await env.list(listProviders); + env.rounds.push(new Error('model access unavailable')); + const failed = await env.list(listProviders, true); + assert.equal(failed.error, 'Model access could not be refreshed. Try again.'); + assert.deepEqual(env.fed, [1], 'only the successful round feeds the prices'); + assert.deepEqual(await usagePricing.getGatewayModelPricing(), first); + assert.equal(fs.readFileSync(env.cacheFile, 'utf8'), written); + assert.equal(fs.statSync(env.cacheFile).mtimeMs, writtenAt); +}); + +// Rule: a providers read cannot write shared pricing while the desktop holds the profile. +// Gap: the existing admission check ran before fetching, so a response could arrive during the hold. +// Minimal input: a forced round crosses into a hold while the previous price is still fresh. +// Tier: unit through the Host provider catalog and pricing writer with a temporary profile. +test('a model response that arrives during a desktop hold leaves the pricing files unchanged', async t => { + const env = setup(t, 'pricing-owner-held'); + const usagePricing = env.pricing(); + let held = false; + const listProviders = env.catalog(usagePricing, () => held); + const readFiles = () => [env.cacheFile, path.join(env.profile, 'cache', 'ledger-currency.json')] + .map(file => fs.readFileSync(file)); + env.rounds.push(PRICED); + await env.list(listProviders); + await env.settle(); + const before = readFiles(); + + let reply; + env.rounds.push(new Promise(resolve => { reply = resolve; })); + const refreshing = env.list(listProviders, true); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(env.rounds.length, 0, 'the refresh has started'); + held = true; + reply([{ ...PRICED[0], currency: 'CNY', inputCostPerToken: 0.000009 }]); + await refreshing; + await env.settle(); + assert.deepEqual(env.fed, [1], 'the round never reaches the pricing writer'); + assert.deepEqual(readFiles(), before); + + held = false; + env.rounds.push([{ ...PRICED[0], inputCostPerToken: 0.000006 }]); + await env.list(listProviders); + assert.deepEqual(env.fed, [1, 1], 'the next ordinary read refreshes'); + assert.equal((await usagePricing.getGatewayModelPricing())?.xd?.['claude-sonnet-4']?.inputPerMtok, 6); +}); + +test('a fresh Host process restores the price snapshot from its profile before any round', async t => { + const env = setup(t, 'pricing-owner-restart'); + const before = env.pricing(); + env.rounds.push(PRICED); + await env.list(env.catalog(before)); + const expected = await before.getGatewayModelPricing(); + await env.settle(); + assert.ok(fs.existsSync(env.cacheFile), 'the price snapshot reaches the profile'); + + const after = env.pricing(); + await after.prewarmModelPricing(); + assert.deepEqual(await after.getGatewayModelPricing(), expected); + assert.equal(await after.getGatewayAccountCurrency('pricing-owner-restart'), 'USD'); +}); + +test('an account boundary clears the prices, and a replaced key file retires the cached snapshot', async t => { + const env = setup(t, 'pricing-owner-boundary'); + const usagePricing = env.pricing(); + const listProviders = env.catalog(usagePricing); + env.rounds.push(PRICED); + await env.list(listProviders); + assert.ok((await usagePricing.getGatewayModelPricing())?.xd); + + // Another key file (a rotated key) is another cache scope: the old snapshot no longer answers. + await env.settle(); + assert.ok(fs.existsSync(env.cacheFile), 'the price snapshot reaches the profile'); + fs.rmSync(env.keyFile); + fs.writeFileSync(env.keyFile, 'encrypted-key-b, rotated'); + assert.equal(await env.pricing().getGatewayModelPricing(), null); + + // A new owner generation is an account boundary: the catalog clears, so do the prices. + env.nextGeneration(); + env.rounds.push(new Error('the new account has not loaded yet')); + await env.list(listProviders); + assert.deepEqual(env.fed, [1, 0], 'the boundary feeds an empty list'); + assert.deepEqual(await usagePricing.getGatewayModelPricing(), {}); +}); + +// The two desktop branches: failed (437–439) and disabled / unsupported / idle (440–441). +for (const state of ['failed', 'disabled']) { + test(`credentials ${state}: the last prices stop answering, and come back with the /models round after ok`, async t => { + const env = setup(t, `pricing-owner-${state}`); + const usagePricing = env.pricing(); + const listProviders = env.catalog(usagePricing); + const endpoint = 'https://gateway.example.test'; + let key = 'fixture-key-a'; + let writable = true; + let respond = () => ({ endpoint, apiKey: key }); + const access = createHostModelAccess({ ownerId: `pricing-owner-${state}`, region: 'global', + readKey: () => key, writeKey: value => { if (!writable) return false; key = value; return true; }, + request: async () => respond(), + // As main.ts: the status the Host publishes also goes to the catalog. + publish: status => listProviders.noteCredentialStatus(status), + onKeyChanged: () => {}, + }); + t.after(() => access.close()); + assert.equal((await access.start()).state, 'ok'); + env.rounds.push(PRICED); + await env.list(listProviders); + const priced = await usagePricing.getGatewayModelPricing(); + assert.equal(priced?.xd?.['claude-sonnet-4']?.inputPerMtok, 3); + + if (state === 'failed') { + writable = false; + respond = () => ({ endpoint, apiKey: 'fixture-key-b' }); + } else { + respond = () => { throw Object.assign(new Error('model access disabled'), { code: 'MODEL_ACCESS_DISABLED', statusCode: 503 }); }; + } + assert.equal((await access.sync.retry()).state, state); + assert.deepEqual(await usagePricing.getGatewayModelPricing(), {}, 'the failed account\'s prices are gone'); + // Until the credentials recover no /models round starts, not even for a forced read (the desktop + // starts one only on ok), so no price comes back either. + env.rounds.push(PRICED); + await env.list(listProviders, true); + assert.equal(env.rounds.length, 1, 'no /models round while the credentials are held'); + assert.deepEqual(await usagePricing.getGatewayModelPricing(), {}); + + writable = true; + respond = () => ({ endpoint, apiKey: key }); + assert.equal((await access.sync.retry()).state, 'ok'); + assert.deepEqual(await usagePricing.getGatewayModelPricing(), {}, 'ok alone restores no price'); + // Not forced: ok made the last round stale, so this read runs the next /models round. + await env.list(listProviders); + assert.equal(env.rounds.length, 0, 'the read after ok ran a /models round'); + assert.deepEqual(await usagePricing.getGatewayModelPricing(), priced); + }); +} + +// 测试价值(登出,审核方 2026-11-17 选 (a):不改生产代码,固定现状) +// - 生产入口:createHostUsagePricing 的读取(/api/usage/model-pricing 用的 getGatewayModelPricing)。登出照 +// main.ts disposeOwnerRuntime 的两步:closeStorage 清掉 DB 客户端(clearCurrentDbClient),会话提交为 +// signed-out(commitVolatileAppSession)。 +// - 规则:价格按账号定。登出后不再给出上一个账号的价格(fail-closed);同一账号重新登录,价格从内存或快照立即 +// 回来;另一个账号拿不到。桌面在登出时传空列表(model-access/index.ts:574),读取得到 `{}` 并改写快照文件; +// Host 不改写,靠价格 scope(用户加 Key 文件身份)对不上而得到 null,同账号的快照因此保留(放行表第 13 行)。 +// - 现有覆盖缺口:上面的账号边界用例走的是目录换身份,不走登出。 +// - 最小失败输入:一次带价格的轮次,然后登出;再登录同一账号(Key 文件不变)或另一个账号。tier:unit。 +function logOut() { + clearCurrentDbClient(); + commitVolatileAppSession('signed-out', null, true); +} +function logIn(env, ownerId) { + configureHostOwner({ userDataDir: env.profile, ownerId }); + env.client = {}; + setCurrentDbClient(env.client, ownerId); +} +async function pricedThenLoggedOut(t, ownerId) { + const env = setup(t, ownerId); + const usagePricing = env.pricing(); + env.rounds.push(PRICED); + await env.list(env.catalog(usagePricing)); + const priced = await usagePricing.getGatewayModelPricing(); + assert.equal(priced?.xd?.['claude-sonnet-4']?.inputPerMtok, 3); + await env.settle(); + logOut(); + t.after(() => clearCurrentDbClient()); + return { env, usagePricing, priced }; +} + +test('after a logout the Host answers no price, not the last account\'s', async t => { + const { usagePricing } = await pricedThenLoggedOut(t, 'pricing-owner-logout'); + assert.equal(await usagePricing.getGatewayModelPricing(), null); +}); + +test('the same account signing in again gets its prices back at once (its key file unchanged)', async t => { + const { env, usagePricing, priced } = await pricedThenLoggedOut(t, 'pricing-owner-relogin'); + logIn(env, 'pricing-owner-relogin'); + assert.deepEqual(await usagePricing.getGatewayModelPricing(), priced, 'from memory'); + assert.deepEqual(await env.pricing().getGatewayModelPricing(), priced, 'and from the snapshot, which the logout left as it was'); +}); + +test('another account signing in after a logout cannot read the previous account\'s prices', async t => { + const { env, usagePricing } = await pricedThenLoggedOut(t, 'pricing-owner-before-switch'); + logIn(env, 'pricing-owner-after-switch'); + assert.equal(await usagePricing.getGatewayModelPricing(), null, 'from memory'); + assert.equal(await env.pricing().getGatewayModelPricing(), null, 'or from the snapshot'); +}); diff --git a/apps/host/src/agent/usage-pricing.ts b/apps/host/src/agent/usage-pricing.ts new file mode 100644 index 00000000000..eda8873a961 --- /dev/null +++ b/apps/host/src/agent/usage-pricing.ts @@ -0,0 +1,53 @@ +import { createAccountCurrencyStore } from '../../../desktop/src/main/usage/accountCurrencyStoreCore.ts'; +import { createModelPricing } from '../../../desktop/src/main/usage/modelPricingCore.ts'; +import { getReferenceModelPricing } from '../../../desktop/src/main/usage/referenceModelPricingCore.ts'; +import { resolveOwnerScopedSecretStorageKey } from '../../../desktop/src/main/secrets/providerSecretOwnerKey.ts'; +import { explicitPorts } from './explicit-ports.ts'; + +/** + * The Host's XD gateway price projection and reference prices (release table row 13, unit 3a): the + * desktop's own modelPricing / accountCurrencyStore cores, one instance each per Host process (one + * account per process, main.ts ensureRuntime). + * + * Ports, as the desktop shells bind them (usage/modelPricing.ts, usage/accountCurrencyStore.ts): + * - app.getPath('userData'): the Host profile, where the desktop keeps the same `cache/` files. + * - BrowserWindow: no windows. The Host has no push channel for usage yet (row 13, 3f); readers ask + * /api/usage/* again. + * - getClientEndpoint('modelAccessApiBaseUrl'): the account region's Model Access endpoint, the one + * main.ts fetches /models from; unavailable throws as main.ts does, as the desktop's endpoint + * service throws before it is initialized. + * - resolveOwnerScopedSecretStorageKey: the desktop's own function. The Host keeps provider keys in the + * same `safe-storage/.enc` files (credentials/store.mjs, agent/provider-config.ts), so + * the key identity in the cache scope is the desktop's. + * + * Prices are fed by the provider catalog (providers.mjs applyPricedModels) only where the desktop's + * applyGatewayModels runs: a successful /models round and an account boundary. + */ +export function createHostUsagePricing(options: { + profileDir: string; + /** The Model Access endpoint for the current account region, or nothing when unavailable. */ + modelAccessApiBaseUrl(): string | undefined; +}) { + const app = { getPath: () => options.profileDir }; + const currency = createAccountCurrencyStore(explicitPorts[0]>({ app })); + const pricing = createModelPricing(explicitPorts[0]>({ + app, + BrowserWindow: { getAllWindows: () => [] }, + getClientEndpoint: () => { + const baseUrl = options.modelAccessApiBaseUrl(); + if (!baseUrl) throw new Error('Model access endpoint is unavailable'); + return baseUrl; + }, + resolveOwnerScopedSecretStorageKey, + hydrateAccountCurrency: (...args) => currency.hydrateAccountCurrency(...args), + noteActiveAccount: (...args) => currency.noteActiveAccount(...args), + rememberAccountCurrency: (...args) => currency.rememberAccountCurrency(...args), + })); + return { + ...pricing, + /** `maker:usage:reference-model-pricing`: the catalog reference prices and user overrides. */ + readReferenceModelPricing: () => getReferenceModelPricing(), + }; +} + +export type HostUsagePricing = ReturnType; diff --git a/apps/host/src/agent/usage-push-channels.ts b/apps/host/src/agent/usage-push-channels.ts new file mode 100644 index 00000000000..b0036bfe461 --- /dev/null +++ b/apps/host/src/agent/usage-push-channels.ts @@ -0,0 +1,50 @@ +import type { BroadcastTapListener } from '../../../desktop/src/main/device-link/broadcastTapCore.ts'; + +/** + * Phase 1: the usage pushes the Host does not forward to remote devices (release table row 13, 3d; + * §二 "用量变化不推给远程设备"; §七). The desktop's usage cores send these through the device-link tap + * (tapWindowBroadcast) when they record usage or a quota snapshot; on the desktop a phone or another + * computer sees them live. The Host's usage reads and pushes are a later batch, so in phase 1 its + * remote devices see usage only when they read it again. + * + * Every `usage:` channel the device-link may forward at all (PUSH_FORWARD_ALLOWLIST) is in exactly one of + * the two lists below; agent/usage-recording.test.mjs fails on a new one, so it cannot slip through. + * Channels outside both lists and outside `usage:` are forwarded as on the desktop. + * + * Lift: delete PHASE1_UNFORWARDED_USAGE_CHANNELS (and its filter in device-link.ts) when the Host's usage + * "reads and pushes" batch lands. + */ +export const PHASE1_UNFORWARDED_USAGE_CHANNELS: ReadonlySet = new Set([ + // Turn usage records (usage-recording.ts). + 'usage:session-spend-changed', + 'usage:session-tokens-changed', + 'usage:message-turn-cost', + 'usage:message-model-mismatch', + // Quota snapshots (usageBroadcasterCore.ts, claudeAccountUsage.ts). The Host binds their refreshes + // empty in phase 1, but a snapshot another path records would still be sent. + 'usage:xai-rate-limit-changed', + 'usage:xai-provider-rate-limit-changed', + 'usage:codex-account-changed', + 'usage:codex-provider-account-changed', + 'usage:claude-subscription-changed', + 'usage:subscription-provider-account-changed', + 'usage:claude-account-changed', + 'usage:xai-subscription-changed', +]); + +/** + * `usage:` channels of PUSH_FORWARD_ALLOWLIST the Host forwards on purpose, each with its reason. None + * today. (`usage:session-context-changed`, the context occupancy, is not in PUSH_FORWARD_ALLOWLIST: the tap + * drops it on the desktop and the Host alike. `usage:today-spend-changed` and `usage:today-tokens-changed` + * go to windows only, never through the tap.) + */ +export const INTENTIONALLY_FORWARDED_USAGE_CHANNELS: ReadonlyMap = new Map(); + +/** The device-link tap listener with the phase 1 usage channels left out; every other push as given. */ +export function withoutPhaseOneUsagePushes(listener: BroadcastTapListener | null): BroadcastTapListener | null { + if (!listener) return null; + return (...args: Parameters) => { + if (PHASE1_UNFORWARDED_USAGE_CHANNELS.has(args[0])) return; + listener(...args); + }; +} diff --git a/apps/host/src/agent/usage-recording.test.mjs b/apps/host/src/agent/usage-recording.test.mjs new file mode 100644 index 00000000000..fa00e0d6173 --- /dev/null +++ b/apps/host/src/agent/usage-recording.test.mjs @@ -0,0 +1,474 @@ +// Host turn usage recording (release table row 13, 3d): the desktop's turn recorders fed by the Host's +// turn executor, over a real owner database. +// +// Test value +// - Production entry and observable result: turn-executor.mjs listen() with usage-recording.ts, as main.ts +// wires them; the daily usage tables, the task row and the reply's agent_meta in a real owner database +// (better-sqlite3, the desktop migrations), and the device-link pushes the Host forwards. +// - Rule: release table row 13 (3d, reviewer 2026-11-18): usage recorded exactly once per turn, late usage +// kept, the account that started the turn, no request on the recording path, no per-party file, phase 1 +// usage pushes not forwarded. +// - Gap: the desktop's own tests drive these recorders through its pipeline with mocked sinks; nothing ran +// them through the Host executor and its owner database. +// - Minimal failing input: one Claude done with usage after a reply (or a paired done after a terminal error). +// - Tier: Host unit (node:test), temporary profile and HOME; no network, no real account. +import { test, after, before } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { PUSH_FORWARD_ALLOWLIST } from '@cindy/device-link'; +import { createTurnExecutor } from './turn-executor.mjs'; +import { createHostUsageRecording } from './usage-recording.ts'; +import { PHASE1_UNFORWARDED_USAGE_CHANNELS, INTENTIONALLY_FORWARDED_USAGE_CHANNELS, withoutPhaseOneUsagePushes } from './usage-push-channels.ts'; +import { createHostMessageStore } from '../message-store.ts'; +import { configureHostOwner } from './claude-auth.mjs'; +import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { openOwnerDatabase } from '../../../desktop/src/main/localDb/startupCore.ts'; +import { createDbClientForHandle } from '../../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; +import { setCurrentDbClient, clearCurrentDbClient, getCurrentDbClientSnapshot } from '../../../desktop/src/main/localDb/client/current.ts'; +import { setSessionProvider } from '../../../desktop/src/main/maker-host/session-provider-store.ts'; +import * as broadcastTap from '../../../desktop/src/main/device-link/broadcast-tap.ts'; +import { recordSessionTurnSpend } from '../../../desktop/src/main/sessionSpendBroadcasterCore.ts'; +import { setActiveLedgerCurrency } from '../../../desktop/src/main/usage/ledgerCurrency.ts'; +import { hostRuntimeLayout } from '../runtime-layout.mjs'; + +const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'host-usage-recording-'))); +const savedEnv = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, shared: process.env.XDT_OFFICIAL_SHARED_PROFILE }; +process.env.HOME = path.join(root, 'home'); +process.env.USERPROFILE = path.join(root, 'home'); +fs.mkdirSync(process.env.HOME, { recursive: true }); +// A fixture profile: the development guard against migrating the official shared profile is lifted to open it. +delete process.env.XDT_OFFICIAL_SHARED_PROFILE; + +// Outbound requests on the recording path fail the test (case 10). +const realFetch = globalThis.fetch; +let fetchCalls = 0; +globalThis.fetch = async () => { fetchCalls += 1; throw new Error('no request on the usage recording path'); }; + +configureAppDataDir(path.join(root, 'app-data')); +configureHostOwner({ userDataDir: root, ownerId: 'usage-a' }); +const layout = hostRuntimeLayout(); +async function openOwner(ownerId) { + const opened = await openOwnerDatabase({ userDataDir: root, ownerId, isPackaged: false, + drizzleDir: layout.drizzleDir, sqliteVecExtPath: layout.sqliteVecPath }); + return { sqlite: opened.db, client: createDbClientForHandle({ db: opened.db, drizzle: opened.drizzle, dispose: async () => opened.db.close() }) }; +} +const ownerA = await openOwner('usage-a'); +const ownerB = await openOwner('usage-b'); +const useOwner = owner => { clearCurrentDbClient(); setCurrentDbClient(owner.client, owner === ownerA ? 'usage-a' : 'usage-b'); }; +useOwner(ownerA); +// The account's ledger currency, as a model catalog sync sets it (usage/modelPricingCore.ts). +setActiveLedgerCurrency('USD'); + +let profileHeld = false; +let gatewayPricing = null; +const usage = createHostUsageRecording({ + pricing: { getGatewayModelPricing: async () => gatewayPricing, getGatewayModelPricingForModel: async () => gatewayPricing, + getGatewayAccountCurrency: () => 'USD' }, + isOpenAiSubscriptionProviderId: () => false, + readGatewayKey: () => 'fixture-gateway-key', + codexProxyAuthInjection: () => 'env-key', + isProfileHeld: () => profileHeld, +}); +after(async () => { + usage.close(); + clearCurrentDbClient(); + await ownerA.client.dispose(); + await ownerB.client.dispose(); + globalThis.fetch = realFetch; + for (const [key, value] of [['HOME', savedEnv.HOME], ['USERPROFILE', savedEnv.USERPROFILE], ['XDT_OFFICIAL_SHARED_PROFILE', savedEnv.shared]]) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + // Windows cannot unlink either database while its SQLite handle is open. + assert.equal(ownerA.sqlite.open, false); + assert.equal(ownerB.sqlite.open, false); + fs.rmSync(root, { recursive: true, force: true }); +}); + +let taskSeq = 0; +/** A task in both owner databases, a fake runtime for it and a Host turn executor wired as main.ts does. */ +function harness({ agentKind = 'claude-code', provider = 'fixture-api', failFirstAssistantRow = false } = {}) { + const id = `task-${++taskSeq}`; + for (const owner of [ownerA, ownerB]) { + owner.sqlite.prepare(`INSERT INTO sessions(id,source,status,created_at,updated_at,model) VALUES (?, 'desktop', 'active', 1, 1, 'claude-sonnet-4-6')`).run(id); + } + setSessionProvider(id, provider); + const listeners = new Set(); + let generation = 1; + const session = { + id, instanceId: `runtime-${id}`, agentKind, remoteHostId: null, agentDeviceId: null, workDir: root, + getTurnGeneration: () => generation, isTurnRunning: () => false, + onEvent(listener) { listeners.add(listener); return () => listeners.delete(listener); }, + holdEventStream() {}, async abort() {}, + }; + const emit = event => { for (const listener of [...listeners]) listener({ sessionTurnGeneration: generation, ...event }); }; + const store = createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish() {} }); + // A failing reply write pauses the task's write queue (messagePersistBroadcaster.ts failedWrites). + let failAssistant = failFirstAssistantRow; + const persistMessage = async (sid, input, options) => { + if (failAssistant && input.role === 'assistant') { failAssistant = false; throw new Error('disk full'); } + return store(sid, input, options); + }; + const persistenceErrors = []; + let runtimeOwner = null; + const maker = { getSession: sid => (sid === id ? session : null), async closeSession() {} }; + const executor = createTurnExecutor({ + getMaker: () => maker, + assertCurrent() { if (runtimeOwner === null) runtimeOwner = getCurrentDbClientSnapshot(); if (runtimeOwner !== getCurrentDbClientSnapshot()) throw new Error('input runtime owner changed'); }, + isCurrent: () => runtimeOwner !== null && runtimeOwner === getCurrentDbClientSnapshot(), + isStoppingRuntime: () => false, hub: { publish() {} }, persistMessage, + getOwner: getCurrentDbClientSnapshot, + onPersistenceError: (_id, error) => { persistenceErrors.push(error); }, onTerminal() {}, markStarted: async () => {}, markEnded: async () => {}, + usage, runtimeOwner: () => runtimeOwner, + }); + const base = { a: globalTotals(ownerA), b: globalTotals(ownerB) }; + return { + id, session, emit, executor, persistenceErrors, + /** What this test added to an owner's daily tables, and the task's row. */ + added(owner = ownerA) { + const now = globalTotals(owner); const was = owner === ownerA ? base.a : base.b; + const task = owner.sqlite.prepare('SELECT total_cost_amount AS amount, total_token_usage AS tokens FROM sessions WHERE id = ?').get(id); + const sessionUsage = owner.sqlite.prepare('SELECT COALESCE(SUM(tokens),0) AS tokens FROM daily_session_usage WHERE session_id = ?').get(id); + return { spend: round(now.spend - was.spend), model: { input: now.input - was.input, output: now.output - was.output }, + sessionTokens: sessionUsage.tokens, task: { amount: task.amount ?? 0, tokens: task.tokens ?? 0 } }; + }, + nextGeneration() { generation += 1; }, + begin: () => executor.beginHostTurn(id), + reply(clientId, text = 'reply') { emit({ type: 'text', source: agentKind, data: { text, isFinal: true }, agentMeta: { uuid: clientId } }); }, + async settled() { + for (let i = 0; i < 20; i += 1) await new Promise(resolve => setImmediate(resolve)); + await usage.drain(); usage.open(); + }, + }; +} + +const claudeDone = (costUSD, inputTokens = 100, outputTokens = 20, extra = {}) => ({ type: 'done', source: 'claude-code', data: { + total_cost_usd: costUSD, modelUsageCumulativeStartsAtZero: true, + modelUsage: { 'claude-sonnet-4-6': { inputTokens, outputTokens, costUSD } }, ...extra } }); + +const round = value => Math.round(value * 1e6) / 1e6; +function globalTotals(owner) { + const spend = owner.sqlite.prepare('SELECT COALESCE(SUM(cost_amount),0) AS amount FROM daily_spend').get().amount; + const model = owner.sqlite.prepare('SELECT COALESCE(SUM(input_tokens),0) AS input, COALESCE(SUM(output_tokens),0) AS output FROM daily_model_usage').get(); + const sessionTokens = owner.sqlite.prepare('SELECT COALESCE(SUM(tokens),0) AS tokens FROM daily_session_usage').get().tokens; + return { spend, input: model.input, output: model.output, sessionTokens }; +} +function turnCostOf(owner, id) { + return Object.fromEntries(owner.sqlite.prepare(`SELECT client_id AS clientId, agent_meta AS meta FROM messages WHERE session_id = ? AND role = 'assistant'`) + .all(id).map(row => [row.clientId, JSON.parse(row.meta ?? '{}').turnCost?.amount ?? null])); +} + +const segment = { id: 'pi:1', model: 'test-model', inputTokens: 100, outputTokens: 20, cacheReadTokens: 0, cacheCreateTokens: 0 }; +const piReceipt = settlementId => ({ settlementId, inputTokens: 100, outputTokens: 20, cacheReadTokens: 0, cacheCreationTokens: 0, + receipts: [{ ...segment, id: `pi:${settlementId}`, recordedAt: Date.now() }] }); +const xdQuote = { xd: { 'test-model': { providerId: 'xd', modelId: 'test-model', currency: 'USD', source: 'gateway', + inputPerMtok: 1000, outputPerMtok: 2000, cacheReadPerMtok: 100 } } }; +const receiptRows = (owner, id) => owner.sqlite.prepare('SELECT priced FROM pi_usage_receipts WHERE session_id = ?').all(id); + +// Case 1: one turn of each engine records once, where the desktop's recorders record it. +test('usage-recording: a Claude turn records its spend and tokens once, on its reply', async () => { + const h = harness(); + await h.begin(); + h.emit({ type: 'status', source: 'claude-code', data: { isRunning: true } }); + h.reply('reply'); + h.emit(claudeDone(2)); + await h.settled(); + const t = h.added(); + assert.equal(t.task.amount, 2); + assert.deepEqual(t.model, { input: 100, output: 20 }); + assert.equal(t.sessionTokens, 120); + assert.deepEqual(Object.values(turnCostOf(ownerA, h.id)), [2]); +}); + +test('usage-recording: a Codex turn records its tokens once', async () => { + const h = harness({ agentKind: 'codex' }); + await h.begin(); + h.emit({ type: 'status', source: 'codex', data: { isRunning: true } }); + h.reply('reply'); + h.emit({ type: 'done', source: 'codex', data: { usage: { promptTokens: 100, completionTokens: 20, cachedTokens: 10 } } }); + await h.settled(); + const t = h.added(); + assert.deepEqual(t.model, { input: 100, output: 20 }); + assert.equal(t.task.tokens, 130); +}); + +test('usage-recording: a Pi turn records its request receipt once', async () => { + const h = harness({ agentKind: 'pi' }); + await h.begin(); + h.emit({ type: 'status', source: 'pi', data: { isRunning: true } }); + const usageFacts = piReceipt('pi-turn'); + h.emit({ type: 'account_usage', source: 'pi', data: { type: 'pi/request_usage', usage: usageFacts } }); + h.reply('reply'); + h.emit({ type: 'done', source: 'pi', data: { usage: usageFacts } }); + await h.settled(); + assert.equal(receiptRows(ownerA, h.id).length, 1); + assert.deepEqual(h.added().model, { input: 100, output: 20 }); +}); + +// Case 1b: the turn cost write waits behind a reply write that failed (the task's queue paused); the queue's +// retry replays it outside any recording context, and it still lands once on the reply. +test('usage-recording: a turn cost queued behind a failed write lands once when the writes are retried', async () => { + const h = harness({ failFirstAssistantRow: true }); + await h.begin(); + h.reply('paused'); + h.emit(claudeDone(2)); + await h.settled(); + assert.ok(h.persistenceErrors.length > 0, 'the reply write failed'); + assert.deepEqual(Object.values(turnCostOf(ownerA, h.id)), []); + await h.executor.retryPersistence(h.id); + await h.settled(); + assert.deepEqual(Object.values(turnCostOf(ownerA, h.id)), [2]); + assert.equal(h.added().task.amount, 2); +}); + +// Case 2: an automatic resume continues the runtime; Claude's cumulative model usage is recorded as deltas. +test('usage-recording: a resumed turn adds only its own delta of the cumulative usage', async () => { + const h = harness(); + await h.begin(); + h.reply('first'); + h.emit(claudeDone(2, 100, 20)); + await h.settled(); + await h.begin(); + h.reply('resumed'); + h.emit({ type: 'done', source: 'claude-code', data: { total_cost_usd: 5, + modelUsage: { 'claude-sonnet-4-6': { inputTokens: 250, outputTokens: 50, costUSD: 5 } } } }); + await h.settled(); + const t = h.added(); + assert.equal(t.task.amount, 5); + assert.deepEqual(t.model, { input: 250, output: 50 }); + assert.deepEqual(Object.values(turnCostOf(ownerA, h.id)).sort(), [2, 3]); +}); + +// Cases 3 and 4: a failed turn's usage comes on its paired done, after the Host's turn ended (:559); it is +// recorded once on the failed reply. A replay on a new runtime is a turn of its own. +test('usage-recording: a failed turn records its paired done once, on the failed reply; its replay separately', async () => { + const h = harness(); + await h.begin(); + h.reply('failed'); + h.emit({ type: 'error', source: 'claude-code', data: { message: 'prompt is too long', isTerminal: true } }); + h.emit(claudeDone(2)); + await h.settled(); + const failedCost = turnCostOf(ownerA, h.id); + assert.deepEqual(Object.values(failedCost), [2]); + await h.executor.close(h.id); + // The replay's new runtime is wired with the task's provider again (the close cleared it). + setSessionProvider(h.id, 'fixture-api'); + h.nextGeneration(); + await h.begin(); + h.reply('replayed'); + h.emit(claudeDone(1.5, 40, 10)); + await h.settled(); + const t = h.added(); + assert.equal(t.task.amount, 3.5); + assert.deepEqual(t.model, { input: 140, output: 30 }); + assert.deepEqual(Object.values(turnCostOf(ownerA, h.id)).sort(), [1.5, 2]); +}); + +// Case 5: a Claude continuation boundary does not settle; the product turn's usage lands on the last reply +// that carried output. +test('usage-recording: across a continuation boundary the turn cost lands once, on the last reply with output', async () => { + const h = harness(); + await h.begin(); + h.reply('segment'); + h.emit({ ...claudeDone(2, 100, 20), turnContinuationId: 1 }); + h.emit({ type: 'done', source: 'claude-code', data: { total_cost_usd: 3, + modelUsage: { 'claude-sonnet-4-6': { inputTokens: 150, outputTokens: 30, costUSD: 3 } } } }); + await h.settled(); + // The final segment's delta (1) lands on the reply the boundary kept; the task row has both segments. + assert.deepEqual(Object.values(turnCostOf(ownerA, h.id)), [1]); + assert.equal(h.added().task.amount, 3); +}); + +// Case 6: a background turn's done carries its own usage. +test('usage-recording: a background turn records its usage once', async () => { + const h = harness(); + await h.begin(); + h.reply('foreground'); + h.emit(claudeDone(2)); + await h.settled(); + h.emit({ type: 'text', source: 'claude-code', turnScope: 'background', data: { text: 'background', isFinal: true } }); + h.emit({ ...claudeDone(4, 200, 40), data: { total_cost_usd: 4, + modelUsage: { 'claude-sonnet-4-6': { inputTokens: 200, outputTokens: 40, costUSD: 4 } } }, turnScope: 'background' }); + await h.settled(); + assert.equal(h.added().task.amount, 4); +}); + +// Case 7: a stopped Codex turn's done carries partial usage: tokens once, no money without a quote. +test('usage-recording: an interrupted Codex turn records its tokens once and no money without a quote', async () => { + const h = harness({ agentKind: 'codex' }); + await h.begin(); + h.reply('partial'); + h.emit({ type: 'done', source: 'codex', data: { raw: { id: 'turn', status: 'interrupted' }, + usage: { promptTokens: 30, completionTokens: 5 } } }); + await h.settled(); + const t = h.added(); + assert.deepEqual(t.model, { input: 30, output: 5 }); + assert.equal(t.task.amount ?? 0, 0); +}); + +// Case 8: late usage. A done after a stop ended the Host's turn is recorded; an earlier generation's late done +// does not take the next turn's reply. +test('usage-recording: a done after the turn was stopped is still recorded once', async () => { + const h = harness({ agentKind: 'codex' }); + await h.begin(); + h.reply('stopped'); + await h.executor.abort(h.id); + h.emit({ type: 'done', source: 'codex', data: { usage: { promptTokens: 30, completionTokens: 5 } } }); + await h.settled(); + assert.deepEqual(h.added().model, { input: 30, output: 5 }); +}); + +test('usage-recording: a previous generation\'s late done stays off the next turn\'s reply', async () => { + const h = harness(); + await h.begin(); + h.reply('failed'); + h.emit({ type: 'error', source: 'claude-code', data: { message: 'failed', isTerminal: true } }); + await h.settled(); + h.nextGeneration(); + await h.begin(); + h.reply('next'); + h.emit({ ...claudeDone(2), sessionTurnGeneration: 1 }); + await h.settled(); + const costs = turnCostOf(ownerA, h.id); + const nextReply = ownerA.sqlite.prepare(`SELECT client_id AS id FROM messages WHERE session_id = ? AND role = 'assistant' ORDER BY rowid DESC LIMIT 1`).get(h.id).id; + assert.equal(costs[nextReply], null); + assert.equal(h.added().task.amount, 2); +}); + +// Case 9: the account that started the turn. Switch first, then the old turn's done; and a switch while the +// recorder still waits for the turn's model (the Codex model rows are written after it), before its writes. +test('usage-recording: an old turn\'s usage never reaches the next account\'s database', async () => { + const before = globalTotals(ownerB); + const first = harness(); + await first.begin(); + first.reply('old-a'); + useOwner(ownerB); + first.emit(claudeDone(2)); + await first.settled(); + useOwner(ownerA); + const second = harness({ agentKind: 'codex' }); + await second.begin(); + second.reply('old-b'); + second.emit({ type: 'done', source: 'codex', data: { usage: { promptTokens: 30, completionTokens: 5 } } }); + useOwner(ownerB); + await second.settled(); + useOwner(ownerA); + assert.deepEqual(globalTotals(ownerB), before); + for (const h of [first, second]) assert.equal(h.added(ownerB).task.amount, 0); +}); + +test('usage-recording: a write port called outside a task context is dropped', async () => { + const { recordTurnSpend } = await import('../../../desktop/src/main/maker-ipc/turnUsagePorts.ts'); + const before = globalTotals(ownerA).spend; + await recordTurnSpend({ amount: 9, currency: 'USD', approximate: false, kind: 'actual-cost' }); + assert.equal(globalTotals(ownerA).spend, before); +}); + +// Case 10: nothing on the recording path asks a server (the four quota refreshes are bound empty). +test('usage-recording: no request was made on the recording path', () => { + assert.equal(fetchCalls, 0); +}); + +// Case 11: while a desktop uses the profile, a turn that is allowed to finish still writes its usage, and so +// does its late paired done. +test('usage-recording: during the profile hold a finishing turn and its late done are recorded', async () => { + profileHeld = true; + try { + const h = harness(); + await h.begin(); + h.reply('held'); + h.emit({ type: 'error', source: 'claude-code', data: { message: 'failed', isTerminal: true } }); + h.emit(claudeDone(2)); + await h.settled(); + assert.equal(h.added().task.amount, 2); + } finally { profileHeld = false; } +}); + +// Case 13: closing the runtime clears its usage tables; a new runtime's first cumulative report is only its baseline. +test('usage-recording: a new runtime after close starts its cumulative baseline again', async () => { + const h = harness(); + await h.begin(); + h.reply('first'); + h.emit({ type: 'done', source: 'claude-code', data: { total_cost_usd: 2 } }); + await h.settled(); + await h.executor.close(h.id); + setSessionProvider(h.id, 'fixture-api'); + h.nextGeneration(); + await h.begin(); + h.reply('second'); + h.emit({ type: 'done', source: 'claude-code', data: { total_cost_usd: 3 } }); + await h.settled(); + assert.equal(h.added().task.amount ?? 0, 0); +}); + +// Case 14: phase 1 usage pushes stay off the device-link; other pushes go as before. Every forwardable +// `usage:` channel is classified, so a new one cannot slip through. +test('usage-recording: the device-link tap drops the phase 1 usage channels and forwards the rest', async () => { + const usageChannels = [...PUSH_FORWARD_ALLOWLIST].filter(channel => channel.startsWith('usage:')); + for (const channel of usageChannels) { + assert.ok(PHASE1_UNFORWARDED_USAGE_CHANNELS.has(channel) !== INTENTIONALLY_FORWARDED_USAGE_CHANNELS.has(channel), channel); + } + for (const channel of [...PHASE1_UNFORWARDED_USAGE_CHANNELS, ...INTENTIONALLY_FORWARDED_USAGE_CHANNELS.keys()]) { + assert.ok(PUSH_FORWARD_ALLOWLIST.has(channel), `${channel} is not forwardable at all`); + } + const forwarded = []; + broadcastTap.setBroadcastTapListener(withoutPhaseOneUsagePushes((channel, payload) => { forwarded.push(channel); })); + try { + await recordSessionTurnSpend('task-1', { amount: 1, currency: 'USD', approximate: false, kind: 'actual-cost' }); + const other = [...PUSH_FORWARD_ALLOWLIST].find(channel => !channel.startsWith('usage:')); + broadcastTap.tapWindowBroadcast(other, {}); + for (const channel of PHASE1_UNFORWARDED_USAGE_CHANNELS) broadcastTap.tapWindowBroadcast(channel, {}); + assert.deepEqual(forwarded, [other]); + } finally { broadcastTap.setBroadcastTapListener(null); } +}); + +// Case 15: Pi receipts. A receipt without a price waits in its own account's database; it is priced once +// prices are back, not while a desktop uses the profile, and never in another account's database. +test('usage-recording: a pending Pi receipt is priced on retry, after the profile hold, in its own account only', async () => { + const h = harness({ agentKind: 'pi', provider: 'xd' }); + await h.begin(); + h.emit({ type: 'account_usage', source: 'pi', data: { type: 'pi/request_usage', usage: piReceipt('pending') } }); + await h.settled(); + assert.deepEqual(receiptRows(ownerA, h.id).map(row => row.priced), [0]); + gatewayPricing = xdQuote; + try { + profileHeld = true; + await usage.retryPending(); + assert.deepEqual(receiptRows(ownerA, h.id).map(row => row.priced), [0]); + useOwner(ownerB); + profileHeld = false; + usage.onProfileReleased(); + await usage.drain(); usage.open(); + assert.deepEqual(receiptRows(ownerA, h.id).map(row => row.priced), [0]); + assert.deepEqual(h.added(ownerB), { spend: 0, model: { input: 0, output: 0 }, sessionTokens: 0, task: { amount: 0, tokens: 0 } }); + useOwner(ownerA); + await usage.retryPending(); + await usage.drain(); usage.open(); + assert.deepEqual(receiptRows(ownerA, h.id).map(row => row.priced), [1]); + assert.ok(h.added().task.amount > 0); + } finally { gatewayPricing = null; profileHeld = false; useOwner(ownerA); } +}); + +test('usage-recording: the owner teardown waits for the Pi writes and starts no new recording', async () => { + const h = harness({ agentKind: 'pi' }); + await h.begin(); + h.emit({ type: 'account_usage', source: 'pi', data: { type: 'pi/request_usage', usage: piReceipt('drained') } }); + await usage.drain(); + assert.equal(receiptRows(ownerA, h.id).length, 1); + h.emit({ type: 'account_usage', source: 'pi', data: { type: 'pi/request_usage', usage: piReceipt('after-drain') } }); + await usage.drain(); + usage.open(); + assert.equal(receiptRows(ownerA, h.id).length, 1); +}); + +// Case 12: per-party usage (provider-usage-by-party.json) is not written in phase 1. +test('usage-recording: no per-party usage file was written', () => { + const found = []; + const walk = dir => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walk(full); else if (entry.name === 'provider-usage-by-party.json') found.push(full); + } }; + walk(root); + assert.deepEqual(found, []); +}); diff --git a/apps/host/src/agent/usage-recording.ts b/apps/host/src/agent/usage-recording.ts new file mode 100644 index 00000000000..f6c65f29b65 --- /dev/null +++ b/apps/host/src/agent/usage-recording.ts @@ -0,0 +1,346 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { AgentEvent, Session } from '@cindy/maker-core'; +import { isTurnContinuationBoundaryEvent } from '@cindy/maker-shared/turn-continuation'; +import { bindUsageBroadcastPorts } from '../../../desktop/src/main/usageBroadcastPorts.ts'; +import { bindTurnUsagePorts } from '../../../desktop/src/main/maker-ipc/turnUsagePorts.ts'; +import { recordSessionTurnSpend, recordSessionTurnTokens } from '../../../desktop/src/main/sessionSpendBroadcasterCore.ts'; +import { + codexUsageToTokens, + piUsageToTokens, + recordSchedulerTurnCost, + recordTurnCostOnMessage, + recordTurnUsageOnMessage, + type TurnCostDeps, +} from '../../../desktop/src/main/turnCostBroadcasterCore.ts'; +import { recordModelMismatchOnMessage } from '../../../desktop/src/main/modelMismatchBroadcasterCore.ts'; +import { recordCodexTurnUsage, recordModelTurnUsage, recordTurnSpend } from '../../../desktop/src/main/usageBroadcasterCore.ts'; +import { recordSessionClaudeTurnUsage } from '../../../desktop/src/main/maker-ipc/sessionClaudeTurnUsageCore.ts'; +import { recordSessionCodexTurnUsage } from '../../../desktop/src/main/maker-ipc/sessionCodexTurnUsageCore.ts'; +import { recordSessionPiTurnUsage } from '../../../desktop/src/main/maker-ipc/sessionPiTurnUsageCore.ts'; +import { captureTurnUsageContext, type TurnUsageContext } from '../../../desktop/src/main/maker-ipc/turnUsageContextCore.ts'; +import { flushSessionPiTurnUsage, retryPendingPiUsageReceipts } from '../../../desktop/src/main/maker-ipc/piUsageReceiptsCore.ts'; +import { ProductTurnUsageTargetTracker, ProductTurnWallClockTracker } from '../../../desktop/src/main/maker-ipc/turnWallClock.ts'; +import { readSessionModelForUsage, unpricedSubscriptionValueMarker } from '../../../desktop/src/main/maker-ipc/turnUsageSessionDefaults.ts'; +import { ClaudeOutputLagTimingGuard, type ModelUsageCumulative } from '../../../desktop/src/main/usage/modelUsageDelta.ts'; +import { getModelPriceQuote } from '../../../desktop/src/main/usage/modelPricingCore.ts'; +import { readPriorUserRoundCost } from '../../../desktop/src/main/localDb/ipc/localHistoryViewReader.ts'; +import { patchMessageAgentMetaWithResultRow } from '../../../desktop/src/main/localDb/messageMutations.ts'; +import { getCurrentDbClientSnapshot, type CurrentDbClientSnapshot } from '../../../desktop/src/main/localDb/client/current.ts'; +import { applyScheduleRunCostMetaChange, recordScheduleRunCostDirect } from '../../../desktop/src/main/scheduler-host/runCostLedger.ts'; +import { onUsagePricingChanged } from '../../../desktop/src/main/usage/pricingChanges.ts'; +import type { CodexProxyAuthInjection } from '../../../desktop/src/main/maker-host/codex-proxy-host.ts'; +import { createLogger } from '../../../desktop/src/main/logger.ts'; +import type { HostUsagePricing } from './usage-pricing.ts'; + +const log = createLogger('host-usage-recording'); + +/** + * The Host's turn usage recording (release table row 13, 3d): the desktop's three turn recorders + * (sessionClaudeTurnUsageCore.ts, sessionCodexTurnUsageCore.ts, sessionPiTurnUsageCore.ts) and the + * write cores they call, over the Host's own owner database, prices and accounts. turn-executor.mjs + * feeds them each event where the desktop's pipeline does (sessionEventPipeline.ts). + * + * What the Host does itself (release table §七): + * - Task context. The recorders' ports (usageBroadcastPorts.ts, turnUsagePorts.ts) are process-wide, + * but a task's message writes go through that task's durable write queue (event-persistence.ts). + * Every recorder call runs inside an AsyncLocalStorage context holding the task's queue and its + * owner; the ports read it there, also those without a task id (recordTurnSpend(money)). A write + * port called outside any context is dropped and logged; it never falls back to the current owner. + * - Owner. The context owner is the owner database the input runtime was bound to when its turns + * started (input-queue.mjs assertCurrent), not the one current when an event arrives; late events + * without a turn record use the same runtime owner. A write port runs only while that owner is the + * current one (the Host writes by the account that started the turn; the desktop writes into + * whichever database is current: release table §二, desktop item 9). + * - Owner teardown. A core may take getDbClient() again after an await inside one port call + * (recordModelTurnUsage: incrementDailyModelUsage, then incrementDailySessionUsage). So every write + * port call is tracked, and `drain()`, which the Host's owner teardown awaits before closing the + * owner database (main.ts disposeOwnerRuntime), first stops new recordings and port calls, then + * waits for the tracked ones and the Pi receipt writes. The Host installs the next owner database + * only after closing this one, so a tracked write cannot reach another account's database. A recording + * still waiting for prices or the turn's model when the teardown begins is refused its later write + * ports, so that turn may be recorded only in part (its tokens without its money; release table §二). + * - A write inside a started port call (a message patch, a scheduled run's cost) checks the owner that + * call captured, not the store: a paused task write queue replays it later outside any context. + * - Pi receipts. Their writes use the database captured when the session's first receipt was recorded + * (piUsageReceiptsCore.ts); pending ones live in that account's own database (pi_usage_receipts, + * priced = 0), so a retry only ever prices that account's rows. While a desktop uses the profile + * (coexistence plan A) the Host does not retry; it retries once the profile is released. + * - Nothing is pushed to windows (the Host has none) and nothing on the recording path asks a server: + * the four quota refreshes and the scheduler change push are bound empty (phase 2 binds them; + * desktop-module-setters.ts). Per-party usage (provider-usage-by-party.json) is not written in phase 1 + * (release table row 13): the desktop's `recordProviderPartyUsage` is optional and absent here. + */ + +type HistoryQueue = { enqueueDurableWrite(label: string, fn: () => Promise | T): Promise }; +interface RecordingContext { + sessionId: string; + owner: CurrentDbClientSnapshot; + history: HistoryQueue; +} + +export interface HostUsageRecordingOptions { + pricing: Pick; + isOpenAiSubscriptionProviderId(providerId?: string | null): boolean; + /** The Cindy AI key held in memory (the desktop's readClaudeApiKey), or null. */ + readGatewayKey(): string | null; + /** The local Codex proxy's credential mode, in memory (the desktop's getCodexProxyAuthInjection). */ + codexProxyAuthInjection(): CodexProxyAuthInjection; + /** Coexistence plan A (input-queue.mjs isHeldForDesktop): a desktop uses this profile. */ + isProfileHeld(): boolean; + /** The owner database now (main.ts: getCurrentDbClientSnapshot). */ + getOwner?: () => CurrentDbClientSnapshot | null; +} + +export function createHostUsageRecording(options: HostUsageRecordingOptions) { + const getOwner = options.getOwner ?? getCurrentDbClientSnapshot; + const context = new AsyncLocalStorage(); + let accepting = true; + const tracked = new Set>(); + let retryDeferred = false; + + /** Whether a write port may run now: inside a task context, for the current owner, before drain. */ + function writeAllowed(port: string): RecordingContext | null { + const current = context.getStore(); + if (!current) { + log.warn('usage write outside a task context dropped', { port }); + return null; + } + if (!accepting) { + log.info('usage write dropped: the owner teardown began', { port }); + return null; + } + return ownerHolds(current, port) ? current : null; + } + /** + * A write inside a port call already started (a message patch, a scheduled run's cost), for the owner + * that call captured. It may run later outside any context: a paused task write queue replays it + * (retryFailedWrites), so it compares the captured owner, not the store; drain lets a started call finish. + */ + function ownerHolds(current: RecordingContext, port: string): boolean { + if (current.owner === getOwner()) return true; + log.info('usage write dropped: the account changed', { port }); + return false; + } + function track(promise: Promise): Promise { + tracked.add(promise); + void promise.then(() => tracked.delete(promise), () => tracked.delete(promise)); + return promise; + } + const guardedWrite = (port: string, write: (...args: A) => Promise, dropped: R) => + (...args: A): Promise => (writeAllowed(port) ? track(write(...args)) : Promise.resolve(dropped)); + + /** The desktop's turn cost deps (turnCostBroadcasterCore.ts defaultDeps) for the task in context. */ + const turnCostDeps = (current: RecordingContext): TurnCostDeps => ({ + patchAgentMeta: (sessionId, clientId, patch) => (ownerHolds(current, 'patchAgentMeta') + ? patchMessageAgentMetaWithResultRow(current.owner.client, sessionId, clientId, patch) : Promise.resolve(null)), + applyScheduleRunCostChange: (previous, next) => (ownerHolds(current, 'applyScheduleRunCostChange') + ? applyScheduleRunCostMetaChange(previous, next) : Promise.resolve()), + readPriorUserRoundCost: (sessionId, clientId) => readPriorUserRoundCost(sessionId, clientId, current.owner.client), + enqueue: (label, fn) => current.history.enqueueDurableWrite(label, fn), + // Phase 1 pushes no usage (release table row 13, 3f; §二). + broadcast() {}, + broadcastWithOwnerScope() {}, + }); + /** A message write port: the task in context, its owner, its queue; dropped (resolving `dropped`) otherwise. */ + const messageWrite = (port: string, write: (args: A, current: RecordingContext) => Promise, dropped: R) => + (args: A): Promise => { + const current = writeAllowed(port); + return current ? track(write(args, current)) : Promise.resolve(dropped); + }; + + bindUsageBroadcastPorts({ + getAllWindows: () => [], + getGatewayModelPricing: () => options.pricing.getGatewayModelPricing(), + }); + bindTurnUsagePorts({ + isOpenAiSubscriptionProviderId: providerId => options.isOpenAiSubscriptionProviderId(providerId), + readClaudeApiKey: () => options.readGatewayKey(), + getCodexProxyAuthInjection: () => options.codexProxyAuthInjection(), + recordSessionTurnSpend: guardedWrite('recordSessionTurnSpend', recordSessionTurnSpend, undefined), + recordSessionTurnTokens: guardedWrite('recordSessionTurnTokens', recordSessionTurnTokens, undefined), + recordModelTurnUsage: guardedWrite('recordModelTurnUsage', recordModelTurnUsage, undefined), + recordTurnSpend: guardedWrite('recordTurnSpend', recordTurnSpend, undefined), + recordSchedulerTurnCost: messageWrite('recordSchedulerTurnCost', (args: Parameters[0], current) => + recordSchedulerTurnCost(args, { + recordOnMessage: messageArgs => recordTurnCostOnMessage(messageArgs, turnCostDeps(current)), + recordDirect: direct => (ownerHolds(current, 'recordScheduleRunCostDirect') ? recordScheduleRunCostDirect(direct) : Promise.resolve(null)), + }), null), + recordTurnUsageOnMessage: messageWrite('recordTurnUsageOnMessage', (args: Parameters[0], current) => + recordTurnUsageOnMessage(args, turnCostDeps(current)), false), + recordModelMismatchOnMessage: messageWrite('recordModelMismatchOnMessage', + (args: Parameters[0], current) => recordModelMismatchOnMessage(args, { + patchAgentMeta: async (sessionId, clientId, patch) => (await turnCostDeps(current).patchAgentMeta(sessionId, clientId, patch)) !== null, + enqueue: (label, fn) => current.history.enqueueDurableWrite(label, fn), + broadcast() {}, + }), undefined), + // The day's Codex token snapshot is process memory the desktop pushes to its windows; no database write. + recordCodexTurnUsage: usage => { if (writeAllowed('recordCodexTurnUsage')) recordCodexTurnUsage(usage); }, + // Reads. + getGatewayAccountCurrency: (...args) => options.pricing.getGatewayAccountCurrency(...args), + getGatewayModelPricing: () => options.pricing.getGatewayModelPricing(), + getGatewayModelPricingForModel: () => options.pricing.getGatewayModelPricingForModel(), + codexUsageToTokens, + piUsageToTokens, + getModelPriceQuote, + // Pushes: none in phase 1 (release table row 13, 3f). + broadcastSessionSpend: () => {}, + broadcastSessionTokens: () => {}, + rebroadcastTodaySpend: async () => {}, + rebroadcastCodexTodayUsage: () => {}, + broadcastSchedulerChanged: () => {}, + // No request on the recording path in phase 1 (desktop-module-setters.ts). + triggerClaudeAccountUsageRefresh: async () => {}, + triggerClaudeSubscriptionUsageRefresh: () => {}, + triggerCodexAccountUsageRefresh: () => {}, + triggerXaiSubscriptionUsageRefresh: () => {}, + }); + + // The desktop's per-task usage tables (register.ts :4229–4284, :4802–4804), cleared on close (:6064–6070). + const lastReportedCostUsdBySession = new Map(); + const lastReportedModelUsageBySession = new Map>(); + const turnModelPromiseBySession = new Map>(); + const turnUsageContextBySession = new Map(); + const productTurnWallClockTracker = new ProductTurnWallClockTracker(); + const productTurnUsageTargetTracker = new ProductTurnUsageTargetTracker(); + const claudeOutputLagTimingGuard = new ClaudeOutputLagTimingGuard(); + /** The desktop's sessionTurnActivityTracker.isSessionInTurn, for the turn-start steps (release table §七). */ + const inTurn = new Set(); + const recorderDeps = { + turnUsageContextBySession, + turnModelPromiseBySession, + readSessionModelForUsage, + lastReportedModelUsageBySession, + claudeOutputLagTimingGuard, + lastReportedCostUsdBySession, + log, + unpricedSubscriptionValueMarker, + }; + + /** Pending Pi receipts are priced again, unless a desktop uses the profile (then after its release). */ + function retryPending(): Promise { + if (!accepting) return Promise.resolve(); + if (options.isProfileHeld()) { + retryDeferred = true; + return Promise.resolve(); + } + retryDeferred = false; + return retryPendingPiUsageReceipts(); + } + const stopPricingRecovery = onUsagePricingChanged(() => { void retryPending(); }); + + return { + /** The trackers the silent-stop steps clear and preserve (silentStopSettle.ts, silentStopTurnEnd.ts). */ + productTurnWallClockTracker, + productTurnUsageTargetTracker, + + /** + * A foreground running status (sessionEventPreparation.ts :266–304): the product turn's wall clock + * for Claude, then the turn's model and billing identity for the three engines. + */ + noteRunningStatus(session: Session, event: AgentEvent): void { + const wasInTurn = inTurn.has(session.id); + if (!wasInTurn && event.source === 'claude-code') { + const startedProductTurn = productTurnWallClockTracker.start(session.id); + if (startedProductTurn) productTurnUsageTargetTracker.clear(session.id); + } + if ((event.data as { isRunning?: boolean } | undefined)?.isRunning) inTurn.add(session.id); + else inTurn.delete(session.id); + if ((event.source === 'claude-code' || event.source === 'codex' || event.source === 'pi') + && !turnModelPromiseBySession.has(session.id)) { + turnModelPromiseBySession.set(session.id, readSessionModelForUsage(session.id)); + } + if ((event.source === 'pi' || event.source === 'codex' || event.source === 'claude-code') + && (!wasInTurn || !turnUsageContextBySession.has(session.id))) { + turnUsageContextBySession.set(session.id, captureTurnUsageContext(session.id)); + } + }, + + /** The foreground turn ended (a final done, a terminal error, a not-running status). */ + noteTurnEnded(sessionId: string): void { inTurn.delete(sessionId); }, + + /** + * A terminal error (sessionEventPreparation.ts :391–395): the turn's model goes, its billing + * identity stays for the paired done. + */ + noteTerminalError(event: AgentEvent, sessionId: string): void { + if (event.source === 'claude-code' || event.source === 'codex' || event.source === 'pi') { + turnModelPromiseBySession.delete(sessionId); + } + }, + + /** + * The usage target of a done or terminal error (sessionEventTerminal.ts :186–221): the last assistant + * message the event consumed; a failed turn hands it to its paired done; a Claude continuation + * boundary keeps it for the final segment. `consumed` is undefined for a late event, which takes only + * the handed-over id (release table row 13: a late event must not take the next turn's message). + */ + usageTarget(sessionId: string, event: AgentEvent, consumed: string | undefined, pendingFailed: Map, + isTerminalError: boolean): string | undefined { + let target = consumed; + if (isTerminalError && event.type !== 'done') { + if (target) pendingFailed.set(sessionId, target); + } else { + const handedOver = pendingFailed.get(sessionId); + if (!target && handedOver) target = handedOver; + pendingFailed.delete(sessionId); + } + if (event.type === 'done' && event.source === 'claude-code') { + if (isTurnContinuationBoundaryEvent(event)) productTurnUsageTargetTracker.remember(sessionId, target); + else target = productTurnUsageTargetTracker.finish(sessionId, target); + } + return target; + }, + + /** + * The three recorders, in the desktop's order (sessionEventPipeline.ts :61–71), for the task's queue and + * the runtime's owner. The Claude product turn's wall clock is read at its final done, as the desktop's + * preparation reads it (sessionEventPreparation.ts :326–328). Nothing is recorded without an owner, for + * an owner that is no longer current, or once the owner teardown began (drain). + */ + record(session: Session, event: AgentEvent, persistId: string | undefined, history: HistoryQueue, + owner: CurrentDbClientSnapshot | null | undefined): void { + const isContinuationBoundary = isTurnContinuationBoundaryEvent(event); + const silentStopDone = event.type === 'done' && (event.data as { silentStop?: boolean } | null | undefined)?.silentStop === true; + const completedTurnWallClockMs = event.type === 'done' && event.source === 'claude-code' && !isContinuationBoundary && !silentStopDone + ? productTurnWallClockTracker.finish(session.id) : undefined; + if (!accepting || !owner || owner !== getOwner()) return; + context.run({ sessionId: session.id, owner, history }, () => { + recordSessionClaudeTurnUsage(recorderDeps, session, event, persistId, completedTurnWallClockMs, isContinuationBoundary); + recordSessionCodexTurnUsage(recorderDeps, session, event, persistId); + recordSessionPiTurnUsage(recorderDeps, session, event, persistId); + }); + }, + + /** The task's runtime closed (register.ts :6064–6070). */ + clear(sessionId: string): void { + lastReportedCostUsdBySession.delete(sessionId); + lastReportedModelUsageBySession.delete(sessionId); + turnModelPromiseBySession.delete(sessionId); + turnUsageContextBySession.delete(sessionId); + productTurnWallClockTracker.clear(sessionId); + productTurnUsageTargetTracker.clear(sessionId); + claudeOutputLagTimingGuard.clear(sessionId); + inTurn.delete(sessionId); + }, + + /** Pending Pi receipts once prices are ready (bootstrap-electron.ts :10384) or the profile is released. */ + retryPending, + /** The desktop released the profile: a retry held meanwhile runs now. */ + onProfileReleased(): void { if (retryDeferred) void retryPending(); }, + + /** + * Before the owner database closes (bootstrap-electron.ts :2639, :2667, :11275 flush the Pi writes + * there): no new recording or write port call starts; the started ones and the Pi writes finish. + */ + async drain(): Promise { + accepting = false; + while (tracked.size) await Promise.allSettled([...tracked]); + await flushSessionPiTurnUsage(); + }, + /** A new owner database is installed: recording resumes. */ + open(): void { accepting = true; }, + close(): void { stopPricingRecovery(); }, + }; +} + +export type HostUsageRecording = ReturnType; diff --git a/apps/host/src/agent/user-input.ts b/apps/host/src/agent/user-input.ts new file mode 100644 index 00000000000..69bf3647937 --- /dev/null +++ b/apps/host/src/agent/user-input.ts @@ -0,0 +1,21 @@ +import { withSessionPermissionChange } from '../../../desktop/src/main/maker-ipc/sessionPermissionChange.ts'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.ts'; + +/** + * A client's new input to a task, as the desktop's maker:send and INPUT_ENQUEUE take it (register.ts): + * it waits for the task's permission and Plan changes in flight (the permission queue, + * sessionPermissionChange.ts) before anything takes the task's send lock, and is refused if the account + * changed while it waited. Only these client entries wait: the queue's own next input, recovery replays + * and other internal sends do not come through here, so a turn can always finish and drain. + */ +export function createUserInputEnqueue(ports: { + getOwner(): unknown; + enqueue(sessionId: string, input: unknown): Promise; +}) { + return async (sessionId: string, input: unknown): Promise => { + const owner = ports.getOwner(); + await withSessionPermissionChange(sessionId, async () => undefined); + if (!owner || owner !== ports.getOwner()) throwIpcError('PRECONDITION_FAILED', 'Account changed before input'); + return ports.enqueue(sessionId, input); + }; +} diff --git a/apps/host/src/agent/working-directory.ts b/apps/host/src/agent/working-directory.ts new file mode 100644 index 00000000000..c41c324e198 --- /dev/null +++ b/apps/host/src/agent/working-directory.ts @@ -0,0 +1,92 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { canRecreateOwnerWorkingDirectory, createWorkingDirectoryRecovery, isUnavailableFilesystemError } from '../../../desktop/src/main/maker-ipc/workingDirectoryRecovery.ts'; +import { isAppSessionBoundaryPending } from '../../../desktop/src/main/appSessionState.ts'; +import { ownerScopedPath } from '../../../desktop/src/main/ownerContext.ts'; +import { createWorkingDirectoryPreflight } from '../../../desktop/src/main/maker-ipc/workingDirectoryPreflight.ts'; +import { + allocateDialogueRecoveryWorkspace, findDialogueRecoveryWorkspace, requiredDialogueRecoveryRoot, +} from '../../../desktop/src/main/maker-ipc/dialogueRecoveryWorkspace.ts'; +import { dialogueWorkspaceRoots } from '../../../desktop/src/main/dialogue-workspace-settings.ts'; +import { + findSimilarWorkingDirectory, mkdirWorkingDirectory, realpathWorkingDirectory, statWorkingDirectory, +} from '../../../desktop/src/main/workdir-probe-host/index.ts'; +import { getManagedWorktreeBasePath } from '../../../desktop/src/shared/managedWorktreePaths.ts'; +import { isCindyMakeWorktreePath } from '../../../desktop/src/main/cindy-make/sourcePaths.ts'; +import { getUserDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.ts'; +import { createLogger, type Logger } from '../../../desktop/src/main/logger.ts'; +import { explicitPorts } from './explicit-ports.ts'; + +type Stat = Parameters[0]['statWorkingDirectory']; + +/** + * A task's working directory before a send, with the desktop's shared check and recovery + * (register.ts `checkWorkDirExists` and `workingDirectoryRecovery`): the same preflight factory, the + * same recovery, the same conversation recovery directories in the profile, the same directory probes + * (workdir-probe-host, bounded and with a deadline). An ordinary directory that is gone continues in + * a recovery directory, and the next send carries the recovery note once. + * + * Two ports differ: + * - Managed worktree readiness: the desktop restores a missing worktree with Git and turns to a + * recovery directory only when it cannot (`gone`). The Host does not restore worktrees: a managed + * worktree directory that exists is ready, anything else is `retry`, so the send fails as it did + * before. The Host must not answer `gone` until worktree restoration is on the Host: that would move + * the task to a recovery directory where the desktop would have restored the worktree. + * - A Cindy Make workspace is refused, as the Host refuses Cindy Make input. + * A missing directory is logged; the send's failure (`WORKDIR_MISSING`) reaches the client as before. + */ +export function createHostWorkingDirectory(deps: { + stat?: Stat; + readBoundWorkingDir(sessionId: string): Promise; + listActiveSessions(): { id: string; workDir: string; remoteHostId?: string | null }[]; + log: Pick; +}) { + const stat = deps.stat ?? statWorkingDirectory; + const workdirLog = createLogger('workdir-diagnostics'); + const recovery = createWorkingDirectoryRecovery(explicitPorts[0]>({ + stat, mkdir: mkdirWorkingDirectory, realpath: realpathWorkingDirectory, + requiredRoot: requiredDialogueRecoveryRoot, findFallback: findDialogueRecoveryWorkspace, + // As the desktop (register.ts, main e322628568): only the active owner's namespace is recreated, + // and nothing during an account switch. + canRecreateDirectory: (dir: string) => !isAppSessionBoundaryPending() + && canRecreateOwnerWorkingDirectory(getUserDataDir(), ownerScopedPath(), dir), + }), allocateDialogueRecoveryWorkspace, workdirLog); + const checkWorkDirExists = createWorkingDirectoryPreflight(explicitPorts[0]>({ + workingDirectoryRecovery: recovery, + statWorkingDirectory: stat, + readBoundWorkingDir: deps.readBoundWorkingDir, + getUserDataPath: getUserDataDir, + isCindyMakeWorktreePath, + assertCindyMakeWorkspace: async () => { + throwIpcError('UNSUPPORTED_CAPABILITY', 'Host does not yet support managed product tasks'); + }, + getManagedWorktreeBasePath, + getManagedWorktreeReadinessForSession: async (_sessionId, workingDir) => { + try { return (await fs.stat(workingDir)).isDirectory() ? 'ready' : 'retry'; } + catch { return 'retry'; } + }, + findSimilarDirOnDisk: dir => findSimilarWorkingDirectory(dir).catch((error) => { + if (isUnavailableFilesystemError(error)) throw error; + return null; + }), + listActiveSessions: deps.listActiveSessions, + emitWorkDirMissingError: (sessionId, workingDir, _source, reason, similarPath) => { + deps.log.warn('send aborted: workdir missing', { sessionId, workingDir, reason, similarPath: similarPath ?? undefined }); + }, + workdirLog, + log: deps.log, + })); + return { + checkWorkDirExists, + statDirectory: stat, + // The send transaction's ports, as register.ts passes them. + resolveRecoveredWorkingDir: (sessionId: string, dir: string) => recovery.resolve(sessionId, dir), + isPersistedWorktreeFallback: (dir: string) => dialogueWorkspaceRoots().some(root => + path.dirname(path.resolve(dir)) === path.join(root, 'worktree-recovery')), + peekWorkingDirectoryRecoveryNote: (sessionId: string, workingDir: string) => recovery.peek(sessionId, workingDir), + consumeWorkingDirectoryRecoveryNote: (sessionId: string, note: string) => recovery.consume(sessionId, note), + /** At a task's archive or delete (the runtime cleanup, as register.ts's workingDirectoryRecovery.discard). */ + discardWorkingDirectoryRecovery: (sessionId: string) => recovery.discard(sessionId), + }; +} diff --git a/apps/host/src/agent/xai-held-login.ts b/apps/host/src/agent/xai-held-login.ts new file mode 100644 index 00000000000..23b92884654 --- /dev/null +++ b/apps/host/src/agent/xai-held-login.ts @@ -0,0 +1,62 @@ +/** + * Coexistence plan A (reviewer, 2026-11-17): the xAI (SuperGrok) login while a Cindy desktop app + * running on its own uses this profile. + * + * The login is one JSON blob in the profile's safe-storage (provider secret `xai`, or the generic + * OAuth slot of an added xAI account; grok-oauth-login.ts readBlob), the same file the desktop reads + * and writes, and its binding is in the same profile. Two things write it: renewing a token about to + * expire (getGrokAccessToken → refreshIfNeeded), and the forced renewal after an upstream rejection, + * which signs out and unbinds when it cannot renew (recoverGrokAuthAfterRejection → logoutGrok). Two + * processes renewing one login rotate each other's refresh token out. + * + * While held, this wrapper of the Host's one Grok service (provider-config.ts; the subscription + * bridge, the Codex proxy's xAI observer, provider OAuth token reads and auto-review all use it): + * - does not renew: a token about to expire fails with a reason; + * - after an upstream rejection renews, signs out and unbinds nothing; the rejection is remembered in + * this process and requests with the same token fail with a reason, not reaching the upstream again; + * - once released forgets everything and behaves as the service does. + */ +import { heldCredentialError } from './held-credentials.js'; +import type { createGrokOAuthService } from '../../../desktop/src/main/maker-host/grok-oauth-login.js'; + +type GrokService = ReturnType; + +/** grok-oauth-login.ts REFRESH_MARGIN_SEC; a guard test keeps the two equal. */ +export const GROK_REFRESH_MARGIN_SEC = 120; + +export function holdGrokLoginWrites(service: GrokService, ports: { + isProfileHeld(): boolean; + /** The stored blob of an xAI login, as grok-oauth-login.ts readBlob reads it. */ + readStoredLogin(providerId: string): string | null; +}): GrokService { + const rejected = new Map(); + const held = () => ports.isProfileHeld(); + const expiresAt = (providerId: string): number | null => { + try { + const value = JSON.parse(ports.readStoredLogin(providerId) ?? 'null')?.expires_at; + return typeof value === 'number' ? value : null; + } catch { return null; } + }; + const refusal = heldCredentialError; + return { + ...service, + async getGrokAccessToken(providerId = 'xai') { + if (!held()) { rejected.clear(); return service.getGrokAccessToken(providerId); } + const token = service.peekGrokAccessToken(providerId); + if (token && rejected.get(providerId) === token) throw refusal('xAI rejected this SuperGrok sign-in, and it is not renewed or signed out'); + if (token) rejected.delete(providerId); + const exp = expiresAt(providerId); + // As grok-oauth-login.ts isExpired: without an expiry the service does not renew early either. + if (token && exp !== null && Date.now() >= exp - GROK_REFRESH_MARGIN_SEC * 1000) + throw refusal('the SuperGrok sign-in has expired, and it is not renewed'); + return service.getGrokAccessToken(providerId); + }, + async recoverGrokAuthAfterRejection(rejectedAccessToken: string, providerId = 'xai') { + if (!held()) { rejected.clear(); return service.recoverGrokAuthAfterRejection(rejectedAccessToken, providerId); } + // As the service: a rejection of a token that is no longer current changes nothing. + if (service.peekGrokAccessToken(providerId) !== rejectedAccessToken) return 'superseded'; + rejected.set(providerId, rejectedAccessToken); + return 'unchanged'; + }, + }; +} diff --git a/apps/host/src/auth-state.ts b/apps/host/src/auth-state.ts index 670140ff714..8704e80d058 100644 --- a/apps/host/src/auth-state.ts +++ b/apps/host/src/auth-state.ts @@ -1,4 +1,5 @@ import type { User as AccountUser } from '../../desktop/src/shared/authUser.js'; +import type { HostStartFailureReason } from '../../desktop/src/shared/hostStartFailure.js'; /** * The auth state the Host projects to windows and the web client. @@ -14,6 +15,8 @@ export function projectHostAuthState(input: { owner: string | null; generation: number; deviceId: string | null; + /** Why the last start failed or was refused (start-failure.ts); null for an ordinary signed-out start. */ + unavailable?: HostStartFailureReason | null; }) { const { account, accountUser, owner } = input; const authenticated = Boolean(account.authenticated && accountUser && accountUser.id === owner); @@ -24,5 +27,7 @@ export function projectHostAuthState(input: { ownerGeneration: input.generation, isCanary: false, deviceId: input.deviceId, hasAccountDeletionReceipt: false, accountDeletionRestored: false, credentialStoreUnavailable: Boolean(account.error), + // Only the code (shared/hostStartFailure.ts): the window shows why and does not sign in on its own. + ...(!authenticated && input.unavailable ? { hostUnavailable: { reason: input.unavailable } } : {}), }; } diff --git a/apps/host/src/auth/device-identity.test.mjs b/apps/host/src/auth/device-identity.test.mjs index bf04096a20b..0c234a819b9 100644 --- a/apps/host/src/auth/device-identity.test.mjs +++ b/apps/host/src/auth/device-identity.test.mjs @@ -30,8 +30,10 @@ test('legacy records remain refreshable but cannot displace a desktop connection }); test('refresh rotation preserves the identity bound at login', async () => { let raw = serializeHostSession('global', 'synthetic-old-refresh', 'host-test'); - const store = { read: key => { assert.equal(key, AUTH_SESSION_KEY); return raw; }, write: (key, value) => { assert.equal(key, AUTH_SESSION_KEY); raw = value; } }; - await refreshHostSession({ store, refresh: async () => ({ accessToken: 'synthetic-access', refreshToken: 'synthetic-new-refresh' }) }); + // Only the session record exists; the renewal also reads the vault and legacy records (absent). + const store = { read: key => (key === AUTH_SESSION_KEY ? raw : null), write: (key, value) => { assert.equal(key, AUTH_SESSION_KEY); raw = value; } }; + await refreshHostSession({ store, refresh: async () => ({ accessToken: 'synthetic-access', refreshToken: 'synthetic-new-refresh' }), + withVaultLock: task => task(), buildRegion: 'global' }); assert.equal(readSessionDeviceId(raw), 'host-test'); assert.equal(JSON.parse(raw).refreshToken, 'synthetic-new-refresh'); }); diff --git a/apps/host/src/auth/login.loopback.test.mjs b/apps/host/src/auth/login.loopback.test.mjs index 3873cd4cca4..b34c7bf6504 100644 --- a/apps/host/src/auth/login.loopback.test.mjs +++ b/apps/host/src/auth/login.loopback.test.mjs @@ -3,6 +3,8 @@ import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { createServer } from 'node:http'; +import { CindyAuthClient, parseAuthSessionRecord } from '@cindy/auth-client'; + import { runHostLogin } from './login.mjs'; /** @@ -95,6 +97,7 @@ test('completes the hosted-callback login once polling returns a code', async () }, store: { write: (key, value) => written.set(key, value) }, region: 'cn', + packageRegion: 'cn', hostedCallbackUrl: 'https://auth.example.invalid/desktop/callback', method: 'apple', openBrowser: async () => {}, @@ -140,3 +143,130 @@ test('refuses a callback whose state does not match the request', async () => { await new Promise((resolve) => provider.close(() => resolve())); } }); + +/* + * H-1 (release table; user decision 2026-11-17 “和桌面版一致”): `cindy-host login` applies the + * Desktop's cross-region rule (`canRestoreAuthSessionForMembership`) to the package region, the + * `--region` realm and the account kind returned by the exchange. + * Production entry: runHostLogin with the real CindyAuthClient against two fake auth servers on + * loopback (one per region, each reporting its own region), as the region inventory did. + * Gap: the tests above use client stubs without a membership and never cross regions. + * Minimal failure: package global, --region=cn, personal account → must not be stored. + * Tier: unit (loopback HTTP only). + */ +async function fakeAuthServers(kind, logout = 'ok') { + const hits = []; + const servers = {}; + for (const region of ['cn', 'global']) { + const server = createServer((request, response) => { + hits.push(`${region} ${request.url}`); + const json = (value) => response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(value)); + const membership = { id: `fixture-${region}-member`, kind, role: 'owner', displayName: 'Fixture', email: null, + orgId: kind === 'org' ? 'fixture-org' : null, orgName: kind === 'org' ? 'Fixture Org' : null }; + if (request.url === '/api/auth/providers') return json({ region, attribution: 'email', email: true, phone: false, social: ['google'] }); + if (request.url === '/api/auth/desktop/callback/poll') return json({ status: 'ok', code: 'fixture-code' }); + if (request.url === '/api/auth/token') return json({ status: 'ok', accessToken: 'fixture-access-value', refreshToken: `fixture-refresh-${region}`, membership }); + if (request.url === '/api/auth/logout') { + if (logout === 'hang') return undefined; + if (logout === 'fail') return response.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: { code: 'INTERNAL' } })); + return json({ status: 'ok' }); + } + return response.writeHead(404).end('{}'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + servers[region] = { server, url: `http://127.0.0.1:${server.address().port}` }; + } + const close = () => Promise.all(Object.values(servers).map(({ server }) => { + server.closeAllConnections?.(); + return new Promise((resolve) => server.close(resolve)); + })); + return { hits, servers, close }; +} + +test('login follows the Desktop rule: personal accounts stay in the package region, organizations may cross', async () => { + for (const [packageRegion, region, kind, admitted] of [ + ['global', 'cn', 'personal', false], + ['cn', 'global', 'personal', false], + ['global', 'cn', 'org', true], + ['cn', 'global', 'org', true], + ['global', 'global', 'personal', true], + ['cn', 'cn', 'personal', true], + ]) { + const label = `package ${packageRegion}, --region=${region}, ${kind}`; + const fake = await fakeAuthServers(kind); + const written = new Map(); + try { + const login = runHostLogin({ + client: new CindyAuthClient({ baseUrl: fake.servers[region].url, region, deviceId: 'fixture-device', clientType: 'desktop', fetch }), + store: { write: (key, value) => written.set(key, value) }, + deviceId: 'fixture-device', + region, + packageRegion, + hostedCallbackUrl: `${fake.servers[region].url}/desktop/callback`, + openBrowser: async () => {}, + }); + if (admitted) { + assert.deepEqual(await login, { authenticated: true, realm: region, method: 'google' }, label); + assert.equal(parseAuthSessionRecord([...written.values()][0])?.realm, region, label); + } else { + await assert.rejects(login, (error) => error.code === 'HOST_CROSS_REGION_PERSONAL_ACCOUNT' + && error.message.includes(`"${region}" region`) && error.message.includes(`"${packageRegion}" region`), label); + assert.equal(written.size, 0, `${label}: no session is saved`); + // The issued session is ended once, at the account's own region only (the Host addition). + assert.deepEqual(fake.hits.filter((hit) => hit.endsWith('/api/auth/logout')), [`${region} /api/auth/logout`], label); + } + if (admitted) assert.equal(fake.hits.some((hit) => hit.endsWith('/api/auth/logout')), false, label); + // Every request went to the account's own region, admitted or not. + assert.ok(fake.hits.length > 0 && fake.hits.every((hit) => hit.startsWith(`${region} `)), label); + } finally { + await fake.close(); + } + } +}); + +// The Host addition after a refusal: ending the issued session is best effort. A failing or hanging +// sign-in service must not change the refusal or keep the command waiting, and the warning carries +// neither the token nor the account. Minimal failure: logout answers 500, or never answers. +test('a refused login ends its session at most best effort and stays refused', async () => { + for (const logout of ['fail', 'hang']) { + const fake = await fakeAuthServers('personal', logout); + const warnings = []; + const written = new Map(); + try { + await assert.rejects(runHostLogin({ + client: new CindyAuthClient({ baseUrl: fake.servers.cn.url, region: 'cn', deviceId: 'fixture-device', clientType: 'desktop', fetch }), + store: { write: (key, value) => written.set(key, value) }, deviceId: 'fixture-device', + region: 'cn', packageRegion: 'global', hostedCallbackUrl: `${fake.servers.cn.url}/desktop/callback`, + openBrowser: async () => {}, warn: (line) => warnings.push(line), refusedSessionLogoutTimeoutMs: 50, + }), (error) => error.code === 'HOST_CROSS_REGION_PERSONAL_ACCOUNT', logout); + assert.equal(written.size, 0, logout); + assert.equal(warnings.length, 1, logout); + assert.doesNotMatch(warnings[0], /fixture-access-value|fixture-cn-member|fixture-device/, logout); + assert.ok(fake.hits.every((hit) => hit.startsWith('cn ')), logout); + } finally { + await fake.close(); + } + } +}); + +// The package region of a release (区域单元, 甲 20): built for cn, run with CINDY_HOST_REGION unset, +// the rule must judge against cn, not the source default global. Only a release has a build region, +// so this runs one child process with the release constant the builder bakes in +// (__CINDY_HOST_RELEASE__, runtime-layout.mjs). Minimal failure: hostPackageRegion() ignoring the +// release and answering global. +test('a cn release judges sign-in against cn with CINDY_HOST_REGION unset', async () => { + const { execFile } = await import('node:child_process'); + const { promisify } = await import('node:util'); + const { fileURLToPath } = await import('node:url'); + const hostDir = fileURLToPath(new URL('../..', import.meta.url)); + const script = ` + globalThis.__CINDY_HOST_RELEASE__ = { region: 'cn' }; + const { hostPackageRegion, assertHostSessionRegion } = await import(${JSON.stringify(new URL('./region-policy.ts', import.meta.url).href)}); + const verdict = (sessionRealm) => { try { assertHostSessionRegion({ packageRegion: hostPackageRegion(), sessionRealm, membershipKind: 'personal' }); return 'admitted'; } catch (error) { return error.code; } }; + process.stdout.write(JSON.stringify({ region: hostPackageRegion(), cn: verdict('cn'), global: verdict('global') }));`; + const env = { ...process.env }; + delete env.CINDY_HOST_REGION; + const { stdout } = await promisify(execFile)(process.execPath, + ['--import', 'tsx', '--import', './src/loaders/register-raw.mjs', '--input-type=module', '-e', script], { cwd: hostDir, env }); + assert.deepEqual(JSON.parse(stdout), { region: 'cn', cn: 'admitted', global: 'HOST_CROSS_REGION_PERSONAL_ACCOUNT' }); +}); diff --git a/apps/host/src/auth/login.mjs b/apps/host/src/auth/login.mjs index d737712d93c..6df5d85183c 100644 --- a/apps/host/src/auth/login.mjs +++ b/apps/host/src/auth/login.mjs @@ -19,8 +19,10 @@ import { runHostedCallbackPolling, } from '../../../desktop/src/main/authHostedCallback.ts'; import { parseAuthLoopbackCallback } from '../../../desktop/src/main/authLoopbackCallback.ts'; +import { assertHostSessionRegion, hostPackageRegion } from './region-policy.ts'; const BROWSER_AUTH_TIMEOUT_MS = 5 * 60_000; +const REFUSED_SESSION_LOGOUT_TIMEOUT_MS = 5_000; function pkce() { const verifier = crypto.randomBytes(32).toString('base64url'); @@ -84,6 +86,11 @@ function listenOnLoopback(server) { * client: any, * store: {write(key: string, value: string): void}, * region: 'cn' | 'global', + * packageRegion?: 'cn' | 'global', + * warn?: (line: string) => void, + * admitAccount?: (membership: { id: string }) => void, + * persistSession?: (record: string, membership: { id: string }) => Promise, + * refusedSessionLogoutTimeoutMs?: number, * hostedCallbackUrl?: string, * openBrowser: (url: string) => Promise, * method?: string, @@ -107,11 +114,53 @@ export async function runHostLogin(deps) { const pair = await deps.client.exchangeAuthorizationCode(authorization.code, verifier); if (pair?.status !== 'ok') throw new Error(unfinishedLoginMessage(pair)); - deps.store.write(AUTH_SESSION_KEY, deps.deviceId ? serializeHostSession(deps.region, pair.refreshToken, deps.deviceId) : serializeAuthSessionRecord(deps.region, pair.refreshToken)); + // H-1, as the Desktop: a personal account of another region is refused before anything is saved. + try { + assertHostSessionRegion({ packageRegion: deps.packageRegion ?? hostPackageRegion(), sessionRealm: deps.region, + membershipKind: pair.membership?.kind }); + // A running serve with another account's runtime: that account must stop first (login-cli.mjs). + deps.admitAccount?.(pair.membership); + } catch (error) { + await endRefusedSession(deps, pair.accessToken); + throw error; + } + const record = deps.deviceId ? serializeHostSession(deps.region, pair.refreshToken, deps.deviceId) : serializeAuthSessionRecord(deps.region, pair.refreshToken); + // The Skill projection owner commit (login-cli.mjs) saves the session inside its own transaction. + if (deps.persistSession) { + // A save or commit that fails leaves an issued session nobody holds: end it, as a refusal does. + try { await deps.persistSession(record, pair.membership); } + catch (error) { await endRefusedSession(deps, pair.accessToken); throw error; } + } else deps.store.write(AUTH_SESSION_KEY, record); if (deps.onSignedIn && typeof pair.accessToken === 'string' && pair.accessToken) await deps.onSignedIn(pair.accessToken); return { authenticated: true, realm: deps.region, method: method.providerOrConnectionId ?? method.type }; } +/** + * The exchange above already issued a session that nobody will hold. The Desktop has no such path + * (its personal code login always uses the build region); the Host ends it so no orphan is left. + * Only through the client that exchanged the code, i.e. the account's own region's sign-in service, + * never the package region's. Best effort: a few seconds at most, a failure is logged without the + * token or the account, and the refusal stands either way. + */ +async function endRefusedSession(deps, accessToken) { + const warn = deps.warn ?? ((line) => console.warn(line)); + if (!accessToken || typeof deps.client.logout !== 'function') return; + let timer; + try { + await Promise.race([ + deps.client.logout(accessToken), + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error('timeout')), deps.refusedSessionLogoutTimeoutMs ?? REFUSED_SESSION_LOGOUT_TIMEOUT_MS); + timer.unref?.(); + }), + ]); + } catch { + warn('The refused sign-in could not be ended on the sign-in service; it will expire on its own.'); + } finally { + clearTimeout(timer); + } +} + async function authorizeViaHostedCallback({ client, method, challenge, hostedCallbackUrl, openBrowser, onAuthorizeUrl, signal, now }) { const { clientState, pollSecret } = createDesktopPollCredentials(); const url = client.buildAuthorizeUrl({ diff --git a/apps/host/src/auth/refresh.mjs b/apps/host/src/auth/refresh.mjs index 536641acaef..fad89c17e27 100644 --- a/apps/host/src/auth/refresh.mjs +++ b/apps/host/src/auth/refresh.mjs @@ -1,45 +1,267 @@ /** - * Refresh the adopted Desktop login from the host process. + * Renew the adopted Cindy account session from the Host. * - * Rotation semantics match the Desktop: the server may return a new refresh - * token, and the record must be replaced atomically; the access token stays in - * memory only. Callers must not run this while the Desktop holds the same - * session — the host runtime lease exists for that reason. + * The one renewal of the account session the Host has; every caller in main.ts (the renewal timer, + * the server API's 401 retry, Device Link's auth failure, the first startup, /api/auth/refresh) + * goes through it. It is the one shared credential the Host writes while a Cindy desktop app + * running on its own uses the profile (coexistence row, C): the Host would sign itself out + * otherwise. So it renews as the desktop's runtime refresh does (authManager.ts refresh() and + * commitDesktopRefreshCredentials), and the two processes can renew one login in turn: + * 1. A rejected token is retried with the replacement another process wrote: the shared + * runRefreshWithReplacementRetry over the three stored sources, in the desktop's order (the v1 + * session record, the vault's active resource, the legacy bare token of the build's region). + * 2. After the request, before judging a failure, the v1 record is read again; when it no longer + * holds a token this renewal had rejected, the failure is another session's and is dropped. + * Host difference: the desktop compares only the last token tried. A Host login leaves an older + * token of the same account in the vault (`cindy-host login` writes only the v1 record); when + * the v1 token is rejected and that older one is tried last, the v1 record still holds a + * rejected token, and the failure is definitive instead of being retried for ever. + * 3. Only a definitive failure while the record still holds that token signs out (the caller does, + * in this process only; the Host deletes no stored credential). DEVICE_MISMATCH the same: this + * process only, the stored credentials stay. + * 4. The result is written under the account-vault lock both processes take, after reading + * everything again: the vault by the desktop's rule (authRefreshCommit.ts), then the v1 record + * (with this login's Host device binding) and the legacy bare token when it exists. A renewal + * that no longer holds its token writes no v1 record. + * Host difference: the v1 record is also kept when it still held the token although the vault + * names no or another active account (`cindy-host login` writes only the v1 record). + * 5. A record that exists but cannot be read now is a transient failure; only a missing one + * ends the session. + * The access token stays in memory only. */ +import path from 'node:path'; + +import { accountVaultKey, AuthApiError, parseAuthSessionRecord, serializeAuthSessionRecord } from '@cindy/auth-client'; + import { readSessionDeviceId, serializeHostSession } from './device-identity.mjs'; -import { serializeAuthSessionRecord } from '@cindy/auth-client'; +import { + AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY, + AUTH_ACCOUNT_VAULT_KEY, + AUTH_SESSION_KEY, + LEGACY_RESOURCE_REFRESH_TOKEN_KEY, +} from '../../../desktop/src/main/authCredentialKeys.ts'; +import { runRefreshWithReplacementRetry } from '../../../desktop/src/main/authRefreshFailure.ts'; +import { + applyRefreshedCredentialsToVault, + AUTH_ACCOUNT_VAULT_LOCK_FILE, + AUTH_ACCOUNT_VAULT_VERSION, +} from '../../../desktop/src/main/authRefreshCommit.ts'; +import { withCrossProcessLock } from '../../../desktop/src/main/device-link/crossProcessLock.ts'; + +/** authManager.ts REFRESH_TOKEN_REPLACEMENT_RETRY_LIMIT and RUNTIME_REFRESH_TOKEN_REPLACEMENT_RECHECK_DELAYS_MS. */ +export const HOST_REFRESH_REPLACEMENT_RETRY_LIMIT = 2; +export const HOST_REFRESH_REPLACEMENT_RECHECK_DELAYS_MS = Object.freeze([250, 1000]); + +/** The stored session is gone: the session ends (step 5). */ +export class HostSessionMissingError extends Error { + constructor() { + super('no stored Cindy session to refresh'); + this.name = 'HostSessionMissingError'; + } +} -import { AUTH_SESSION_KEY } from '../../../desktop/src/main/authCredentialKeys.ts'; -import { parseAuthSessionRecord } from '@cindy/auth-client'; +/** The renewal did not settle anything: the session stays, renew again later. */ +export class HostRefreshDeferredError extends Error { + /** @param {string} message @param {{retryAt?: number, networkFailure?: boolean}} [options] */ + constructor(message, options = {}) { + super(message); + this.name = 'HostRefreshDeferredError'; + this.retryAt = options.retryAt; + this.networkFailure = options.networkFailure === true; + } +} + +/** + * The account-vault lock of a profile, as the desktop's transactAuthAccountVault takes it. The + * server has already rotated the token when the result is written, so a busy lock is waited out + * (as `waitWhileBusyAfterRotation`); an unavailable one fails. + * @param {string} userDataDir + * @returns {(task: () => T | Promise) => Promise} + */ +export function hostAccountVaultLock(userDataDir) { + const lockPath = path.join(userDataDir, AUTH_ACCOUNT_VAULT_LOCK_FILE); + return async (task) => { + for (;;) { + const attempt = await withCrossProcessLock(lockPath, { label: 'auth-account-vault', waitMs: 5000 }, + async (lock) => (lock.held ? { done: true, value: await task() } : { done: false, reason: lock.reason })); + if (attempt.done) return attempt.value; + if (attempt.reason !== 'busy') throw new HostRefreshDeferredError('Saved account credentials are unavailable now'); + } + }; +} + +function readOrNull(store, key) { + try { return store.read(key); } catch { return null; } +} + +function readSession(store) { + return parseAuthSessionRecord(readOrNull(store, AUTH_SESSION_KEY)); +} + +/** + * The vault as the desktop's readAuthAccountVault presents it to the commit rule (logout tombstones + * merged, an active account that is logged out or missing is none), and the stored object. + * Throws when either record cannot be read or is not a vault. + */ +function readVault(store) { + const raw = store.read(AUTH_ACCOUNT_VAULT_KEY); + const tombstoneRaw = store.read(AUTH_ACCOUNT_LOGOUT_TOMBSTONES_KEY); + const tombstones = tombstoneRaw ? JSON.parse(tombstoneRaw) : { version: 1, accountKeys: [] }; + if (tombstones?.version !== 1 || !Array.isArray(tombstones.accountKeys)) throw new Error('Saved account logout state is unavailable'); + const stored = raw ? JSON.parse(raw) : null; + if (stored !== null && (![1, AUTH_ACCOUNT_VAULT_VERSION].includes(stored?.version) || !stored.resources || typeof stored.resources !== 'object' + || !stored.passports || typeof stored.passports !== 'object')) throw new Error('Saved accounts are unavailable'); + const resources = { ...(stored?.resources ?? {}) }; + const loggedOut = [...new Set([...(stored?.loggedOutAccountKeys ?? []), ...tombstones.accountKeys])]; + const active = typeof stored?.activeAccountKey === 'string' ? stored.activeAccountKey : null; + const view = { + version: AUTH_ACCOUNT_VAULT_VERSION, + activeAccountKey: active && resources[active] && !loggedOut.includes(active) ? active : null, + resources, + passports: stored?.passports ?? {}, + ...(loggedOut.length > 0 ? { loggedOutAccountKeys: loggedOut } : {}), + ...(typeof stored?.signedOutAt === 'number' ? { signedOutAt: stored.signedOutAt } : {}), + }; + return { stored, view }; +} + +/** authManager.ts readStoredRefreshTokenCandidates: every source, in order, not folded. */ +function readStoredRefreshTokenCandidates(store, realm, buildRegion) { + const session = readSession(store); + let activeResource; + try { + const { view } = readVault(store); + activeResource = view.activeAccountKey ? view.resources[view.activeAccountKey] : undefined; + } catch { activeResource = undefined; } + return [ + session?.realm === realm ? session.refreshToken : null, + activeResource?.realm === realm && typeof activeResource.refreshToken === 'string' ? activeResource.refreshToken : null, + realm === buildRegion ? readOrNull(store, LEGACY_RESOURCE_REFRESH_TOKEN_KEY) : null, + ]; +} + +/** CindyAuthClient.refresh as the shared runner's request (authManager.ts refreshSavedResourceSession). */ +async function requestRefresh(refresh, refreshToken) { + try { + const pair = await refresh(refreshToken); + return { ok: true, status: 200, data: pair }; + } catch (error) { + if (!(error instanceof AuthApiError)) throw error; + return { ok: false, status: error.statusCode, data: { error: { code: error.code } }, retryAt: error.retryAt, error }; + } +} + +/** + * Write the renewal under the account-vault lock (step 4). Returns whether this renewal still owned + * the session and wrote its v1 record. + */ +function commitRenewal(store, input) { + const { pair, realm, requestedToken, buildRegion, deviceId } = input; + const session = readSession(store); + const sessionHeldToken = session?.realm === realm && session.refreshToken === requestedToken; + let commit = 'unknown'; + if (pair.membership?.id) { + try { + const { stored, view } = readVault(store); + const key = accountVaultKey(realm, pair.membership.id); + const activeBefore = view.activeAccountKey; + const resourceBefore = JSON.stringify(view.resources[key] ?? null); + commit = applyRefreshedCredentialsToVault(view, { + pair, realm, requestedRefreshToken: requestedToken, buildRegion, + readStoredSession: () => session, + readLegacyResourceRefreshToken: () => readOrNull(store, LEGACY_RESOURCE_REFRESH_TOKEN_KEY), + }); + if (stored && JSON.stringify(view.resources[key] ?? null) !== resourceBefore) { + // Only what the rule changed; the rest of the stored vault is written back as it was read. + // Legacy-readable version, as the desktop's writeAuthAccountVault. + const next = { ...stored, version: 1, resources: { ...stored.resources, [key]: view.resources[key] } }; + if (view.activeAccountKey !== activeBefore) { next.activeAccountKey = view.activeAccountKey; delete next.signedOutAt; } + store.write(AUTH_ACCOUNT_VAULT_KEY, JSON.stringify(next)); + } + } catch (error) { + // The vault cannot be read or written now: the v1 record this login renews from is still kept. + console.warn('[host] auth refresh: the saved-account vault was not updated:', error instanceof Error ? error.message : String(error)); + } + } + if (commit !== 'active' && !sessionHeldToken) return { owned: false, commit }; + if (session?.realm !== realm || session.refreshToken !== pair.refreshToken) { + store.write(AUTH_SESSION_KEY, deviceId + ? serializeHostSession(realm, pair.refreshToken, deviceId) + : serializeAuthSessionRecord(realm, pair.refreshToken)); + } + mirrorLegacyResourceRefreshToken(store, pair.refreshToken, realm, buildRegion); + return { owned: true, commit }; +} + +/** authManager.ts mirrorLegacyResourceRefreshToken: only the build's region, only when the file exists. */ +function mirrorLegacyResourceRefreshToken(store, refreshToken, realm, buildRegion) { + if (realm !== buildRegion) return; + let current; + try { current = store.read(LEGACY_RESOURCE_REFRESH_TOKEN_KEY); } catch { current = undefined; } + if (current === null || current === refreshToken) return; + try { store.write(LEGACY_RESOURCE_REFRESH_TOKEN_KEY, refreshToken); } + catch (error) { + console.warn('[host] auth refresh: the legacy credential file was not updated; older apps catch up at the next renewal:', + error instanceof Error ? error.message : String(error)); + } +} /** * @typedef {object} RefreshResult * @property {string} sessionToken * @property {'cn' | 'global'} realm * @property {boolean} rotated + * @property {number} replacementRetries */ /** * @param {{ * store: {read(key: string): string | null, write(key: string, value: string): void}, - * refresh(refreshToken: string): Promise<{accessToken: string, refreshToken?: string}>, + * refresh(refreshToken: string): Promise<{accessToken: string, refreshToken?: string, membership?: {id: string, passportId?: string}}>, + * withVaultLock(task: () => T | Promise): Promise, + * buildRegion: 'cn' | 'global', + * sleep?: (ms: number) => Promise, * }} deps * @returns {Promise} + * @throws {HostSessionMissingError} the stored session is gone + * @throws {HostRefreshDeferredError} nothing settled; keep the session and renew later + * @throws {AuthApiError} a definitive rejection (or DEVICE_MISMATCH) of the token still stored */ export async function refreshHostSession(deps) { - const raw = deps.store.read(AUTH_SESSION_KEY); + let raw; + try { raw = deps.store.read(AUTH_SESSION_KEY); } + catch { throw new HostRefreshDeferredError('the stored Cindy session cannot be read now'); } + if (raw === null) throw new HostSessionMissingError(); const record = parseAuthSessionRecord(raw); + if (!record) throw new HostRefreshDeferredError('the stored Cindy session cannot be read now'); const deviceId = readSessionDeviceId(raw); - if (!record) throw new Error('no stored Cindy session to refresh'); - const tokens = await deps.refresh(record.refreshToken); - if (!tokens.accessToken) throw new Error('refresh response contained no access token'); - const rotated = Boolean(tokens.refreshToken && tokens.refreshToken !== record.refreshToken); - if (rotated) { - deps.store.write( - AUTH_SESSION_KEY, - deviceId ? serializeHostSession(record.realm, tokens.refreshToken, deviceId) : serializeAuthSessionRecord(record.realm, tokens.refreshToken), - ); - } - return { sessionToken: tokens.accessToken, realm: record.realm, rotated }; + const { realm } = record; + + const run = await runRefreshWithReplacementRetry(record.refreshToken, { + doRefresh: token => requestRefresh(deps.refresh, token), + readLatestStoredTokens: () => readStoredRefreshTokenCandidates(deps.store, realm, deps.buildRegion), + maxReplacementRetries: HOST_REFRESH_REPLACEMENT_RETRY_LIMIT, + replacementRecheck: { delaysMs: HOST_REFRESH_REPLACEMENT_RECHECK_DELAYS_MS, sleep: deps.sleep }, + }); + const { result, requestedToken } = run; + if (!result.ok) { + const latest = readSession(deps.store); + if (latest?.realm !== realm || !run.rejectedTokens.includes(latest.refreshToken)) + throw new HostRefreshDeferredError('the stored session changed while renewing; that failure is not the current session\'s'); + const action = run.failureAction ?? { kind: 'transient-failure' }; + if (action.kind === 'definitive-failure' || action.kind === 'foreign-device') throw result.error; + throw new HostRefreshDeferredError(`the renewal failed for now (${result.error?.code ?? result.status}): ${result.error?.message ?? 'no response'}`, + { retryAt: result.retryAt, networkFailure: result.status === 0 }); + } + const pair = result.data; + if (!pair?.accessToken) throw new Error('refresh response contained no access token'); + const rotated = Boolean(pair.refreshToken && pair.refreshToken !== requestedToken); + if (rotated || requestedToken !== record.refreshToken) { + const { owned } = await deps.withVaultLock(() => commitRenewal(deps.store, { + pair: { ...pair, refreshToken: pair.refreshToken || requestedToken }, realm, requestedToken, buildRegion: deps.buildRegion, deviceId, + })); + if (!owned) throw new HostRefreshDeferredError('another process holds the stored session now'); + } + return { sessionToken: pair.accessToken, realm, rotated, replacementRetries: run.replacementRetries }; } diff --git a/apps/host/src/auth/refresh.test.mjs b/apps/host/src/auth/refresh.test.mjs index a54e977cb6b..83d12c5922a 100644 --- a/apps/host/src/auth/refresh.test.mjs +++ b/apps/host/src/auth/refresh.test.mjs @@ -1,10 +1,18 @@ import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; import test from 'node:test'; -import { serializeAuthSessionRecord } from '@cindy/auth-client'; +import { accountVaultKey, AuthApiError, parseAuthSessionRecord, serializeAuthSessionRecord } from '@cindy/auth-client'; -import { AUTH_SESSION_KEY } from '../../../desktop/src/main/authCredentialKeys.ts'; -import { refreshHostSession } from './refresh.mjs'; +import { + AUTH_ACCOUNT_VAULT_KEY, + AUTH_SESSION_KEY, + LEGACY_RESOURCE_REFRESH_TOKEN_KEY, +} from '../../../desktop/src/main/authCredentialKeys.ts'; +import { serializeHostSession, readSessionDeviceId } from './device-identity.mjs'; +import { hostAccountVaultLock, HostRefreshDeferredError, HostSessionMissingError, refreshHostSession } from './refresh.mjs'; // Field names are composed from parts so credential scanners do not flag test // fixtures whose values are obviously synthetic. @@ -21,10 +29,12 @@ function memoryStore(initial) { }; } +const noLock = task => task(); + test('persists a rotated refresh token and never returns it', async () => { const store = memoryStore([[AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'old-token')]]); const result = await refreshHostSession({ - store, + store, withVaultLock: noLock, buildRegion: 'global', refresh: async () => tokenPair('access-value', 'rotated-value'), }); assert.equal(result.realm, 'global'); @@ -39,7 +49,7 @@ test('keeps the stored record when the server does not rotate', async () => { const original = serializeAuthSessionRecord('cn', 'same-token'); const store = memoryStore([[AUTH_SESSION_KEY, original]]); const result = await refreshHostSession({ - store, + store, withVaultLock: noLock, buildRegion: 'cn', refresh: async () => tokenPair('same-access', 'same-token'), }); assert.equal(result.rotated, false); @@ -47,7 +57,243 @@ test('keeps the stored record when the server does not rotate', async () => { }); test('fails loudly without a stored session or without an access token', async () => { - await assert.rejects(() => refreshHostSession({ store: memoryStore([]), refresh: async () => tokenPair('x', undefined) }), /no stored Cindy session/); + await assert.rejects(() => refreshHostSession({ store: memoryStore([]), withVaultLock: noLock, buildRegion: 'global', + refresh: async () => tokenPair('x', undefined) }), HostSessionMissingError); const store = memoryStore([[AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'old')]]); - await assert.rejects(() => refreshHostSession({ store, refresh: async () => tokenPair('', undefined) }), /no access token/); + await assert.rejects(() => refreshHostSession({ store, withVaultLock: noLock, buildRegion: 'global', + refresh: async () => tokenPair('', undefined) }), /no access token/); +}); + +/* + * C (reviewer, 2026-11-17): the Host renews the account session as the desktop's runtime refresh + * does, so a desktop and the Host, or two Hosts, can renew one login in turn. Before: the Host read + * only the v1 record, signed out on any rejection, and wrote only the v1 record, so the other + * process's next renewal, or a switch back to the account from the vault, signed out a valid login + * (reproduced 2026-11-17, desktop authColdStartRecovery.test.ts). Gap: the cases above use a server + * that never rejects. Minimal failure: two processes renew the same stored token. Tier: unit, one + * in-memory store shared as the profile's credential files, a fake auth server, the real lock on a + * temporary directory; no real account, profile or keychain. + */ +const MEMBERSHIP = { id: 'member-a', passportId: 'passport-a', kind: 'personal', role: 'owner', displayName: 'Fixture', + email: null, orgId: null, orgName: null }; +const KEY_A = accountVaultKey('global', 'member-a'); +const noWait = async () => {}; + +/** One account on a fake auth server: only the latest refresh token works; each renewal rotates it. */ +function authServer(first = 'r0') { + let current = first; + let next = 0; + const requests = []; + return { + requests, + current: () => current, + rotateElsewhere() { current = `elsewhere-${++next}`; return current; }, + async refresh(token) { + requests.push(token); + if (token !== current) throw new AuthApiError('INVALID_REFRESH_TOKEN', 401, 'rotated'); + current = `r${++next}`; + return { [ACCESS]: `access-${next}`, [REFRESH]: current, membership: MEMBERSHIP }; + }, + }; +} + +function vaultWith(token, extra = {}) { + return JSON.stringify({ version: 1, activeAccountKey: KEY_A, passports: {}, ...extra, + resources: { [KEY_A]: { realm: 'global', refreshToken: token, metadata: { membershipId: 'member-a', passportId: 'passport-a', + displayName: 'Fixture', email: null, avatarUrl: null, kind: 'personal', role: 'owner', orgId: null, orgName: null, orgLogoUrl: null }, + lastUsedAt: 1 } } }); +} + +/** The profile's records as the desktop leaves them: v1, the vault with account A active, the legacy token. */ +function profileStore(token = 'r0', { legacy = true, deviceId } = {}) { + return memoryStore([ + [AUTH_SESSION_KEY, deviceId ? serializeHostSession('global', token, deviceId) : serializeAuthSessionRecord('global', token)], + [AUTH_ACCOUNT_VAULT_KEY, vaultWith(token)], + ...(legacy ? [[LEGACY_RESOURCE_REFRESH_TOKEN_KEY, token]] : []), + ]); +} + +const stored = store => ({ + session: parseAuthSessionRecord(store.records.get(AUTH_SESSION_KEY))?.refreshToken, + vault: JSON.parse(store.records.get(AUTH_ACCOUNT_VAULT_KEY) ?? 'null')?.resources?.[KEY_A]?.refreshToken, + legacy: store.records.get(LEGACY_RESOURCE_REFRESH_TOKEN_KEY), +}); + +function tempLock(t) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-refresh-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + return hostAccountVaultLock(dir); +} + +test('two processes sharing one profile renew in turn, also at the same moment, and neither signs out', async (t) => { + const server = authServer(); + const store = profileStore(); + const withVaultLock = tempLock(t); + // Process 2's request reaches the server only after process 1 has renewed and written. + let releaseSecond; + const firstDone = new Promise(resolve => { releaseSecond = resolve; }); + const renew = (refresh = token => server.refresh(token)) => + refreshHostSession({ store, refresh, withVaultLock, buildRegion: 'global', sleep: noWait }); + const second = renew(async token => { await firstDone; return server.refresh(token); }); + const first = await renew(); + releaseSecond(); + const late = await second; + assert.equal(first.sessionToken, 'access-1'); + assert.equal(late.sessionToken, 'access-2'); + assert.equal(late.replacementRetries, 1, 'the late one renews with the token the first one wrote'); + for (let i = 0; i < 4; i++) await renew(); + assert.equal(server.current(), 'r6'); + assert.deepEqual(stored(store), { session: 'r6', vault: 'r6', legacy: 'r6' }); +}); + +test('a rejected token is renewed with the newer one another process already stored, in any of the three sources', async () => { + for (const source of ['session', 'vault', 'legacy']) { + const server = authServer(); + const store = profileStore(); + const refresh = async (token) => { + if (token === 'r0') { + // Another process renewed first and stored its token in this one source. + const newer = server.rotateElsewhere(); + if (source === 'session') store.write(AUTH_SESSION_KEY, serializeAuthSessionRecord('global', newer)); + if (source === 'vault') store.write(AUTH_ACCOUNT_VAULT_KEY, vaultWith(newer)); + if (source === 'legacy') store.write(LEGACY_RESOURCE_REFRESH_TOKEN_KEY, newer); + } + return server.refresh(token); + }; + const result = await refreshHostSession({ store, refresh, withVaultLock: noLock, buildRegion: 'global', sleep: noWait }); + assert.equal(result.replacementRetries, 1, source); + assert.deepEqual(server.requests, ['r0', 'elsewhere-1'], source); + assert.equal(stored(store).session, server.current(), source); + } +}); + +test('only a rejection of the token still stored is definitive; it signs out without deleting anything', async () => { + const server = authServer('valid-elsewhere'); + const store = profileStore('rejected'); + const before = new Map(store.records); + await assert.rejects(refreshHostSession({ store, refresh: token => server.refresh(token), withVaultLock: noLock, + buildRegion: 'global', sleep: noWait }), error => error instanceof AuthApiError && error.code === 'INVALID_REFRESH_TOKEN'); + assert.deepEqual(store.records, before); +}); + +test('DEVICE_MISMATCH signs out this process only and keeps the stored credentials', async () => { + const store = profileStore('bound-elsewhere'); + const before = new Map(store.records); + const requests = []; + await assert.rejects(refreshHostSession({ store, withVaultLock: noLock, buildRegion: 'global', sleep: noWait, + refresh: async (token) => { requests.push(token); throw new AuthApiError('DEVICE_MISMATCH', 401, 'device'); } }), + error => error.code === 'DEVICE_MISMATCH'); + assert.deepEqual(requests, ['bound-elsewhere']); + assert.deepEqual(store.records, before); +}); + +test('a definitive failure of a token the store no longer holds is dropped, not a sign-out', async () => { + const store = profileStore('rejected', { legacy: false }); + // Another process stores its renewal just after this renewal's last re-read of the stored sources. + let rechecksDone = false; + let sessionReads = 0; + const read = store.read; + store.read = (key) => { + if (key === AUTH_SESSION_KEY && rechecksDone && ++sessionReads === 2) store.write(key, serializeAuthSessionRecord('global', 'newer')); + return read(key); + }; + await assert.rejects(refreshHostSession({ store, withVaultLock: noLock, buildRegion: 'global', + sleep: async (ms) => { if (ms === 1000) rechecksDone = true; }, + refresh: async () => { throw new AuthApiError('INVALID_REFRESH_TOKEN', 401, 'rotated'); } }), HostRefreshDeferredError); + assert.equal(stored(store).session, 'newer'); +}); + +test('the renewal writes the vault, its v1 record with its Host device and the existing legacy token; nothing more', async () => { + const server = authServer(); + const store = profileStore('r0', { deviceId: 'host-device' }); + await refreshHostSession({ store, refresh: token => server.refresh(token), withVaultLock: noLock, buildRegion: 'global' }); + assert.deepEqual(stored(store), { session: 'r1', vault: 'r1', legacy: 'r1' }); + assert.equal(readSessionDeviceId(store.records.get(AUTH_SESSION_KEY)), 'host-device'); + assert.equal(JSON.parse(store.records.get(AUTH_ACCOUNT_VAULT_KEY)).activeAccountKey, KEY_A); + + // A Host-only profile (`cindy-host login` writes only the v1 record): no vault or legacy record is made. + const hostOnly = memoryStore([[AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'r1')]]); + await refreshHostSession({ store: hostOnly, refresh: token => server.refresh(token), withVaultLock: noLock, buildRegion: 'global' }); + assert.deepEqual([...hostOnly.records.keys()], [AUTH_SESSION_KEY]); + assert.equal(stored(hostOnly).session, 'r2'); + + // The desktop signed out, then `cindy-host login`: the vault names no account, the v1 record is still kept. + const signedOutVault = JSON.stringify({ version: 1, activeAccountKey: null, resources: {}, passports: {}, signedOutAt: 1 }); + const afterDesktopLogout = memoryStore([[AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'r2')], + [AUTH_ACCOUNT_VAULT_KEY, signedOutVault]]); + await refreshHostSession({ store: afterDesktopLogout, refresh: token => server.refresh(token), withVaultLock: noLock, buildRegion: 'global' }); + assert.equal(stored(afterDesktopLogout).session, 'r3'); + assert.equal(afterDesktopLogout.records.get(AUTH_ACCOUNT_VAULT_KEY), signedOutVault); +}); + +test('a renewal that no longer holds its token when it writes writes nothing', async () => { + const server = authServer(); + const store = profileStore(); + const otherAccount = [serializeAuthSessionRecord('global', 'b-token'), JSON.stringify({ version: 1, activeAccountKey: 'other', + passports: {}, resources: { other: { realm: 'global', refreshToken: 'b-token', metadata: {}, lastUsedAt: 1 } } }), 'b-token']; + const refresh = async (token) => { + const pair = await server.refresh(token); + // While this request was out, the desktop switched to account B. + [AUTH_SESSION_KEY, AUTH_ACCOUNT_VAULT_KEY, LEGACY_RESOURCE_REFRESH_TOKEN_KEY].forEach((key, i) => store.write(key, otherAccount[i])); + return pair; + }; + await assert.rejects(refreshHostSession({ store, refresh, withVaultLock: noLock, buildRegion: 'global' }), HostRefreshDeferredError); + assert.deepEqual([...store.records.values()], otherAccount); +}); + +test('a stored session that exists but cannot be read now is kept; only a missing one ends the session', async () => { + const requests = []; + const refresh = async (token) => { requests.push(token); return tokenPair('x', 'y'); }; + const unreadable = { read: () => { throw new Error('the keychain is locked'); }, write: () => assert.fail('nothing is written') }; + await assert.rejects(refreshHostSession({ store: unreadable, refresh, withVaultLock: noLock, buildRegion: 'global' }), HostRefreshDeferredError); + const damaged = memoryStore([[AUTH_SESSION_KEY, '{not a session']]); + await assert.rejects(refreshHostSession({ store: damaged, refresh, withVaultLock: noLock, buildRegion: 'global' }), HostRefreshDeferredError); + await assert.rejects(refreshHostSession({ store: memoryStore([]), refresh, withVaultLock: noLock, buildRegion: 'global' }), HostSessionMissingError); + assert.deepEqual(requests, []); +}); + +test('a renewal whose replacements are used up while other apps keep rotating is retried later, not a sign-out', async () => { + const store = profileStore('va'); + const before = new Map(store.records); + // A new app and an old one (it reads and writes only the legacy token) keep renewing first. + const elsewhere = { va: [[LEGACY_RESOURCE_REFRESH_TOKEN_KEY, 'lb']], lb: [[LEGACY_RESOURCE_REFRESH_TOKEN_KEY, 'lc']], + lc: [[AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'lc')], [LEGACY_RESOURCE_REFRESH_TOKEN_KEY, 'ld']] }; + const requests = []; + const refresh = async (token) => { + requests.push(token); + for (const [key, value] of elsewhere[token] ?? []) store.write(key, value); + throw new AuthApiError('INVALID_REFRESH_TOKEN', 401, 'rotated'); + }; + await assert.rejects(refreshHostSession({ store, refresh, withVaultLock: noLock, buildRegion: 'global', sleep: noWait }), + HostRefreshDeferredError); + assert.deepEqual(requests, ['va', 'lb', 'lc']); + assert.equal(store.records.get(AUTH_ACCOUNT_VAULT_KEY), before.get(AUTH_ACCOUNT_VAULT_KEY), 'nothing of this renewal is written'); +}); + +test('the write-back waits for the account-vault lock another process holds', async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-refresh-lock-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const server = authServer(); + const store = profileStore(); + let renewal; + // The other process (the desktop's transactAuthAccountVault) holds the same lock file. + await hostAccountVaultLock(dir)(async () => { + renewal = refreshHostSession({ store, refresh: token => server.refresh(token), withVaultLock: hostAccountVaultLock(dir), buildRegion: 'global' }); + await new Promise(resolve => setTimeout(resolve, 50)); + assert.equal(server.current(), 'r1', 'the server has rotated'); + assert.deepEqual(stored(store), { session: 'r0', vault: 'r0', legacy: 'r0' }, 'nothing is written under the other process'); + }); + await renewal; + assert.deepEqual(stored(store), { session: 'r1', vault: 'r1', legacy: 'r1' }); +}); + +test('after `cindy-host login` left an older token of the account in the vault, a revoked login is still definitive', async () => { + // v1: the Host login's token; the vault: the desktop's older token of the same account. Both rejected. + const store = profileStore('older-desktop-token', { legacy: false }); + store.write(AUTH_SESSION_KEY, serializeAuthSessionRecord('global', 'host-login-token')); + const requests = []; + await assert.rejects(refreshHostSession({ store, withVaultLock: noLock, buildRegion: 'global', sleep: noWait, + refresh: async (token) => { requests.push(token); throw new AuthApiError('INVALID_REFRESH_TOKEN', 401, 'revoked'); } }), + error => error instanceof AuthApiError && error.code === 'INVALID_REFRESH_TOKEN'); + assert.deepEqual(requests, ['host-login-token', 'older-desktop-token']); }); diff --git a/apps/host/src/auth/region-policy.ts b/apps/host/src/auth/region-policy.ts new file mode 100644 index 00000000000..08a4195bdbe --- /dev/null +++ b/apps/host/src/auth/region-policy.ts @@ -0,0 +1,44 @@ +/** + * Cross-region sign-in rule for the Host, the same as the Desktop's (user decision 2026-11-17, + * release table: “和桌面版一致”). A personal account signs in only to a package of its own + * region; an organization account may sign in across regions. The rule is the Desktop's own + * function (`authRealmPolicy.ts`), applied to the package region, the session realm and the + * account kind, at `cindy-host login` (H-1) and whenever the Host adopts a stored session (H-2). + */ +import { canRestoreAuthSessionForMembership } from '../../../desktop/src/main/authRealmPolicy.ts'; +import { resolveHostRegion } from '../profile-path.mjs'; + +export type HostRegion = 'cn' | 'global'; + +/** + * The region of this Host package: the region unit's edition (release table 甲 20). A release answers + * the region it was built for (`release.json`, `scripts/build.mjs --region`), and refuses a + * `CINDY_HOST_REGION` naming the other edition; from source it is `CINDY_HOST_REGION`, global when + * unset (development only). The one place the sign-in rule reads it. + */ +export function hostPackageRegion(): HostRegion { + return resolveHostRegion() as HostRegion; +} + +/** A personal session from another region: refused, never adopted. Carries regions, no ids. */ +export class HostCrossRegionPersonalAccountError extends Error { + readonly code = 'HOST_CROSS_REGION_PERSONAL_ACCOUNT'; + constructor(readonly sessionRealm: string, readonly packageRegion: HostRegion) { + super(`This personal account belongs to the "${sessionRealm}" region, and this Cindy Host is for the ` + + `"${packageRegion}" region. Personal accounts sign in only to a Host of their own region; ` + + 'organization accounts can sign in across regions.'); + this.name = 'HostCrossRegionPersonalAccountError'; + } +} + +/** Throws unless the Desktop's rule admits this session on this package. */ +export function assertHostSessionRegion(input: { + packageRegion: HostRegion; + sessionRealm: HostRegion; + membershipKind: unknown; +}): void { + const kind = input.membershipKind === 'org' ? 'org' : 'personal'; + if (!canRestoreAuthSessionForMembership(input.packageRegion, input.sessionRealm, kind)) { + throw new HostCrossRegionPersonalAccountError(input.sessionRealm, input.packageRegion); + } +} diff --git a/apps/host/src/boundary.test.mjs b/apps/host/src/boundary.test.mjs index a01c1c531a4..a223512cdcb 100644 --- a/apps/host/src/boundary.test.mjs +++ b/apps/host/src/boundary.test.mjs @@ -4,7 +4,9 @@ import os from 'node:os'; import { createHash } from 'node:crypto'; import path from 'node:path'; import test from 'node:test'; -import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; +import { spawn } from 'node:child_process'; +import { fileURLToPath, pathToFileURL } from 'node:url'; import { createMediaTransfer, AttachmentIntegrityError } from '../../desktop/src/main/device-link/mediaTransfer.js'; import { createDeviceLinkApi } from '../../desktop/src/main/device-link/deviceLinkApi.js'; import { createServerApiClient } from '../../desktop/src/main/serverApiClient.js'; @@ -15,20 +17,41 @@ function sourceFiles(dir) { return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { const full = path.join(dir, entry.name); if (entry.isDirectory()) return sourceFiles(full); - return /\.(mjs|ts)$/.test(entry.name) && !entry.name.endsWith('.test.mjs') ? [full] : []; + return /\.(?:[cm]?ts|tsx|jsx?|mjs)$/.test(entry.name) ? [full] : []; }); } -test('host sources never import Electron', () => { +// Source Host must never execute the npm entry: even require('electron') via +// an aliased createRequire can synchronously install the missing runtime. +// The .cjs workers, unlike the Node Host, run inside Electron. +test('host sources never import or execute the Electron package entry', () => { const offenders = []; for (const file of sourceFiles(srcDir)) { const text = fs.readFileSync(file, 'utf8'); - for (const match of text.matchAll(/from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]/g)) { - const spec = match[1] ?? match[2]; - if (spec === 'electron' || spec.startsWith('electron/')) { - offenders.push(`${path.relative(srcDir, file)} -> ${spec}`); + if (!/['"`]electron(?:\/|['"`])/.test(text)) continue; + const tree = ts.createSourceFile(file, text, ts.ScriptTarget.Latest); + const resolvesPath = node => ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) + && node.expression.name.text === 'resolve'; + function visit(node) { + // Match literal entry loads regardless of the local name of require. + // require.resolve only finds the file, and does not execute it. + const declaration = ts.isImportDeclaration(node) || ts.isExportDeclaration(node); + let spec; + if (declaration) spec = node.moduleSpecifier; + else if (ts.isExternalModuleReference(node)) spec = node.expression; + else if (ts.isCallExpression(node) && (!ts.isPropertyAccessExpression(node.expression) + || /^(?:require|_load)$/.test(node.expression.name.text))) { + spec = node.arguments[0]; + if (spec && resolvesPath(spec)) spec = spec.arguments[0]; } + if (spec && ts.isStringLiteralLike(spec) && (/^electron(?:\/(?:index(?:\.js)?)?)?$/.test(spec.text) + || declaration && spec.text.startsWith('electron/'))) { + const line = tree.getLineAndCharacterOfPosition(spec.getStart(tree)).line + 1; + offenders.push(`${path.relative(srcDir, file)}:${line} -> ${spec.text}`); + } + ts.forEachChild(node, visit); } + visit(tree); } assert.deepEqual(offenders, [], `host must not depend on Electron:\n${offenders.join('\n')}`); }); @@ -115,3 +138,503 @@ test('Node device API isolates relay credentials and rechecks prepared routes', await assert.rejects(api.deviceLinkApiFetch('/api/device-link/devices/peer', { method: 'DELETE' }), /DEVICE_LINK_SCOPE_CHANGED/); assert.equal(requests.length, 2); }); + +/* + * Skill projection owner boundary in the Node Host (release table row 25, step 25a). + * Production entry: the desktop's authBoundaryQuarantine.ts loaded by the Host, and the Host's + * read-only observer agent/skill-projection-boundary.ts that main.ts calls after configureHostOwner + * and on every authorized /health (runtime.skillProjectionBoundary). + * Rule: option A (reviewer, 2026-11-17): the window commits the owner, the Host joins only an exact + * stable owner; the status reports a category and never an owner id; mutations fail closed. + * Gap: the desktop's unit test mocks Electron, the lock and the logger, and cannot see whether the + * module loads under Node, which profile it resolves, or that the Host defaults to "not passive". + * Minimal failure: before 25a the import itself throws (electron has no `app` export under Node). + * Tier: unit. One real child process holds the lock; the wait is shortened through `__testing`. + * Every case runs under a temporary HOME and profile, and checks the lock paths are inside them + * before touching anything, so ~/.agents/skills, ~/.claude/skills and ~/.cindy are never reached. + */ +/** Restore owner write and search permission on every directory, then remove the tree. */ +const skipDirectoryChmod = process.platform === 'win32' && 'Windows chmod(0) does not deny directory access'; + +function removeTemporaryTree(root) { + const makeWritable = (dir) => { + try { fs.chmodSync(dir, 0o700); } catch { /* removed or not ours */ } + let entries = []; + try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const entry of entries) if (entry.isDirectory()) makeWritable(path.join(dir, entry.name)); + }; + makeWritable(root); + fs.rmSync(root, { recursive: true, force: true }); +} + +async function skillBoundaryProfile(t) { + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-skill-boundary-'))); + const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE }; + const home = path.join(root, 'home'); + const profile = path.join(root, 'profile'); + fs.mkdirSync(home); + fs.mkdirSync(profile); + process.env.HOME = home; + process.env.USERPROFILE = home; + const appData = path.join(root, 'app-data'); + fs.mkdirSync(appData); + const { configureUserDataDir, getUserDataDir, configureAppDataDir, getAppDataDir } = await import('../../desktop/src/main/userDataPath.ts'); + let previousProfile = null; + let previousAppData = null; + try { previousProfile = getUserDataDir(); } catch { /* not configured yet */ } + try { previousAppData = getAppDataDir(); } catch { /* not configured yet */ } + configureUserDataDir(profile); + configureAppDataDir(appData); + const boundary = await import('../../desktop/src/main/authBoundaryQuarantine.ts'); + const observer = await import('./agent/skill-projection-boundary.ts'); + t.after(() => { + boundary.__testing.setStrictLockWaitMs(null); + if (previousProfile) configureUserDataDir(previousProfile); + if (previousAppData) configureAppDataDir(previousAppData); + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + // A case may leave a directory unreadable (the sweep blockers). A throwing after-hook would skip + // every hook registered after this one (node:test runs them in order), so never throw here. + try { removeTemporaryTree(root); } + catch (error) { t.diagnostic(`temporary profile not removed: ${root} (${error?.code ?? error})`); } + }); + for (const file of [boundary.__testing.filePath(), boundary.__testing.lockPath(), boundary.__testing.sharedSkillRootsLockPath()]) { + assert.ok(file.startsWith(root + path.sep), `boundary path escapes the temporary profile: ${file}`); + } + // As the window does on sign-in; the Host itself never commits (option A). + const commitOwner = (nextOwnerId, previousOwnerId = null) => boundary.withGhostSkillProjectionOwnerCommit({ + previousOwnerId, nextOwnerId, prepareTransition: async () => {}, commit: () => undefined, + }); + return { root, home, profile, appData, boundary, observer, commitOwner }; +} + +test('skill projection boundary loads in the Host, uses its profile and joins the stable owner', async (t) => { + const { profile, boundary, observer, commitOwner } = await skillBoundaryProfile(t); + assert.equal(boundary.__testing.filePath(), path.join(profile, 'ghost-skill-projection-boundary.json')); + // Not passive by default: a passive instance could not publish an owner at all. + await commitOwner('owner-a'); + const warnings = []; + const observe = observer.createSkillProjectionBoundaryObserver({ warn: (message, fields) => warnings.push({ message, fields }) }); + assert.equal(observe('owner-a'), 'stable'); + assert.equal(await boundary.withSharedGlobalSkillProjectionMutation('owner-a', async () => 'projected'), 'projected'); + assert.deepEqual(warnings, []); +}); + +test('skill projection boundary reports each unstable category without owner ids and refuses the mutation', async (t) => { + const { boundary, observer, commitOwner } = await skillBoundaryProfile(t); + const stateFile = boundary.__testing.filePath(); + const quarantineFile = boundary.__testing.quarantinePath(); + const record = (fields) => JSON.stringify({ version: 1, transitionId: 'fixture-transition', updatedAt: 1, ...fields }); + const cases = [ + { name: 'other owner', status: 'other-owner', error: /not stable for the active owner/, + arrange: () => commitOwner('owner-b') }, + { name: 'pending', status: 'pending', error: /not stable for the active owner/, + arrange: () => fs.writeFileSync(stateFile, record({ phase: 'pending', previousOwnerId: 'owner-b', nextOwnerId: 'owner-a' })) }, + { name: 'durably quarantined', status: 'quarantined', error: /quarantined after an uncertain owner commit/, + arrange: async () => { + await commitOwner('owner-a'); + fs.writeFileSync(quarantineFile, record({ phase: 'quarantined', previousOwnerId: 'owner-b', nextOwnerId: 'owner-a' })); + } }, + { name: 'missing', status: 'missing-or-invalid', error: /not stable for the active owner/, arrange: () => {} }, + { name: 'malformed', status: 'missing-or-invalid', error: /not stable for the active owner/, + arrange: () => fs.writeFileSync(stateFile, '{"version":1,"phase":"stable"') }, + ]; + for (const entry of cases) { + fs.rmSync(stateFile, { force: true }); + fs.rmSync(quarantineFile, { force: true }); + await entry.arrange(); + const warnings = []; + const observe = observer.createSkillProjectionBoundaryObserver({ warn: (message, fields) => warnings.push({ message, fields }) }); + assert.equal(observe('owner-a'), entry.status, entry.name); + observe('owner-a'); + assert.deepEqual(warnings, [{ message: 'skill projection boundary is not stable for this Host owner', fields: { boundary: entry.status } }], entry.name); + assert.doesNotMatch(JSON.stringify(warnings), /owner-[ab]|profile/, entry.name); + let ran = false; + await assert.rejects(boundary.withSharedGlobalSkillProjectionMutation('owner-a', async () => { ran = true; }), entry.error, entry.name); + assert.equal(ran, false, entry.name); + } +}); + +test('skill projection boundary fails closed while another process holds the owner lock', async (t) => { + const { boundary, commitOwner } = await skillBoundaryProfile(t); + await commitOwner('owner-a'); + boundary.__testing.setStrictLockWaitMs(20); + const lockModule = pathToFileURL(path.join(srcDir, '../../desktop/src/main/device-link/crossProcessLock.ts')).href; + // The Host's own loaders (package.json "test"), so the desktop module resolves as in the Host. + const holder = spawn(process.execPath, ['--import', 'tsx', '--import', './src/loaders/register-raw.mjs', '--input-type=module', '-e', ` + const { withSecurityBoundaryLock } = await import(${JSON.stringify(lockModule)}); + await withSecurityBoundaryLock(process.argv[1], { label: 'host-test-holder', waitMs: 0 }, async (status) => { + process.stdout.write(status.held ? 'HELD\\n' : 'NOT-HELD\\n'); + await new Promise((resolve) => process.stdin.once('end', resolve).resume()); + }); + `, boundary.__testing.lockPath()], { cwd: path.join(srcDir, '..'), stdio: ['pipe', 'pipe', 'inherit'] }); + const exited = new Promise((resolve) => holder.once('exit', resolve)); + t.after(() => { if (holder.exitCode === null) process.kill(holder.pid); }); + const first = await new Promise((resolve, reject) => { + holder.stdout.once('data', (chunk) => resolve(String(chunk).trim())); + holder.once('exit', (code) => reject(new Error(`lock holder exited early (${code})`))); + }); + assert.equal(first, 'HELD'); + let ran = false; + await assert.rejects(boundary.withSharedGlobalSkillProjectionMutation('owner-a', async () => { ran = true; }), /boundary lock is busy or unavailable/); + assert.equal(ran, false); + holder.stdin.end(); + assert.equal(await exited, 0); + assert.equal(await boundary.withSharedGlobalSkillProjectionMutation('owner-a', async () => 'after release'), 'after release'); +}); + +/* + * Release table row 25, step 25b (reviewer decision (a) and its conditions). Production entries: + * the serve refusal (agent/skill-projection-owner.ts, injected by main.ts; the guard + * scripts/__tests__/host-skill-projection-owner.test.mjs pins that call), `cindy-host login` + * (login-cli.mjs runLoginCommand, with fake auth servers on loopback and an in-memory credential + * store), serve's logout sweep, the shared global Skill preparation and `/api/agent-skills`. + * Gap: 25a covered only joining; nothing published the owner of a Host's own profile, swept an + * outgoing owner's Skills, or honoured the desktop's hold. Every case runs under the temporary HOME, + * profile and app-data of skillBoundaryProfile, which asserts the lock paths are inside them first. + * Tier: unit (loopback HTTP and the file system only). + */ +function snapshotTree(dir) { + const out = []; + const walk = (current) => { + for (const entry of fs.readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { + const full = path.join(current, entry.name); + const stat = fs.lstatSync(full); + // Directory mtimes move when a lock record is published and removed; a file keeps its mtime. + out.push(`${path.relative(dir, full).split(path.sep).join('/')}:${entry.isSymbolicLink() ? 'l' : entry.isDirectory() ? 'd' : 'f'}:${stat.isFile() ? `${stat.size}:${stat.mtimeMs}` : ''}`); + if (entry.isDirectory()) walk(full); + } + }; + walk(dir); + return out; +} + +/** An owner projection with one Ghost Skill linked from the shared ~/.claude/skills and privately. */ +async function plantOwnerSkillLinks(profile, home, ownerId) { + const { ownerScopedPath } = await import('../../desktop/src/main/dataOwnerPath.ts'); + const { ghostSkillPluginRoot } = await import('../../desktop/src/main/cindy-brain/skillSlot.ts'); + const root = ownerScopedPath(profile, ownerId, 'cindy-brain'); + const source = path.join(root, 'fixture-ghost', 'skills', 'fixture-skill'); + fs.mkdirSync(source, { recursive: true }); + fs.writeFileSync(path.join(source, 'SKILL.md'), '---\nname: fixture-skill\ndescription: fixture\n---\n'); + const shared = path.join(home, '.claude', 'skills', 'fixture-ghost--fixture-skill'); + const privateDir = path.join(ghostSkillPluginRoot(root), 'skills'); + fs.mkdirSync(path.dirname(shared), { recursive: true }); + fs.mkdirSync(privateDir, { recursive: true }); + fs.symlinkSync(source, shared, 'dir'); + fs.symlinkSync(source, path.join(privateDir, 'fixture-ghost--fixture-skill'), 'dir'); + return { shared, privateLink: path.join(privateDir, 'fixture-ghost--fixture-skill') }; +} + +const linkExists = (file) => { try { fs.lstatSync(file); return true; } catch { return false; } }; + +test('25b: serve refuses to publish the projection owner and writes no state', async (t) => { + const { boundary } = await skillBoundaryProfile(t); + const owner = await import('./agent/skill-projection-owner.ts'); + owner.refuseSkillProjectionOwnerCommit(); + t.after(() => owner.allowSkillProjectionOwnerCommit()); + const prepareTransition = async () => { throw new Error('the teardown must not run'); }; + await assert.rejects(boundary.withGhostSkillProjectionOwnerCommit({ previousOwnerId: null, nextOwnerId: 'owner-a', prepareTransition, commit: () => undefined }), + /This process cannot publish the Ghost projection owner/); + assert.equal(fs.existsSync(boundary.__testing.filePath()), false); + assert.equal(fs.existsSync(boundary.__testing.quarantinePath()), false); +}); + +async function fakeLoginAuth() { + const { createServer } = await import('node:http'); + const hits = []; + let member = 'member-a'; + let kind = 'personal'; + const server = createServer((request, response) => { + hits.push(request.url); + const json = (value) => response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(value)); + const membership = { id: member, kind, role: 'owner', displayName: 'Fixture', email: null, orgId: null, orgName: null }; + if (request.url === '/api/auth/providers') return json({ region: 'global', attribution: 'email', email: true, phone: false, social: ['google'] }); + if (request.url === '/api/auth/desktop/callback/poll') return json({ status: 'ok', code: 'fixture-code' }); + if (request.url === '/api/auth/token') return json({ status: 'ok', accessToken: 'fixture-access', refreshToken: `fixture-refresh-${member}`, membership }); + if (request.url === '/api/auth/logout') return json({ status: 'ok' }); + return response.writeHead(404).end('{}'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const port = server.address().port; + const close = () => new Promise((resolve) => { server.closeAllConnections?.(); server.close(resolve); }); + return { hits, port, close, setMember: (id) => { member = id; }, setKind: (value) => { kind = value; } }; +} + +async function loginEnvironment(t, root, profile, port) { + const endpointDir = path.join(root, 'endpoints'); + fs.mkdirSync(endpointDir, { recursive: true }); + const manifest = JSON.stringify({ authApiBaseUrl: `https://127.0.0.1:${port}`, authDesktopCallbackUrl: `https://127.0.0.1:${port}/desktop/callback` }); + for (const file of ['endpoint.json', 'endpoint.global.json']) fs.writeFileSync(path.join(endpointDir, file), manifest); + const saved = { CINDY_HOST_DATA_DIR: process.env.CINDY_HOST_DATA_DIR, CINDY_HOST_ENDPOINT_DIR: process.env.CINDY_HOST_ENDPOINT_DIR, + CINDY_HOST_APP_DATA_DIR: process.env.CINDY_HOST_APP_DATA_DIR }; + process.env.CINDY_HOST_DATA_DIR = profile; + process.env.CINDY_HOST_ENDPOINT_DIR = endpointDir; + process.env.CINDY_HOST_APP_DATA_DIR = path.join(root, 'app-data'); + t.after(() => { for (const [key, value] of Object.entries(saved)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } }); + const records = new Map(); + const store = { read: (key) => records.get(key) ?? null, write: (key, value) => records.set(key, value), remove: (key) => records.delete(key) }; + const { runLoginCommand } = await import('./login-cli.mjs'); + const { CindyAuthClient } = await import('@cindy/auth-client'); + const login = (deps = {}, stdout = () => {}) => runLoginCommand(['--no-open'], { stdout, stderr: () => {}, deps: { + store, readStatus: async () => ({ running: false }), scanDesktops: async () => [], + // The manifest must be https (endpoints.mjs); the fake server listens on plain loopback HTTP. + createAuthClient: (options) => new CindyAuthClient({ ...options, fetch: (input, init) => fetch(String(input).replace(/^https:/, 'http:'), init) }), + ...deps } }); + return { login, records }; +} + +test('25b: cindy-host login publishes the owner that serve then reads as stable, and sweeps the previous account', async (t) => { + const { root, home, profile, observer, boundary } = await skillBoundaryProfile(t); + const auth = await fakeLoginAuth(); + try { + const { login, records } = await loginEnvironment(t, root, profile, auth.port); + const { AUTH_SESSION_KEY } = await import('../../desktop/src/main/authCredentialKeys.ts'); + const { parseAuthSessionRecord } = await import('@cindy/auth-client'); + + await login(); + assert.equal(observer.readSkillProjectionBoundaryStatus('member-a'), 'stable'); + assert.equal(parseAuthSessionRecord(records.get(AUTH_SESSION_KEY))?.refreshToken, 'fixture-refresh-member-a'); + + // Switching to B revokes A's shared and private Ghost Skill links before B becomes visible. + const links = await plantOwnerSkillLinks(profile, home, 'member-a'); + auth.setMember('member-b'); + await login(); + assert.equal(observer.readSkillProjectionBoundaryStatus('member-b'), 'stable'); + assert.equal(linkExists(links.shared), false); + assert.equal(linkExists(links.privateLink), false); + + // A sweep blocker aborts the switch: B is not published, the boundary stays pending, and B's + // session is rolled back to the previous record. Fixing it and running login again recovers. + const again = await plantOwnerSkillLinks(profile, home, 'member-b'); + auth.setMember('member-c'); + await t.test('a failed sweep rolls back the switch', { skip: skipDirectoryChmod }, async () => { + const sharedDir = path.dirname(again.shared); + fs.chmodSync(sharedDir, 0o000); + try { + await assert.rejects(login(), /cleanup incomplete/); + assert.equal(boundary.readGhostSkillProjectionBoundaryState()?.phase, 'pending'); + assert.equal(parseAuthSessionRecord(records.get(AUTH_SESSION_KEY))?.refreshToken, 'fixture-refresh-member-b'); + } finally { + fs.chmodSync(sharedDir, 0o755); + } + }); + await login(); + assert.equal(observer.readSkillProjectionBoundaryStatus('member-c'), 'stable'); + assert.equal(linkExists(again.shared), false); + } finally { + await auth.close(); + } +}); + +test('25b: login refuses while a desktop uses the profile, or the scan cannot tell, and commits nothing', async (t) => { + const { root, profile, boundary } = await skillBoundaryProfile(t); + const auth = await fakeLoginAuth(); + try { + const { login, records } = await loginEnvironment(t, root, profile, auth.port); + await assert.rejects(login({ scanDesktops: async () => [4242] }), /Quit the Cindy desktop app that is using this profile/); + await assert.rejects(login({ scanDesktops: async () => { throw Object.assign(new Error('EACCES: registry'), { code: 'EACCES' }); } }), + /Cannot tell whether the Cindy desktop app is using this profile \(EACCES: registry\)/); + assert.equal(records.size, 0); + assert.deepEqual(auth.hits, []); + assert.equal(fs.existsSync(boundary.__testing.filePath()), false); + } finally { + await auth.close(); + } +}); + +test('25b: a running serve admits a first login and the same account, and refuses replacing its account', async (t) => { + const { root, profile, observer } = await skillBoundaryProfile(t); + const auth = await fakeLoginAuth(); + try { + const { login, records } = await loginEnvironment(t, root, profile, auth.port); + // Serve running without an account runtime: the first login goes through. + const printed = []; + await login({ readStatus: async () => ({ running: true, runtime: { state: 'uninitialized', owner: null } }) }, (line) => printed.push(line)); + assert.equal(observer.readSkillProjectionBoundaryStatus('member-a'), 'stable'); + // serve does not adopt the new session while running: the output says a restart is needed, and how. + assert.ok(printed.some((line) => line.includes('takes effect after Cindy Host restarts') + && line.includes('systemctl --user restart cindy-host') && line.includes('cindy-host stop')), printed.join('\n')); + const quiet = []; + await login({}, (line) => quiet.push(line)); + assert.equal(quiet.some((line) => line.includes('restarts')), false, 'no restart hint when serve is not running'); + // Serve running A: A signs in again. + await login({ readStatus: async () => ({ running: true, runtime: { state: 'ready', owner: 'member-a' } }) }); + // Serve running A: B is refused after the exchange, its session ended and not saved. + auth.setMember('member-b'); + const before = records.get([...records.keys()][0]); + await assert.rejects(login({ readStatus: async () => ({ running: true, runtime: { state: 'ready', owner: 'member-a' } }) }), + /Cindy Host is running another account/); + assert.equal(records.get([...records.keys()][0]), before); + assert.equal(auth.hits.filter((hit) => hit === '/api/auth/logout').length, 1); + assert.equal(observer.readSkillProjectionBoundaryStatus('member-a'), 'stable'); + // An unresponsive serve is refused before anything else. + await assert.rejects(login({ readStatus: async () => ({ running: null }) }), /Cindy Host is not responding/); + } finally { + await auth.close(); + } +}); + +test('25b: serve logout sweeps the outgoing owner once, skips while a desktop holds the profile, and never refuses', async (t) => { + const { root, home, profile, commitOwner, boundary } = await skillBoundaryProfile(t); + const { sweepOwnerSkillProjectionsAtLogout } = await import('./agent/skill-projection-owner.ts'); + await commitOwner('owner-a'); + const links = await plantOwnerSkillLinks(profile, home, 'owner-a'); + const warnings = []; + const sweep = (held) => sweepOwnerSkillProjectionsAtLogout({ userDataDir: profile, ownerId: 'owner-a', + isProfileHeld: () => held, warn: (_message, fields) => warnings.push(fields.outcome) }); + // Held: the shared projections are the running desktop's; not a byte changes. + await boundary.withSharedSkillRootsLock(async () => {}); // materialize the shared-roots lock directory first + const before = snapshotTree(root); + assert.equal(await sweep(true), 'skipped-profile-held'); + assert.deepEqual(snapshotTree(root), before); + assert.equal(linkExists(links.shared), true); + // Not held: revoked, and a second sweep (both sides in client mode) finds nothing and does not fail. + assert.equal(await sweep(false), 'revoked'); + assert.equal(linkExists(links.shared), false); + assert.equal(linkExists(links.privateLink), false); + assert.equal(await sweep(false), 'revoked'); + // The window signed out first (stable(null)): serve leaves its transition alone. + await commitOwner(null, 'owner-a'); + assert.equal(await sweep(false), 'skipped-not-stable'); + assert.deepEqual(warnings, ['skipped-profile-held', 'skipped-not-stable']); +}); + +test('25b: shared Skill preparation publishes the bundle under the stable owner, writes nothing when held, and without locks writes only the empty ~/.agents/skills root the desktop also creates before taking the lock', async (t) => { + const { root, appData, commitOwner } = await skillBoundaryProfile(t); + const { createHostSharedGlobalSkills } = await import('./agent/shared-global-skills.ts'); + const { configureHostOwner } = await import('./agent/claude-auth.mjs'); + const bundle = path.join(srcDir, '../../desktop/resources/system-skills'); + const lockDir = path.join(appData, 'Cindy', 'shared-skill-mutation-locks'); + configureHostOwner({ userDataDir: path.join(root, 'profile'), ownerId: 'owner-a' }); + await commitOwner('owner-a'); + let held = true; + const skills = () => createHostSharedGlobalSkills({ isProfileHeld: () => held, bundledSystemSkillsRoot: () => bundle }); + const before = snapshotTree(root); + await skills().ensureSharedGlobalSkills(); + assert.deepEqual(snapshotTree(root), before, 'held: nothing written'); + // The Skill mutation lock directory cannot be created (a file occupies it): this round is skipped. + held = false; + fs.mkdirSync(path.dirname(lockDir), { recursive: true }); + fs.writeFileSync(lockDir, 'occupied'); + const { withSharedSkillRootsLock } = await import('../../desktop/src/main/authBoundaryQuarantine.ts'); + await withSharedSkillRootsLock(async () => {}); // the boundary's own lock directory, made once + const blocked = snapshotTree(root); + await skills().ensureSharedGlobalSkills(); + // No bundle, no manifest, no link is written. The one addition is the empty ~/.agents/skills root: + // the desktop's prepareSharedGlobalSkillLinks creates it before it asks for the Skill mutation + // lease (shared-global-skills.ts), so the Host, running that code, does too (reported, not changed). + assert.deepEqual(snapshotTree(root).sort(), [...blocked, 'home/.agents:d:', 'home/.agents/skills:d:'].sort(), 'no lock directory: only the empty ~/.agents/skills root, a known behavior shared with the desktop: its prepareSharedGlobalSkillLinks creates this directory before it takes the Skill mutation lock'); + assert.deepEqual(fs.readdirSync(path.join(root, 'home', '.agents', 'skills')), []); + // With the locks available the bundle this Host carries is published in the shared app-data root. + fs.rmSync(lockDir); + await skills().ensureSharedGlobalSkills(); + assert.ok(fs.existsSync(path.join(appData, 'Cindy', 'shared-system-skills', '.cindy-system-skills.json'))); +}); + +test('25b L1: /api/agent-skills drops a Skill the user switched off, and only lists while a desktop holds the profile', async (t) => { + const { root, appData } = await skillBoundaryProfile(t); + const { Maker } = await import('@cindy/maker-core'); + const { BaseAgent } = await import('../../../packages/maker-core/src/agents/base-agent.ts'); + const { setCindySkillEnabled } = await import('../../desktop/src/main/skillhub/activationPreferences.ts'); + const { createHostAgentSkillList } = await import('./agent/agent-skills.ts'); + void appData; + const kept = path.join(root, 'skills', 'kept', 'SKILL.md'); + const off = path.join(root, 'skills', 'off', 'SKILL.md'); + for (const file of [kept, off]) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, '---\nname: x\n---\n'); } + await setCindySkillEnabled(off, false); + const agent = Object.create(BaseAgent.prototype); + agent.deps = {}; + agent.listAgentSkills = async () => ({ skills: [{ name: 'kept', path: kept }, { name: 'off', path: off }] }); + const maker = { storage: { get: async () => null }, requireAgent: () => agent, getSession: () => undefined, listAgentSkills: Maker.prototype.listAgentSkills }; + let held = false; + let refreshes = 0; + const list = createHostAgentSkillList({ maker: () => maker, hasAgent: () => true, readStoredWorkDir: async () => ({ found: false }), + isProfileHeld: () => held, ensureSharedGlobalSkills: async () => { refreshes += 1; } }); + assert.deepEqual((await list({ agentKind: 'claude-code' })).skills.map((skill) => skill.name), ['kept']); + assert.equal(refreshes, 1); + held = true; + assert.deepEqual((await list({ agentKind: 'pi' })).skills.map((skill) => skill.name), ['kept']); + assert.equal(refreshes, 1, 'held: listed without refreshing'); +}); + +// Review follow-ups (25b): the browser step can take minutes, so the desktop scan and serve's state are +// read again right before the commit; a running serve's account must not be transitioned under it; a +// save that fails ends the issued session. Minimal failures: a desktop appearing after the first scan +// is ignored; serve running A with an unset boundary loses A's links; a failed commit leaves a session. +test('25b: login re-checks right before committing, protects a running serve, and ends a session it could not save', async (t) => { + const { root, home, profile, boundary } = await skillBoundaryProfile(t); + const auth = await fakeLoginAuth(); + try { + const { login, records } = await loginEnvironment(t, root, profile, auth.port); + // A desktop appears while the browser step runs (the second scan sees it). + let scans = 0; + await assert.rejects(login({ scanDesktops: async () => (scans++ === 0 ? [] : [4242]) }), /Quit the Cindy desktop app/); + assert.equal(records.size, 0); + assert.equal(fs.existsSync(boundary.__testing.filePath()), false); + assert.equal(auth.hits.filter((hit) => hit === '/api/auth/logout').length, 1, 'the unsaved session is ended'); + // serve runs A, the boundary is not set yet: A signing in again is refused, A's links stay. + const links = await plantOwnerSkillLinks(profile, home, 'member-a'); + await assert.rejects(login({ readStatus: async () => ({ running: true, runtime: { state: 'ready', owner: 'member-a' } }) }), + /Stop Cindy Host \(cindy-host stop\), run cindy-host login again/); + assert.equal(linkExists(links.shared), true); + assert.equal(records.size, 0); + assert.equal(auth.hits.filter((hit) => hit === '/api/auth/logout').length, 2); + } finally { + await auth.close(); + } +}); + +// Review (25b, before the Host commits land): a commit that fails and rolls back must release every +// lock on its way out: the account vault's cross-process lock (with its heartbeat), the boundary's +// strict owner lock and the shared-roots lock. A leaked file lock would not keep the process alive, +// so the case looks for the lock records themselves and then signs in again in the same process. +// Minimal failure: the failure path keeps the vault lock (the next login waits its 5 s and is refused +// as busy) or the strict lock's in-process tail (the next commit never starts). +test('25b: a login whose commit failed releases every lock, and the next login goes straight through', { timeout: 30_000, skip: skipDirectoryChmod }, async (t) => { + const { root, home, profile, observer, boundary } = await skillBoundaryProfile(t); + const auth = await fakeLoginAuth(); + try { + const { login } = await loginEnvironment(t, root, profile, auth.port); + // Every login is bounded, so a lock that is never released fails this case fast instead of hanging the run. + const bounded = (promise, label) => { + let timer; + return Promise.race([promise, new Promise((_resolve, reject) => { + // real-wait: a deadline, not a wait; it fires only when a leaked lock blocks the login and is cleared otherwise. + timer = setTimeout(() => reject(new Error(`${label} is still waiting for a lock after 8 s`)), 8_000); + })]).finally(() => clearTimeout(timer)); + }; + await bounded(login(), 'the first login'); + const links = await plantOwnerSkillLinks(profile, home, 'member-a'); + const sharedDir = path.dirname(links.shared); + // Track the intervals the failing login starts (the vault lock's heartbeat); each must be cleared. + const started = new Set(); + const { setInterval: realSetInterval, clearInterval: realClearInterval } = globalThis; + globalThis.setInterval = (...args) => { const handle = realSetInterval(...args); started.add(handle); return handle; }; + globalThis.clearInterval = (handle) => { started.delete(handle); return realClearInterval(handle); }; + fs.chmodSync(sharedDir, 0o000); + try { + auth.setMember('member-b'); + await assert.rejects(bounded(login(), 'the failing login'), /cleanup incomplete/); + } finally { + fs.chmodSync(sharedDir, 0o755); + globalThis.setInterval = realSetInterval; + globalThis.clearInterval = realClearInterval; + } + const leftRunning = started.size; + for (const handle of started) realClearInterval(handle); + assert.equal(leftRunning, 0, 'a lock heartbeat was left running after the failed commit'); + for (const lock of [path.join(profile, '.cindy-auth-accounts-v1.lock'), boundary.__testing.lockPath(), boundary.__testing.sharedSkillRootsLockPath()]) { + assert.equal(linkExists(lock), false, `lock still held after the failed commit: ${path.relative(root, lock)}`); + } + const retryStarted = Date.now(); + await bounded(login(), 'the retry'); + assert.ok(Date.now() - retryStarted < 4_000, `the retry waited ${Date.now() - retryStarted} ms for a lock`); + assert.equal(observer.readSkillProjectionBoundaryStatus('member-b'), 'stable'); + assert.equal(linkExists(links.shared), false); + } finally { + await auth.close(); + } +}); diff --git a/apps/host/src/chat.interactions.test.mjs b/apps/host/src/chat.interactions.test.mjs index b41c1731bb5..8625512211e 100644 --- a/apps/host/src/chat.interactions.test.mjs +++ b/apps/host/src/chat.interactions.test.mjs @@ -1,7 +1,15 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createServer } from 'node:http'; +import { mkdtempSync, rmSync } from 'node:fs'; import os from 'node:os'; +import path from 'node:path'; +import { configureHostOwner } from './agent/claude-auth.mjs'; +import { configureAppDataDir } from '../../desktop/src/main/userDataPath.ts'; +import { hostRuntimeLayout } from './runtime-layout.mjs'; +import { openOwnerDatabase } from '../../desktop/src/main/localDb/startupCore.ts'; +import { createDbClientForHandle } from '../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../desktop/src/main/localDb/client/current.ts'; import { createChatHandler } from './chat.mjs'; import { createEventHub } from './events.mjs'; @@ -14,6 +22,25 @@ import { createInputQueue } from './agent/input-queue.mjs'; * is how file access silently stopped working for API clients. */ test('chat uses the durable queue and approvals reach the client once', async (t) => { + // The Host always sends with a signed-in profile and its database: the working-directory check + // reads the profile's conversation recovery directories (agent/working-directory.ts), and the send + // reads the task's rows (a fixture profile: the guard against migrating the official shared + // profile is lifted while it opens). + const profile = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-chat-interactions-')); + configureHostOwner({ userDataDir: profile, ownerId: 'chat-interactions' }); + configureAppDataDir(path.join(profile, 'app-data')); + const sharedProfile = process.env.XDT_OFFICIAL_SHARED_PROFILE; + delete process.env.XDT_OFFICIAL_SHARED_PROFILE; + const layout = hostRuntimeLayout(); + const opened = await openOwnerDatabase({ userDataDir: profile, ownerId: 'chat-interactions', + isPackaged: false, drizzleDir: layout.drizzleDir, sqliteVecExtPath: layout.sqliteVecPath }) + .finally(() => { if (sharedProfile !== undefined) process.env.XDT_OFFICIAL_SHARED_PROFILE = sharedProfile; }); + const database = createDbClientForHandle({ db: opened.db, drizzle: opened.drizzle, dispose: async () => opened.db.close() }); + setCurrentDbClient(database, 'chat-interactions'); + t.after(async () => { + clearCurrentDbClient(); await database.dispose(); + configureHostOwner({ userDataDir: profile, ownerId: null }); rmSync(profile, { recursive: true, force: true }); + }); const hub = createEventHub(); const broker = createInteractionBroker({ hub }); const published = []; @@ -32,6 +59,8 @@ test('chat uses the durable queue and approvals reach the client once', async (t id: 'session-1', instanceId: 'runtime-1', agentKind: 'claude-code', workDir: os.tmpdir(), isTurnRunning: () => false, + // The Session's turn generation (maker-core session.ts), read at a terminal for its product-turn owner. + getTurnGeneration: () => 1, onEvent(callback) { emitEvent = callback; return () => {}; @@ -61,6 +90,8 @@ test('chat uses the durable queue and approvals reach the client once', async (t createSession: async () => { live = true; return session; }, closeSession: async () => { live = false; } }), persistMessage: async (_id, message) => { saved.push(message); }, interactions: broker, + // Fixture does not test admission (夹具不测准入): the runtime start admission lets every start through. + admitLocalRoute: async () => {}, }); t.after(() => queue.dispose()); const handler = createChatHandler({ readSession, events: hub, @@ -95,3 +126,55 @@ test('chat uses the durable queue and approvals reach the client once', async (t 'a settled request cannot be answered twice'); }); + +// §3.2 integration through the real handler over HTTP. Entry: POST /chat (createChatHandler), observed through +// the response and the create call. Rule: while a desktop holds the profile, an entry outside the service gate +// writes nothing the desktop shares; /chat used to create the task row (and a dialogue folder) before the queue +// refused the input. Gap: the queue's own refusal was covered, the row created before it was not. Minimal failing +// input: drop the profileHold check before createSession in chat.mjs. Tier: integration (in-process HTTP, fake +// task store and queue). Measured standalone with the whole file. +test('a held profile refuses /chat before creating a task, and input to an existing task as before', async (t) => { + const held = { message: null }; + const holdError = () => Object.assign(new Error(`[PRECONDITION_FAILED] ${held.message}`), { code: 'PRECONDITION_FAILED' }); + const tasks = new Map([['existing', { id: 'existing', status: 'active' }]]); + const created = []; + const handler = createChatHandler({ + readSession: async id => tasks.get(id), + createSession: async body => { created.push(body.id); tasks.set(body.id, { id: body.id, status: 'active' }); return tasks.get(body.id); }, + // The real queue refuses new input while held (input-queue.mjs refuseWhileHeld) with the same answer. + enqueue: async () => { if (held.message) throw holdError(); return { items: [] }; }, + inputStatus: async () => 'recorded', + events: createEventHub(), + profileHold: () => held.message, + }); + const server = createServer((request, response) => { void handler(request, response); }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => server.close(resolve))); + const chat = async sessionId => { + const response = await fetch(`http://127.0.0.1:${server.address().port}/chat`, { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ sessionId, prompt: 'hello', workDir: os.tmpdir() }), + }); + return { status: response.status, body: await response.text() }; + }; + + held.message = 'HOST_PROFILE_IN_USE_BY_DESKTOP: a desktop is using this profile.'; + const refusedNew = await chat('new-task'); + const refusedExisting = await chat('existing'); + assert.deepEqual(created, [], 'no task is created while held'); + assert.equal(tasks.has('new-task'), false); + // Both end with the same chat_failed event naming PRECONDITION_FAILED. The status differs as other failures + // do: a new task is refused before the stream opens (500, like an unknown task), input to an existing task + // after it opened (200, unchanged). + assert.equal(refusedNew.status, 500); + assert.equal(refusedExisting.status, 200); + for (const refused of [refusedNew, refusedExisting]) { + assert.match(refused.body, /"reason":"chat_failed"/); + assert.match(refused.body, /PRECONDITION_FAILED/); + } + + held.message = null; + const accepted = await chat('new-task'); + assert.equal(accepted.status, 200); + assert.deepEqual(created, ['new-task']); +}); diff --git a/apps/host/src/chat.mjs b/apps/host/src/chat.mjs index c282612f7c8..8ceb60d4764 100644 --- a/apps/host/src/chat.mjs +++ b/apps/host/src/chat.mjs @@ -72,7 +72,8 @@ export function createChatHandler(deps) { const sessionId = payload.sessionId ?? randomUUID(); const clientId = payload.clientId ?? randomUUID(); let unsubscribe = () => {}; - const cleanup = () => { unsubscribe(); unsubscribe = () => {}; }; + let offBoundaryStop = () => {}; + const cleanup = () => { unsubscribe(); unsubscribe = () => {}; offBoundaryStop(); offBoundaryStop = () => {}; }; response.once('close', cleanup); const write = event => { if (!response.destroyed && !response.writableEnded) response.write(`data: ${JSON.stringify(event)}\n\n`); @@ -83,6 +84,13 @@ export function createChatHandler(deps) { }; try { const stored = await deps.readSession(sessionId); + // /chat answers outside the service gate. A task it creates is a row in the database a desktop shares, + // so a held profile refuses it here, synchronously before the create call, with the answer the queue + // gives input while held; input to an existing task is refused by the queue as before. + if (!stored) { + const held = deps.profileHold?.(); + if (held) throw Object.assign(new Error(`[PRECONDITION_FAILED] ${held}`), { code: 'PRECONDITION_FAILED' }); + } if (!stored) await deps.createSession({ id: sessionId, ...(payload.workDir ? { workingDir: payload.workDir, workspaceKind: 'project' } : { workspaceKind: 'dialogue' }), model: payload.model ?? deps.defaultModel, @@ -94,12 +102,23 @@ export function createChatHandler(deps) { 'cache-control': 'no-store', connection: 'keep-alive', }); write({ type: 'session', sessionId, clientId }); + // An owner boundary (logout, session invalidation, shutdown; agent/owner-boundary.ts) stops this + // input's turn as an interruption and the executor publishes no receipt for it: the stream ends here + // with the receipt a stopped turn gets (turn-executor.mjs, an abort without a terminal event). + offBoundaryStop = deps.onBoundaryStop?.(() => { + write({ type: 'input_receipt', sessionId, inputClientId: clientId, clientId, status: 'interrupted' }); + end(); + }) ?? (() => {}); + // Once this input's terminal error is taken over by an automatic resume, the stream follows the + // resume's turns (their events name this input as autoResumeOf) and ends with the resume. + let followingResume = false; unsubscribe = deps.events.subscribe(event => { if (event.type === 'auth_changed' && event.canEnterApp === false) { end(); return; } if (event.sessionId !== sessionId) return; // Queue projections and questions remain task-wide; model events must // belong to this exact input, not the turn ahead of it in the queue. - if (event.inputClientId && event.inputClientId !== clientId) return; + const own = event.inputClientId === clientId || (followingResume && event.autoResumeOf === clientId); + if (event.inputClientId && !own) return; write(event); // Dispatch can fail after admission (session start, pre-send preparation). // The queue then keeps this input as the recoverable head and publishes @@ -111,14 +130,23 @@ export function createChatHandler(deps) { end(); return; } - if (event.type === 'input_receipt' && event.inputClientId === clientId - && event.status === 'interrupted') { + // An interrupted input, or a silent-stop turn that settled without its continuation (recorded, + // agent/turn-executor.mjs endSilentStopTurn), ends the stream; so do those of a resume it follows. + if (event.type === 'input_receipt' && own + && (event.status === 'interrupted' || event.status === 'recorded')) { end(); return; } - if (event.inputClientId === clientId && event.turnScope !== 'background' + if (own && event.turnScope !== 'background' && !isTurnContinuationBoundaryEvent(event) - && (event.type === 'done' || isTerminalTurnErrorEvent(event))) end(); + && (event.type === 'done' || isTerminalTurnErrorEvent(event))) { + // The resume answers this input, or gives up with an interrupted receipt (input-queue.mjs). + if (event.type === 'error' && event.autoResumePending) { followingResume = true; return; } + // A silent stop is decided later (agent/silent-stop.ts): the continuation, its banner or the + // recorded receipt ends the stream. + if (event.type === 'done' && event.silentStopPending) return; + end(); + } }); const projection = await deps.enqueue(sessionId, { clientId, text: payload.prompt }); write({ type: 'input_projection', sessionId, projection }); diff --git a/apps/host/src/chromium-proxy-worker.cjs b/apps/host/src/chromium-proxy-worker.cjs new file mode 100644 index 00000000000..77bf323f4d1 --- /dev/null +++ b/apps/host/src/chromium-proxy-worker.cjs @@ -0,0 +1,88 @@ +/** + * The Host's Chromium proxy helper (release table row 28, 28c), run by Electron. It answers one question — + * which proxy Chromium would use for a URL under the system settings, PAC and auto-discovery included — so the + * Host follows the same rules as the desktop's session.resolveProxy. The Host starts it on demand and owns its + * lifetime (chromium-proxy.ts). + * + * Boundary: parent-child IPC on Windows and stdin/stdout elsewhere, one JSON text per message; no window, + * page, port or socket of its own. Its userData is its own directory under the Host data directory; + * it takes no single-instance lock and opens no + * desktop profile. It asks an in-memory session (no `persist:` partition: nothing on disk, no cookies), never + * calls safeStorage and receives no credentials, tokens or request bodies: only URLs, answered with Chromium's + * PAC result string. Chromium itself fetches PAC files and tries auto-discovery, as for the desktop. + * + * Readiness: it says `ready` only after the proxy configuration has been applied and one resolution under it + * has completed (a PAC file fetched and initialised). Until then every question is answered `not_ready`, never + * DIRECT: an answer given before the PAC script is ready could send a request direct that should use a proxy. + * + * Tests only: CINDY_PROXY_WORKER_TEST_CONFIG holds a session.setProxy configuration to use instead of the system + * settings. The Host's launcher removes every CINDY_ variable from the environment it passes, so a production + * start cannot carry it (guarded in hostDesktopSourceContracts.guard.test.ts). + */ +const { app, session } = require('electron'); +const { createInterface } = require('node:readline'); + +const MAX_LINE = 8192; +const MAX_URL = 4096; +// Resolved once before saying ready, so that the configuration (and a PAC script) is loaded. `.invalid` never +// resolves in DNS, so a PAC script that looks the host up gets a quick answer and learns nothing. +const READINESS_PROBE = 'https://cindy-proxy-helper.invalid/'; + +const profile = process.env.CINDY_PROXY_WORKER_PROFILE; +if (!profile) throw new Error('PROXY_WORKER_PROFILE_REQUIRED'); +app.setPath('userData', profile); +app.setName('Cindy Proxy'); +app.dock?.hide(); +app.disableHardwareAcceleration(); + +const transport = process.platform === 'win32' ? { + write(line) { + if (process.connected) process.send(line, (error) => { if (error) app.quit(); }); + }, + listen(onLine) { + process.on('disconnect', () => app.quit()); + if (!process.connected) { app.quit(); return; } + process.on('message', line => { if (typeof line === 'string') onLine(line); }); + }, +} : { + write: (line) => process.stdout.write(`${line}\n`), + listen(onLine) { + const lines = createInterface({ input: process.stdin }); + lines.on('close', () => app.quit()); + lines.on('line', onLine); + }, +}; +const send = (value) => transport.write(JSON.stringify(value)); +let ses = null; + +transport.listen((line) => { + if (line.length > MAX_LINE) return; + let request; + try { request = JSON.parse(line); } catch { return; } + if (!request || !Number.isSafeInteger(request.id)) return; + if (request.method === 'ping') return send({ id: request.id, result: 'pong' }); + if (request.method !== 'resolve' || typeof request.url !== 'string' || request.url.length > MAX_URL) { + return send({ id: request.id, error: 'invalid_request' }); + } + if (!ses) return send({ id: request.id, error: 'not_ready' }); + ses.resolveProxy(request.url).then( + (result) => send({ id: request.id, result: String(result) }), + () => send({ id: request.id, error: 'resolve_failed' }), + ); +}); + +app.whenReady().then(async () => { + const candidate = session.fromPartition('cindy-proxy-helper', { cache: false }); + const testConfig = process.env.CINDY_PROXY_WORKER_TEST_CONFIG; + await candidate.setProxy(testConfig ? JSON.parse(testConfig) : { mode: 'system' }); + // setProxy resolves before the network service applies the configuration: a resolution right after it can + // still see the previous configuration and answer DIRECT (seen 2 runs in 3). forceReloadProxyConfig is a round + // trip queued after it, so once it resolves the configuration is in effect; the probe then waits for the PAC + // script (or auto-discovery) to load. + await candidate.forceReloadProxyConfig(); + await candidate.resolveProxy(READINESS_PROBE); + ses = candidate; + send({ ready: true, pid: process.pid }); +}).catch(() => app.exit(1)); + +process.once('SIGTERM', () => app.quit()); diff --git a/apps/host/src/chromium-proxy.test.mjs b/apps/host/src/chromium-proxy.test.mjs new file mode 100644 index 00000000000..16bb7fac822 --- /dev/null +++ b/apps/host/src/chromium-proxy.test.mjs @@ -0,0 +1,557 @@ +/* + * Test value (release table row 28, 28c; reviewer 2026-11-18) + * - Production entry: the Host's outbound proxy resolver (resolveHostOutboundProxy, outbound-proxy.ts, which every + * Host outbound request goes through) with the system proxy session main.ts sets (macOS: static settings plus the + * Chromium proxy helper; Windows: the helper), and the helper's Host side (createChromiumProxyHelper) on a + * stand-in helper process speaking the same line protocol. The real Electron helper is exercised by + * scripts/chromium-proxy-worker.e2e.mjs. + * - Rules: never an answer before the helper is ready (a premature DIRECT would send a proxied request direct); + * started on demand only (not with proxy environment variables; on macOS not for static settings); every wait + * bounded, with a backoff restart; the fallback while it has no answer (macOS: the static reading, 28b; Windows: + * direct, recorded unknown); stopped by its handle; the helper gets the URL without user info or query, and an + * environment without any XDT_ / CINDY_ variable. + * - Gap: nothing ran PAC or auto-discovery on the Host before 28c. + * - Minimal failing input: a helper that answers DIRECT before it is ready; HTTPS_PROXY set; a helper that never + * becomes ready. + * - Tier: unit with a process stand-in and mocked timers. The startup login case also uses a loopback HTTP proxy. + */ +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { execFile, spawn } from 'node:child_process'; +import fs from 'node:fs'; +import { createServer } from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { PassThrough, Writable } from 'node:stream'; +import test, { mock } from 'node:test'; +import { promisify } from 'node:util'; +import ts from 'typescript'; +import { createHostServer } from './server.mjs'; + +import { + ANSWER_WAIT_MS, FIRST_BACKOFF_MS, START_TIMEOUT_MS, STOP_TIMEOUT_MS, WARMUP_WAIT_MS, createChromiumProxyHelper, helperEnv, helperUrl, +} from './chromium-proxy.ts'; +import { + getHostOutboundPathSnapshotFor, resolveHostOutboundProxy, startHostSystemProxySettings, useHostChromiumProxySession, useHostSystemProxySettings, +} from './outbound-proxy.ts'; + +import { hostAuthFetch } from './auth-fetch.mjs'; + +const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy']; +const savedEnv = Object.fromEntries(PROXY_ENV_KEYS.map(key => [key, process.env[key]])); +for (const key of PROXY_ENV_KEYS) delete process.env[key]; +const profileDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-chromium-proxy-')); +mock.timers.enable({ apis: ['setTimeout', 'Date'], now: Date.now() }); +test.after(() => { + mock.timers.reset(); + useHostSystemProxySettings(null); + for (const [key, value] of Object.entries(savedEnv)) if (value === undefined) delete process.env[key]; else process.env[key] = value; + fs.rmSync(profileDir, { recursive: true, force: true }); +}); + +/** + * A stand-in for the helper process: records what the Host writes; `behaviour` decides its answers. Like the real + * helper it quits when its stdin closes, unless `ignoreStdinEnd`. + */ +function standIn(behaviour = {}) { + const spawned = []; + const spawnImpl = (binary, args, options) => { + const child = new EventEmitter(); + child.pid = 4000 + spawned.length; + child.args = args; + child.options = options; + child.signals = []; + child.written = []; + child.stdout = new PassThrough(); + child.send = value => child.stdout.write(`${JSON.stringify(value)}\n`); + child.stdin = new Writable({ + write(chunk, _encoding, done) { + for (const line of chunk.toString().split('\n').filter(Boolean)) { + const message = JSON.parse(line); + child.written.push(message); + behaviour.onRequest?.(child, message); + } + done(); + }, + final(done) { + child.stdinEnded = true; + if (!behaviour.ignoreStdinEnd) queueMicrotask(() => child.exit()); + done(); + }, + }); + child.kill = (signal) => { child.signals.push(signal); return true; }; + child.exit = (code = null) => { if (!child.exited) { child.exited = true; child.emit('exit', code, null); } }; + spawned.push(child); + behaviour.onSpawn?.(child); + return child; + }; + return { spawned, spawnImpl }; +} + +const ready = child => child.send({ ready: true, pid: child.pid }); +const answer = result => (child, message) => { if (message.method === 'resolve') child.send({ id: message.id, result }); }; +const helperFor = (spawnImpl) => createChromiumProxyHelper({ profileDir, spawnImpl, platform: 'darwin', + assets: () => ({ binary: 'electron', script: 'worker.cjs' }) }); + +const ipcWorker = path.join(profileDir, 'ipc-worker.cjs'); +fs.writeFileSync(ipcWorker, ` + const send = value => process.send(JSON.stringify(value)); + let first; + process.on('disconnect', () => process.exit()); + process.on('message', line => { + const request = JSON.parse(line); + if (!first) { first = request; return; } + send({ id: request.id, result: request.url }); + send({ id: first.id, result: first.url }); + }); + send({ ready: true, pid: process.pid }); +`); +const settle = async () => { for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve)); }; + +/** Starts a resolution and reports whether it settled, and how, without awaiting it. */ +function track(promise) { + const state = { settled: false, value: undefined, error: undefined }; + promise.then(value => { state.settled = true; state.value = value; }, error => { state.settled = true; state.error = error; }); + return state; +} + +test('never an answer before the helper is ready: the resolution waits, within its limit, then gets Chromium\'s', async () => { + // A helper that would answer DIRECT at once; only the Host's wait for `ready` keeps that answer out. + const { spawned, spawnImpl } = standIn({ onRequest: answer('DIRECT') }); + const helper = helperFor(spawnImpl); + const early = track(helper.resolveProxy('https://user:secret@api.example.test/v1?token=t#frag')); + await settle(); + assert.equal(spawned.length, 1); + assert.deepEqual(spawned[0].written, [], 'nothing is asked before ready'); + mock.timers.tick(ANSWER_WAIT_MS); + await settle(); + assert.equal(early.settled, true); + assert.equal(early.value, undefined, 'no answer before ready'); + assert.match(String(early.error?.message), /not ready yet/); + + ready(spawned[0]); + await settle(); + spawned[0].written.length = 0; + assert.equal(await helper.resolveProxy('https://user:secret@api.example.test/v1?token=t#frag'), 'DIRECT'); + assert.deepEqual(spawned[0].written, [{ id: 1, method: 'resolve', url: 'https://api.example.test/v1' }], 'no user info, query or fragment'); + assert.equal(helper.state(), 'ready'); +}); + +// Rule: stdout outside the JSON protocol cannot interrupt proxy resolution. Gap: the Windows +// acceptance run saw an empty line before a reply. Minimal input: CRLF and a non-JSON line before +// ready and before a reply. Tier: unit through the production client's child stream. +test('the proxy helper client ignores unrelated stdout before ready and a reply', async () => { + const noise = child => child.stdout.write('\r\nChromium startup output\r\n'); + const { spawnImpl } = standIn({ + onSpawn(child) { noise(child); ready(child); }, + onRequest(child, message) { noise(child); answer('PROXY 127.0.0.1:9')(child, message); }, + }); + const helper = helperFor(spawnImpl); + try { + assert.equal(await helper.resolveProxy('https://api.example.test/'), 'PROXY 127.0.0.1:9'); + } finally { + await helper.close(); + } +}); + +// Entry: the production helper and Host resolver. Rule: an early exit releases readiness and uses +// the Windows fallback without starting another worker during backoff. Gap: the current crash test +// exits after ready. Minimal input: one code-zero exit before ready, then requests bracketing retry. +// Tier: unit with the child and clock injected. +test('a clean exit before ready falls back immediately and retries only after backoff', async () => { + const { spawned, spawnImpl } = standIn(); + const helper = helperFor(spawnImpl); + try { + const warmup = track(startHostSystemProxySettings({ platform: 'win32', makeHelper: () => helper })); + const upstream = 'https://exit-before-ready.example.test/'; + const first = track(resolveHostOutboundProxy(upstream)); + spawned[0].exit(0); + await settle(); + assert.equal(warmup.settled, true); + assert.ifError(warmup.error); + assert.equal(first.settled, true); + assert.ifError(first.error); + assert.equal(first.value, null); + assert.equal(getHostOutboundPathSnapshotFor([upstream]).kind, 'unknown'); + assert.equal(helper.state(), 'backoff'); + + mock.timers.tick(FIRST_BACKOFF_MS - 1); + await assert.rejects(helper.resolveProxy(upstream), /restarting/); + assert.equal(spawned.length, 1); + mock.timers.tick(1); + const retry = track(helper.resolveProxy(upstream)); + assert.equal(spawned.length, 2); + spawned[1].exit(0); + await settle(); + assert.match(retry.error?.message ?? '', /helper exited/); + mock.timers.tick(FIRST_BACKOFF_MS); + await assert.rejects(helper.resolveProxy(upstream), /restarting/); + assert.equal(spawned.length, 2, 'a second early exit doubles the backoff'); + } finally { + await helper.close(); + } +}); + +// Entry: createChromiumProxyHelper with a real Node subprocess in place of Electron. +// Rule: Windows IPC carries unchanged JSON and pairs replies by id. Gap: stream-only stand-ins +// miss IPC wiring. Minimal input: two concurrent requests, replied to in reverse. Tier: unit with +// a local IPC fixture, exercising the parent transport without system proxy settings. +test('the Windows transport pairs out-of-order replies over Node IPC', { timeout: 5000 }, async t => { + let child; + const helper = createChromiumProxyHelper({ profileDir, platform: 'win32', + spawnImpl: (binary, args, options) => { child = spawn(binary, args, { ...options, signal: AbortSignal.timeout(3500) }); return child; }, + assets: () => ({ binary: process.execPath, script: ipcWorker }) }); + t.after(() => helper.close()); + const first = 'https://ipc-first.example.test/path'; + const second = 'https://ipc-second.example.test/other'; + const replies = Promise.all([helper.resolveProxy(first), helper.resolveProxy(second)]); + // The helper's deadlines use the mock clock, so keep the real fixture referenced until it exits. + child.ref(); + assert.deepEqual(await replies, [first, second]); +}); + +// Entry: a short-lived Node Host calls the real helper's warmUp and optional close. Rule: an idle +// Windows IPC channel must not keep login alive. Gap: mocks cannot detect a referenced OS handle. +// Minimal input: a ready IPC worker, with and without explicit close. Tier: unit with a subprocess +// fixture and real IPC, isolated from Electron and system settings. +test('the Windows IPC channel allows a short Host to exit after warmup or close', { timeout: 32_000 }, async () => { + const source = ` + import { createChromiumProxyHelper } from ${JSON.stringify(new URL('./chromium-proxy.ts', import.meta.url).href)}; + const [script, profileDir, action] = process.argv.slice(1); + const helper = createChromiumProxyHelper({ profileDir, platform: 'win32', + assets: () => ({ binary: process.execPath, script }) }); + await helper.warmUp(); + if (helper.state() !== 'ready') throw new Error('fixture did not become ready'); + if (action === 'close') await helper.close(); + console.log(helper.state()); + `; + const run = promisify(execFile); + for (const [action, expected] of [['warmup', 'ready'], ['close', 'stopped']]) { + const exit = new AbortController(); + const result = run(process.execPath, ['--import', 'tsx', + '--import', new URL('./loaders/register-raw.mjs', import.meta.url).href, + '--input-type=module', '-e', source, ipcWorker, profileDir, action], + { signal: AbortSignal.any([AbortSignal.timeout(15_000), exit.signal]) }); + + // Start the liveness check when the short Host reports its final state. Loading its + // TypeScript dependencies under the parallel Host suite has a separate deadline. + let exitDeadline; + const abort = () => exit.abort(new Error(`${action}: the short Host reported its final state but did not exit`)); + result.child.stdout.once('data', () => { + exitDeadline = AbortSignal.timeout(3500); + exitDeadline.addEventListener('abort', abort, { once: true }); + }); + try { + const { stdout } = await result; + assert.equal(stdout.trim(), expected); + } catch (error) { + if (exit.signal.aborted) throw exit.signal.reason; + throw error; + } finally { + exitDeadline?.removeEventListener('abort', abort); + } + } +}); + +test('started on demand: not with proxy environment variables, not for static macOS settings, at the first need on Windows', async () => { + const { spawned, spawnImpl } = standIn({ onSpawn: ready, onRequest: answer('PROXY 10.9.9.9:8080') }); + const helper = helperFor(spawnImpl); + assert.equal(spawned.length, 0, 'creating the helper starts nothing'); + + useHostChromiumProxySession(helper); + process.env.HTTPS_PROXY = 'http://127.0.0.1:3128'; + try { + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy('https://env.example.test/'), 'http://127.0.0.1:3128'); + } finally { delete process.env.HTTPS_PROXY; } + assert.equal(spawned.length, 0, 'proxy environment variables come first; no helper'); + + const STATIC = ' {\n HTTPSEnable : 1\n HTTPSProxy : 10.0.0.2\n HTTPSPort : 3129\n}\n'; + useHostSystemProxySettings(async () => STATIC, helper); + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy('https://static.example.test/'), 'http://10.0.0.2:3129'); + assert.equal(spawned.length, 0, 'static macOS settings: the 28b reading, no helper'); + + for (const extra of [' ProxyAutoConfigEnable : 1\n ProxyAutoConfigURLString : http://pac.example.test/proxy.pac\n', ' ProxyAutoDiscoveryEnable : 1\n']) { + useHostSystemProxySettings(async () => STATIC.replace(' {\n', ` {\n${extra}`), helper); + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy(`https://dynamic-${spawned.length}.example.test/`), 'http://10.9.9.9:8080', extra); + } + assert.equal(spawned.length, 1, 'PAC and auto-discovery ask Chromium, through one helper'); + + useHostChromiumProxySession(helper); + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy('https://windows.example.test/'), 'http://10.9.9.9:8080'); + assert.equal(spawned.length, 1, 'the helper stays running'); + await helper.close(); +}); + +// Startup regression (row 28c): exercise the startup gate followed by the actual auth transport. +// The PAC answer is delayed past the normal 1.8 s deadline. Only the loopback proxy receives the POST. +test('the first login reaches the PAC proxy after a three-second cold start', async t => { + const seen = []; + const proxy = createServer((req, res) => { + seen.push([req.method, req.url]); + res.end('via PAC'); + }); + await new Promise(resolve => proxy.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => { proxy.closeAllConnections(); proxy.close(resolve); })); + const { spawnImpl, spawned } = standIn({ + onRequest: answer(`PROXY 127.0.0.1:${proxy.address().port}`), + }); + const helper = helperFor(spawnImpl); + t.after(() => helper.close()); + const url = 'http://cold-auth.example.test/v1/session/refresh'; + const startup = track(startHostSystemProxySettings({ platform: 'darwin', makeHelper: () => helper, + readSettings: async () => ' {\n ProxyAutoConfigEnable : 1\n ProxyAutoConfigURLString : http://pac.example.test/proxy.pac\n}\n', + })); + await settle(); + assert.equal(spawned.length, 1, 'start before any network request'); + mock.timers.tick(2999); + await settle(); + assert.equal(startup.settled, false, 'startup must wait for the cold PAC'); + assert.deepEqual(spawned[0].written, []); + mock.timers.tick(1); + ready(spawned[0]); + await settle(); + assert.equal(startup.settled, true); + assert.ifError(startup.error); + const response = await hostAuthFetch(url, { method: 'POST' }); + assert.equal(await response.text(), 'via PAC'); + assert.deepEqual(seen, [['POST', url]]); +}); + +// Row 28c, integration: run main's command preparation and listen/startup callback together, as +// startup-account.test.mjs runs the real startup functions. Substitute profile/account storage; +// exercise the real loopback /health handler, proxy helper protocol and login transport. +function launchServe(t, { startHostSystemProxySettings, resolveAccountUser, warn }) { + const server = createHostServer({ token: 'fixture-token' }); + // Let early rejections surface before the listener's startup callback runs. + const listen = server.listen.bind(server); + server.listen = (port, host, onListening) => listen(port, host, () => setImmediate(() => { + if (server.listening) onListening(); + })); + t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); })); + + const source = fs.readFileSync(new URL('./main.ts', import.meta.url), 'utf8'); + const preparation = source.slice(source.indexOf('const command ='), source.indexOf("if (command === '--help'")); + const listener = source.slice(source.indexOf("server.on('error'"), source.indexOf('let shuttingDown =')); + const ports = { + server, PORT: 0, profileDir, instanceId: 'fixture', account: {}, runtime: {}, shuttingDown: false, + process: { argv: ['node', 'main.ts', 'serve'], env: {}, stdout: { write() {} } }, + console: { log() {}, warn, error() {} }, resolveHostRegion() {}, publishHostEndpoint() {}, resolveHostDataDir: () => profileDir, + discoverHostOwner: () => ({}), readAdoptedSessionState: async () => ({ authenticated: true }), + startHostSystemProxySettings, resolveAccountUser, + disposeOwnerRuntime() {}, commitVolatileAppSession() {}, classifyHostStartFailure() {}, + }; + const body = ts.transpileModule(`return async () => { + let startup, removeEndpoint; + ${preparation} + ${listener} + return () => startup; + }`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText; + const launch = new Function(...Object.keys(ports), body)(...Object.values(ports)); + return { server, listening: launch() }; +} + +test('serve answers health before the cold PAC is ready and sends its first login through the proxy', async t => { + const seen = []; + const proxy = createServer((req, res) => { seen.push(req.url); res.end('via PAC'); }); + await new Promise(resolve => proxy.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise(resolve => { proxy.closeAllConnections(); proxy.close(resolve); })); + const { spawned, spawnImpl } = standIn({ onRequest: answer(`PROXY 127.0.0.1:${proxy.address().port}`) }); + const helper = helperFor(spawnImpl); + t.after(() => helper.close()); + const loginUrl = 'http://listen-first.example.test/v1/session/refresh'; + let loginStarted = false; + const { server, listening } = launchServe(t, { + startHostSystemProxySettings: () => startHostSystemProxySettings({ platform: 'win32', makeHelper: () => helper }), + resolveAccountUser: async () => { + loginStarted = true; + const response = await hostAuthFetch(loginUrl, { method: 'POST' }); + await response.text(); + return null; + }, + }); + await settle(); + assert.ok(server.listening, 'serve must listen while proxy warmup is still pending'); + const startup = await listening; + const health = await fetch(`http://127.0.0.1:${server.address().port}/health`); + assert.equal(health.status, 200); + assert.equal((await health.json()).service, 'cindy-host'); + mock.timers.tick(2999); + await settle(); + assert.equal(loginStarted, false); + assert.deepEqual(spawned[0].written, [], 'no proxy resolution for login yet'); + assert.deepEqual(seen, []); + mock.timers.tick(1); + ready(spawned[0]); + await startup(); + assert.deepEqual(seen, [loginUrl]); +}); + +// Row 28c: a helper factory can throw before startup awaits warmup (for example, a bad profile path). +test('serve keeps listening and continues startup after proxy warmup rejects', async t => { + const warnings = []; + let loginRoute; + const { server, listening } = launchServe(t, { + startHostSystemProxySettings: () => startHostSystemProxySettings({ + platform: 'darwin', + makeHelper: () => { throw new TypeError('private profile path'); }, + readSettings: async () => ' {\n HTTPSEnable : 1\n HTTPSProxy : 127.0.0.1\n HTTPSPort : 3129\n}\n', + }), + resolveAccountUser: async () => { + loginRoute = await resolveHostOutboundProxy('https://warmup-error.example.test/'); + return null; + }, + warn: (...args) => warnings.push(args), + }); + const startup = await listening; + await settle(); + assert.ok(server.listening); + await startup(); + assert.equal(loginRoute, 'http://127.0.0.1:3129', 'startup reached login using the static fallback'); + assert.deepEqual(warnings, [['[host] system proxy warmup failed:', 'TypeError']]); +}); + +// Removing the 8 s bound leaves startup blocked until the independent 15 s watchdog. +test('startup continues at the warmup deadline with the first route unknown', async t => { + const { spawnImpl, spawned } = standIn(); + const helper = helperFor(spawnImpl); + t.after(() => helper.close()); + const startup = track(startHostSystemProxySettings({ platform: 'win32', makeHelper: () => helper })); + await settle(); + assert.equal(spawned.length, 1); + mock.timers.tick(WARMUP_WAIT_MS - 1); + await settle(); + assert.equal(startup.settled, false); + mock.timers.tick(1); + await settle(); + assert.equal(startup.settled, true, 'startup continued at its own deadline'); + assert.ifError(startup.error); + const upstream = 'https://auth-timeout.example.test'; + const first = track(resolveHostOutboundProxy(upstream)); + await settle(); + mock.timers.tick(ANSWER_WAIT_MS); + await settle(); + assert.equal(first.settled, true); + assert.equal(first.value, null); + assert.equal(getHostOutboundPathSnapshotFor([upstream]).kind, 'unknown'); + assert.equal(helper.state(), 'starting', 'a slow PAC can still finish within the independent start watchdog'); +}); + +test('startup skips the helper for proxy variables or static macOS settings', async t => { + const { spawnImpl, spawned } = standIn(); + const helper = helperFor(spawnImpl); + t.after(() => helper.close()); + let reads = 0; + const ports = { makeHelper: () => helper, readSettings: async () => { reads++; return ' {\n}\n'; } }; + process.env.HTTPS_PROXY = 'http://127.0.0.1:9'; + try { + for (const platform of ['win32', 'darwin']) await startHostSystemProxySettings({ ...ports, platform }); + } finally { delete process.env.HTTPS_PROXY; } + assert.equal(reads, 0); + await startHostSystemProxySettings({ ...ports, platform: 'darwin' }); + assert.equal(reads, 1); + assert.equal(spawned.length, 0); +}); + +test('every wait is bounded: a helper that never gets ready is stopped and started again after a growing backoff', async () => { + const { spawned, spawnImpl } = standIn(); + const helper = helperFor(spawnImpl); + const first = track(helper.resolveProxy('https://slow.example.test/')); + await settle(); + mock.timers.tick(ANSWER_WAIT_MS - 1); + await settle(); + assert.equal(first.settled, false); + mock.timers.tick(1); + await settle(); + assert.equal(first.settled, true, 'settled at the limit'); + assert.ok(first.error, 'rejected, so the caller falls back'); + + mock.timers.tick(START_TIMEOUT_MS); + await settle(); + assert.equal(spawned[0].stdinEnded, true, 'stopped by its handle'); + assert.equal(helper.state(), 'backoff'); + await assert.rejects(helper.resolveProxy('https://slow.example.test/'), /restarting/); + assert.equal(spawned.length, 1, 'no start during the backoff'); + + mock.timers.tick(FIRST_BACKOFF_MS); + const second = track(helper.resolveProxy('https://slow.example.test/')); + await settle(); + assert.equal(spawned.length, 2, 'started again after the backoff'); + mock.timers.tick(START_TIMEOUT_MS); + await settle(); + assert.equal(second.settled, true); + mock.timers.tick(FIRST_BACKOFF_MS); + await assert.rejects(helper.resolveProxy('https://slow.example.test/'), /restarting/, 'the backoff doubled'); + await helper.close(); +}); + +test('while the helper has no answer: macOS falls back to the static reading, Windows goes direct and is recorded unknown', async () => { + const { spawned, spawnImpl } = standIn({ onSpawn: ready, onRequest: answer('PROXY 10.9.9.9:8080') }); + const helper = helperFor(spawnImpl); + useHostChromiumProxySession(helper); + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy('https://before-crash.example.test/'), 'http://10.9.9.9:8080'); + spawned[0].exit(); + await settle(); + assert.equal(helper.state(), 'backoff'); + + // Within the backoff (no time passes); each upstream below is new to the resolver's cache. + // Windows: no system answer, so direct, and the path says the verdict is unknown rather than direct. + assert.equal(await resolveHostOutboundProxy('https://windows-crash.example.test/'), null); + const { at: _at, ...snapshot } = getHostOutboundPathSnapshotFor(['https://windows-crash.example.test']); + assert.deepEqual(snapshot, { source: 'system', kind: 'unknown', reason: 'resolve_failed', upstream: 'https://windows-crash.example.test' }); + + // macOS with auto-discovery and a manual proxy: the static reading (28b) answers meanwhile. + useHostSystemProxySettings(async () => ' {\n ProxyAutoDiscoveryEnable : 1\n HTTPSEnable : 1\n HTTPSProxy : 10.0.0.2\n HTTPSPort : 3129\n}\n', helper); + assert.equal(await resolveHostOutboundProxy('https://mac-crash.example.test/'), 'http://10.0.0.2:3129'); + await helper.close(); +}); + +test('closed by its handle: stdin first, then SIGTERM, then SIGKILL; nothing starts afterwards', async () => { + const { spawned, spawnImpl } = standIn({ onSpawn: ready, onRequest: answer('DIRECT'), ignoreStdinEnd: true }); + const helper = helperFor(spawnImpl); + await helper.resolveProxy('https://close.example.test/'); + const closing = helper.close(); + assert.equal(spawned[0].stdinEnded, true); + mock.timers.tick(500); + assert.deepEqual(spawned[0].signals, ['SIGTERM']); + mock.timers.tick(1000); + assert.deepEqual(spawned[0].signals, ['SIGTERM', 'SIGKILL']); + spawned[0].exit(); + await closing; + await assert.rejects(helper.resolveProxy('https://close.example.test/'), /stopped/); + assert.equal(spawned.length, 1); +}); + +// Entry: the real helper's close. Rule: Host shutdown finishes even when neither a signal nor +// closing the transport yields an exit event. Gap: the existing close test supplies exit. +// Minimal input: a ready worker that ignores close and both signals. Tier: unit with a mock clock. +test('close finishes at its deadline when the worker emits neither exit nor error', async () => { + const { spawned, spawnImpl } = standIn({ onSpawn: ready, ignoreStdinEnd: true }); + const helper = helperFor(spawnImpl); + await helper.warmUp(); + const closing = track(helper.close()); + mock.timers.tick(STOP_TIMEOUT_MS - 1); + await settle(); + assert.deepEqual(spawned[0].signals, ['SIGTERM', 'SIGKILL']); + assert.equal(closing.settled, false); + mock.timers.tick(1); + await settle(); + assert.equal(closing.settled, true); + assert.ifError(closing.error); + await assert.rejects(helper.resolveProxy('https://closed.example.test/'), /stopped/); + assert.equal(spawned.length, 1); +}); + +test('the helper\'s environment and command line carry nothing of the Host\'s configuration', () => { + const env = helperEnv('/tmp/profile/proxy-helper', { + OPENAI_API_KEY: 'fixture-key', GH_TOKEN: 'fixture-token', HTTPS_PROXY: 'http://user:pass@proxy.test', + PATH: '/bin', XDT_OFFICIAL_SHARED_PROFILE: '/should/not/leak', CINDY_HOST_DATA_DIR: '/leak', cindy_lower: 'leak', + CINDY_PROXY_WORKER_TEST_CONFIG: '{"mode":"direct"}', NODE_OPTIONS: '--inspect', ELECTRON_RUN_AS_NODE: '1', + }); + assert.deepEqual(env, { PATH: '/bin', CINDY_PROXY_WORKER_PROFILE: '/tmp/profile/proxy-helper' }); + assert.equal(helperUrl('wss://a:b@relay.example.test:8443/socket?key=k'), 'wss://relay.example.test:8443/socket'); +}); diff --git a/apps/host/src/chromium-proxy.ts b/apps/host/src/chromium-proxy.ts new file mode 100644 index 00000000000..36147142434 --- /dev/null +++ b/apps/host/src/chromium-proxy.ts @@ -0,0 +1,357 @@ +/** + * The Host side of the Chromium proxy helper (release table row 28, 28c). The helper + * (chromium-proxy-worker.cjs, run by the Electron the Host release carries on macOS and Windows) asks + * Chromium which proxy a URL takes, PAC and auto-discovery included, as the desktop's session.resolveProxy + * does. This module starts it on demand, waits for it with limits, restarts it with backoff and stops it by its + * handle. outbound-proxy.ts decides when it is asked: never while proxy environment variables are set (the + * resolver core answers from them first); on macOS only when the system settings use PAC or auto-discovery; + * on Windows at startup, before the first upstream request. + * + * Every wait has a limit: a resolution that the helper cannot answer within ANSWER_WAIT_MS (starting, + * restarting, slow or gone) rejects, and the caller falls back (macOS: the static settings, 28b; Windows: + * direct, reported unknown by the resolver core). The limit stays under the core's own 2 s timeout so that the + * caller's fallback, not the core's, applies. A helper that does not become ready within START_TIMEOUT_MS, or + * stops answering a ping, is stopped and started again later, after a backoff that doubles up to + * MAX_BACKOFF_MS and resets once it is ready. + * + * The helper is told only the URL, without user info, query or fragment, and answers only a PAC result string. + * The helper process, its transport and its start timer are unreferenced, so an idle helper never keeps a short Host + * command alive; a resolution in progress keeps it alive through its own bounded timer. When the Host exits, + * the transport closes and the helper quits. + */ +import { spawn as nodeSpawn, type ChildProcess, type StdioOptions } from 'node:child_process'; +import { mkdirSync } from 'node:fs'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +import { createMakerLogger } from '../../desktop/src/main/maker-host/logger-adapter.ts'; +import { hostRuntimeLayout, resolveSourceElectronBinary } from './runtime-layout.mjs'; + +const log = createMakerLogger('outbound-proxy'); + +/** Total wait of one resolution, from the call to the answer (below the resolver core's 2 s). */ +export const ANSWER_WAIT_MS = 1800; +/** A helper not ready by then is stopped and started again after the backoff. */ +export const START_TIMEOUT_MS = 15_000; +/** Startup alone allows a cold PAC longer than the individual request deadline. */ +export const WARMUP_WAIT_MS = 8_000; +/** A helper that does not answer a ping within this, after a resolution timed out, is stopped. */ +export const PING_TIMEOUT_MS = 3000; +export const STOP_TIMEOUT_MS = 3000; +export const FIRST_BACKOFF_MS = 1000; +export const MAX_BACKOFF_MS = 60_000; +const MAX_LINE = 8192; + +export type ChromiumProxyHelperState = 'not-started' | 'starting' | 'ready' | 'backoff' | 'unavailable' | 'stopped'; + +export class ChromiumProxyUnavailableError extends Error { + constructor(reason: string) { + super(`the Chromium proxy helper is unavailable (${reason})`); + this.name = 'ChromiumProxyUnavailableError'; + } +} + +export interface ChromiumProxyHelper { + warmUp(): Promise; + /** Chromium's PAC result string for the URL; rejects with ChromiumProxyUnavailableError when it has none in time. */ + resolveProxy(url: string): Promise; + state(): ChromiumProxyHelperState; + /** Stops the helper by its handle (transport closed, then SIGTERM, then SIGKILL); nothing starts afterwards. */ + close(): Promise; +} + +export interface ChromiumProxyHelperOptions { + /** The Host data directory; the helper's userData is its own subdirectory. */ + profileDir: string; + /** Electron and the helper script; by default the release's, or the repository's when run from source. */ + assets?: () => { binary: string; script: string } | null; + spawnImpl?: typeof nodeSpawn; + now?: () => number; + platform?: NodeJS.Platform; +} + +/** Only scheme, host, port and path go to the helper: never user info, a query or a fragment. */ +export function helperUrl(url: string): string { + const parsed = new URL(url); + parsed.username = ''; + parsed.password = ''; + parsed.search = ''; + parsed.hash = ''; + return parsed.href; +} + +/** Only platform paths and locale reach Chromium. Host environments can carry arbitrary provider credentials. */ +const SYSTEM_ENV = new Set([ + 'HOME', 'PATH', 'TMP', 'TEMP', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', + 'SYSTEMROOT', 'WINDIR', 'USERPROFILE', 'LOCALAPPDATA', 'APPDATA', 'PROGRAMDATA', + 'SYSTEMDRIVE', 'HOMEDRIVE', 'HOMEPATH', +]); +export function helperEnv(profile: string, base: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(base)) { + if (SYSTEM_ENV.has(key.toUpperCase())) env[key] = value; + } + env.CINDY_PROXY_WORKER_PROFILE = profile; + return env; +} + +function defaultAssets(): { binary: string; script: string } | null { + const layout = hostRuntimeLayout(); + if (layout.packaged) { + return layout.electronBinary && layout.proxyWorker ? { binary: layout.electronBinary, script: layout.proxyWorker } : null; + } + const binary = resolveSourceElectronBinary(); + return binary ? { binary, script: fileURLToPath(new URL('./chromium-proxy-worker.cjs', import.meta.url)) } : null; +} + +export function chromiumProxyWorkerStdio(platform: NodeJS.Platform, stderr: 'ignore' | 'pipe' = 'ignore'): StdioOptions { + // Electron's Windows main process exposes an already-ended stdin even when fd 0 is a pipe. + return platform === 'win32' ? ['ignore', 'ignore', stderr, 'ipc'] : ['pipe', 'pipe', stderr]; +} + +type WriteResult = (error: Error | null | undefined) => void; +type ReadLine = (line: string) => void; +type StreamError = (error: Error) => void; + +/** Both transports carry the same JSON text, with a newline only as stream framing. */ +export function createChromiumProxyWorkerTransport(child: ChildProcess, platform: NodeJS.Platform) { + if (platform === 'win32') { + return { + canWrite: () => child.connected, + write: (line: string, done: WriteResult) => { child.send(line, done); }, + listen(onLine: ReadLine, _onStreamError?: StreamError, onDisconnect?: () => void) { + child.on('message', (line) => { if (typeof line === 'string') onLine(line); }); + if (onDisconnect) child.once('disconnect', onDisconnect); + }, + unref: () => child.channel?.unref(), + close: () => { if (child.connected) child.disconnect(); }, + }; + } + return { + canWrite: () => Boolean(child.stdin?.writable && !child.stdin.destroyed), + write: (line: string, done: WriteResult) => { child.stdin?.write(`${line}\n`, done); }, + listen(onLine: ReadLine, onStreamError?: StreamError) { + child.stdin?.on('error', onStreamError ?? (() => {})); + const lines = createInterface({ input: child.stdout! }); + lines.on('line', onLine); + if (onStreamError) lines.on('error', onStreamError); + }, + unref() { + (child.stdin as unknown as { unref?: () => void } | null)?.unref?.(); + (child.stdout as unknown as { unref?: () => void } | null)?.unref?.(); + }, + close: () => { child.stdin?.end(); }, + }; +} + +interface Pending { resolve: (value: string) => void; reject: (error: Error) => void } + +interface Worker { + child: ChildProcess; + transport: ReturnType; + ready: Promise; + isReady: () => boolean; + request: (message: Record, timeoutMs: number) => Promise; + exited: Promise; +} + +export function createChromiumProxyHelper(options: ChromiumProxyHelperOptions): ChromiumProxyHelper { + const spawnImpl = options.spawnImpl ?? nodeSpawn; + const now = options.now ?? Date.now; + const assets = options.assets ?? defaultAssets; + const platform = options.platform ?? process.platform; + let worker: Worker | null = null; + let state: ChromiumProxyHelperState = 'not-started'; + let retryAt = 0; + let backoff = FIRST_BACKOFF_MS; + let closed = false; + let warned = false; + + function warnOnce(reason: string): void { + if (warned) return; + warned = true; + log.warn('Chromium proxy helper unavailable — using the fallback for system proxy settings', { reason }); + } + + function stopWorker(target: Worker): Promise { + if (worker === target) worker = null; + target.transport.close(); + const terminate = setTimeout(() => target.child.kill('SIGTERM'), 500); + const kill = setTimeout(() => target.child.kill('SIGKILL'), 1500); + terminate.unref?.(); + kill.unref?.(); + let deadline: NodeJS.Timeout | undefined; + const stopped = Promise.race([target.exited, new Promise(resolve => { + deadline = setTimeout(() => { + log.warn('Chromium proxy helper did not exit before the shutdown deadline'); + target.child.unref?.(); + resolve(); + }, STOP_TIMEOUT_MS); + deadline.unref?.(); + })]); + return stopped.finally(() => { clearTimeout(terminate); clearTimeout(kill); clearTimeout(deadline); }); + } + + function deferRestart(reason: string, nextState: 'backoff' | 'unavailable' = 'backoff'): void { + state = nextState; + retryAt = now() + backoff; + backoff = Math.min(backoff * 2, MAX_BACKOFF_MS); + warnOnce(reason); + } + + /** Stop this worker and allow the next start only after the backoff. */ + function fail(target: Worker, reason: string): void { + if (worker !== target) return; + void stopWorker(target); + if (!closed) deferRestart(reason); + } + + function start(): Worker | null { + const found = assets(); + if (!found) { + deferRestart('no Electron runtime', 'unavailable'); + return null; + } + const profile = path.join(options.profileDir, 'proxy-helper'); + let child: ChildProcess; + try { + mkdirSync(profile, { recursive: true, mode: 0o700 }); + child = spawnImpl(found.binary, [found.script], { + env: helperEnv(profile), stdio: chromiumProxyWorkerStdio(platform), windowsHide: true, + }); + } catch { + deferRestart('start failed'); + return null; + } + child.unref?.(); + const transport = createChromiumProxyWorkerTransport(child, platform); + transport.unref(); + let ready = false; + let sequence = 0; + const pending = new Map(); + let resolveReady!: () => void; + let rejectReady!: (error: Error) => void; + const readyPromise = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; }); + readyPromise.catch(() => {}); + const exited = new Promise(resolve => { child.once('exit', () => resolve()); child.once('error', () => resolve()); }); + const self: Worker = { + child, + transport, + ready: readyPromise, + isReady: () => ready, + exited, + request(message, timeoutMs) { + const id = ++sequence; + return new Promise((resolve, reject) => { + // Referenced: a short command (cindy-host login) waiting for this answer must not exit meanwhile. + const timer = setTimeout(() => { pending.delete(id); reject(new ChromiumProxyUnavailableError('no answer in time')); }, timeoutMs); + pending.set(id, { + resolve: (value) => { clearTimeout(timer); resolve(value); }, + reject: (error) => { clearTimeout(timer); reject(error); }, + }); + transport.write(JSON.stringify({ id, ...message }), (error) => { + if (error) { + pending.get(id)?.reject(new ChromiumProxyUnavailableError('write failed')); + pending.delete(id); + } + }); + }); + }, + }; + const gone = () => { + const error = new ChromiumProxyUnavailableError('the helper exited'); + rejectReady(error); + for (const entry of pending.values()) entry.reject(error); + pending.clear(); + fail(self, 'the helper exited'); + }; + child.once('exit', gone); + child.once('error', gone); + transport.listen((line) => { + if (line.length > MAX_LINE) return; + let value: { ready?: unknown; pid?: unknown; id?: unknown; result?: unknown; error?: unknown }; + try { value = JSON.parse(line); } catch { return; } + if (worker !== self || !value || typeof value !== 'object') return; + if (value.ready === true && value.pid === child.pid) { + ready = true; + state = 'ready'; + backoff = FIRST_BACKOFF_MS; + warned = false; + resolveReady(); + return; + } + const entry = typeof value.id === 'number' ? pending.get(value.id) : undefined; + if (!entry) return; + pending.delete(value.id as number); + if (typeof value.result === 'string') entry.resolve(value.result); + else entry.reject(new ChromiumProxyUnavailableError(typeof value.error === 'string' ? value.error : 'no result')); + }, undefined, gone); + const startTimer = setTimeout(() => { if (!ready) fail(self, 'not ready in time'); }, START_TIMEOUT_MS); + startTimer.unref?.(); + void readyPromise.then(() => clearTimeout(startTimer), () => clearTimeout(startTimer)); + state = 'starting'; + return self; + } + + /** After a resolution timed out: a helper that does not answer a ping is stopped. */ + function checkAlive(target: Worker): void { + target.request({ method: 'ping' }, PING_TIMEOUT_MS).catch(() => fail(target, 'no answer to a ping')); + } + + return { + async warmUp() { + if (closed || state !== 'not-started') return; + const target = worker = start(); + if (!target) return; + let timer: NodeJS.Timeout | undefined; + try { + await Promise.race([target.ready, new Promise(resolve => { + timer = setTimeout(() => { + warnOnce('not ready during startup'); + resolve(); + }, WARMUP_WAIT_MS); + })]); + } catch { + // The exit handler already entered backoff. Startup uses the existing fallback. + } finally { + clearTimeout(timer); + } + }, + async resolveProxy(url) { + const deadline = now() + ANSWER_WAIT_MS; + if (closed) throw new ChromiumProxyUnavailableError('stopped'); + if (!worker) { + if (state === 'unavailable' && now() < retryAt) throw new ChromiumProxyUnavailableError('no Electron runtime'); + if (state === 'backoff' && now() < retryAt) throw new ChromiumProxyUnavailableError('restarting'); + worker = start(); + if (!worker) throw new ChromiumProxyUnavailableError((state as ChromiumProxyHelperState) === 'unavailable' ? 'no Electron runtime' : 'start failed'); + } + const target = worker; + if (!target.isReady()) { + // Never an answer before the helper is ready: wait for it, within the limit. + let timer: NodeJS.Timeout | undefined; + try { + await Promise.race([target.ready, new Promise((_, reject) => { + timer = setTimeout(() => reject(new ChromiumProxyUnavailableError('not ready yet')), Math.max(0, deadline - now())); + })]); + } finally { clearTimeout(timer); } + } + try { + return await target.request({ method: 'resolve', url: helperUrl(url) }, Math.max(1, deadline - now())); + } catch (error) { + if (error instanceof ChromiumProxyUnavailableError && error.message.includes('no answer in time')) checkAlive(target); + throw error; + } + }, + state: () => state, + async close() { + closed = true; + state = 'stopped'; + if (worker) { + worker.child.ref?.(); + await stopWorker(worker); + } + }, + }; +} diff --git a/apps/host/src/control.mjs b/apps/host/src/control.mjs index defa794388f..1bef36eb911 100644 --- a/apps/host/src/control.mjs +++ b/apps/host/src/control.mjs @@ -57,6 +57,11 @@ export async function readHostProcessStatus(profile) { if (endpoint.instanceId && health.instanceId !== endpoint.instanceId) throw new Error('Host endpoint belongs to another instance'); if (health.clientProtocol === 1 && health.pid !== endpoint.pid) throw new Error('Host process identity changed'); return { running: true, pid: endpoint.pid, baseUrl: endpoint.baseUrl, runtime: health.runtime, instanceId: health.instanceId, + // The running Host's edition (a release's build region), so a client can refuse the other edition. + ...(typeof health.region === 'string' ? { region: health.region } : {}), + // How the running Host finds its outbound proxy (row 28; never an address or a setting). + ...(health.outboundProxy && typeof health.outboundProxy === 'object' ? { outboundProxy: health.outboundProxy } : {}), + ...(health.legacyPluginApprovals === undefined ? {} : { legacyPluginApprovals: health.legacyPluginApprovals }), ...(health.clientProtocol === undefined ? {} : { clientProtocol: health.clientProtocol }) }; } catch (error) { // An unresponsive service is not proof that its process has exited. diff --git a/apps/host/src/credentials/native-codec.mjs b/apps/host/src/credentials/native-codec.mjs index 437a44937b6..5b9d52898c9 100644 --- a/apps/host/src/credentials/native-codec.mjs +++ b/apps/host/src/credentials/native-codec.mjs @@ -1,10 +1,13 @@ import path from 'node:path'; import { spawnSync } from 'node:child_process'; -import { createRequire } from 'node:module'; -import { hostRuntimeLayout } from '../runtime-layout.mjs'; +import { hostRuntimeLayout, resolveSourceElectronBinary } from '../runtime-layout.mjs'; import { KEYCHAIN_IDENTITY_MARKER_FILE, resolveDevKeychainDecision } from '../../../desktop/src/main/devKeychainName.js'; import { createKeychainMarkerIo } from '../../../desktop/src/main/devKeychainMarkerIo.js'; +function unavailable() { + return Object.assign(new Error('CREDENTIAL_STORE_UNAVAILABLE'), { code: 'CREDENTIAL_STORE_UNAVAILABLE' }); +} + /** Preserve Electron's existing Keychain/DPAPI format instead of inventing a * second vault or exporting its master key into Node. Secrets use stdio only. * Linux keeps its display-independent Secret Service adapter. @@ -25,20 +28,21 @@ export function createNativeCredentialCodec(options) { const appName = identity.kind === 'rename' ? identity.appName : 'Cindy'; const run = options.run ?? spawnSync; const layout = hostRuntimeLayout(); - const binary = options.electronBinary ?? layout.electronBinary - ?? createRequire(new URL('../../../desktop/package.json', import.meta.url))('electron'); const script = layout.credentialScript; function invoke(operation, value) { + const binary = options.electronBinary + ?? (layout.packaged ? layout.electronBinary : resolveSourceElectronBinary()); + if (!binary) throw unavailable(); const env = { ...process.env, CINDY_HOST_DATA_DIR: options.userDataDir, CINDY_HOST_CREDENTIAL_APP: appName }; delete env.ELECTRON_RUN_AS_NODE; delete env.NODE_OPTIONS; const result = run(binary, [script], { input: JSON.stringify({ operation, value }), encoding: 'utf8', env, windowsHide: true, timeout: 30_000, maxBuffer: 1024 * 1024 }); - if (result.error || result.status !== 0) throw new Error('CREDENTIAL_STORE_UNAVAILABLE'); + if (result.error || result.status !== 0) throw unavailable(); try { const response = JSON.parse(result.stdout); if (typeof response.value !== 'string') throw new Error(); return response.value; - } catch { throw new Error('CREDENTIAL_STORE_UNAVAILABLE'); } + } catch { throw unavailable(); } } return { encrypt: value => invoke('encrypt', value), decrypt: value => invoke('decrypt', value) }; } diff --git a/apps/host/src/credentials/store.test.mjs b/apps/host/src/credentials/store.test.mjs index ece26c6b550..ab00d86e206 100644 --- a/apps/host/src/credentials/store.test.mjs +++ b/apps/host/src/credentials/store.test.mjs @@ -4,6 +4,8 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import test from 'node:test'; +import { pathToFileURL } from 'node:url'; +import { createSourceElectronTree } from '../test-support/source-electron-tree.mjs'; import { createCredentialStore, createPreparedLinuxCredentialStore, SafeStorageUnavailableError } from './store.mjs'; import { decryptOsCryptPayload, deriveLinuxOsCryptKey, encryptOsCryptPayload } from './oscrypt.mjs'; @@ -140,3 +142,37 @@ test('native codec rejects an incomplete identity and does not replace a record assert.equal(fs.readFileSync(path.join(storageDir, 'synthetic.enc'), 'utf8'), 'existing ciphertext'); assert.deepEqual(fs.readdirSync(storageDir), ['synthetic.enc']); }); + +// Source Host integration: the previous injected binary always existed. An +// empty profile must not even read path.txt; real credential reads and writes +// must fail closed until an executable is installed in that dependency tree. +test('native credentials resolve Electron only for encryption or decryption and report a missing binary', async t => { + const tree = createSourceElectronTree(tempProfile(t)); + const { createCredentialStore } = await import(pathToFileURL(path.join(tree.host, 'src/credentials/store.mjs'))); + const userDataDir = tempProfile(t); + // Node resolves the package directory through symlinks in the temporary path. + const electron = fs.realpathSync(tree.electron); + const marker = path.join(electron, 'path.txt'); + const binary = path.join(electron, 'dist', 'nested', 'electron'); + fs.writeFileSync(marker, 'nested/electron\n'); + const read = t.mock.method(fs, 'readFileSync'); + const store = await createCredentialStore({ platform: 'darwin', userDataDir, run(executable) { + assert.equal(executable, binary); + return { status: 0, stdout: '{"value":"synthetic-ciphertext"}' }; + } }); + assert.equal(store.read('absent'), null); + assert.ok(!read.mock.calls.some(call => call.arguments[0] === marker)); + read.mock.restore(); + const dir = path.join(userDataDir, 'safe-storage'); + fs.mkdirSync(dir); + fs.writeFileSync(path.join(dir, 'existing.enc'), 'synthetic-record'); + const unavailable = { code: 'CREDENTIAL_STORE_UNAVAILABLE', message: 'CREDENTIAL_STORE_UNAVAILABLE' }; + assert.throws(() => store.read('existing'), unavailable); + assert.throws(() => store.write('existing', 'synthetic-replacement'), unavailable); + assert.equal(fs.readFileSync(path.join(dir, 'existing.enc'), 'utf8'), 'synthetic-record'); + fs.mkdirSync(path.dirname(binary), { recursive: true }); + fs.writeFileSync(binary, ''); + store.write('existing', 'synthetic-replacement'); + assert.equal(fs.readFileSync(path.join(dir, 'existing.enc'), 'utf8'), 'synthetic-ciphertext'); + assert.equal(fs.existsSync(path.join(electron, 'entry-ran')), false); +}); diff --git a/apps/host/src/desktop-module-setters.ts b/apps/host/src/desktop-module-setters.ts new file mode 100644 index 00000000000..d77fbee09e5 --- /dev/null +++ b/apps/host/src/desktop-module-setters.ts @@ -0,0 +1,164 @@ +/** + * Module-level port setters in the desktop and shared modules the Host loads, and what the Host does + * about each. + * + * A shared module can keep a port in a module variable that the desktop fills once at startup + * (setX(impl)). Unlike a factory port, nothing fails when the Host does not call the setter: the + * module quietly falls back (null, a no-op, an empty table, a refusal). The desktop guard + * (hostDesktopSourceContracts.guard.test.ts, "module-level port setters the Host loads") collects + * these setters from the Host's import graph and compares them with this table both ways: a new + * setter missing here, or an entry whose setter is gone, fails it. + * Not covered here: the ports the Host hands the shared device-link dispatch. HOST_DISPATCH_PORTS_WHILE_HELD + * (apps/host/src/device-link.ts) lists each of them with what it does while the profile gate is held, + * pinned as `Record`; this table only answers whether a module-level setter + * the Host loads is bound. The two do not overlap. + * A not-applicable entry whose reason is a task kind the Host refuses at admission (Orca, remote + * hosting, teammates) is revisited when that kind opens; the release table rows of those kinds say so. + * + * Key: `#`, sorted, one entry per line. Status: + * - bound: the Host binds it; `where` is the Host file that does, or `#` (the guard checks + * that file or function calls it, mutates the container, or hands it over as a port value). + * - pending: the Host has to bind it, now or in a later stage (M2, M3); `reason` names the release table + * row or 甲/乙 gap it goes with, never an id still to be given. + * - not-applicable: by design the Host never needs it (window only, Electron only, or a task kind the + * Host refuses at admission); `reason` cites the code or release table row. + * - internal: called by shared code itself when that code runs, or not a port in practice. + * Release table (docs/host/personal-migration-release-table.md) references are stable ids only: `row N` + * (section 一), `甲 N` / `乙 N` (section 五 gaps), or a section and item name as written there. Never file lines; they drift. + */ +export type DesktopModuleSetterStatus = 'bound' | 'pending' | 'not-applicable' | 'internal'; +export interface DesktopModuleSetterEntry { status: DesktopModuleSetterStatus; where?: string; reason?: string } + +export const DESKTOP_MODULE_SETTERS: Readonly> = { + 'apps/desktop/src/main/appSessionState.ts#setAppSessionCommitBoundaryHook': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/authBoundaryQuarantine.ts#configureProjectionBoundaryOwnerCommit': { status: 'bound', where: 'apps/host/src/agent/skill-projection-owner.ts#refuseSkillProjectionOwnerCommit', reason: 'Release table row 25 (25b): serve refuses the owner commit (main.ts calls refuseSkillProjectionOwnerCommit); cindy-host login allows it (login-cli.mjs calls allowSkillProjectionOwnerCommit, the same file)' }, + 'apps/desktop/src/main/authBoundaryQuarantine.ts#configureProjectionBoundaryPassive': { status: 'not-applicable', reason: 'Only a desktop development instance on a shared profile is passive (index.ts, unpackaged and XDT_PASSIVE_SHARED_USER_DATA=1); the Host keeps the default false (authBoundaryQuarantine.ts) and reads the boundary under release table row 25 (25a)' }, + 'apps/desktop/src/main/cindy-brain/forgePackStaging.ts#bindForgePackStagingTempDir': { status: 'pending', reason: 'Plugin batch (release table row 33), classified with the plugin turn hooks' }, + 'apps/desktop/src/main/cindy-brain/ghostGrantConfirmBridge.ts#initGhostGrantConfirmBridge': { status: 'pending', reason: 'Plugin batch (release table row 33); the Host builds its own GhostGrantConfirmBridge (main.ts)' }, + 'apps/desktop/src/main/cindy-brain/ghostModelPicker.ts#setPluginModelPickerAgentProvider': { status: 'not-applicable', reason: 'The headless runtime binds its own Maker.listAvailableAgents reader to modelRouteSources in main.ts. The desktop module variable supplies the window picker.' }, + 'apps/desktop/src/main/cindy-brain/ghostModelPicker.ts#setPluginRouteAgentStatusProvider': { status: 'not-applicable', reason: 'The Host has no plugin model picker window. Its runtime hooks call isGhostCardModelRouteAvailable, which reads modelRouteSources and never queries the picker binary-status callback.' }, + 'apps/desktop/src/main/cindy-brain/ghostSetupCoordinator.ts#initGhostSetupCoordinator': { status: 'pending', reason: 'Plugin batch (release table row 33)' }, + 'apps/desktop/src/main/cindy-brain/ghostSetupInteractionBridge.ts#initGhostSetupInteractionBridge': { status: 'pending', reason: 'Plugin batch (release table row 33)' }, + 'apps/desktop/src/main/cindy-brain/ghostSnapshotCapability.ts#configureGhostSnapshotProcess': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/cindy-media/generatedImageRecovery.ts#setGeneratedImageRecovery': { status: 'bound', where: 'apps/host/src/agent/generated-images.ts#createHostGeneratedImages', reason: '甲 11: the shared generated-image delivery recovers and releases the images of a task on history reads and deletion, and reconciles cleanup receipts once the owner database is ready (main.ts)' }, + 'apps/desktop/src/main/device-link/controllerPlatform.ts#setControllerPlatform': { status: 'bound', where: 'apps/host/src/device-link.ts' }, + 'apps/desktop/src/main/device-link/historyViewPush.ts#setHistoryWorkPageReader': { status: 'pending', reason: 'M2 push channel (release table section 六, row HISTORY_WORK_PATCH_CHANNEL): unbound, controllers get { kind: refresh } and reload the page (historyViewPush.ts buildHistoryWorkPatch)' }, + 'apps/desktop/src/main/device-link/remoteBotSessionBoundary.ts#setRemoteBotSessionLookup': { status: 'bound', where: 'apps/host/src/device-link.ts' }, + 'apps/desktop/src/main/device-link/sharedTaskDispatch.ts#setSharedTaskDispatchHost': { status: 'pending', reason: 'Shared tasks are M3 (release table row 22: sharedTask M3); unbound, share peers get no session (sharedTaskDispatch.ts)' }, + 'apps/desktop/src/main/device-link/sharedTaskDispatch.ts#setSharedTaskInteractionReader': { status: 'pending', reason: 'Shared tasks are M3 (release table row 22: sharedTask M3)' }, + 'apps/desktop/src/main/device-link/sharedTaskDispatch.ts#setSharedTaskQueueReader': { status: 'pending', reason: 'Shared tasks are M3 (release table row 22: sharedTask M3)' }, + 'apps/desktop/src/main/device-link/subscriptions.ts#setTopicsReleasedListener': { status: 'pending', reason: '乙 6 (device-link controller entries on the Host): bound by the remote file browser (file-browser/device-op.ts), which the Host does not load; its file peer answers FILE_PEER_UNAVAILABLE (device-link.test.mjs)' }, + 'apps/desktop/src/main/device-link/subscriptions.ts#setTopicsSubscribedListener': { status: 'pending', reason: '乙 6 (device-link controller entries on the Host): bound by the remote file browser (file-browser/device-op.ts), which the Host does not load' }, + 'apps/desktop/src/main/downloader/transport.ts#configureDefaultDownloadRequest': { status: 'not-applicable', reason: 'The only Host downloader is the plugin download slot, which passes its own request each time (cindy-brain/downloadSlot.ts)' }, + 'apps/desktop/src/main/embedders/chat-history-embedder.ts#setChatEmbeddingEnabled': { status: 'pending', reason: 'Chat history embedding goes with the embedding host (plugin batch, release table row 33, with registerEmbeddingHostLazyStart); unbound the embedder stays off and chat history search falls back to full-text by design (localDb/chatHistorySearch.ts)' }, + 'apps/desktop/src/main/embedding-host/index.ts#registerEmbeddingHostLazyStart': { status: 'pending', reason: 'Plugin vectors go with the plugin batch (release table row 33); without an embedding host, chat history search falls back to full-text by design (localDb/chatHistorySearch.ts)' }, + 'apps/desktop/src/main/embedding-host/providers.ts#registerProvider': { status: 'internal', reason: 'Called by the embedding service itself (embedders/chat-history-embedder.ts, EmbeddingService.ts)' }, + 'apps/desktop/src/main/embedding-host/providers.ts#setProviderSuspended': { status: 'internal', reason: 'Called by the embedding worker itself (embedding-host/EmbeddingWorker.ts)' }, + 'apps/desktop/src/main/git-context/ghBinary.ts#configureManagedGhRoot': { status: 'not-applicable', reason: 'Desktop installs and publishes a managed GitHub CLI. Host project lookups fall back to the system GitHub CLI.' }, + 'apps/desktop/src/main/git-context/githubReadRuntime.ts#setGithubReadRuntime': { status: 'pending', reason: 'With the cindy_helper github port (M1, release table row 22); unbound it throws HOST_NOT_READY (githubReadRuntime.ts)' }, + 'apps/desktop/src/main/git-context/prRefsStore.ts#setPrRefsChangedListener': { status: 'pending', reason: '乙 13 (task PR association window channels and push, with the M2 push batch; release table section 六, row git-context:pr-refs-changed; section 二, item 任务的 PR 关联): the desktop pushes git-context:pr-refs-changed to its windows (git-context/ipc.ts); no Host window reads PR associations (the web client returns none, client mode does not forward git-context:pr-refs:*), so unbound the Host PR writes (localDb/messagePrRefs.ts from message-store.ts and agent/event-persistence.ts, the clear recovery, mcp-apps/service.ts) leave nothing a window shows stale' }, + 'apps/desktop/src/main/input-handoff/askpass/index.ts#initInputHandoffAskpass': { status: 'pending', reason: 'Input handoff is M2 (release table row 22: inputHandoff M2; section 二, item 代输入(sudo、ssh、git 密码提示))' }, + 'apps/desktop/src/main/localDb/client/current.ts#setCurrentDbClient': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/localDb/mapper.ts#setSessionRuntimeProjector': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/localDb/migrationRuntime.ts#configureMigrationRuntime': { status: 'internal', reason: 'Called by localDb/startupCore.ts when the owner database opens' }, + 'apps/desktop/src/main/localDb/provisionalSessions.ts#configureProvisionalSessions': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/localDb/sessionActiveTurn.ts#setOnSessionTurnEndedPersisted': { status: 'pending', reason: 'M2 push channel (release table section 六, row local-db:sessions:patched lastTurnEndedAt): the Host writes turn markers but does not push the patch (sessionActiveTurn.ts notifyTurnEndedPersisted)' }, + 'apps/desktop/src/main/localDb/sessionArchiveSync.ts#setSessionArchiveSyncRequester': { status: 'pending', reason: '乙 11 (release table section 二, items 恢复已归档任务 and 手动归档): native Codex archive sync is not on the Host; unbound, requestSessionArchiveSync from the shared cleanup is a no-op (sessionArchiveSync.ts)' }, + 'apps/desktop/src/main/localDb/sessionOpening.ts#setSessionOpeningModelAdmission': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/localDb/sessionRestoreRetention.ts#setSessionRestoreObserver': { status: 'bound', where: 'apps/host/src/agent/task-restore.ts#bindTaskRestoreRetention', reason: '甲 22: the desktop task management observer (task-management/restoreObserver.ts), installed by main.ts' }, + 'apps/desktop/src/main/localDb/sessionRouteLock.ts#setSessionRouteLockImplementation': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/localDb/sessionRuntimeCleanup.ts#setSessionRuntimeCleanup': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/localDb/sqliteVecLoader.ts#configureSqliteVecExtPath': { status: 'internal', reason: 'Called by localDb/startupCore.ts when the owner database opens' }, + 'apps/desktop/src/main/logger.ts#initLogger': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/logger.ts#setLogLevel': { status: 'not-applicable', reason: 'Only the desktop debug network switch changes it at run time (bootstrap-electron.ts, the cc:set-debug-net window channel); the Host takes its level once from the log configuration when initLogger runs (logger.ts readLevelFromConfigFile)' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setActiveCatalog': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setActiveCatalogChangedListener': { status: 'not-applicable', reason: 'By design the Host refreshes engine model lists itself, after listProviders and before each start (release table section 二, item 引擎模型清单刷新)' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setAnthropicDiscoveredModels': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): Anthropic model discovery' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setCodexApiModelCapabilities': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): Codex API model capabilities' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setCustomProviderConfigs': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setCustomProviders': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setDiscoveredCodexModels': { status: 'internal', reason: 'Called by maker-host/codexLocalModelSink.ts, which the Host Codex runtime uses' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setDiscoveredProviderMediaModels': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): provider media model discovery' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setDiscoveredProviderModels': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): subscription pool discovery (section 二, item 订阅池按账号发现的 Codex 模型清单)' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setLocalCatalogOverrides': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setManagedProviders': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): managed provider views' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setOpenAiImagesApiKeyConfigured': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): set by the desktop OpenAI media discovery (model-discovery/openai-media.ts); unbound it stays false, so the OpenAI subscription provider keeps the hosted gpt-image-2 entry even when an Images API key is configured (active-catalog.ts)' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setSubscriptionPoolProviders': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setXaiDiscoveredModels': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): xAI model discovery' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#setXdGatewayModels': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/maker-host/attachmentPreservation.ts#bindHostedAttachmentPreservation': { status: 'not-applicable', reason: 'Remote agent hosting: only the desktop hosted run binds it (remote-agent/host/runHost.ts), which the Host does not load; inbound remote agent runs get REMOTE_AGENT_UNAVAILABLE (device-link/dispatch.ts, no handler). Unbound, the Host attachment recovery (oversizedAttachmentRecoveryCore.ts) takes the local task path, as a local desktop task does; revisit when remote execution opens (release table section 七, item 18)' }, + 'apps/desktop/src/main/maker-host/claude-auto-permission-fallback.ts#setClaudeAutoClassifierUnavailableListener': { status: 'bound', where: 'apps/host/src/agent/runtime.ts' }, + 'apps/desktop/src/main/maker-host/claude-native-cli-status.ts#setClaudeCliLoginStatusListenerErrorHandler': { status: 'internal', reason: 'Called by maker-host/claude-native-cli.ts, which the Host provider config uses' }, + 'apps/desktop/src/main/maker-host/claude-rate-limit-headers-observer.ts#setClaudeRateLimitHeadersListener': { status: 'internal', reason: 'No production caller (only its own module and tests)' }, + 'apps/desktop/src/main/maker-host/claude-session-background-activity.ts#setClaudeBackgroundActivityBroadcaster': { status: 'pending', reason: 'M2 push channel (release table section 六, row maker:session-background-activity); the Host keeps the state (idle-release.ts)' }, + 'apps/desktop/src/main/maker-host/claude-session-background-activity.ts#setClaudeBackgroundCommandWorkBroadcaster': { status: 'pending', reason: 'M2 push channel (release table section 六, row maker:session-background-activity)' }, + 'apps/desktop/src/main/maker-host/claude-transcript-relocation.ts#setLiveCcSessionBridge': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/maker-host/codex-api-model-capabilities.ts#setCodexApiModelProbe': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): backfills Codex API model capabilities after a custom provider catalog refresh (createDesktopProviderService.ts)' }, + 'apps/desktop/src/main/maker-host/codex-custom-provider-route.ts#registerCodexScopedCustomProviderRoutes': { status: 'internal', reason: 'Called by maker-host/codexSpawnConfigCore.ts when a Codex process starts' }, + 'apps/desktop/src/main/maker-host/codex-custom-provider-route.ts#setCodexAppliedCustomProviderRoutes': { status: 'bound', where: 'apps/host/src/agent/codex-runtime.ts' }, + 'apps/desktop/src/main/maker-host/codex-text-only-policy.ts#registerCodexTextOnlyPolicy': { status: 'bound', where: 'apps/host/src/agent/codex-runtime.ts' }, + 'apps/desktop/src/main/maker-host/guest-provider-route-store.ts#registerGuestProviderRoute': { status: 'pending', reason: 'Provider sharing is M3 (release table 乙 6); share guests get ACCESS_REVOKED on the Host (device-link.test.mjs)' }, + 'apps/desktop/src/main/maker-host/guest-provider-route-store.ts#setGuestProviderModelCatalogReader': { status: 'bound', where: 'apps/host/src/agent/model-context.ts', reason: 'The Host reader applies the account filter, the desktop one does not (release table section 二, item 托管推理的模型目录(账号过滤))' }, + 'apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts#setGhostToolApprovalResolver': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/maker-host/model-usage-pricing.ts#registerUsagePricing': { status: 'bound', where: 'apps/host/src/agent/start-options.ts' }, + 'apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts#bindNativeProviderAuth': { status: 'internal', reason: 'Not a port: it records a native login binding in the owner binding file; the module state it reaches is the mutation lock depth (nativeBindingMutationLockDepth), held only while it runs. The Host calls it itself where the desktop does (agent/runtime.ts)' }, + 'apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts#setNewMakerDraftCache': { status: 'internal', reason: 'No production caller (only its own module and tests)' }, + 'apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts#setProviderModelMemoryCache': { status: 'pending', reason: 'Renderer mirror; the Host copy stays empty until the M2 push channel (release table row 6d)' }, + 'apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts#setThinkingEnabledInMemory': { status: 'internal', reason: 'Called by maker-ipc/agentSwitchDepsCore.ts, shared with the Host' }, + 'apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts#setWorkerCreationPrefsCache': { status: 'not-applicable', reason: 'Orca worker defaults; the Host refuses Orca tasks (send-preflight.ts); revisit when Orca opens (release table 乙 3)' }, + 'apps/desktop/src/main/maker-host/override-settings-file.ts#setPreserveUnreadableSettingsFilesByDefault': { status: 'bound', where: 'apps/host/src/boot-settings.ts' }, + 'apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts#registerPiProxySession': { status: 'bound', where: 'apps/host/src/agent/claude-proxy-runtime.ts' }, + 'apps/desktop/src/main/maker-host/provider-route.ts#setCustomProviderHeaderReader': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/provider-route.ts#setCustomProviderKeyReader': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/provider-route.ts#setOAuthTokenReader': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/provider-route.ts#setPendingCredentialSwitchReader': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/maker-host/provider-route.ts#setProviderOAuthTokenReader': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/provider-route.ts#setProviderViewsReader': { status: 'bound', where: 'apps/host/src/agent/provider-config.ts' }, + 'apps/desktop/src/main/maker-host/provider-upstream-error-observer.ts#setProviderUpstreamErrorBroadcaster': { status: 'pending', reason: 'M2 push channel (release table section 六, row maker:provider:upstream-error): unbound the broadcast is a no-op (provider-upstream-error-observer.ts)' }, + 'apps/desktop/src/main/maker-host/session-effort-store.ts#setSessionEffort': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/maker-host/session-effort-store.ts#setSessionFastMode': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/maker-host/session-model-interface.ts#configureSessionModelInterfaceStorage': { status: 'bound', where: 'apps/host/src/agent/start-options.ts' }, + 'apps/desktop/src/main/maker-host/session-provider-store.ts#bindHostedSessionProvider': { status: 'not-applicable', reason: 'Remote agent hosting; the Host refuses remote execution (send-preflight.ts); revisit when it opens (release table section 七, item 18)' }, + 'apps/desktop/src/main/maker-host/session-provider-store.ts#setSessionProvider': { status: 'bound', where: 'apps/host/src/agent/turn-executor.mjs' }, + 'apps/desktop/src/main/maker-ipc/botAuthorizationService.ts#initBotAuthorizationService': { status: 'not-applicable', reason: 'Teammates; the Host refuses teammate tasks (send-preflight.ts); revisit when they open (release table section 四, item 伙伴的会话环境(`resolveSessionEnvironment`)与伙伴工具集)' }, + 'apps/desktop/src/main/maker-ipc/interactionRouter.ts#installDesktopInteractionHandler': { status: 'bound', where: 'apps/host/src/agent/interactions.mjs' }, + 'apps/desktop/src/main/maker-ipc/interactionRouter.ts#installInteractionLifecycleObserver': { status: 'pending', reason: 'Plugin batch (release table row 33): the desktop observer feeds the plugin session tap (ghostSessionTap interactionObserver) and teammate group chats, which the Host refuses (send-preflight.ts); unbound, interactions run without lifecycle observation (interactionRouter.ts)' }, + 'apps/desktop/src/main/maker-ipc/sessionContextWindowBudgetState.ts#appliedContextWindowBudgets': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/maker-ipc/sessionContextWindowBudgetState.ts#pendingSessionContextWindowBudgetReconciles': { status: 'bound', where: 'apps/host/src/agent/runtime-selection.ts' }, + 'apps/desktop/src/main/maker-ipc/turnUsagePorts.ts#bindTurnUsagePorts': { status: 'bound', where: 'apps/host/src/agent/usage-recording.ts', reason: 'Release table row 13 (3d): the turn recorders\' ports; the four quota refreshes and broadcastSchedulerChanged are bound empty in phase 1 (no request, no push) and are bound for real with the usage reads and pushes batch' }, + 'apps/desktop/src/main/mcp-integrations/hostToolCaller.ts#setHostToolProviders': { status: 'not-applicable', reason: 'The Host builds plugin host tool runtimes from its own providers (host-tools.ts createProviderHostToolRuntime)' }, + 'apps/desktop/src/main/model-access/byokPricing.ts#setByokPricing': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, item 安装型 BYOK 供应商的凭据): set by the desktop BYOK runtime (model-access/byokRuntime.ts), which the Host does not load; unbound, the reference pricing has no BYOK provider prices (usage/referenceModelPricingCore.ts)' }, + 'apps/desktop/src/main/ownerContext.ts#configureOwnerContext': { status: 'bound', where: 'apps/host/src/agent/claude-auth.mjs' }, + 'apps/desktop/src/main/process-monitor/codex-process-registry.ts#registerAgentProcess': { status: 'bound', where: 'apps/host/src/agent/runtime.ts' }, + 'apps/desktop/src/main/process-monitor/codex-process-registry.ts#registerCodexProcessRole': { status: 'bound', where: 'apps/host/src/agent/runtime.ts' }, + 'apps/desktop/src/main/projectAutomaticIcon.ts#configureProjectIconRuntime': { status: 'bound', where: 'apps/host/src/project-icon.ts#bindHostProjectIconRuntime', reason: 'Only fetch, the Host outbound transport (outbound.mjs); readRemote stays unset, remote workdirs are refused on the Host (send-preflight.ts)' }, + 'apps/desktop/src/main/projectDirectoryValidation.ts#configureProjectDirectoryProbe': { status: 'not-applicable', reason: 'Host does not provide SSH project directory probing. Remote validation reports UNSUPPORTED_CAPABILITY when the probe is absent.' }, + 'apps/desktop/src/main/scheduler-host/pre-run-hook.ts#configurePreRunNodeScriptSpawner': { status: 'not-applicable', reason: 'The default already spawns the Node executable, which is what the Node Host needs; only the desktop replaces it with its own runtime (pre-run-hook.ts, pre-run-hook.desktop.ts)' }, + 'apps/desktop/src/main/scheduler-host/silent-output.ts#setSilencedRunProbe': { status: 'internal', reason: 'Called by scheduler-host/index.ts; scheduled runs are M3 (release table section 四, item 自动化/定时任务的宿主直发接入)' }, + 'apps/desktop/src/main/sidebarSettingsStoreCore.ts#configureSidebarSettingsPlatform': { status: 'not-applicable', reason: 'The Desktop adapter supplies legacy migration and window broadcasts. Host project tools use the owner-scoped store and publish changes through onProjectsChanged.' }, + 'apps/desktop/src/main/sidebarSettingsStoreCore.ts#setLocalMainViewHidden': { status: 'internal', reason: 'Convenience wrapper around the shared owner-scoped main-view visibility setter.' }, + 'apps/desktop/src/main/sidebarSettingsStoreCore.ts#setLocalProjectHidden': { status: 'internal', reason: 'Called by the shared project create and remove flows to update visibility in the owner-scoped store.' }, + 'apps/desktop/src/main/sidebarSettingsStoreCore.ts#setMainViewHidden': { status: 'internal', reason: 'Shared business write to the owner-scoped sidebar store.' }, + 'apps/desktop/src/main/sidebarSettingsStoreCore.ts#setProjectHidden': { status: 'internal', reason: 'Shared owner-scoped write called by setLocalProjectHidden.' }, + 'apps/desktop/src/main/subscription-accounts/session.ts#registerSessionSubscriptionAccount': { status: 'pending', reason: 'Subscription account native session handoff (release table row 30: not done on the Host)' }, + 'apps/desktop/src/main/turn-change-set/store.ts#setTurnChangeSetWindowBroadcast': { status: 'pending', reason: 'Change records are written on the Host; viewing and undo come with M2 (release table row 7)' }, + 'apps/desktop/src/main/uiText.ts#configureUiText': { status: 'bound', where: 'apps/host/src/ui-text.ts#bindHostUiText', reason: '甲 23: the main i18n in the system language, called by main.ts before the owner database opens' }, + 'apps/desktop/src/main/usage/auxiliaryUsage.ts#setAuxiliaryUsageChangedListener': { status: 'pending', reason: 'Release table row 13 (3f) covers usage pushes. Desktop usageHistory binds a listener to refresh today’s spend. The Host currently records the receipt without this broadcast.' }, + 'apps/desktop/src/main/usage/ledgerCurrency.ts#setActiveLedgerCurrency': { status: 'internal', reason: 'Called by usage/modelPricingCore.ts when gateway pricing syncs, which the Host pricing uses (agent/usage-pricing.ts)' }, + 'apps/desktop/src/main/usageBroadcastPorts.ts#bindUsageBroadcastPorts': { status: 'bound', where: 'apps/host/src/agent/usage-recording.ts', reason: 'Release table row 13 (3d): no windows; the message patches and the durable write queue are passed per task instead (the cores\' explicit deps)' }, + 'apps/desktop/src/main/userDataPath.ts#configureAppDataDir': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'apps/desktop/src/main/userDataPath.ts#configureUserDataDir': { status: 'bound', where: 'apps/host/src/agent/claude-auth.mjs' }, + 'apps/desktop/src/main/windowsAtomicRename.ts#configureWindowsAtomicRename': { status: 'bound', where: 'apps/host/src/main.ts' }, + 'packages/browser-control-runtime/src/shim/logging-core.ts#setBrowserRuntimeLogSink': { status: 'internal', reason: 'Called by the browser runtime itself (runtime.ts createBrowserControlRuntime) with the sink mcp-integrations/browser.ts passes, which the Host platform tools use (platform/tools.ts)' }, + 'packages/browser-control-runtime/src/shim/media-understanding-runtime.ts#setDescribeImageFile': { status: 'internal', reason: 'No production caller (only its own module and tests)' }, + 'packages/browser-control-runtime/src/shim/runtime-config-snapshot.ts#setBrowserRuntimeConfig': { status: 'internal', reason: 'Called by the browser runtime itself: createBrowserControlRuntime (runtime.ts) with the config mcp-integrations/browser.ts passes, and the config mutations (shim/config-mutation.ts)' }, + 'packages/browser-control-runtime/src/shim/runtime-env.ts#registerUnhandledRejectionHandler': { status: 'internal', reason: 'Called by the browser runtime itself (_generated/extension/src/browser/unhandled-rejections.ts)' }, + 'packages/file-browser-core/src/logging.ts#setFileBrowserCoreLoggerFactory': { status: 'not-applicable', reason: 'Logging only: unbound, the package drops its logs by design (logging.ts)' }, + 'packages/lizi-mcps/src/browser/tools.ts#registerBrowserTools': { status: 'internal', reason: 'Called by lizi-mcps/src/browser/server.ts when the browser MCP server is built' }, + 'packages/lizi-mcps/src/cindy-docs/read_sheet.ts#registerReadSheetTool': { status: 'internal', reason: 'Not a port: it registers the read_sheet tool when lizi-mcps/src/cindy_docsMcpServer.ts builds the docs MCP server; the module state it reaches is the tool worker pool (activeWorker, workerQueue), changed only while the tool runs' }, + 'packages/lizi-mcps/src/session-path-auth.ts#setSessionPathAuthorizer': { status: 'pending', reason: '甲, plugin batch (release table row 33): unbound, paths outside the workdir are refused (session-path-auth.ts), also those under granted directories, for cindy_computer on the Host' }, + 'packages/maker-core/src/agents/claude-code/index.ts#setClaudeRateLimitInfoListener': { status: 'pending', reason: 'Feeds subscription usage snapshots (maker-ipc/usage.ts); subscription usage is M2 (release table row 22: subscriptionUsage M2)' }, + 'packages/maker-core/src/agents/claude-code/index.ts#setClaudeSupportedModelsListener': { status: 'pending', reason: '乙 12 (model discovery and provider views, M2; release table section 二, subsection 订阅账号放置与供应商视图(rc10)): feeds Anthropic model discovery (model-discovery/anthropic.ts)' }, + 'packages/maker-core/src/agents/shared/image-resizer.ts#configureDefaultImageResizer': { status: 'not-applicable', reason: 'The desktop only gives it a logger; resizing works on the defaults' }, + 'packages/maker-core/src/session-send-terminal.ts#bindSessionSendOwner': { status: 'internal', reason: 'Called by maker-core session.ts' }, +}; diff --git a/apps/host/src/desktop-region-readers.ts b/apps/host/src/desktop-region-readers.ts new file mode 100644 index 00000000000..3aa74a8f7f1 --- /dev/null +++ b/apps/host/src/desktop-region-readers.ts @@ -0,0 +1,33 @@ +/** + * Desktop and package modules the Host loads that read the build region, and how each behaves on the + * Host. The region is fixed per release (scripts/build.mjs --region bakes it into shared/brandRegion.ts; + * from source loaders/raw-hook.mjs follows CINDY_HOST_REGION), so a reader here follows the Host's + * edition, not the account's realm. + * + * Read by the guard in apps/desktop/src/main/maker-host/__tests__/hostDesktopSourceContracts.guard.test.ts + * (pnpm test:guard). It collects, in the Host's static import graph, every file that imports + * CURRENT_CINDY_REGION or CURRENT_APP_ID from shared/brandRegion or reads VITE_CINDY_AUTH_REGION / + * CINDY_AUTH_REGION directly, and fails until each reader is listed here, and each entry still reads. + * A desktop module that starts reading the region, or comes into the graph (release table 甲 20, the + * desktop inventory's files outside it today), is judged here before it ships on the Host. + * It also collects the Host's own region fallbacks, a ternary that maps a realm to cn or global + * (`x === 'cn' ? 'cn' : 'global'`): unlike `account.realm ?? resolveHostRegion()` it falls to a fixed + * region, not the release's, so each one says why it cannot be reached and is rechecked when its code moves. + * + * Key: `#`, or `#:realm-fallback`; one sorted entry per line. + */ +export const DESKTOP_REGION_READERS: Readonly> = { + 'apps/desktop/src/main/claude-orphan-reaper.ts#CURRENT_CINDY_REGION': { host: 'Module-level Claude process markers (XDT_CLAUDE_PATH_MARKERS); the Host imports only killProcessTree (codex-tool-tree-reaper.ts), so they are unused' }, + 'apps/desktop/src/main/maker-host/active-catalog.ts#CURRENT_CINDY_REGION': { host: 'Before /models first succeeds, cn hides the unverified XD image, embedding and non-Seedance video models (provider-access-policy.ts); every catalog reader follows, including the engines\' model lists (3c)' }, + 'apps/desktop/src/main/maker-host/codexLocalSessionsCore.ts#CURRENT_CINDY_REGION': { host: 'cn also looks for old Codex threads in the legacy xdt-maker codex-home when resuming; the fallback codex-home is unreachable (codex-thread-storage.ts binds assertCurrent)' }, + 'apps/desktop/src/main/maker-ipc/piUsageReceiptsCore.ts#CURRENT_CINDY_REGION': { host: 'The Pi receipt pricing context (TurnPricingContext.region) of the turn usage records (release table row 13, 3d): the Host\'s edition, as the desktop\'s' }, + 'apps/desktop/src/main/maker-ipc/sessionClaudeTurnUsageCore.ts#CURRENT_CINDY_REGION': { host: 'The Claude turn pricing context (TurnPricingContext.region) of the turn usage records (release table row 13, 3d): the Host\'s edition, as the desktop\'s' }, + 'apps/desktop/src/main/maker-ipc/sessionPiTurnUsageCore.ts#CURRENT_CINDY_REGION': { host: 'The Pi turn pricing context (TurnPricingContext.region) of the turn usage records (release table row 13, 3d): the Host\'s edition, as the desktop\'s' }, + 'apps/desktop/src/main/usage/modelPricingCore.ts#CURRENT_CINDY_REGION': { host: 'The pricing cache scope (3a): region= next to the Model Access base URL and the account, so a release shares the scope the desktop of its region writes; no user-visible difference' }, + 'apps/desktop/src/shared/brandRegion.ts#env': { host: 'The definition: import.meta.env?.VITE_CINDY_AUTH_REGION, baked from --region in a release (scripts/build.mjs) and CINDY_HOST_REGION from source (loaders/raw-hook.mjs)' }, + 'apps/desktop/src/shared/regionalMoney.ts#CURRENT_CINDY_REGION': { host: 'Module-level DEFAULT_USAGE_CURRENCY: the currency of zero amounts for tasks and runs without a cost (localDb/mapper.ts), CNY for cn' }, + 'apps/desktop/src/shared/voiceInputData.ts#CURRENT_CINDY_REGION': { host: 'Voice input default language without a saved choice, zh-CN for cn (profile-settings.mjs, the web client\'s boot values)' }, + 'apps/host/src/main.ts#disableShareAvailability:realm-fallback': { host: 'account.realm === \'cn\' ? \'cn\' : \'global\' picks the Device Link endpoint; a missing realm would fall to global, not the release region. Unreachable with the current startup order: it is the share availability policy\'s callback (created with the owner runtime, handed to the agent graph and Device Link), and it calls the server with the session token, which exists only once sign-in set the realm' }, + 'apps/host/src/main.ts#hostAgentNetPorts:realm-fallback': { host: 'Selects the Agent-Net service and Device Link directory by the signed-in realm. The global fallback for a missing realm is unreachable because startDeviceLink calls this only after authentication sets the realm.' }, + 'apps/host/src/main.ts#startDeviceLink:realm-fallback': { host: 'account.realm === \'cn\' ? \'cn\' : \'global\' picks the Device Link relay; a missing realm would fall to global, not the release region. Unreachable with the current startup order: the startup task calls it after sign-in set the realm (main.ts ensureRuntime, then startDeviceLink)' }, +}; diff --git a/apps/host/src/device-link.test.mjs b/apps/host/src/device-link.test.mjs index 790e3b2f825..72e5bc94843 100644 --- a/apps/host/src/device-link.test.mjs +++ b/apps/host/src/device-link.test.mjs @@ -8,12 +8,15 @@ import WebSocket, { WebSocketServer } from 'ws'; import Database from 'better-sqlite3'; import { drizzle } from 'drizzle-orm/better-sqlite3'; import { getTableColumns, getTableName } from 'drizzle-orm'; -import { DeviceLinkClient, PROTOCOL_VERSION } from '@cindy/device-link'; +import { DeviceLinkClient, PROTOCOL_VERSION, FILE_PEER_CHANNEL, REMOTE_AGENT_CHANNEL, REMOTE_DESKTOP_CHANNEL, + PROVIDER_SHARE_RELAY_CAPABILITY, isProviderSharePeer, providerShareGuestPeer, providerShareHostPeer, PLUGIN_OAUTH_CHANNEL } from '@cindy/device-link'; import { AgentNetWorkerSocket } from '@cindy/agent-net'; import { createPrivateNetwork, generateIdentity, issueCertificate } from '@cindy/agent-net-relay'; import { readDeviceLinkInvokeSourceDevice, readDeviceLinkModelSelectionOrigin } from '../../desktop/src/main/device-link/invoke-context.ts'; -import { createHostDeviceLink } from './device-link.ts'; +import { createHostDeviceLink, HOST_DISPATCH_PORTS_WHILE_HELD } from './device-link.ts'; import { createHostService } from './service.mjs'; +import { createHostServer } from './server.mjs'; +import { MCP_APPS_INVOKE } from '../../desktop/src/shared/mcpApps.ts'; import { createEventHub } from './events.mjs'; import { configureHostOwner } from './agent/claude-auth.mjs'; import { configureAppDataDir } from '../../desktop/src/main/userDataPath.ts'; @@ -23,6 +26,8 @@ import { createDbClientForHandle } from '../../desktop/src/main/localDb/client/c import { sessions, messages, taskTags, sessionTaskTags, botSessionLinks, botProfiles } from '../../desktop/src/main/localDb/schema.ts'; import { readHostSessionList, readHostSession } from './session-reads.ts'; import { publishAgentEvent } from './agent/turn-executor.mjs'; +import * as broadcastTap from '../../desktop/src/main/device-link/broadcast-tap.ts'; +import { PHASE1_UNFORWARDED_USAGE_CHANNELS } from './agent/usage-push-channels.ts'; import { redactEventForRenderer } from '../../desktop/src/main/maker-ipc/rendererEventRedaction.ts'; const waitFor = async condition => { @@ -59,6 +64,12 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev const clients = []; let host, hold, release, writes = 0, duplicateNext = false; let source; + // Coexistence plan A: the refusal while a desktop uses the profile (null: not held). + let held = null; + const projectHold = 'HOST_PROFILE_IN_USE_BY_DESKTOP: project profile held for this test'; + let holdBeforeProjectWrite = false; + let created = 0, appCalls = 0, oauthCalls = 0, piPrewarms = 0; + const oauthCancelled = []; const modelChoices = []; t.after(async () => { clients.forEach(client => client.stop()); @@ -97,10 +108,16 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev await once(wss, 'listening'); const url = `ws://127.0.0.1:${wss.address().port}`; const service = createHostService({ + profileHold: () => held, + // One USD and one CNY quote: the device-link v1 projection keeps only USD (usageHandlers.ts). + modelPricing: async () => ({ xd: { + 'usd-model': { providerId: 'xd', modelId: 'usd-model', currency: 'USD', source: 'gateway', approximate: false, inputPerMtok: 3, outputPerMtok: 15 }, + 'cny-model': { providerId: 'xd', modelId: 'cny-model', currency: 'CNY', source: 'gateway', approximate: false, inputPerMtok: 20, outputPerMtok: 80 }, + } }), listSessions: options => readHostSessionList(db.drizzle, options), getSession: id => readHostSession(db.drizzle, id), - updateSession: async (id, patch) => { - modelChoices.push({ id, patch, origin: readDeviceLinkModelSelectionOrigin() }); + setSessionModel: async (id, model) => { + modelChoices.push({ id, model, origin: readDeviceLinkModelSelectionOrigin() }); return { deferred: true }; }, input: { enqueue: async (sessionId, item) => { @@ -114,14 +131,23 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev host = createHostDeviceLink({ profileDir: profile, version: 'test', getWsUrl: () => url, getToken: async () => 'synthetic-host', canRegister: () => true, invoke: service, subscribe: hub.subscribe, - isBusyForProjectArchive: () => false, + isBusyForProjectArchive: () => { + if (holdBeforeProjectWrite) held = projectHold; + return false; + }, onProjectTaskStatus: (sessionId, status) => hub.publish({ type: 'session_changed', sessionId, status, patch: { status } }), preparePiSkillRuntime: async (id, dir, route) => { + piPrewarms++; assert.equal(id, 'task'); assert.equal(dir, '/project'); if (route) assert.deepEqual(route, { model: 'pi-test', nextInputChars: 45_000 }); }, createRuntimeSession: async () => { throw new Error('Not part of this transport test'); }, + createRuntimeSession: async () => { created++; throw new Error('Not part of this transport test'); }, disableShareAvailability: async () => { throw new Error('This fixture owns no standby grants'); }, + profileHold: () => held, + mcpApps: { invoke: async () => { appCalls++; return {}; }, releaseCaller: async () => {} }, + requestPluginOauth: async () => { oauthCalls++; return { ok: true }; }, + invalidatePluginOauth: peer => { oauthCancelled.push(peer ?? 'all'); }, }); assert.equal(host.state().enabled, false); assert.equal(sockets.has('host'), false); @@ -155,6 +181,33 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev assert.equal(result.result, 'updated'); assert.equal(sqlite.prepare("SELECT status FROM sessions WHERE id='task'").pluck().get(), expected); } + // Device Link integration: unlike the upstream round trip above, the Host can + // share a profile with Desktop. §3.2: guard the read/write split and the race + // after entry using the existing remote dispatcher and a byte-for-byte DB check. + await t.test('project archive allows previews while held and refuses writes at entry and after preflight', async () => { + const before = sqlite.serialize(); + const assertRefused = async action => { + const reply = await projectArchive({ action, operation: 'apply', sessionId: 'task' }); + assert.equal(reply.ok, false, JSON.stringify(reply)); + assert.match(JSON.stringify(reply.error), /PRECONDITION_FAILED.*HOST_PROFILE_IN_USE_BY_DESKTOP/); + assert.deepEqual(sqlite.serialize(), before); + }; + try { + held = projectHold; + const whileHeld = await projectArchive({ action: 'archive', operation: 'preview' }); + assert.equal(whileHeld.ok, true, JSON.stringify(whileHeld)); + assert.deepEqual(whileHeld.result, preview.result); + await assertRefused('archive'); + await assertRefused('unarchive'); + held = null; + // Discover occupation during the shared membership check inside the task lock. + holdBeforeProjectWrite = true; + await assertRefused('archive'); + } finally { + holdBeforeProjectWrite = false; + held = null; + } + }); // 2026-11-18: exercise the real Host registry over the existing integration relay. // A positive controller window on either picker channel or Skill preparation must fail before applying it. const numericSelections = [ @@ -170,7 +223,7 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev assert.deepEqual(modelChoices, []); const stage = await clients[0].invoke('host', { channel: 'maker:set-model', args: ['task', 'small'] }); assert.deepEqual(stage.result, { deferred: true }); - assert.deepEqual(modelChoices, [{ id: 'task', patch: { model: 'small' }, origin: 'owner' }]); + assert.deepEqual(modelChoices, [{ id: 'task', model: 'small', origin: 'owner' }]); const prepared = await clients[2].invoke('host', { channel: 'maker:session:prewarm', args: ['task', { purpose: 'pi-skill-dispatch', workingDir: '/project' }] }); @@ -181,6 +234,10 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev const unsupported = await clients[2].invoke('host', { channel: 'maker:session:prewarm', args: ['task', { purpose: 'pi-skill-dispatch', workingDir: '/project', model: 'pi-test', pendingPiRoute: { agentDeviceId: 'other' } }] }); assert.equal(unsupported.ok, false); + + // A phone asks the v1 channel, as the desktop answers it: flat USD fields, CNY quotes left out. + const v1 = await clients[0].invoke('host', { channel: 'maker:usage:model-pricing', args: [] }); + assert.deepEqual(v1.result, { 'usd-model': { inputUsdPerMtok: 3, outputUsdPerMtok: 15 } }, JSON.stringify(v1)); const received = clients.map(() => []); clients.forEach((client, i) => client.onFrame(frame => { if (frame.kind === 'push') received[i].push(frame); })); duplicateNext = true; @@ -193,6 +250,16 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev // Saved error rows must reach the channel desktop and mobile already listen on. hub.publish({ type: 'error_persisted', sessionId: 'task', persistId: 'err' }); await waitFor(() => received.every(frames => frames.some(frame => frame.payload.channel === 'local-db:session:error-persisted'))); + // Phase 1 (release table row 13, 3d): the usage pushes the desktop's usage cores send on the tap are not + // forwarded through the Host's device-link wiring (agent/usage-push-channels.ts); another push on the same + // tap still is. A usage frame would arrive before the probe that follows it. + const tapScope = broadcastTap.captureDataOwnerBroadcastScope(); + for (const channel of PHASE1_UNFORWARDED_USAGE_CHANNELS) broadcastTap.tapWindowBroadcast(channel, { sessionId: 'task' }, tapScope.ownerStamp); + broadcastTap.tapWindowBroadcast('local-db:session:error-persisted', { sessionId: 'task', persistId: 'tap-probe' }, tapScope.ownerStamp); + await waitFor(() => received.every(frames => frames.some(frame => JSON.stringify(frame).includes('tap-probe')))); + for (const frames of received) { + assert.deepEqual(frames.filter(frame => String(frame.payload?.channel ?? '').startsWith('usage:')).map(frame => frame.payload.channel), []); + } // An agent event reaches every controller as the Host publishes it for its clients: the desktop's // renderer-boundary projection, without the proxy credential or Host lifecycle fields. const browserEvent = { type: 'tool_use', sessionTurnGeneration: 3, sessionInstanceId: 'fixture-runtime', turnAttemptToken: 'fixture-attempt', @@ -230,6 +297,29 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev sqlite.prepare('UPDATE sessions SET last_turn_ended_at=? WHERE id=?').run(startedAt + 252731, 'task'); assert.equal(writes, 2, 'reattaching the desktop must not replay mobile writes'); hold = undefined; + // Coexistence plan A: while a desktop uses the profile, a phone's send, a new task and a plugin + // page's call are refused with the typed reason, and none reaches its handler; reads still answer. + held = 'HOST_PROFILE_IN_USE_BY_DESKTOP: held for this test'; + for (const [channel, args] of [['maker:input:enqueue', ['task', { clientId: 'held', text: 'refused' }]], + ['maker:create-session', [{}]], ['maker:session:prewarm', ['task', { purpose: 'pi-skill-dispatch', workingDir: '/project' }]], + [MCP_APPS_INVOKE, ['task', {}]], [PLUGIN_OAUTH_CHANNEL, [{}]]]) { + const reply = await clients[0].invoke('host', { channel, args }); + assert.equal(reply.ok, false, `${channel}: ${JSON.stringify(reply)}`); + // The dispatcher answers every plugin OAuth failure with its own fixed text (dispatch.ts:5148). + if (channel !== PLUGIN_OAUTH_CHANNEL) + assert.ok(JSON.stringify(reply.error).includes('HOST_PROFILE_IN_USE_BY_DESKTOP'), `${channel}: ${JSON.stringify(reply)}`); + } + assert.deepEqual([writes, created, appCalls, oauthCalls, piPrewarms], [2, 0, 0, 0, 2], 'nothing reached a handler while held'); + assert.equal((await clients[0].invoke('host', { channel: 'local-db:sessions:get', args: ['task'] })).ok, true, 'reads still answer'); + // A controller closing its link still cancels its pending plugin authorizations while held: that + // cancel only drops in-memory requests (plugin-oauth/runtime.ts invalidatePluginOauth), no stored sign-in. + clients[2].closeLink('host', 'user'); + await waitFor(() => oauthCancelled.includes('desktop')); + await clients[2].openLink('host', { controllerName: 'desktop', protocolVersion: PROTOCOL_VERSION, appVersion: 'test' }); + held = null; + // Released, a remote plugin authorization reaches the plugin OAuth entry again. + assert.equal((await clients[0].invoke('host', { channel: PLUGIN_OAUTH_CHANNEL, args: [{}] })).ok, true); + assert.equal(oauthCalls, 1); await host.revoke('ios'); const denied = await clients[0].invoke('host', { channel: 'local-db:sessions:get', args: ['task'] }).catch(error => ({ denied: error })); assert.ok(denied.denied || denied.ok === false); @@ -259,6 +349,142 @@ test('headless dispatcher serves multiple clients and enforces owner and per-dev clients[1].stop(); await inFlight; }); +// Test value (engineering-conventions §3.2) +// - Production entry and observable result: createHostDeviceLink (the dispatcher the Host starts +// after sign-in, main.ts startDeviceLink), reached by real DeviceLinkClients through a local +// relay. A provider-share guest gets the typed ACCESS_REVOKED result on any channel and never +// reaches the Host service; a same-account controller asking for a file peer or remote desktop +// gets a typed refusal instead of a session. +// - Rule: release table row 乙 6. The Host never calls setProviderShareAccess, so the first gate of +// runProviderShareInvoke (dispatch.ts providerShareGuestAccess) is always empty; requestFilePeer and +// requestRemoteDesktop are not passed, so the dispatcher's unavailable() defaults apply +// (dispatch.ts:494-496). Passing either port later must be a decision, not an accident. +// - Coverage gap: the test above only drives same-account controllers on the contract channels; +// nothing ran a share-guest peer or these two platform channels against the Host assembly. +// - Minimal failing input: a share access port that admits the guest, or a requestRemoteDesktop +// that resolves, in the Host's createInboundDispatch ports. +// - Tier: unit with loopback sockets in-process, as the test above (no relay, no network, no model). +test('Host device-link refuses provider-share guests and the platform features it does not wire', async t => { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-remote-refusals-')); + configureAppDataDir(profile); + configureHostOwner({ userDataDir: profile, ownerId: 'test-refusal-owner' }); + const hostKey = providerShareHostPeer('share-fixture', 'host'); + const guestKey = providerShareGuestPeer('share-fixture', 'member-fixture', 'guest'); + assert.ok(isProviderSharePeer(guestKey)); + const sockets = new Map(); + const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' }); + const reached = []; + let host, desktop, guest; + t.after(async () => { + desktop?.stop(); guest?.stop(); + await host?.stop(); + for (const socket of wss.clients) socket.terminate(); + await new Promise(resolve => wss.close(resolve)); + commitVolatileAppSession('signed-out', null, true); + fs.rmSync(profile, { recursive: true, force: true }); + }); + // The relay stamps src (and the share source for scoped frames); the guest belongs to another account. + wss.on('connection', (socket, request) => { + const id = /^Bearer synthetic-(host|desktop|guest)$/.exec(request.headers.authorization ?? '')?.[1]; + if (!id) { socket.close(1008); return; } + sockets.set(id, socket); + socket.on('message', raw => { + const frame = JSON.parse(raw.toString()); + if (frame.kind === 'hello') { + socket.send(JSON.stringify({ v: PROTOCOL_VERSION, kind: 'hello-ack', payload: { + serverProtocolVersion: PROTOCOL_VERSION, deviceId: id, userId: `synthetic-${id === 'guest' ? 'other' : 'same'}-user`, + capabilities: [PROVIDER_SHARE_RELAY_CAPABILITY], + } })); + if (id === 'desktop') sockets.get('host')?.send(JSON.stringify({ v: PROTOCOL_VERSION, kind: 'presence-changed', + payload: { deviceId: 'desktop', platform: 'darwin', online: true, remoteControlEnabled: true } })); + } else if (frame.kind === 'ping') socket.send(JSON.stringify({ v: PROTOCOL_VERSION, kind: 'pong' })); + else if (frame.dst && sockets.get(frame.dst)?.readyState === WebSocket.OPEN) { + // Like the relay, author the share source from the sender's identity; never trust the client's. + const providerShare = frame.providerShare && { ...frame.providerShare, + source: id === 'guest' ? { role: 'guest', memberId: 'member-fixture' } : { role: 'host' } }; + sockets.get(frame.dst).send(JSON.stringify({ ...frame, src: id, ...(providerShare ? { providerShare } : {}) })); + } + }); + }); + await once(wss, 'listening'); + const url = `ws://127.0.0.1:${wss.address().port}`; + host = createHostDeviceLink({ profileDir: profile, version: 'test', getWsUrl: () => url, + getToken: async () => 'synthetic-host', canRegister: () => true, + invoke: async route => { reached.push(route); return { status: 404, body: { message: `unexpected ${route}` } }; }, + subscribe: () => () => {}, + createRuntimeSession: async () => { throw new Error('Not part of this test'); }, + disableShareAvailability: async () => { throw new Error('This fixture owns no standby grants'); }, + }); + await host.setEnabled(true); + await waitFor(() => host.state().status === 'online'); + const client = id => { + const value = new DeviceLinkClient({ getWsUrl: () => url, getToken: async () => `synthetic-${id}`, + getHello: () => ({ deviceName: id, platform: 'darwin', appVersion: 'test', remoteControlEnabled: false }), + createWebSocket: (address, headers) => new WebSocket(address, { headers }), + }); + value.start(); + return value; + }; + desktop = client('desktop'); + guest = client('guest'); + await waitFor(() => desktop.getStatus() === 'online' && guest.getStatus() === 'online'); + await desktop.openLink('host', { controllerName: 'desktop', protocolVersion: PROTOCOL_VERSION, appVersion: 'test' }); + + const filePeer = await desktop.invoke('host', { channel: FILE_PEER_CHANNEL, args: [{}] }); + assert.deepEqual(filePeer, { ok: false, error: { code: 'IPC_ERROR', message: 'FILE_PEER_UNAVAILABLE' } }); + const remoteDesktop = await desktop.invoke('host', { channel: REMOTE_DESKTOP_CHANNEL, args: [{}] }); + assert.equal(remoteDesktop.ok, false, JSON.stringify(remoteDesktop)); + assert.equal(remoteDesktop.error.code, 'IPC_ERROR'); + assert.match(remoteDesktop.error.message, /^\[NOT_SUPPORTED\] requestRemoteDesktop /); + + for (const channel of [REMOTE_AGENT_CHANNEL, 'local-db:sessions:list', 'host:execute-arbitrary']) { + const reply = await guest.invoke(hostKey, { channel, args: [] }); + assert.equal(reply.ok, false, `${channel}: ${JSON.stringify(reply)}`); + assert.equal(reply.error.code, 'ACCESS_REVOKED', `${channel}: ${JSON.stringify(reply)}`); + } + assert.deepEqual(reached, [], 'neither refusal may reach the Host service'); +}); + +/* + * Test value (engineering-conventions §3.2) + * - Production entry: createHostDeviceLink checks, before it creates the shared inbound dispatch, that + * every port it passes has a class in HOST_DISPATCH_PORTS_WHILE_HELD and that `unbound` ports are + * the ones left undefined (the tests above construct it through that path; a mismatch throws there). + * - Rule: coexistence plan A (reviewer, 2026-11-17). While a desktop uses this profile each port the + * Host hands the dispatcher is read-only, behind the service gate, refused at its entry, or unbound; + * the list is pinned here so a port is only added, or moved between classes, by changing this table. + * - Coverage gap: the service gate test covers /api/* paths only; the dispatcher's own ports + * (plugin OAuth, the invoke registry) were not listed anywhere. + * - Minimal failing input: an extra port in the Host's dispatch ports without a class, or a class + * changed in device-link.ts and not here. + * - Tier: guard (the table compared with the production list; no IO). + */ +const PINNED_DISPATCH_PORTS = { + read: ['sameAccountCapabilities', 'TASK_TAG_CHANNEL', 'app', 'readDeviceLinkSettings', 'noteControllerAccessAllowed', + 'noteControllerAccessDenied', 'syncRemoteControlAccessGeneration', 'invalidatePluginOauth', + 'assertRemoteBotInvocationAllowed', 'projectRemoteSessionResult', 'projectRemoteBotPush', 'hasRemoteBotSessionLookup', + 'setRemoteBotSessionLookup', 'captureSharedTaskPeer', 'captureSharedTaskPush', 'assertSharedTaskInvoke', + 'sharedTaskMetadataTopic', 'sharedTaskAccessFailure', 'MAX_SHARED_TASK_TOPICS', 'refreshSharedTaskPeer', + 'releaseSharedTaskWatchesOnWorkdirChange', 'admitSharedTaskFsWatchTopics', 'setBroadcastTapListener', 'broadcastTap', + 'RECOVERY_CHECKPOINT_MARKER', 'sanitizeBotAuthorizationMetaForRemote', 'projectInteractionDismissedForRemote', + 'projectInteractionRequestForRemote', 'remoteWorkingDirRejectionToIpcError'], + 'service-gate': ['executeTaskTags', 'dispatchLocalInvoke'], + 'refused-at-entry': ['requestPluginOauth'], + unbound: ['readUsageWidgetSnapshot', 'configureStandbyGuestCleanup', 'prepareShareAvailability', + 'readKimiCodingAccountUsage', 'readOpenCodeGoAccountUsage', 'requestFilePeer', 'stopFilePeers', 'requestTaskMigration', + 'delegatedProviderShareGuestAccess', 'locallyProvenProviderShareDelegation', + 'delegatedProviderShareLeases', 'invalidateProviderShareDelegation', + 'remoteDesktop', 'requestRemoteDesktop', 'remoteCredentialHost', 'fetchLocalMediaToOss', 'transcribeRemoteVoiceInput', + 'readTelegramRemoteStatus', 'setTelegramRemoteOnline', 'adviseAndRecordVoiceInputDictionaryLearning', + 'buildMobileDictionarySnapshot'], +}; + +test('every port the Host passes the inbound dispatch has the class pinned here', () => { + const pinned = Object.fromEntries(Object.entries(PINNED_DISPATCH_PORTS).flatMap(([kind, names]) => names.map(name => [name, kind]))); + const sorted = value => Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))); + assert.deepEqual(sorted(HOST_DISPATCH_PORTS_WHILE_HELD), sorted(pinned)); +}); + // An outage on the main connection must release only its own MCP App views and OAuth callers. test('keeps compatibility app callers alive when only the Agent-Net connection drops', async t => { const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-app-routes-')); @@ -363,3 +589,69 @@ test('routes project writes by their authenticated caller', async () => { await service('/api/project-info/desktop-set', envelope, local); assert.deepEqual(writes.pop(), [input, { desktopRequest: 'from-main' }]); }); + +// §3.2 integration: the authenticated CLI control handler bypasses the service +// gate, and its formerly pre-queue-only owner check missed a queued account change. +test('Agent-Net control refuses profile hold and rechecks the owner inside the settings lock', async t => { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'host-agent-net-setting-')); + configureHostOwner({ userDataDir: profile, ownerId: 'first-owner' }); + const file = path.join(profile, 'device-link-settings.json'); + const initial = '{"agentNetEnabled":false,"remoteControlEnabled":false}'; + fs.writeFileSync(file, initial); + const holdMessage = 'HOST_PROFILE_IN_USE_BY_DESKTOP: The desktop window is using this profile.'; + let held = holdMessage; + let canRegister = false; + const host = createHostDeviceLink({ + profileDir: profile, version: 'test', getWsUrl: () => 'ws://127.0.0.1:9', + getToken: async () => null, canRegister: () => canRegister, profileHold: () => held, + invoke: async () => ({ status: 200, body: {} }), subscribe: () => () => {}, + createRuntimeSession: async () => ({}), disableShareAvailability: async () => {}, + agentNet: { base: () => null, subject: () => null, deviceId: () => null }, + }); + const server = createHostServer({ instanceId: 'fixture', token: 'fake-token', + remoteControl: action => action === 'enable' ? host.setEnabled(true) + : host.setAgentNetEnabled(action === 'agent-net-on') }); + t.after(async () => { + await new Promise(resolve => server.close(resolve)); + await host.stop(); + commitVolatileAppSession('signed-out', null, true); + fs.rmSync(profile, { recursive: true, force: true }); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const control = action => fetch(`http://127.0.0.1:${server.address().port}/control/remote`, { + method: 'POST', + headers: { authorization: 'Bearer fake-token', 'content-type': 'application/json' }, + body: JSON.stringify({ instanceId: 'fixture', action }), + }); + // Turning remote control on writes the same settings file through the same bypass (`/control/remote`); + // before this it skipped the hold. Minimal failure: drop refuseWhileHeld() from setEnabled. + await t.test('CLI commands that turn something on, or Agent-Net off, refuse a held profile', async () => { + canRegister = true; + for (const action of ['enable', 'agent-net-on', 'agent-net-off']) { + const response = await control(action); + assert.equal(response.status, 409); + assert.deepEqual(await response.json(), { error: 'PRECONDITION_FAILED', message: '[PRECONDITION_FAILED] ' + holdMessage }); + assert.equal(fs.readFileSync(file, 'utf8'), initial); + } + }); + held = null; + await t.test('turning remote control on works again once the hold clears', async () => { + const response = await control('enable'); + assert.equal(response.status, 200); + assert.equal(JSON.parse(fs.readFileSync(file, 'utf8')).remoteControlEnabled, true); + }); + canRegister = false; + await t.test('queued switch does not write once the owner changes', async t => { + const before = fs.readFileSync(file, 'utf8'); + const open = fs.openSync; + t.mock.method(fs, 'openSync', (target, ...args) => { + const fd = open(target, ...args); + if (target === file + '.lock' && args[0] === 'wx') + configureHostOwner({ userDataDir: profile, ownerId: 'next-owner' }); + return fd; + }); + await assert.rejects(host.setAgentNetEnabled(false), /Host account changed/); + assert.equal(fs.readFileSync(file, 'utf8'), before); + assert.equal(fs.existsSync(file + '.lock'), false); + }); +}); diff --git a/apps/host/src/device-link.ts b/apps/host/src/device-link.ts index 6e0ffbe7989..9287a402fe2 100644 --- a/apps/host/src/device-link.ts +++ b/apps/host/src/device-link.ts @@ -8,8 +8,9 @@ import { createAgentNetNode, type AgentNetNodePorts } from '../../desktop/src/ma import { AgentNetSessionLinks, agentNetSessionLane, routeSessionPeers, type PeerLinks } from '@cindy/agent-net'; import { HOST_CONTRACT_CHANNELS } from '@cindy/maker-shared/host-channel-contract'; import type { TaskTagRequest } from '@cindy/maker-shared'; -import { createInboundDispatch } from '../../desktop/src/main/device-link/dispatch.js'; +import { createInboundDispatch, type InboundDispatchPorts } from '../../desktop/src/main/device-link/dispatch.js'; import { createInvokeRegistry } from '../../desktop/src/main/device-link/invokeRegistryCore.js'; +import { toLegacyUsdModelPricing } from '../../desktop/src/main/maker-ipc/usageHandlers.js'; import { createDeviceLinkSettingsStore } from '../../desktop/src/main/device-link/settings-store.js'; import { createRemoteControlAccess } from '../../desktop/src/main/device-link/remoteControlAccessCore.js'; import { createAvailabilityPolicy } from '../../desktop/src/main/device-link/providerShareAvailabilityPolicyCore.js'; @@ -17,6 +18,7 @@ import * as botBoundary from '../../desktop/src/main/device-link/remoteBotSessio import * as sharedTasks from '../../desktop/src/main/device-link/sharedTaskDispatch.js'; import { admitSharedTaskFsWatchTopics } from '../../desktop/src/main/device-link/sharedTaskFileAccess.js'; import * as broadcastTap from '../../desktop/src/main/device-link/broadcast-tap.js'; +import { withoutPhaseOneUsagePushes } from './agent/usage-push-channels.js'; import { PROJECT_ARCHIVE_CHANNEL } from '../../desktop/src/shared/projectArchive.js'; import { runProjectArchive } from '../../desktop/src/main/localDb/projectArchive.js'; import { getDbClient } from '../../desktop/src/main/localDb/client/current.js'; @@ -35,6 +37,90 @@ import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../../desktop/ import { MAKER_INVOKE, MAKER_PUSH } from '../../desktop/src/main/maker-ipc/channels.js'; import { MCP_APPS_INVOKE } from '../../desktop/src/shared/mcpApps.js'; import { deviceLinkInvokeControllerSupports, getDeviceLinkInvokeContext, readDeviceLinkModelSelectionOrigin } from '../../desktop/src/main/device-link/invoke-context.js'; +import { explicitPorts } from './agent/explicit-ports.js'; + +/** + * What each port the Host hands the shared inbound dispatch (dispatch.ts InboundDispatchPorts) can do + * while a desktop uses this profile (coexistence plan A, reviewer 2026-11-17): + * - `read`: reads, or changes only this process's memory (controller access generations, the broadcast + * tap, pending plugin authorizations); nothing in the profile is written. + * - `service-gate`: reaches the Host service, whose gate refuses writes while held (service.mjs). + * - `refused-at-entry`: writes without the service, so refused here (refuseWhileHeld below). + * - `unbound`: not passed; the dispatcher answers NOT_SUPPORTED or skips it (dispatch.ts `unavailable`). + * A port that is not listed here, or is bound against its entry, stops the Host device link from + * starting; the list is pinned in device-link.test.mjs. + */ +export const HOST_DISPATCH_PORTS_WHILE_HELD = Object.freeze({ + sameAccountCapabilities: 'read', + readUsageWidgetSnapshot: 'unbound', + configureStandbyGuestCleanup: 'unbound', + prepareShareAvailability: 'unbound', + readKimiCodingAccountUsage: 'unbound', + readOpenCodeGoAccountUsage: 'unbound', + // `/api/task-tags/execute`, refused by the service gate while held. + executeTaskTags: 'service-gate', + TASK_TAG_CHANNEL: 'read', + requestFilePeer: 'unbound', + stopFilePeers: 'unbound', + requestTaskMigration: 'unbound', + delegatedProviderShareGuestAccess: 'unbound', + locallyProvenProviderShareDelegation: 'unbound', + delegatedProviderShareLeases: 'unbound', + invalidateProviderShareDelegation: 'unbound', + app: 'read', + remoteDesktop: 'unbound', + requestRemoteDesktop: 'unbound', + remoteCredentialHost: 'unbound', + readDeviceLinkSettings: 'read', + // remoteControlAccessCore.ts: generation counters and the observed-revocation set, in memory. + noteControllerAccessAllowed: 'read', + noteControllerAccessDenied: 'read', + syncRemoteControlAccessGeneration: 'read', + requestPluginOauth: 'refused-at-entry', + // Cancels pending authorizations in memory only (plugin-oauth/runtime.ts invalidatePluginOauth, + // transactions.ts cancelPeer, authentication.ts invalidate); nothing stored is deleted. + invalidatePluginOauth: 'read', + // The invoke registry: contract channels call the service (gated); maker:create-session and + // MCP_APPS_INVOKE are refused where they are registered. + dispatchLocalInvoke: 'service-gate', + assertRemoteBotInvocationAllowed: 'read', + projectRemoteSessionResult: 'read', + projectRemoteBotPush: 'read', + hasRemoteBotSessionLookup: 'read', + setRemoteBotSessionLookup: 'read', + // No shared-task host is set on the Host (setSharedTaskDispatchHost), so these answer "unavailable". + captureSharedTaskPeer: 'read', + captureSharedTaskPush: 'read', + assertSharedTaskInvoke: 'read', + sharedTaskMetadataTopic: 'read', + sharedTaskAccessFailure: 'read', + fetchLocalMediaToOss: 'unbound', + MAX_SHARED_TASK_TOPICS: 'read', + refreshSharedTaskPeer: 'read', + releaseSharedTaskWatchesOnWorkdirChange: 'read', + admitSharedTaskFsWatchTopics: 'read', + transcribeRemoteVoiceInput: 'unbound', + readTelegramRemoteStatus: 'unbound', + setTelegramRemoteOnline: 'unbound', + adviseAndRecordVoiceInputDictionaryLearning: 'unbound', + buildMobileDictionarySnapshot: 'unbound', + setBroadcastTapListener: 'read', + broadcastTap: 'read', + RECOVERY_CHECKPOINT_MARKER: 'read', + sanitizeBotAuthorizationMetaForRemote: 'read', + projectInteractionDismissedForRemote: 'read', + projectInteractionRequestForRemote: 'read', + remoteWorkingDirRejectionToIpcError: 'read', +} as const satisfies Record); +type UnboundDispatchPort = { [K in keyof typeof HOST_DISPATCH_PORTS_WHILE_HELD]: + (typeof HOST_DISPATCH_PORTS_WHILE_HELD)[K] extends 'unbound' ? K : never }[keyof typeof HOST_DISPATCH_PORTS_WHILE_HELD]; + +function assertDispatchPortsClassified(ports: object): void { + const kinds: Record = HOST_DISPATCH_PORTS_WHILE_HELD; + const wrong = Object.entries(ports).filter(([name, value]) => !Object.hasOwn(kinds, name) + || (kinds[name] === 'unbound') !== (value === undefined)).map(([name]) => name); + if (wrong.length) throw new Error(`Host dispatch ports without a matching hold class: ${wrong.join(', ')}`); +} import { normalizeDeviceLinkSetModelWireArgs } from '../../desktop/src/main/maker-ipc/setModelWireArgs.js'; type ServiceResult = { status: number; body: any }; @@ -53,6 +139,12 @@ export interface HostDeviceLinkPorts { onProjectTaskStatus(sessionId: string, status: 'active' | 'archived'): void; preparePiSkillRuntime(id: string, workingDir: string, route?: { model: string; nextInputChars?: number }): Promise; createRuntimeSession(input: unknown): Promise; + /** Coexistence plan A: the refusal while a desktop uses this profile, or null. */ + profileHold?(): string | null; + /** The remote plugin OAuth entry; the desktop's plugin-oauth runtime unless a test passes its own. */ + requestPluginOauth?(peer: string, raw: unknown): Promise; + /** Cancels a peer's (or every) pending plugin authorization in memory; the runtime's unless a test passes its own. */ + invalidatePluginOauth?(peer?: string): void; subscribe(listener: (event: any) => void): () => void; // Cloud revocation is required before narrowing a persisted standby grant. availabilityPolicy?: ReturnType; @@ -112,21 +204,39 @@ export function createHostDeviceLink(deps: HostDeviceLinkPorts) { return contract.map ? contract.map(result) : result; }); } - registry.register(PROJECT_ARCHIVE_CHANNEL, ([input]) => runProjectArchive(input, true, { - withLock: withSendToSessionLock, - busy: deps.isBusyForProjectArchive, - write: async (sessionId, status, beforeWrite, projectGuard) => { - const client = getDbClient(); - beforeWrite(); - if (status === 'archived') { - await client.tx('sessions.setTerminalStatus', { sessionId, status, projectGuard }); - } else { - await client.tx('sessions.setStatus', { sessionIds: [sessionId], status, projectGuard }); - } - assertCurrent(); - deps.onProjectTaskStatus(sessionId, status); - }, - })); + // The desktop answers `maker:usage:model-pricing` (device-link v1) with the flat USD projection and + // `-v2` with the native quotes (usageHandlers.ts). Both contract entries share one Host path, which + // answers v2 for the renderer; v2 is not on the device-link allowlist, so v1 is projected here. + registry.register('maker:usage:model-pricing', async () => toLegacyUsdModelPricing(await call('/api/usage/model-pricing', {}))); + // Coexistence plan A: while a desktop uses this profile, a new task's runtime and a plugin page's + // calls (they write through the plugin) are refused, as the service refuses other writes. + const refuseWhileHeld = () => { + const held = deps.profileHold?.(); + if (held) throw Object.assign(new Error(`[PRECONDITION_FAILED] ${held}`), { code: 'PRECONDITION_FAILED' }); + }; + registry.register('maker:create-session', ([input]) => { refuseWhileHeld(); return deps.createRuntimeSession(input); }); + registry.register(PROJECT_ARCHIVE_CHANNEL, ([input]) => { + // The preview is a read. Like project-info writes at the service boundary, + // apply is refused on entry and rechecked at the write boundary after waiting. + if ((input as { operation?: unknown } | null)?.operation === 'apply') refuseWhileHeld(); + return runProjectArchive(input, true, { + withLock: withSendToSessionLock, + busy: deps.isBusyForProjectArchive, + write: async (sessionId, status, beforeWrite, projectGuard) => { + beforeWrite(); + assertCurrent(); + refuseWhileHeld(); + const client = getDbClient(); + if (status === 'archived') { + await client.tx('sessions.setTerminalStatus', { sessionId, status, projectGuard }); + } else { + await client.tx('sessions.setStatus', { sessionIds: [sessionId], status, projectGuard }); + } + assertCurrent(); + deps.onProjectTaskStatus(sessionId, status); + }, + }); + }); registry.register(MAKER_INVOKE.SET_MODEL, async ([sessionId, model, wireProviderId, revision, wireSelection]) => { const { providerId, selection } = normalizeDeviceLinkSetModelWireArgs(true, deviceLinkInvokeControllerSupports(CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1), @@ -140,17 +250,11 @@ export function createHostDeviceLink(deps: HostDeviceLinkPorts) { if (typeof model !== 'string' || (providerId !== undefined && providerId !== null && typeof providerId !== 'string')) { throw new Error('[INVALID_PARAMS] invalid model or provider'); } - const axes = selection as { effort?: string; fastMode?: boolean | 'ultrafast' } | undefined; - const result = await call('/api/sessions/update', { - sessionId, - patch: { model, ...(providerId !== undefined ? { providerId } : {}), - ...(axes?.effort ? { effort: axes.effort } : {}), - ...(axes?.fastMode !== undefined ? { fastMode: axes.fastMode } : {}) }, - }); + const result = await call('/api/sessions/set-model', { sessionId, model, providerId, revision, selection }); if (result && typeof result === 'object') dispatch.markRemoteSettingPersistedInsideHandler(result); return result; }); - registry.register(MAKER_INVOKE.SWITCH_SESSION_AGENT, ([sessionId, targetAgentKind, model, providerId, effort, fastMode, options]) => { + registry.register(MAKER_INVOKE.SWITCH_SESSION_AGENT, ([sessionId, targetAgentKind, model, providerId, effort, fastMode, options, thinking]) => { if (options && typeof options === 'object') { if ('confirmedContextWindow' in options) { throw new Error('[PRECONDITION_FAILED] remote model-window confirmation is unsupported'); @@ -161,16 +265,20 @@ export function createHostDeviceLink(deps: HostDeviceLinkPorts) { (providerId !== null && providerId !== undefined && typeof providerId !== 'string')) { throw new Error('[INVALID_PARAMS] invalid model or provider'); } - return call('/api/sessions/switch-agent', { sessionId, targetAgentKind, model, providerId, effort, fastMode }); + if (readDeviceLinkModelSelectionOrigin() !== 'owner') { + throw new Error('[PRECONDITION_FAILED] remote agent switching requires an owner controller'); + } + return call('/api/sessions/switch-agent', { sessionId, targetAgentKind, model, providerId, effort, fastMode, + options, thinking }); }); registry.register(MAKER_INVOKE.GET_SESSION_AGENT_SWITCH_INTENT, ([sessionId]) => call('/api/sessions/agent-switch-intent', { sessionId })); - registry.register('maker:create-session', ([input]) => deps.createRuntimeSession(input)); registry.register('maker:session:prewarm', async ([id, input]) => { assertCurrent(); if (readDeviceLinkModelSelectionOrigin() !== 'owner') throw new Error('[PRECONDITION_FAILED] Task owner required'); const request = input as { purpose?: string; workingDir?: string; pendingPiRoute?: unknown; model?: unknown } | null; if (request?.purpose !== 'pi-skill-dispatch') return { accepted: false }; + refuseWhileHeld(); if (typeof id !== 'string' || !id || typeof request.workingDir !== 'string' || !request.workingDir) throw new Error('[INVALID_PARAMS] Session and working directory required'); const pending = request.pendingPiRoute; @@ -189,10 +297,12 @@ export function createHostDeviceLink(deps: HostDeviceLinkPorts) { ? { model: request.model as string, ...(nextInputChars !== undefined ? { nextInputChars } : {}) } : undefined; await deps.preparePiSkillRuntime(id, request.workingDir, route); + refuseWhileHeld(); assertCurrent(); return { accepted: true, piRuntimePrepared: true, ...(route ? { pendingRouteApplied: true } : {}) }; }); if (deps.mcpApps) registry.register(MCP_APPS_INVOKE, async ([sessionId, input]) => { + refuseWhileHeld(); const source = getDeviceLinkInvokeContext(); if (!source || source.sharedTask) throw new Error('[PRECONDITION_FAILED] MCP_APP_OWNER_ONLY'); if (typeof sessionId !== 'string' || (input && typeof input === 'object' && 'deviceId' in input)) @@ -207,26 +317,61 @@ export function createHostDeviceLink(deps: HostDeviceLinkPorts) { try { const result = await work; assertCurrent(); return result; } finally { pending.delete(work); } }; + const cancelPluginOauth = deps.invalidatePluginOauth ?? invalidatePluginOauth; const tags = { executeTaskTags: (request: TaskTagRequest) => call('/api/task-tags/execute', { request }) }; /** This Host runs on Agent-Net right now (set once the node exists, below). */ let agentNetActive = (): boolean => false; - const dispatch = createInboundDispatch({ + const unboundPorts = Object.fromEntries(Object.entries(HOST_DISPATCH_PORTS_WHILE_HELD) + .filter(([, kind]) => kind === 'unbound').map(([name]) => [name, undefined])); + const interactions = createInteractionProjection(supportsRemotePluginOauth); + const dispatchPorts = explicitPorts({ + ...(unboundPorts as Record), // Platform capabilities are added only when their backing services are wired. Background links need none: this // dispatch already keeps a link that declares no subscriptions out of the controlled state. Without it a desktop // closes every background link it opens here (backgroundLink.ts) and opens the next one for its next read; on // Agent-Net that is a session link reopened per read. Only while Agent-Net is on: off, the Host answers as before. sameAccountCapabilities: () => (agentNetActive() ? [DEVICE_LINK_CAPABILITY_BACKGROUND_LINK_V1] : []), app: { getVersion: () => deps.version }, - ...tags, TASK_TAG_CHANNEL, ...settings, ...access, + ...tags, TASK_TAG_CHANNEL, readDeviceLinkSettings: () => ({ ...settings.readDeviceLinkSettings(), remoteControlEnabled: current() && settings.readDeviceLinkSettings().remoteControlEnabled }), + noteControllerAccessAllowed: access.noteControllerAccessAllowed, + noteControllerAccessDenied: access.noteControllerAccessDenied, + syncRemoteControlAccessGeneration: access.syncRemoteControlAccessGeneration, dispatchLocalInvoke: invoke, - ...botBoundary, ...sharedTasks, admitSharedTaskFsWatchTopics, - setBroadcastTapListener: broadcastTap.setBroadcastTapListener, broadcastTap, - requestPluginOauth, invalidatePluginOauth, - ...createInteractionProjection(supportsRemotePluginOauth), projectInteractionDismissedForRemote, + assertRemoteBotInvocationAllowed: botBoundary.assertRemoteBotInvocationAllowed, + projectRemoteSessionResult: botBoundary.projectRemoteSessionResult, + projectRemoteBotPush: botBoundary.projectRemoteBotPush, + hasRemoteBotSessionLookup: botBoundary.hasRemoteBotSessionLookup, + setRemoteBotSessionLookup: botBoundary.setRemoteBotSessionLookup, + captureSharedTaskPeer: sharedTasks.captureSharedTaskPeer, + captureSharedTaskPush: sharedTasks.captureSharedTaskPush, + assertSharedTaskInvoke: sharedTasks.assertSharedTaskInvoke, + sharedTaskMetadataTopic: sharedTasks.sharedTaskMetadataTopic, + sharedTaskAccessFailure: sharedTasks.sharedTaskAccessFailure, + MAX_SHARED_TASK_TOPICS: sharedTasks.MAX_SHARED_TASK_TOPICS, + refreshSharedTaskPeer: sharedTasks.refreshSharedTaskPeer, + releaseSharedTaskWatchesOnWorkdirChange: sharedTasks.releaseSharedTaskWatchesOnWorkdirChange, + admitSharedTaskFsWatchTopics, + // Phase 1: the usage pushes are not forwarded to remote devices (agent/usage-push-channels.ts). + setBroadcastTapListener: (listener: Parameters[0]) => + broadcastTap.setBroadcastTapListener(withoutPhaseOneUsagePushes(listener)), + broadcastTap, + // A remote plugin authorization writes the plugin's sign-in on this computer: refused while a + // desktop uses this profile, as the service refuses other writes (the dispatcher handles this + // channel itself, PLUGIN_OAUTH_CHANNEL, so the service gate does not see it). + requestPluginOauth: async (peer: string, raw: unknown) => { + refuseWhileHeld(); + return (deps.requestPluginOauth ?? requestPluginOauth)(peer, raw); + }, + invalidatePluginOauth: cancelPluginOauth, + sanitizeBotAuthorizationMetaForRemote: interactions.sanitizeBotAuthorizationMetaForRemote, + projectInteractionRequestForRemote: interactions.projectInteractionRequestForRemote, + projectInteractionDismissedForRemote, RECOVERY_CHECKPOINT_MARKER, remoteWorkingDirRejectionToIpcError, }); + assertDispatchPortsClassified(dispatchPorts); + const dispatch = createInboundDispatch(dispatchPorts); botBoundary.setRemoteBotSessionLookup(readRemoteBotSessionAccess, readRemoteBotSessionAccessBatch); dispatch.setRemoteWorkingDirGuard((dir, context) => { // SSH needs its own endpoint authority and cannot fall through to local IO. @@ -450,15 +595,30 @@ export function createHostDeviceLink(deps: HostDeviceLinkPorts) { ...(agentNet.active() && compatibilityIssue ? { compatibilityIssue } : {}) } } : {}) }), async setEnabled(enabled: boolean) { assertCurrent(); + // Turning remote control on writes the profile's device-link settings outside the service gate, so it + // refuses a held profile as setAgentNetEnabled does: at entry and again inside the settings lock. + // Turning it off keeps its current path (disable and revoke under a hold are decided separately). + if (enabled) refuseWhileHeld(); if (enabled && !deps.canRegister()) throw new Error('Sign in with cindy-host login to register an independent Host device.'); - await settings.writeDeviceLinkSetting('remoteControlEnabled', enabled); + if (enabled) { + await settings.updateDeviceLinkSetting('remoteControlEnabled', () => { + assertCurrent(); + refuseWhileHeld(); + return true; + }); + } else await settings.writeDeviceLinkSetting('remoteControlEnabled', false); sync(); return this.state(); }, /** This Host's 「Agent-Net (Beta)」 setting (off by default); the main connection follows it right away. */ async setAgentNetEnabled(enabled: boolean) { assertCurrent(); + refuseWhileHeld(); if (!agentNet) throw new Error('Agent-Net is not available on this Host.'); - await settings.writeDeviceLinkSetting('agentNetEnabled', enabled); + await settings.updateDeviceLinkSetting('agentNetEnabled', () => { + assertCurrent(); + refuseWhileHeld(); + return enabled; + }); sync(); return this.state(); }, async revoke(deviceId: string) { @@ -470,7 +630,7 @@ export function createHostDeviceLink(deps: HostDeviceLinkPorts) { }, async stop() { if (closed) return; - closed = true; invalidatePluginOauth(); + closed = true; cancelPluginOauth(); clearInterval(poll); offSettings(); offEvents(); offPresence(); offIssue(); offCompatibilityIssue?.(); offStatus(); unbind(); dispatch.dropAllControllers(client, 'shutdown'); client.stop(); agentNet?.close(); registry.clear(); clearControllerPlatforms(); await releaseApps(); diff --git a/apps/host/src/host-network-modules.ts b/apps/host/src/host-network-modules.ts new file mode 100644 index 00000000000..14491b29006 --- /dev/null +++ b/apps/host/src/host-network-modules.ts @@ -0,0 +1,78 @@ +/** + * Every module the Host loads that opens network connections itself, and why its traffic to other machines goes + * through the Host's outbound proxy resolver or does not need to (release table row 28). + * + * "Opens network connections itself": a value import of node:http, https, net, tls, http2 or dgram, of undici or + * ws (or a require / dynamic import of them), references to global fetch, direct calls to a local fetch + * parameter, or WebSocket construction. Counts cover fetch uses, WebSocket constructions and calls through + * statically imported network APIs so adding a call in an already classified module also needs review. + * + * Guard: hostDesktopSourceContracts.guard.test.ts ("network modules the Host loads") collects them over the Host's + * import graph (the entries of scripts/build.mjs and the acceptance scripts) and fails on a module missing here, an + * entry whose module no longer does it, or a different `uses`: a new outbound call that bypasses the resolver + * cannot land unnoticed. + * + * route: + * - resolver: its requests to other machines take the resolver's verdict (hostOutbound, resolveHostOutboundProxy, + * or an agent built from them); + * - injected: the transport is a port, and the Host passes hostOutbound (where says where); + * - loopback: it talks to this machine only (a local server, a local control plane, the Host's own endpoint); + * - no-connection: it imports the module for addresses or types and opens nothing; + * - same-as-desktop: it goes to other machines without the resolver, as the desktop does too (recorded in the + * release table, row 28). + */ +export type HostNetworkRoute = 'resolver' | 'injected' | 'loopback' | 'no-connection' | 'same-as-desktop'; + +export const HOST_NETWORK_MODULES: Readonly> = { + 'apps/desktop/scripts/mcp-apps-mock.mjs': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'A mock MCP app server on loopback for an acceptance script' }, + 'apps/desktop/src/main/browser-extension/bridge.ts': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'The browser extension bridge listens on loopback for the local extension' }, + 'apps/desktop/src/main/browser-extension/native-binding.ts': { uses: ['imports net', 'network API calls ×1'], route: 'loopback', reason: 'Connects to 127.0.0.1 only (the native messaging binding)' }, + 'apps/desktop/src/main/cindy-brain/ghostOauthFlow.ts': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'The plugin OAuth redirect listener on loopback; its token requests use the injected fetch (plugins/authorization.ts passes hostOutbound)' }, + 'apps/desktop/src/main/cindy-brain/networkConnections.ts': { uses: ['imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'injected', reason: 'Plugin WebSockets take the injected agent: plugins/runtime.ts passes hostOutbound.createOutboundHttpAgent' }, + 'apps/desktop/src/main/host-ipc-proxy.ts': { uses: ['fetch ×1'], route: 'loopback', reason: 'A client window\'s proxy to the Host\'s loopback endpoint' }, + 'apps/desktop/src/main/input-handoff/askpass/host.ts': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'The askpass server on loopback' }, + 'apps/desktop/src/main/maker-host/cli-proxy-bridge.ts': { uses: ['imports http', 'imports net', 'network API calls ×3'], route: 'resolver', reason: 'The Claude and Pi CLI CONNECT bridge resolves each target through resolveHostOutboundProxy, injected by provider-config.ts and agent/runtime.ts' }, + 'apps/desktop/src/main/maker-host/generic-oauth.ts': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'The OAuth redirect listener on loopback; token requests use the injected fetch (provider-config.ts passes hostOutbound)' }, + 'apps/desktop/src/main/maker-host/grok-oauth-login.ts': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'The Grok sign-in redirect listener on loopback; token requests use the injected outboundFetch (provider-config.ts passes hostOutbound)' }, + 'apps/desktop/src/main/maker-host/outbound-fetch.ts': { uses: ['fetch ×2', 'imports undici', 'network API calls ×8'], route: 'resolver', reason: 'The outbound transport itself: it goes direct only where the resolver says direct' }, + 'apps/desktop/src/main/mcp-apps/connection.ts': { uses: ['fetch ×1'], route: 'same-as-desktop', reason: 'A remote (URL) MCP app connects with Node\'s fetch, without the resolver, as in the desktop main process; plugin MCP apps use the plugin transport' }, + 'apps/desktop/src/main/mcp-integrations/browser-backend/external-link-handoff.ts': { uses: ['imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'loopback', reason: 'The managed browser\'s DevTools endpoint on loopback' }, + 'apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts': { uses: ['fetch ×2', 'imports net', 'imports ws', 'network API calls ×4', 'new WebSocket ×3'], route: 'loopback', reason: 'The managed browser\'s DevTools endpoint, checked to be loopback' }, + 'apps/desktop/src/main/mcp-integrations/browser-real-profile/launch.ts': { uses: ['imports net', 'network API calls ×1'], route: 'loopback', reason: 'Takes a free local port' }, + 'apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'The Codex task action bridge server on loopback' }, + 'apps/desktop/src/main/projectIconDiscovery.ts': { uses: ['fetch ×5'], route: 'injected', reason: 'The Host project icon runtime passes hostOutbound.outboundFetch for icon discovery' }, + 'apps/desktop/src/main/reviewer/reviewOwnerLiveness.ts': { uses: ['imports net', 'network API calls ×2'], route: 'loopback', reason: 'The reviewer owner liveness socket on loopback' }, + 'apps/host/src/auth/device-link-registration.mjs': { uses: ['imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'resolver', reason: 'Fresh sign-in restores relay registration with createHostWebSocketAgent.' }, + 'apps/host/src/auth/login.mjs': { uses: ['imports http', 'network API calls ×1'], route: 'loopback', reason: 'The sign-in callback listener on loopback; auth requests use hostAuthFetch' }, + 'apps/host/src/browser-open.mjs': { uses: ['fetch ×1'], route: 'loopback', reason: 'The Host\'s own loopback endpoint (pairing)' }, + 'apps/host/src/control.mjs': { uses: ['fetch ×1'], route: 'loopback', reason: 'The running Host\'s loopback control endpoint' }, + 'apps/host/src/device-link.ts': { uses: ['imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'resolver', reason: 'The relay WebSocket takes createHostWebSocketAgent (outbound.mjs)' }, + 'apps/host/src/main.ts': { uses: ['imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'resolver', reason: 'hostAgentNetPorts supplies the HTTP fetch and WebSocket agent from the Host outbound transport.' }, + 'apps/host/src/platform/client-bridge.ts': { uses: ['imports ws'], route: 'loopback', reason: 'Accepts the platform client\'s socket on the Host\'s loopback server' }, + 'apps/host/src/plugins/node-worker.ts': { uses: ['imports net', 'network API calls ×1'], route: 'no-connection', reason: 'Wraps the inherited control pipe (fd 3)' }, + 'apps/host/src/server.mjs': { uses: ['imports http', 'imports ws', 'network API calls ×2'], route: 'loopback', reason: 'The Host\'s own loopback server' }, + 'packages/agent-net-core/wasm/node.mts': { uses: ['imports dgram', 'imports net', 'network API calls ×2'], route: 'same-as-desktop', reason: 'The Agent-Net worker uses direct UDP for session paths, STUN and UDP relay, as on the desktop.' }, + 'packages/agent-net-relay/src/client.ts': { uses: ['fetch ×9', 'imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'injected', reason: 'The live Agent-Net client takes fetch and createWebSocket from hostAgentNetPorts through createAgentNetNode.' }, + 'packages/agent-net-relay/src/cluster.ts': { uses: ['imports http', 'imports https'], route: 'no-connection', reason: 'Loaded through the Agent-Net relay exports. Cindy Host runs a client and never starts the relay service.' }, + 'packages/agent-net-relay/src/datagramQueue.ts': { uses: ['imports ws'], route: 'no-connection', reason: 'The relay queue uses the WebSocket module for its ready state constant.' }, + 'packages/agent-net-relay/src/gateway.ts': { uses: ['imports http', 'imports https', 'network API calls ×2'], route: 'no-connection', reason: 'Loaded through the Agent-Net relay exports. Cindy Host runs a client and never starts the relay service.' }, + 'packages/agent-net-relay/src/ingress.ts': { uses: ['imports http', 'network API calls ×1'], route: 'no-connection', reason: 'Loaded through the Agent-Net relay exports. Cindy Host runs a client and never starts the relay service.' }, + 'packages/agent-net-relay/src/server.ts': { uses: ['imports dgram', 'imports http', 'imports https', 'imports net', 'imports ws', 'network API calls ×7'], route: 'no-connection', reason: 'Loaded through the Agent-Net relay exports. Cindy Host runs a client and never starts the relay service.' }, + 'packages/agent-net/src/lan.ts': { uses: ['imports dgram', 'network API calls ×1'], route: 'same-as-desktop', reason: 'The Agent-Net worker uses direct UDP to discover peers on a local network, as on the desktop.' }, + 'packages/agent-net/src/sharingClient.ts': { uses: ['fetch ×1'], route: 'no-connection', reason: 'Loaded through Agent-Net exports. Host device links use AgentNetClient and never construct the sharing client.' }, + 'packages/agent-net/src/workerSocket.ts': { uses: ['fetch ×1', 'imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'injected', reason: 'Worker HTTP and WebSocket requests use the parent AgentNetClient transport supplied by hostAgentNetPorts.' }, + 'packages/anthropic-compat-proxy/src/outbound-proxy.ts': { uses: ['imports http', 'imports https', 'network API calls ×1'], route: 'resolver', reason: 'The HTTP CONNECT agents for the resolver\'s verdicts' }, + 'packages/anthropic-compat-proxy/src/server.ts': { uses: ['imports http', 'imports https', 'network API calls ×1'], route: 'resolver', reason: 'The loopback compat proxy; upstream requests take the injected resolver (claude-proxy-runtime.ts passes resolveHostOutboundProxy)' }, + 'packages/anthropic-compat-proxy/src/socks5.ts': { uses: ['imports http', 'imports https', 'imports net', 'network API calls ×4'], route: 'resolver', reason: 'The SOCKS5 agents for the resolver\'s verdicts' }, + 'packages/anthropic-responses-bridge/src/handler.ts': { uses: ['fetch ×1'], route: 'injected', reason: 'Global fetch only as the default of fetchImpl; anthropicResponsesBridgeHostCore.ts passes outboundFetch (hostOutbound on the Host)' }, + 'packages/browser-control-runtime/src/_generated/extension/src/browser/cdp-proxy-bypass.ts': { uses: ['imports http', 'imports https', 'network API calls ×2'], route: 'loopback', reason: 'Agents that keep DevTools traffic to loopback off any proxy' }, + 'packages/browser-control-runtime/src/_generated/extension/src/browser/cdp.helpers.ts': { uses: ['imports ws', 'network API calls ×1', 'new WebSocket ×1'], route: 'loopback', reason: 'DevTools WebSockets of the controlled browser on loopback' }, + 'packages/browser-control-runtime/src/_generated/extension/src/browser/navigation-guard.ts': { uses: ['imports net', 'network API calls ×1'], route: 'no-connection', reason: 'Parses addresses for navigation checks' }, + 'packages/browser-control-runtime/src/_generated/leaf/src/infra/net/undici-family-policy.ts': { uses: ['imports net', 'network API calls ×4'], route: 'no-connection', reason: 'The address family policy of the guarded dispatcher' }, + 'packages/browser-control-runtime/src/_generated/leaf/src/infra/net/undici-runtime.ts': { uses: ['imports net', 'imports undici', 'network API calls ×1'], route: 'loopback', reason: 'The guarded fetch runtime of the browser control client, whose callers target loopback control planes (shim/ssrf-runtime.ts)' }, + 'packages/browser-control-runtime/src/shim/_local/ports.ts': { uses: ['imports net', 'network API calls ×1'], route: 'loopback', reason: 'Takes free local ports' }, + 'packages/browser-control-runtime/src/shim/ssrf-runtime.ts': { uses: ['fetch ×1', 'imports undici', 'network API calls ×2'], route: 'loopback', reason: 'The guarded fetch of the control client and DevTools helper, which target loopback control planes' }, + 'packages/embedding-client/src/client.ts': { uses: ['fetch ×1'], route: 'no-connection', reason: 'The shared embedding implementation is imported; only the desktop starts the embedding host and supplies its outbound fetch' }, + 'packages/responses-anthropic-bridge/src/handler.ts': { uses: ['fetch ×1'], route: 'injected', reason: 'Global fetch only as the default of fetchImpl; the Host\'s bridges pass outboundFetch' }, + 'packages/responses-chat-bridge/src/handler.ts': { uses: ['fetch ×1'], route: 'injected', reason: 'Global fetch only as the default of fetchImpl; anthropicCompatProxyHostCore.ts passes outboundFetch (hostOutbound on the Host)' }, +}; diff --git a/apps/host/src/host-tools.test.mjs b/apps/host/src/host-tools.test.mjs index 961682751a0..4d68f5d5c82 100644 --- a/apps/host/src/host-tools.test.mjs +++ b/apps/host/src/host-tools.test.mjs @@ -7,7 +7,7 @@ import { getTableColumns, getTableName } from 'drizzle-orm'; import { createDbClientForHandle } from '../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; import { sessions, botSessionLinks, botProfiles, projectAliases, recentWorkdirs } from '../../desktop/src/main/localDb/schema.ts'; import { configureHostOwner } from './agent/claude-auth.mjs'; -import { getActiveDataOwnerPushStamp, commitVolatileAppSession } from '../../desktop/src/main/appSessionState.ts'; +import { getActiveDataOwnerPushStamp, commitVolatileAppSession, ownerScopedUserDataPath } from '../../desktop/src/main/appSessionState.ts'; import { writeProjectsRootDirectory } from '../../desktop/src/main/projects-root-settings.ts'; import assert from 'node:assert/strict'; import test from 'node:test'; @@ -15,12 +15,15 @@ import { createHostConfirmations } from './host-confirmations.ts'; import { createHostToolService } from './agent/host-tools.ts'; import { setCurrentDbClient, clearCurrentDbClient } from '../../desktop/src/main/localDb/client/current.ts'; import { createHostServer } from './server.mjs'; +import { createHostService } from './service.mjs'; +import { createHostProjectInfoUpdate } from './project-info.ts'; import { createWebAuth } from './web-auth.mjs'; import { createEventHub } from './events.mjs'; import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; import { createLiziMcpProviders } from '@cindy/mcps'; import { handlePluginHostToolRequest } from '../../desktop/src/main/cindy-brain/hostToolSlot.ts'; import { createHostToolRuntime, setHostToolProviders } from '../../desktop/src/main/mcp-integrations/hostToolCaller.ts'; +import { HELP_KNOWLEDGE } from '../../desktop/src/main/maker-ipc/helpKnowledge.generated.ts'; // Unit: existing installation and business confirmations use the Host's // window-bound confirmation bridge; a different paired controller, disconnection @@ -284,13 +287,50 @@ test('negotiated HTTP event streams deliver one live owner dialog without puttin assert.equal(received[0].type, 'plugin_push'); }); +// Test value (engineering-conventions §3.2) +// - Production entry and observable result: the Host's cindy_helper provider from createHostToolService, +// called the way an engine calls it (toHostTools(...).call). get_capabilities({ scope: 'help' }) returns +// the desktop's product help (index, then a full document) instead of HELP_UNAVAILABLE. +// - Rule: release table row 22 (cindy_helper ports); the desktop passes productHelpDocs: HELP_KNOWLEDGE +// (mcp-providers.ts). Without it an agent on the Host answers "where is X / how do I" without the docs. +// - Coverage gap: the tests above call plugin host tools and history; none reads get_capabilities. +// - Minimal failing input: the Host xdtHelper deps without productHelpDocs. +// - Tier: unit, in process with an in-memory SQLite task row; no engine or network. +test('the Host cindy_helper serves the desktop product help to agents', async () => { + // An ordinary active task of the current owner, in the real tables the helper's authorizer and surface read. + const sqlite = new Database(':memory:'); + for (const table of [sessions, botSessionLinks, botProfiles]) { + sqlite.exec(`CREATE TABLE "${getTableName(table)}" (${Object.values(getTableColumns(table)).map(column => `"${column.name}" ${column.getSQLType()}`).join(',')})`); + } + sqlite.exec("INSERT INTO sessions(id,title,source,status,created_at,updated_at) VALUES ('task','Task','desktop','active',1,1)"); + const database = createDbClientForHandle({ db: sqlite, drizzle: drizzle(sqlite) }); + setCurrentDbClient(database, 'owner'); + const confirmations = createHostConfirmations({ current: () => true }); + const service = createHostToolService({ profileDir: '/fixture', ownerId: 'owner', current: () => true, + owner: () => ({ dataOwnerId: 'owner', ownerGeneration: 1 }), getGhost: () => null, + getSession: () => undefined, confirmations, t: key => key, + // As main.ts: the input coordinator's facts for the calling turn, here an owner-typed turn. + taskActions: { input: () => ({ key: 'owner-turn', ownerInput: true, boundary: 'fixture' }) } }); + const agent = service.providers.find(p => p.name === 'cindy_helper').toHostTools({ agentKind: 'codex', workingDir: '', sessionId: 'task' }); + const body = result => JSON.parse(result.content.find(item => item.type === 'text').text); + try { + const index = body(await agent.call('get_capabilities', { scope: 'help' })); + assert.equal(index.ok, true, JSON.stringify(index)); + assert.deepEqual(index.docs.map(doc => doc.key), HELP_KNOWLEDGE.map(doc => doc.id)); + const first = HELP_KNOWLEDGE[0]; + const doc = body(await agent.call('get_capabilities', { scope: 'help', key: first.id })); + assert.equal(doc.ok, true, JSON.stringify(doc)); + assert.equal(doc.doc.content, first.content); + } finally { await agent.close(); service.close(); confirmations.close(); clearCurrentDbClient(database); sqlite.close(); } +}); + // Integration: the Node provider previously exposed no project callbacks. Exercise // its actual MCP dispatch, shared core, isolated SQLite and temporary directories; // no Electron shim, credentials, Git service or real user paths are involved. test('Node AI tools create, inspect and edit the complete project profile in the current owner', async t => { const profile = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'host-project-tools-'))); configureHostOwner({ userDataDir: profile, ownerId: 'projects-owner' }); - const sqlite = new Database(':memory:'); + const sqlite = new Database(path.join(profile, 'owner.sqlite')); for (const table of [sessions, botSessionLinks, botProfiles, projectAliases, recentWorkdirs]) { sqlite.exec(`CREATE TABLE "${getTableName(table)}" (${Object.values(getTableColumns(table)).map(column => `"${column.name}" ${column.getSQLType()}${column.primary ? ' PRIMARY KEY' : ''}`).join(',')})`); @@ -302,11 +342,18 @@ test('Node AI tools create, inspect and edit the complete project profile in the await Promise.all([root, first, second].map(dir => fs.mkdir(dir))); await writeProjectsRootDirectory(root); let current = true; + let held = null; + const profileHold = () => held; + const snapshot = async () => { + const entries = await fs.readdir(profile, { recursive: true, withFileTypes: true }); + const files = entries.filter(entry => entry.isFile()).map(entry => path.join(entry.parentPath, entry.name)).sort(); + return Promise.all(files.map(async file => [path.relative(profile, file), await fs.readFile(file)])); + }; const changes = []; const confirmations = createHostConfirmations({ current: () => current }); const service = createHostToolService({ profileDir: profile, ownerId: 'projects-owner', current: () => current, owner: () => getActiveDataOwnerPushStamp(), deviceId: () => 'this-host', onProjectsChanged: catalogChanged => { changes.push(catalogChanged); }, - getGhost: () => null, getSession: () => undefined, confirmations, t: key => key, + getGhost: () => null, getSession: () => undefined, confirmations, profileHold, t: key => key, taskActions: { input: () => ({ key: 'input', ownerInput: true, boundary: 'input' }) }, }); const runtime = service.providers.find(provider => provider.name === 'cindy_helper').toHostTools({ @@ -344,6 +391,93 @@ test('Node AI tools create, inspect and edit the complete project profile in the assert.ok(list.projects.some(item => item.working_dir === created.working_dir)); assert.equal((await call('update_project_info', { project_key: created.project_key, field: 'profile', value: { directories: [] } })).ok, true); assert.deepEqual((await call('get_project_info', { project_key: created.project_key })).project.directories, []); + // §3.2 integration: the MCP entry bypassed the HTTP profile hold. A running task with + // a valid owner must get the service's refusal for each new project write. The original + // case covered an owner change only. Use the actual profile and SQLite bytes to catch writes. + await t.test('profile hold refuses project writes and still serves project reads', async () => { + const before = await snapshot(); + const beforePushes = changes.length; + held = 'HOST_PROFILE_IN_USE_BY_DESKTOP: The desktop window is using this profile.'; + const invoke = createHostService({ profileHold }); + const serviceError = await invoke('/api/project-info/set').catch(error => error); + assert.equal(serviceError.code, 'PRECONDITION_FAILED'); + const expected = { ok: false, errorCode: serviceError.code, + data: { hint: serviceError.message.replace(/^\[PRECONDITION_FAILED\] /, '') } }; + for (const [tool, args] of [ + ['create_project', { name: 'Denied' }], + ['update_project_info', { project_key: created.project_key, field: 'name', value: 'Denied' }], + ['rename_project', { working_dir: created.working_dir, name: 'Denied' }], + ['remove_project', { working_dir: created.working_dir }], + ]) { + assert.deepEqual(await call(tool, args), expected, tool); + } + assert.deepEqual(await fs.readdir(root), ['Demo']); + assert.equal(changes.length, beforePushes); + assert.deepEqual(await snapshot(), before); + const projects = await call('list_projects', {}); + assert.ok(projects.projects.some(item => item.working_dir === created.working_dir)); + assert.equal((await call('get_project_info', { project_key: created.project_key })).project.name, 'Updated'); + held = null; + }); + // §3.2 integration: the existing entry-held case has no native-confirmation await + // or project lock. A request admitted before either wait must leave every profile file intact. + const holdMessage = 'HOST_PROFILE_IN_USE_BY_DESKTOP: The desktop window is using this profile.'; + await t.test('HTTP project settings recheck profile hold after native confirmation', async () => { + const before = await snapshot(); + const beforePushes = changes.length; + const confirmation = Promise.withResolvers(); + const entered = Promise.withResolvers(); + const updateProjectInfo = createHostProjectInfoUpdate({ + profileHold, + changed: catalogChanged => changes.push(catalogChanged), + platform: () => ({ + status: () => ({ attached: true }), + call: async request => { + assert.equal(request.method, 'project.check'); + entered.resolve(); + return confirmation.promise; + }, + }), + }); + const invoke = createHostService({ profileHold, updateProjectInfo }); + const pending = invoke('/api/project-info/desktop-set', { requestId: 'fixture', input: { + ...getActiveDataOwnerPushStamp(), projectKey: created.project_key, + field: 'profile', value: { name: 'Denied', directories: [{ path: first, access: 'write' }] }, + } }, { caller: 'local-api:host' }); + const rejected = assert.rejects(pending, { code: 'PRECONDITION_FAILED', message: '[PRECONDITION_FAILED] ' + holdMessage }); + await Promise.race([entered.promise, rejected]); + held = holdMessage; + confirmation.resolve(true); + try { + await rejected; + } finally { + held = null; + } + assert.deepEqual(await snapshot(), before); + assert.equal(changes.length, beforePushes); + }); + await t.test('MCP project settings recheck profile hold inside the write lock', async t => { + const before = await snapshot(); + const beforePushes = changes.length; + const open = fs.open; + const lock = ownerScopedUserDataPath('project-info-write.lock'); + const mockedOpen = t.mock.method(fs, 'open', async (file, ...args) => { + const handle = await open(file, ...args); + if (file === lock && args[0] === 'wx') held = holdMessage; + return handle; + }); + try { + const result = await call('update_project_info', { project_key: created.project_key, field: 'name', value: 'Denied' }); + assert.equal(result.errorCode, 'PRECONDITION_FAILED'); + assert.equal(result.data.hint, holdMessage); + assert.equal(held, holdMessage); + } finally { + mockedOpen.mock.restore(); + held = null; + } + assert.deepEqual(await snapshot(), before); + assert.equal(changes.length, beforePushes); + }); current = false; const stale = await call('update_project_info', { project_key: created.project_key, field: 'name', value: 'Wrong owner' }); assert.equal(stale.ok, false); diff --git a/apps/host/src/ipc-route.mjs b/apps/host/src/ipc-route.mjs index 521642a4ecf..31555b3c928 100644 --- a/apps/host/src/ipc-route.mjs +++ b/apps/host/src/ipc-route.mjs @@ -32,12 +32,7 @@ import { hostIpcFingerprint, isHostIpcOwnerStamp, } from '@cindy/maker-shared/host-ipc-registry'; - -const CODED_ERROR = /^\[([A-Z][A-Z0-9_]*)\] ([\s\S]*)$/; -const STATUS_BY_CODE = { - INVALID_PARAMS: 400, PERMISSION_DENIED: 403, NOT_FOUND: 404, PRECONDITION_FAILED: 409, - OWNER_CHANGED: 409, UNSUPPORTED_CAPABILITY: 501, -}; +import { parseTypedError, typedErrorStatus } from './typed-error.mjs'; const reject = (status, code, message) => ({ status, body: { ok: false, error: { code, message } } }); @@ -50,9 +45,8 @@ const sameOwner = (a, b) => a.dataOwnerId === b.dataOwnerId && a.ownerGeneration /** Typed `[CODE] message` errors keep their contract; anything else is not serialised. */ function handlerFailure(error) { - const code = typeof error?.code === 'string' ? error.code : null; - const match = error instanceof Error ? CODED_ERROR.exec(error.message) : null; - if (code && match && match[1] === code) return reject(STATUS_BY_CODE[code] ?? 500, code, match[2]); + const typed = parseTypedError(error); + if (typed) return reject(typedErrorStatus(typed.code) ?? 500, typed.code, typed.message); return reject(500, 'INTERNAL', 'Host handler failed'); } diff --git a/apps/host/src/ipc-route.test.mjs b/apps/host/src/ipc-route.test.mjs index 6e21e1aa71e..b1d49c1a771 100644 --- a/apps/host/src/ipc-route.test.mjs +++ b/apps/host/src/ipc-route.test.mjs @@ -137,6 +137,26 @@ test('a read that straddles an account switch is dropped, and typed errors keep assert.deepEqual((await call('untyped')).body, { ok: false, error: { code: 'INTERNAL', message: 'Host handler failed' } }); }); +// Rule: a model change refused by the task's state is the caller's 409, as PRECONDITION_FAILED, +// never a server failure; the code and message keep their contract (typed-error.mjs, shared with the +// server's catch). Gap: these codes answered 500. A typed code outside the table keeps the 500 it had. +test('model-change refusals answer 409 with their code, and a typed code outside the table stays 500', { timeout: TEST_TIMEOUT_MS }, async t => { + const codes = ['CREDENTIAL_SWITCH_BUSY', 'MODEL_CONTEXT_USAGE_UNKNOWN', 'MODEL_SELECTION_UNAVAILABLE', + 'MODEL_SWITCH_TASK_RUNNING', 'MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN', 'MODEL_WINDOW_PREPARATION_IN_PROGRESS', + 'MODEL_WINDOW_PROTECTION_UNAVAILABLE', 'MODEL_WINDOW_REMOTE_REBUILD_UNSUPPORTED', 'MODEL_WINDOW_TARGET_CONTEXT_UNKNOWN']; + const route = createHostIpcRoute({ instanceId: 'host-a', readOwnerStamp: () => OWNER, unsupported: OTHERS, + bindings: { [CHANNEL]: async ([code]) => { throw Object.assign(new Error(`[${code}] refused for ${code}`), { code }); } } }); + const request = await serve(t, { ipcRoute: route }); + for (const code of codes) { + const answer = await request(hostIpcPath(CHANNEL), { headers: pinned(), body: { args: [code], owner: OWNER } }); + assert.equal(answer.status, 409, code); + assert.deepEqual(answer.body, { ok: false, error: { code, message: `refused for ${code}` } }); + } + const outside = await request(hostIpcPath(CHANNEL), { headers: pinned(), body: { args: ['NOT_IN_TABLE'], owner: OWNER } }); + assert.equal(outside.status, 500); + assert.deepEqual(outside.body, { ok: false, error: { code: 'NOT_IN_TABLE', message: 'refused for NOT_IN_TABLE' } }); +}); + test('manifest needs the bearer and the pin, lists bound entries, and an old Host answers 404', { timeout: TEST_TIMEOUT_MS }, async t => { const route = createHostIpcRoute({ instanceId: 'host-a', readOwnerStamp: () => OWNER, unsupported: OTHERS, bindings: { [CHANNEL]: () => [] } }); diff --git a/apps/host/src/loaders/raw-hook.mjs b/apps/host/src/loaders/raw-hook.mjs index 19169c940df..b16d73cd9fa 100644 --- a/apps/host/src/loaders/raw-hook.mjs +++ b/apps/host/src/loaders/raw-hook.mjs @@ -40,23 +40,23 @@ export async function resolve(specifier, context, nextResolve) { } export async function load(url, context, nextLoad) { - // tsx resolves a `?raw` import itself (this hook's resolve then sees the bare path) and puts the query back on the - // file URL it loads, e.g. Desktop's `page.html?raw` in cindy-brain/forge.ts; load that as raw text too. - const raw = url.startsWith('cindy-raw:') ? url.slice('cindy-raw:'.length) : /^file:[^?#]*\?raw$/.test(url) ? url.slice(0, -'?raw'.length) : null; - if (!raw) { - if (url.includes('/apps/desktop/') && /\.tsx?(?:\?|$)/.test(url)) { - const filename = fileURLToPath(url); - const source = await readFile(filename, 'utf8'); - const result = await transform(source, { loader: filename.endsWith('.tsx') ? 'tsx' : 'ts', format: 'esm', target: 'node22', sourcefile: filename, sourcemap: 'inline' }); - return { format: 'module', shortCircuit: true, source: result.code }; - } - return nextLoad(url, context); + const resolvedRaw = url.startsWith('cindy-raw:'); + const file = resolvedRaw ? new URL(url.slice('cindy-raw:'.length)) : new URL(url); + // tsx's synchronous resolve hook can remove the query before calling our resolve + // and restore it on the final file URL. At load time the original intent is visible. + if (file.protocol === 'file:' && (resolvedRaw || file.searchParams.has('raw') || file.pathname.endsWith('.md'))) { + const text = await readFile(file, 'utf8'); + return { format: 'module', shortCircuit: true, source: `export default ${JSON.stringify(text)};` }; + } + if (url.includes('/apps/desktop/') && /\.tsx?(?:\?|$)/.test(url)) { + const filename = fileURLToPath(url); + const source = await readFile(filename, 'utf8'); + const result = await transform(source, { loader: filename.endsWith('.tsx') ? 'tsx' : 'ts', format: 'esm', target: 'node22', sourcefile: filename, sourcemap: 'inline', + // The desktop modules' build region (shared/brandRegion.ts). A release bakes its --region here + // (scripts/build.mjs); from source it follows CINDY_HOST_REGION, global when unset, for development + // only, the same value profile-path.mjs resolveHostRegion answers. + define: { 'import.meta.env.VITE_CINDY_AUTH_REGION': 'process.env.CINDY_HOST_REGION' } }); + return { format: 'module', shortCircuit: true, source: result.code }; } - const filesystemPath = fileURLToPath(raw); - const text = await readFile(filesystemPath, 'utf8'); - return { - format: 'module', - shortCircuit: true, - source: `export default ${JSON.stringify(text)};`, - }; + return nextLoad(url, context); } diff --git a/apps/host/src/loaders/raw-hook.test.mjs b/apps/host/src/loaders/raw-hook.test.mjs index 6c8a6bff264..d6ef69a5ffe 100644 --- a/apps/host/src/loaders/raw-hook.test.mjs +++ b/apps/host/src/loaders/raw-hook.test.mjs @@ -29,3 +29,23 @@ test('raw asset imports preserve spaces, Unicode and URL delimiters through the assert.equal(stdout, text); } finally { await rm(root, { recursive: true, force: true }); } }); + +// Unit: the production tsx + Host loader chain must return text for a non-Markdown asset. +// Markdown alone also matches the extension fallback and misses the HTML import that stops serve. +test('the Host loader chain imports HTML with ?raw and plain Markdown as text', async () => { + const root = await mkdtemp(path.join(os.tmpdir(), 'host raw-')); + try { + const html = path.join(root, 'page.html'); + const markdown = path.join(root, 'prompt.md'); + await writeFile(html, '

example

\n'); + await writeFile(markdown, '# Example\n'); + const loader = new URL('./register-raw.mjs', import.meta.url).href; + const htmlUrl = pathToFileURL(html); + htmlUrl.search = 'raw'; + const script = `import html from ${JSON.stringify(htmlUrl.href)}; + import md from ${JSON.stringify(pathToFileURL(markdown).href)}; + process.stdout.write(JSON.stringify([html, md]));`; + const { stdout } = await exec(process.execPath, ['--import', 'tsx', '--import', loader, '--input-type=module', '-e', script]); + assert.deepEqual(JSON.parse(stdout), ['

example

\n', '# Example\n']); + } finally { await rm(root, { recursive: true, force: true }); } +}); diff --git a/apps/host/src/loaders/test-region.mjs b/apps/host/src/loaders/test-region.mjs new file mode 100644 index 00000000000..9188b6f4c94 --- /dev/null +++ b/apps/host/src/loaders/test-region.mjs @@ -0,0 +1,7 @@ +// Host tests run as the source default edition (global) whatever the machine's shell carries. From +// source the desktop modules' region follows CINDY_HOST_REGION (raw-hook.mjs) and so does +// profile-path.mjs resolveHostRegion; VITE_CINDY_AUTH_REGION is a desktop build variable that some +// shells inherit. A test of another edition passes CINDY_HOST_REGION to its own child process. +// Imported by the test command (package.json "test"); node --test hands it to every test file's process. +delete process.env.CINDY_HOST_REGION; +delete process.env.VITE_CINDY_AUTH_REGION; diff --git a/apps/host/src/login-cli.mjs b/apps/host/src/login-cli.mjs index 1cd2ca1353a..4c53e5af6c0 100644 --- a/apps/host/src/login-cli.mjs +++ b/apps/host/src/login-cli.mjs @@ -8,6 +8,7 @@ import { getOrCreateHostDeviceId } from './auth/device-identity.mjs'; */ import { spawn } from 'node:child_process'; +import path from 'node:path'; @@ -15,9 +16,51 @@ import { CindyAuthClient } from '@cindy/auth-client'; import { readAuthEndpoints } from './auth/endpoints.mjs'; import { runHostLogin } from './auth/login.mjs'; +import { hostPackageRegion } from './auth/region-policy.ts'; +import { AUTH_SESSION_KEY } from '../../desktop/src/main/authCredentialKeys.ts'; +import { isGhostSkillProjectionBoundaryStableForOwner, readGhostSkillProjectionBoundaryState, withGhostSkillProjectionOwnerCommit } from '../../desktop/src/main/authBoundaryQuarantine.ts'; +import { withCrossProcessLock } from '../../desktop/src/main/device-link/crossProcessLock.ts'; +import { AUTH_ACCOUNT_VAULT_LOCK_FILE } from '../../desktop/src/main/authRefreshCommit.ts'; +import { configureAppDataDir, configureUserDataDir } from '../../desktop/src/main/userDataPath.ts'; +import { createDesktopScanner } from './agent/profile-coexistence.ts'; +import { allowSkillProjectionOwnerCommit, commitLoginSessionAndOwner } from './agent/skill-projection-owner.ts'; +import { discoverHostOwner, resolveHostAppDataDir } from './profile-path.mjs'; import { restoreDeviceLinkRegistration } from './auth/device-link-registration.mjs'; import { createCredentialStore } from './credentials/store.mjs'; import { resolveHostDataDir, resolveHostRegion } from './profile-path.mjs'; + +/** + * Coexistence plan A for the login (release table row 25, 25b condition 1): a desktop that opens this + * profile's database must not run while the login publishes the projection owner. An unreadable + * registry refuses too, as the scan does, and says why. + */ +export async function assertNoDesktopOnProfile(scan) { + let pids; + try { pids = await scan(); } + catch (error) { + throw new Error(`Cannot tell whether the Cindy desktop app is using this profile (${error instanceof Error ? error.message : String(error)}); ` + + 'sign-in is refused until it can be checked.'); + } + if (pids.length > 0) throw new Error('Quit the Cindy desktop app that is using this profile, then run cindy-host login again.'); +} + +/** + * Whether a running serve allows this login (25b condition A). Without an account runtime any + * account may sign in (nothing to tear down); with account A's runtime, only A may sign in again: + * replacing A requires its runtime stopped (its Skill projections and Pi Subagents are swept then). + * Returns the account check to run once the exchange names the account. + */ +export function serveLoginAdmission(status) { + if (status.running === false) return () => {}; + if (status.running !== true) throw new Error('Cindy Host is not responding. Stop it before changing its sign-in, then start it again.'); + const owner = status.runtime?.owner ?? null; + if (!owner) return () => {}; + return (membership) => { + if (membership?.id !== owner) { + throw new Error('Cindy Host is running another account. Stop it (cindy-host stop), sign in, then start it again.'); + } + }; +} import { hostAuthFetch } from './auth-fetch.mjs'; import { hostRuntimeLayout } from './runtime-layout.mjs'; @@ -53,21 +96,29 @@ export async function runLoginCommand(argv, io = {}) { const endpoints = readAuthEndpoints(region); const userDataDir = resolveHostDataDir(); - const running = await readHostProcessStatus(userDataDir); - if (running.running !== false) throw new Error('Stop Cindy Host before changing its sign-in, then start it again.'); - const store = await createCredentialStore({ + const deps = io.deps ?? {}; + const running = await (deps.readStatus ?? readHostProcessStatus)(userDataDir); + const admitAccount = serveLoginAdmission(running); + await assertNoDesktopOnProfile(deps.scanDesktops ?? createDesktopScanner(userDataDir)); + // This process is the one that publishes the Skill projection owner of a Host's own profile. + configureUserDataDir(userDataDir); + configureAppDataDir(resolveHostAppDataDir()); + allowSkillProjectionOwnerCommit(); + const store = deps.store ?? await createCredentialStore({ userDataDir, keyringApplication: process.env.CINDY_HOST_KEYRING_APPLICATION?.trim() || undefined, }); const deviceId = getOrCreateHostDeviceId(userDataDir); - const client = new CindyAuthClient({ + const clientOptions = { baseUrl: endpoints.authApiBaseUrl, region, deviceId, clientType: 'desktop', fetch: (input, init) => hostAuthFetch(input, init), - }); + }; + // Tests replace the transport only (their fake auth servers listen on plain loopback HTTP). + const client = deps.createAuthClient ? deps.createAuthClient(clientOptions) : new CindyAuthClient(clientOptions); const noOpen = argv.includes('--no-open') || (process.platform === 'linux' && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY); out(noOpen ? 'Open the following Cindy login page on a device with a browser.' : 'Opening the Cindy login page in your browser…'); @@ -76,6 +127,32 @@ export async function runLoginCommand(argv, io = {}) { deviceId, store, region, + packageRegion: hostPackageRegion(), + warn: err, + admitAccount, + persistSession: async (record, membership) => { + // The browser step can take minutes: check the desktop and serve again right before committing. + await assertNoDesktopOnProfile(deps.scanDesktops ?? createDesktopScanner(userDataDir)); + const now = await (deps.readStatus ?? readHostProcessStatus)(userDataDir); + serveLoginAdmission(now)(membership); + // A running serve's sessions use the current projections: a transition would revoke them under + // it, and serve cannot project them again. Only a boundary already stable for this account may + // be committed while serve runs; otherwise serve must stop first. + if (now.running === true && now.runtime?.owner && !isGhostSkillProjectionBoundaryStableForOwner(membership.id)) { + throw new Error('Stop Cindy Host (cindy-host stop), run cindy-host login again, then start it: this sign-in needs to set up the account\'s Skills.'); + } + const stable = readGhostSkillProjectionBoundaryState(); + const previousOwnerId = stable?.phase === 'stable' ? stable.ownerId : discoverHostOwner(userDataDir).ownerId; + await commitLoginSessionAndOwner({ + userDataDir, record, nextOwnerId: membership.id, store, sessionKey: AUTH_SESSION_KEY, previousOwnerId, + withVaultLock: (task) => withCrossProcessLock(path.join(userDataDir, AUTH_ACCOUNT_VAULT_LOCK_FILE), + { label: 'auth-account-vault', waitMs: 5000 }, async (lock) => { + if (!lock.held) throw new Error('Saved account credentials are busy; retry cindy-host login'); + return task(); + }), + commitOwner: (options) => withGhostSkillProjectionOwnerCommit(options), + }); + }, hostedCallbackUrl: endpoints.authDesktopCallbackUrl, openBrowser: async (url) => { out(`If it does not open, visit:\n${url}`); @@ -100,6 +177,11 @@ export async function runLoginCommand(argv, io = {}) { }, }); out(`Signed in (${result.realm}). Cindy host will reuse this login on restart.`); + // serve keeps its current session until it restarts (it does not adopt a new one while running). + if (running.running === true) { + out('This sign-in takes effect after Cindy Host restarts. As a systemd user service (docs/host/systemd.md): ' + + 'systemctl --user restart cindy-host. Otherwise: cindy-host stop, then start cindy-host again.'); + } if (process.env.CINDY_HOST_DATA_DIR?.trim()) { err(`Profile: ${userDataDir}`); } diff --git a/apps/host/src/macos-system-proxy.test.mjs b/apps/host/src/macos-system-proxy.test.mjs new file mode 100644 index 00000000000..90c4a01b36c --- /dev/null +++ b/apps/host/src/macos-system-proxy.test.mjs @@ -0,0 +1,302 @@ +/* + * 测试价值(放行表第 28 行 28b,第七节第 26 项“macOS 静态系统代理”) + * - 生产入口与可观察结果:Host 的出站代理解析器 resolveHostOutboundProxy(outbound-proxy.ts,Host 所有出站请求都经它) + * 在读 macOS 系统代理设置时(useHostSystemProxySettings,生产绑 /usr/sbin/scutil --proxy,这里注入固定的 + * scutil 输出)给每个上游的代理地址,它记下的出站路径判定(getHostOutboundPathSnapshotFor),以及写进 + * 真实日志文件(initLogger 指向临时目录)的内容。 + * - 规则依据:Chromium 148(Electron 42.11.12)读同一份字典后的处理——proxy_config_service_mac.cc(读哪些键)、 + * proxy_chain_util_apple.cc(HTTPS 项仍是 HTTP 代理、SOCKS 为 v5、缺端口用默认端口、缺主机忽略该项)、 + * proxy_config.cc ProxyRules::Apply(按 scheme 选、回落到 SOCKS)、proxy_host_matching_rules.cc 与 + * scheme_host_port_matcher_rule.cc(例外规则、后写的规则优先、隐式例外)、url_canon_ip.h(`169.254` 即 + * 169.0.0.254)、base/strings/pattern.cc(`?` 匹配零或一个字符)。审核方 2026-11-17 定:PAC 拒绝并记 + * unknown;只开自动发现时用手动设置并记一条 warn;带用户名的系统代理按 unknown;读设置这层缓存 5 秒、 + * 并发合并,最长 35 秒生效;不记原始输出。 + * - 现有覆盖缺口:outbound-proxy.test.mjs 只覆盖代理环境变量与“不读系统代理”;Host 原来没有读系统代理的代码。 + * - 最小失败输入:HTTPS 项写成 `HTTPS host:port`(核心会当作用不了、直连);去掉隐式例外;忽略 `*User` 键; + * 把 scutil 的一行或用户名放进错误信息;缓存去掉或不合并并发。 + * - tier:unit(不起进程、不连网、不执行 scutil;Date 用 mock 计时器推进,日志写临时目录)。 + * - 实测耗时:见 PR(单独运行本文件)。 + */ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test, { mock } from 'node:test'; + +import { initLogger } from '../../desktop/src/main/logger.ts'; +import { getHostOutboundPathSnapshotFor, resolveHostOutboundProxy, useHostSystemProxySettings } from './outbound-proxy.ts'; + +const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy']; +const savedEnv = Object.fromEntries([...PROXY_ENV_KEYS, 'LOG_LEVEL'].map(key => [key, process.env[key]])); +for (const key of PROXY_ENV_KEYS) delete process.env[key]; +process.env.LOG_LEVEL = 'info'; +const logDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-system-proxy-logs-')); +initLogger({ isPackaged: true, logDir }); +// Only Date: the resolver core's 30 s cache, its 5 s unresolved cache and the settings' 5 s cache all read it. +mock.timers.enable({ apis: ['Date'], now: Date.now() }); +test.after(() => { + mock.timers.reset(); + useHostSystemProxySettings(null); + for (const [key, value] of Object.entries(savedEnv)) if (value === undefined) delete process.env[key]; else process.env[key] = value; + fs.rmSync(logDir, { recursive: true, force: true }); +}); + +/** scutil --proxy's text for a dictionary (SCPrint: `Key : value`, arrays as `N : item`). */ +function scutil(entries) { + const lines = [' {']; + for (const [key, value] of Object.entries(entries)) { + if (Array.isArray(value)) { + lines.push(` ${key} : {`, ...value.map((item, i) => ` ${i} : ${item}`), ' }'); + } else { + lines.push(` ${key} : ${value}`); + } + } + return `${lines.join('\n')}\n}\n`; +} + +const HTTP = { HTTPEnable: 1, HTTPProxy: '10.0.0.1', HTTPPort: 3128 }; +const HTTPS = { HTTPSEnable: 1, HTTPSProxy: '10.0.0.2', HTTPSPort: 3129 }; +const SOCKS = { SOCKSEnable: 1, SOCKSProxy: '10.0.0.3', SOCKSPort: 1081 }; +const VIA_HTTP = 'http://10.0.0.1:3128'; +const VIA_HTTPS = 'http://10.0.0.2:3129'; +const VIA_SOCKS = 'socks5://10.0.0.3:1081'; + +/** Resolves one upstream with fresh caches under the given scutil output; returns the forwarding address. */ +async function resolveUnder(output, upstream) { + mock.timers.tick(40_000); + useHostSystemProxySettings(async () => output); + return resolveHostOutboundProxy(upstream); +} + +function snapshotOf(upstream) { + const snapshot = getHostOutboundPathSnapshotFor([upstream]); + assert.ok(snapshot, `a judgement for ${upstream}`); + const { at: _at, ...rest } = snapshot; + return rest; +} + +/** The text of every main log file the logger has written, once it contains `expected`. */ +async function logsContaining(expected) { + let text = ''; + for (let i = 0; i < 5000 && !text.includes(expected); i += 1) { + await new Promise(resolve => setImmediate(resolve)); + text = fs.readdirSync(logDir).filter(name => name.startsWith('main-')).map(name => fs.readFileSync(path.join(logDir, name), 'utf8')).join(''); + } + assert.ok(text.includes(expected), `the log has "${expected}"`); + return text; +} + +// [name, settings, upstream, forwarding address (null: direct), Chromium 148 source] +const MANUAL_ROWS = [ + ['no proxy enabled', {}, 'https://api.example.test/', null, 'proxy_config.cc ProxyRules::Apply: empty rules'], + ['HTTP only: http upstream', HTTP, 'http://api.example.test/', VIA_HTTP, 'proxies_for_http'], + ['HTTP only: https upstream goes direct', HTTP, 'https://api.example.test/', null, 'MapUrlSchemeToProxyList: no https list, no fallback'], + ['HTTPS only: the HTTPS proxy is an HTTP proxy', HTTPS, 'https://api.example.test/', VIA_HTTPS, 'proxy_chain_util_apple.cc kCFProxyTypeHTTPS → SCHEME_HTTP'], + ['HTTPS only: http upstream goes direct', HTTPS, 'http://api.example.test/', null, 'MapUrlSchemeToProxyList'], + ['SOCKS only covers http', SOCKS, 'http://api.example.test/', VIA_SOCKS, 'fallback_proxies, SOCKS5'], + ['SOCKS only covers https', SOCKS, 'https://api.example.test/', VIA_SOCKS, 'fallback_proxies, SOCKS5'], + ['HTTP + SOCKS: https falls back to SOCKS', { ...HTTP, ...SOCKS }, 'https://api.example.test/', VIA_SOCKS, 'MapUrlSchemeToProxyList fallback'], + ['HTTPS + SOCKS: http falls back to SOCKS', { ...HTTPS, ...SOCKS }, 'http://api.example.test/', VIA_SOCKS, 'MapUrlSchemeToProxyList fallback'], + ['all three: http', { ...HTTP, ...HTTPS, ...SOCKS }, 'http://api.example.test/', VIA_HTTP, 'per-scheme list first'], + ['all three: https', { ...HTTP, ...HTTPS, ...SOCKS }, 'https://api.example.test/', VIA_HTTPS, 'per-scheme list first'], + ['wss: SOCKS, then HTTPS, then HTTP', { ...HTTP, ...HTTPS }, 'wss://api.example.test/', VIA_HTTPS, 'GetProxyListForWebSocketScheme'], + ['missing HTTPS port: 80', { HTTPSEnable: 1, HTTPSProxy: '10.0.0.2' }, 'https://api.example.test/', 'http://10.0.0.2:80', 'GetDefaultPortForScheme(SCHEME_HTTP)'], + ['missing SOCKS port: 1080', { SOCKSEnable: 1, SOCKSProxy: '10.0.0.3' }, 'https://api.example.test/', 'socks5://10.0.0.3:1080', 'GetDefaultPortForScheme(SCHEME_SOCKS5)'], + ['enabled without a host: ignored', { HTTPSEnable: 1, HTTPSPort: 3129 }, 'https://api.example.test/', null, 'ProxyDictionaryToProxyChain: no host key'], + ['an empty host: ignored', { HTTPSEnable: 1, HTTPSProxy: '', HTTPSPort: 3129 }, 'https://api.example.test/', null, 'ProxyServer::FromSchemeHostAndPort: empty host'], + ['not enabled: ignored', { HTTPSEnable: 0, HTTPSProxy: '10.0.0.2', HTTPSPort: 3129 }, 'https://api.example.test/', null, 'GetBoolFromDictionary'], + ['host canonicalised', { HTTPSEnable: 1, HTTPSProxy: 'Proxy.Corp.EXAMPLE', HTTPSPort: 8080 }, 'https://api.example.test/', 'http://proxy.corp.example:8080', 'url::CanonicalizeHost'], + ['IPv6 proxy host bracketed', { HTTPSEnable: 1, HTTPSProxy: 'fd00::1', HTTPSPort: 8080 }, 'https://api.example.test/', 'http://[fd00::1]:8080', 'FromSchemeHostAndPort adds brackets'], + ['a host that fails canonicalisation: ignored', { HTTPSEnable: 1, HTTPSProxy: 'proxy:8080', HTTPSPort: 3129, ...SOCKS }, 'https://api.example.test/', VIA_SOCKS, 'FromSchemeHostAndPort: CanonicalizeHost fails'], + ['a port that is not a number: the default', { ...HTTPS, HTTPSPort: 'abc' }, 'https://api.example.test/', 'http://10.0.0.2:80', 'GetValueFromDictionary: other types read as missing'], + ['an Enable that is not a number: off', { ...HTTPS, HTTPSEnable: 'TRUE' }, 'https://api.example.test/', null, 'GetBoolFromDictionary: default false'], + ['ExceptionsList that is not an array: none', { ...HTTPS, ExceptionsList: 'api.example.test' }, 'https://api.example.test/', VIA_HTTPS, 'GetValueFromDictionary'], + ['a blank user names no one', { ...HTTPS, HTTPSUser: '' }, 'https://api.example.test/', VIA_HTTPS, 'no user to authenticate with'], +]; + +test('manual proxies give the address Chromium gives for each setting', async t => { + for (const [name, settings, upstream, expected, source] of MANUAL_ROWS) { + await t.test(name, async () => assert.equal(await resolveUnder(scutil(settings), upstream), expected, source)); + } + assert.equal(await resolveUnder('No proxy configuration available\n', 'https://none.example.test/'), null); + assert.deepEqual(snapshotOf('https://none.example.test/'), { source: 'system', kind: 'direct', upstream: 'https://none.example.test' }); + await resolveUnder(scutil(HTTPS), 'https://proxied.example.test/v1'); + assert.deepEqual(snapshotOf('https://proxied.example.test'), { source: 'system', kind: 'proxy', proxy: VIA_HTTPS, upstream: 'https://proxied.example.test' }); +}); + +// [name, ExceptionsList (or settings), upstream, bypassed] +const BYPASS_ROWS = [ + ['a host name matches only itself', ['example.com'], 'https://example.com/', true], + ['a host name does not match its subdomains', ['example.com'], 'https://www.example.com/', false], + ['*.domain matches subdomains', ['*.example.com'], 'https://www.example.com/', true], + ['*.domain does not match the domain', ['*.example.com'], 'https://example.com/', false], + ['.domain is *.domain', ['.example.com'], 'https://www.example.com/', true], + ['host:port needs that port', ['example.com:8443'], 'https://example.com:8443/', true], + ['host:port, other port', ['example.com:8443'], 'https://example.com/', false], + ['scheme://host only for that scheme', ['http://example.com'], 'https://example.com/', false], + ['scheme://host, same scheme', ['http://example.com'], 'http://example.com/', true], + ['rules are lower-cased', ['EXAMPLE.COM'], 'https://example.com/', true], + ['? matches zero characters', ['ex?mple.com'], 'https://exmple.com/', true], + ['? matches one character', ['ex?mple.com'], 'https://example.com/', true], + ['? does not match two', ['ex?mple.com'], 'https://exaample.com/', false], + ['an IP literal', ['10.1.2.3'], 'https://10.1.2.3/', true], + ['an IP literal, other address', ['10.1.2.3'], 'https://10.1.2.4/', false], + ['a bracketed IPv6 literal', ['[fd00::5]'], 'https://[fd00::5]/', true], + ['an IPv4 block', ['10.0.0.0/8'], 'https://10.9.9.9/', true], + ['an IPv4 block does not match host names', ['10.0.0.0/8'], 'https://ten.example.test/', false], + ['an IPv6 block', ['fd00::/8'], 'https://[fd12::1]/', true], + ['169.254/16 is 169.0.0.254/16 (url_canon_ip.h)', ['169.254/16'], 'https://169.0.3.4/', true], + ['169.254/16 does not cover 169.1.x.x', ['169.254/16'], 'https://169.1.0.1/', false], + ['a path is no rule: dropped', ['example.com/path'], 'https://example.com/', false], + ['a hostname rule is split at semicolons when Chromium copies it', ['a.example.com; b.example.com'], 'https://b.example.com/', true], + ['an invalid port drops the item before Chromium copies it', ['a.example.com, b.example.com:bad'], 'https://a.example.com/', false], + ['the macOS default list', ['*.local', '169.254/16'], 'https://printer.local/', true], + ['<-loopback> removes the implicit rules', ['<-loopback>'], 'https://localhost/', false], + ['a later rule overrides an earlier one', ['localhost', '<-loopback>'], 'https://localhost/', false], + ['an earlier rule loses to a later one', ['<-loopback>', 'localhost'], 'https://localhost/', true], + ['simple host names, when excluded', { ExcludeSimpleHostnames: 1 }, 'https://intranet/', true], + ['simple host names: dotted names still proxied', { ExcludeSimpleHostnames: 1 }, 'https://intranet.corp/', false], + ['simple host names: an IP is not one', { ExcludeSimpleHostnames: 1 }, 'https://10.0.0.9/', false], + ['simple host names: a listed rule overrides ', { ExcludeSimpleHostnames: 1, ExceptionsList: ['<-loopback>'] }, 'https://localhost/', false], +]; + +// Implicit rules: Chromium 148 on macOS (proxy_host_matching_rules.cc MatchesImplicitRules); no 0.0.0.0 rule yet. +const IMPLICIT_ROWS = [ + ['localhost', 'https://localhost/', true], + ['*.localhost', 'https://foo.localhost/', true], + ['127/8', 'https://127.0.0.5/', true], + ['[::1]', 'https://[::1]/', true], + ['[::ffff:127.0.0.1]', 'https://[::ffff:127.0.0.1]/', true], + ['169.254/16', 'https://169.254.1.1/', true], + ['[::ffff:169.254.1.1]', 'https://[::ffff:169.254.1.1]/', true], + ['[fe80::]/10', 'https://[fe80::1]/', true], + ['169.255.x.x is not link-local', 'https://169.255.0.1/', false], + ['0.0.0.0 is not bypassed in 148', 'https://0.0.0.0/', false], +]; + +test('exceptions and the implicit rules bypass the proxy as in Chromium', async t => { + for (const [name, rules, upstream, bypassed] of BYPASS_ROWS) { + const settings = Array.isArray(rules) ? { ...HTTP, ...HTTPS, ExceptionsList: rules } : { ...HTTP, ...HTTPS, ...rules }; + const proxied = upstream.startsWith('https:') ? VIA_HTTPS : VIA_HTTP; + await t.test(name, async () => assert.equal(await resolveUnder(scutil(settings), upstream), bypassed ? null : proxied)); + } + for (const [name, upstream, bypassed] of IMPLICIT_ROWS) { + await t.test(`implicit: ${name}`, async () => assert.equal(await resolveUnder(scutil(HTTPS), upstream), bypassed ? null : VIA_HTTPS)); + } +}); + +// Entry/result: the Host outbound resolver reads the captured scutil dictionary and selects DIRECT. +// Rule: #11536 macOS proxy comparison, exceptions row for a.example.com; Chromium splits the +// serialized rule when copying the proxy config. Gap: the old comma case expected a proxy. +// Minimal input: one ExceptionsList entry containing both names. Tier: unit with injected +// scutil output and the production resolver; no system settings or network requests. +// Measured: 0.43 s for this file (node:test, Node 22.22.3). +test('macOS proxy bypass matches both names in the captured CI exception', async () => { + const output = scutil({ + ExceptionsList: ['*.local', '169.254/16', 'example.com:8443', '10.0.0.0/8', 'ex?mple.com', + 'https://www.example.com', 'a.example.com, b.example.com', 'fd00::/8'], + FTPPassive: 1, + ...HTTP, + ...HTTPS, + ProxyAutoConfigEnable: 0, + ProxyAutoDiscoveryEnable: 0, + SOCKSEnable: 0, + }); + + assert.equal(await resolveUnder(output, 'https://a.example.com/'), null); + assert.equal(snapshotOf('https://a.example.com/').kind, 'direct'); + assert.equal(await resolveUnder(output, 'https://b.example.com/'), null); + assert.equal(await resolveUnder(output, 'https://intranet.corp/'), VIA_HTTPS); +}); + +test('without the Chromium proxy helper, PAC is unresolved, direct, with a warn; auto-discovery alone uses the manual settings', async () => { + const PAC = { ProxyAutoConfigEnable: 1, ProxyAutoConfigURLString: 'http://pac.example.test/proxy.pac' }; + assert.equal(await resolveUnder(scutil({ ...PAC, ...HTTPS }), 'https://pac.example.test/'), null); + assert.deepEqual(snapshotOf('https://pac.example.test'), { source: 'system', kind: 'unknown', reason: 'resolve_failed', upstream: 'https://pac.example.test' }); + assert.equal(await resolveUnder(scutil({ ...PAC, ProxyAutoDiscoveryEnable: 1, ...HTTPS }), 'https://pac-wpad.example.test/'), null); + assert.equal(snapshotOf('https://pac-wpad.example.test').kind, 'unknown'); + await logsContaining('proxy auto-config (PAC) URL, and the Chromium proxy helper had no answer'); + // Enabled without a URL, or with one that is not a valid URL: Chromium has no PAC URL (has_pac_url) and + // uses the manual settings. + assert.equal(await resolveUnder(scutil({ ProxyAutoConfigEnable: 1, ...HTTPS }), 'https://pac-no-url.example.test/'), VIA_HTTPS); + assert.equal(await resolveUnder(scutil({ ProxyAutoConfigEnable: 1, ProxyAutoConfigURLString: 'proxy.pac', ...HTTPS }), 'https://pac-bad-url.example.test/'), VIA_HTTPS); + + // Auto-discovery without a PAC URL: the manual settings, and one warn for as long as it stays on. + const reads = []; + useHostSystemProxySettings(async () => { reads.push(1); return scutil({ ProxyAutoDiscoveryEnable: 1, ...HTTPS }); }); + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy('https://wpad-1.example.test/'), VIA_HTTPS); + mock.timers.tick(6_000); + assert.equal(await resolveHostOutboundProxy('https://wpad-2.example.test/'), VIA_HTTPS); + assert.equal(reads.length, 2, 'two readings of the settings'); + const text = await logsContaining('auto-discovery (WPAD) is not tried on the Host'); + assert.equal(text.split('auto-discovery (WPAD) is not tried on the Host').length - 1, 1, 'one warn while it stays on'); + assert.equal(await resolveUnder(scutil({ ProxyAutoDiscoveryEnable: 1 }), 'https://wpad-only.example.test/'), null); +}); + +test('settings the Host cannot use are unresolved, not guessed, and a failed reading is not kept', async () => { + for (const [name, output] of [ + ['unreadable output', 'HTTPSEnable = 1\n'], + ['a port out of range', scutil({ ...HTTPS, HTTPSPort: 70000 })], + ['a host that is not a host', scutil({ ...HTTPS, HTTPSProxy: 'proxy.example/path' })], + ['an unclosed dictionary', ' {\n HTTPSEnable : 1\n'], + ]) { + const upstream = `https://${name.replaceAll(' ', '-')}.example.test/`; + assert.equal(await resolveUnder(output, upstream), null, name); + assert.deepEqual(snapshotOf(upstream), { source: 'system', kind: 'unknown', reason: 'resolve_failed', upstream: new URL(upstream).origin }, name); + } + // A reading that fails, then one that works: the next request after the core's 5 s reads again. + let fail = true; + useHostSystemProxySettings(async () => { if (fail) throw new Error('scutil --proxy failed (ETIMEDOUT)'); return scutil(HTTPS); }); + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy('https://retry.example.test/'), null); + fail = false; + mock.timers.tick(5_001); + assert.equal(await resolveHostOutboundProxy('https://retry.example.test/'), VIA_HTTPS); +}); + +test('one reading serves 5 s and concurrent requests; a change takes effect within 35 s', async () => { + let output = scutil(HTTPS); + let reads = 0; + useHostSystemProxySettings(async () => { reads += 1; return output; }); + mock.timers.tick(40_000); + assert.deepEqual(await Promise.all(['https://c1.example.test/', 'https://c2.example.test/'].map(url => resolveHostOutboundProxy(url))), [VIA_HTTPS, VIA_HTTPS]); + assert.equal(reads, 1, 'concurrent requests share one reading'); + output = scutil({}); + mock.timers.tick(4_999); + // Not yet re-read: a new upstream still gets the old settings, and the core keeps that verdict 30 s. + assert.equal(await resolveHostOutboundProxy('https://c3.example.test/'), VIA_HTTPS); + assert.equal(reads, 1); + mock.timers.tick(29_999); + assert.equal(await resolveHostOutboundProxy('https://c3.example.test/'), VIA_HTTPS, 'still cached at 34.998 s after the change'); + mock.timers.tick(2); + assert.equal(await resolveHostOutboundProxy('https://c3.example.test/'), null, 'the new settings by 35 s'); + assert.equal(reads, 2); +}); + +test('proxy environment variables come first: the system settings are not read', async t => { + let reads = 0; + useHostSystemProxySettings(async () => { reads += 1; return scutil(HTTPS); }); + process.env.HTTPS_PROXY = 'http://127.0.0.1:7890'; + t.after(() => { delete process.env.HTTPS_PROXY; }); + mock.timers.tick(40_000); + assert.equal(await resolveHostOutboundProxy('https://env-first.example.test/'), 'http://127.0.0.1:7890'); + assert.equal(reads, 0); +}); + +test('a proxy that names a user is unresolved, and the user is in no log or judgement', async () => { + const USER = 'proxy-user-fixture-28b'; + const output = scutil({ ...HTTP, HTTPUser: USER, ...HTTPS, HTTPSUser: USER, SOCKSEnable: 0, SOCKSUser: USER }); + assert.equal(await resolveUnder(output, 'https://auth.example.test/'), null, 'the HTTPS proxy names a user'); + assert.deepEqual(snapshotOf('https://auth.example.test'), { source: 'system', kind: 'unknown', reason: 'resolve_failed', upstream: 'https://auth.example.test' }); + // Only the proxy that the request would use matters. + assert.equal(await resolveUnder(scutil({ ...HTTP, ...HTTPS, HTTPSUser: USER }), 'http://auth-other.example.test/'), VIA_HTTP); + // An unreadable line that carries the user: the error names the line, not its text. + assert.equal(await resolveUnder(` {\n HTTPSUser = ${USER}\n}\n`, 'https://auth-unreadable.example.test/'), null); + const text = await logsContaining('requires authentication; its password is in the keychain'); + await logsContaining('unrecognised scutil --proxy output (line 2)'); + assert.ok(!text.includes(USER) && !(await logsContaining('line 2')).includes(USER), 'no log line has the user'); + for (const upstream of ['https://auth.example.test', 'http://auth-other.example.test', 'https://auth-unreadable.example.test']) { + assert.ok(!JSON.stringify(getHostOutboundPathSnapshotFor([upstream])).includes(USER), `no judgement for ${upstream} has the user`); + } +}); diff --git a/apps/host/src/macos-system-proxy.ts b/apps/host/src/macos-system-proxy.ts new file mode 100644 index 00000000000..1dbd4c56be9 --- /dev/null +++ b/apps/host/src/macos-system-proxy.ts @@ -0,0 +1,613 @@ +/** + * macOS static system proxy settings for the Host (release table row 28, 28b). + * + * The desktop asks Chromium (`session.defaultSession.resolveProxy`), which reads + * `SCDynamicStoreCopyProxies(NULL)` and applies the proxy rules per URL. The Host has no Chromium: + * it reads the same dictionary through `scutil --proxy` (Apple configd: `SCDynamicStoreCopyProxies(NULL)`, + * printed with SCPrint after dropping `__SCOPED__`, `__SERVICES__` and `__SUPPLEMENTAL__`) and applies + * Chromium 148's rules (Electron 42.11.12) itself, giving the same PAC result string + * (`PROXY host:port`, `SOCKS5 host:port`, `DIRECT`) to the shared resolver core. Sources, by the + * Chromium file each rule comes from, are cited where the rule is implemented; the macOS CI + * comparison (`.github/workflows/macos-system-proxy-compare.yml`) checks them against Electron. + * + * PAC and auto-discovery (28c): when the settings use either and the Chromium proxy helper is given + * (chromium-proxy.ts, macOS releases carry its Electron), Chromium answers, exactly as for the desktop. Only + * when the helper has no answer in time (starting, restarting, missing) does the Host fall back to what + * follows, the static reading (28b). + * + * What the Host does not do, and reports as an unresolved path (the resolver core's `resolve_failed`: + * direct, a warn, `unknown` in the path snapshot) instead of guessing: + * - a PAC URL without an answer from the Chromium proxy helper; + * - a proxy whose settings name a user (`HTTPUser`, `HTTPSUser`, `SOCKSUser`, macOS 15 and later): its + * password is in the keychain, which the Host never reads; a user name without its password is not + * used; + * - output it cannot read with certainty. + * Auto-discovery (WPAD) without a PAC URL: Chromium tries `http://wpad/wpad.dat` first and falls back to + * the manual settings when that fails (`pac_file_decider.cc` `BuildPacSourcesFallbackList`, + * `configured_proxy_resolution_service.cc` `OnInitProxyResolverComplete`); the Host uses the manual + * settings directly and logs once that it did not try auto-discovery. + * + * Neither the scutil output nor any value in it is logged or kept: errors name a line number only, + * and the parsed settings hold whether a user is set, never the user. + */ +import { execFile } from 'node:child_process'; + +import { createMakerLogger } from '../../desktop/src/main/maker-host/logger-adapter.ts'; + +const log = createMakerLogger('outbound-proxy'); + +/** + * The Electron release whose Chromium these rules follow (Chromium 148.0.7778.280). A guard test + * (hostDesktopSourceContracts.guard.test.ts) fails when apps/desktop/package.json moves to another + * Electron: whoever upgrades updates this constant, which changes this file and so runs the macOS + * system proxy comparison (.github/workflows/macos-system-proxy-compare.yml) on that pull request. + */ +export const CHROMIUM_RULES_ELECTRON_VERSION = '42.11.12'; + +/** The system's own scutil, by absolute path: never looked up on PATH, where a same-named program could stand in. */ +const SCUTIL_PATH = '/usr/sbin/scutil'; +const SCUTIL_TIMEOUT_MS = 1000; +const SCUTIL_MAX_OUTPUT_BYTES = 64 * 1024; +/** + * How long one reading of the settings serves every request. With the resolver core's 30 s cache per + * upstream, a change takes effect within 35 s (the desktop: 30 s; Chromium itself follows changes at once). + */ +const SYSTEM_PROXY_SETTINGS_TTL_MS = 5000; + +/** One enabled manual proxy, as Chromium keeps it: canonical host (IPv6 in brackets) and port. */ +interface ManualProxy { + /** How Chromium's PAC result names it: the macOS HTTPS proxy is still an HTTP proxy (`proxy_chain_util_apple.cc`). */ + pacScheme: 'PROXY' | 'SOCKS5'; + host: string; + port: number; + /** The settings name a user for this proxy; the value itself is never kept. */ + namesUser: boolean; +} + +type BypassRule = + | { kind: 'simple-hostnames' } + | { kind: 'subtract-implicit' } + | { kind: 'hostname'; scheme: string; pattern: string; port: number } + | { kind: 'ip-host'; scheme: string; host: string; port: number } + | { kind: 'ip-block'; scheme: string; prefix: Uint8Array; bits: number }; + +interface MacSystemProxySettings { + /** `ProxyAutoConfigEnable` with a URL string: Chromium runs that PAC script. */ + pacUrl: boolean; + /** `ProxyAutoDiscoveryEnable` (WPAD). */ + autoDiscovery: boolean; + http: ManualProxy | null; + https: ManualProxy | null; + socks: ManualProxy | null; + bypass: BypassRule[]; +} + +/** A failure whose message is safe to log: it never carries output text or a setting's value. */ +class SystemProxySettingsError extends Error {} + +type ScValue = string | ScValue[] | Map; + +/** SCPrint's text: ` {`, `Key : value`, `Key : {` / ` {`, `N : item`, `}`. */ +function parseScPrint(text: string): Map | null { + const lines = text.split(/\r?\n/).map(line => line.trim()).filter(line => line.length > 0); + // scutil's own text when SCDynamicStoreCopyProxies returns NULL (configd `do_showProxyConfiguration`). + if (lines.length === 1 && lines[0] === 'No proxy configuration available') return null; + const unreadable = (lineNumber: number) => + new SystemProxySettingsError(`unrecognised scutil --proxy output (line ${lineNumber})`); + if (lines[0] !== ' {') throw unreadable(1); + const root = new Map(); + const open: Array | ScValue[]> = [root]; + for (let index = 1; index < lines.length; index += 1) { + const container = open.at(-1); + if (!container) throw unreadable(index + 1); + const line = lines[index]!; + if (line === '}') { + open.pop(); + continue; + } + const match = /^(\S+) :(?: (.*))?$/.exec(line); + if (!match) throw unreadable(index + 1); + const key = match[1]!; + const raw = match[2] ?? ''; + const value: ScValue = raw === ' {' ? new Map() : raw === ' {' ? [] : raw; + if (container instanceof Map) { + if (container.has(key)) throw unreadable(index + 1); + container.set(key, value); + } else { + if (key !== String(container.length)) throw unreadable(index + 1); + container.push(value); + } + if (typeof value !== 'string') open.push(value); + } + if (open.length !== 0) throw unreadable(lines.length); + return root; +} + +/** ASCII whitespace as base::TrimWhitespaceASCII trims it. */ +function trimAscii(value: string): string { + return value.replace(/^[\t\n\v\f\r ]+|[\t\n\v\f\r ]+$/g, ''); +} + +function asciiLower(value: string): string { + return value.replace(/[A-Z]/g, c => c.toLowerCase()); +} + +/** + * Chromium's IP literal parsing (`ip_address.h` `ParseIPLiteralToBytes`): with a colon, an IPv6 literal; + * otherwise `url::IPv4AddressToNumber`, the URL standard's IPv4 parser (`url_canon_ip.h`), under which + * `169.254` is 169.0.0.254 and `0x7f.1` is 127.0.0.1. Node's URL parser implements the same standard. + */ +function parseIpLiteral(literal: string): Uint8Array | null { + if (literal.includes(':')) { + if (!/^[0-9A-Fa-f:.]+$/.test(literal)) return null; + try { + return ipv6Bytes(new URL(`http://[${literal}]/`).hostname.slice(1, -1)); + } catch { + return null; + } + } + if (!/^[0-9A-Fa-fXx.]+$/.test(literal)) return null; + let hostname: string; + try { + hostname = new URL(`http://${literal}/`).hostname; + } catch { + return null; + } + const parts = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(hostname); + return parts ? Uint8Array.from(parts.slice(1).map(Number)) : null; +} + +/** Bytes of a canonical (URL-serialised) IPv6 address. */ +function ipv6Bytes(canonical: string): Uint8Array { + const [head = '', tail] = canonical.split('::'); + const headGroups = head ? head.split(':') : []; + const tailGroups = tail === undefined ? [] : tail ? tail.split(':') : []; + const groups = tail === undefined + ? headGroups + : [...headGroups, ...Array(8 - headGroups.length - tailGroups.length).fill('0'), ...tailGroups]; + const bytes = new Uint8Array(16); + groups.forEach((group, i) => { + const value = parseInt(group, 16); + bytes[i * 2] = value >> 8; + bytes[i * 2 + 1] = value & 0xff; + }); + return bytes; +} + +/** The form GURL gives an IP host: dotted IPv4, bracketed canonical IPv6 (`AddBracketsIfIPv6`). */ +function ipHostString(bytes: Uint8Array): string { + if (bytes.length === 4) return Array.from(bytes).join('.'); + const groups: string[] = []; + for (let i = 0; i < 16; i += 2) groups.push(((bytes[i]! << 8) | bytes[i + 1]!).toString(16)); + return new URL(`http://[${groups.join(':')}]/`).hostname; +} + +function isIpv4Mapped(bytes: Uint8Array): boolean { + return bytes.length === 16 && bytes.subarray(0, 10).every(b => b === 0) && bytes[10] === 0xff && bytes[11] === 0xff; +} + +/** `ip_address.cc` `IPAddressMatchesPrefix`, including the IPv4 / IPv6 mismatch mapping. */ +function matchesPrefix(address: Uint8Array, prefix: Uint8Array, bits: number): boolean { + const mapped = (v4: Uint8Array) => Uint8Array.from([...Array(10).fill(0), 0xff, 0xff, ...v4]); + if (address.length !== prefix.length) { + return address.length === 4 ? matchesPrefix(mapped(address), prefix, bits) : matchesPrefix(address, mapped(prefix), 96 + bits); + } + for (let bit = 0; bit < bits; bit += 1) { + const mask = 0x80 >> (bit % 8); + if ((address[bit >> 3]! & mask) !== (prefix[bit >> 3]! & mask)) return false; + } + return true; +} + +/** `url::ParsePort`: digits only, at most 65535; anything else is invalid (null). */ +function parsePort(text: string): number | null { + if (!/^\d+$/.test(text)) return null; + const port = Number(text); + return port <= 0xffff ? port : null; +} + +/** + * `url_util.cc` `ParseHostAndPort` over `url::ParseAuthority`: no user information; the port follows the + * last colon that comes after any `]`; a bracketed host must be an IPv6 literal (brackets removed); + * `host:` with an empty port is refused. Port -1: none given. + */ +function parseHostAndPort(input: string): { host: string; port: number } | null { + if (!input || input.includes('@')) return null; + // `url::ParseServerInfo`: the last `]` ends an IPv6 literal; a leading `[` without one runs to the end. + const closing = input.lastIndexOf(']'); + const terminator = closing !== -1 ? closing : input.startsWith('[') ? input.length : -1; + const colon = input.lastIndexOf(':'); + let host = input; + let port = -1; + if (colon > terminator) { + host = input.slice(0, colon); + const portText = input.slice(colon + 1); + if (!portText) return null; + const parsed = parsePort(portText); + if (parsed === null) return null; + port = parsed; + } + if (!host) return null; + if (host.startsWith('[')) { + const inner = host.slice(1, -1); + if (!host.endsWith(']') || !inner.includes(':') || !parseIpLiteral(inner)) return null; + host = inner; + } + return { host, port }; +} + +/** + * One `ExceptionsList` item, as `ProxyHostMatchingRules::AddRuleFromString` parses it + * (`proxy_host_matching_rules.cc` `ParseRule`, `scheme_host_port_matcher_rule.cc` `FromUntrimmedRawString`). + * null: Chromium drops the rule. + */ +function parseBypassRule(rawUntrimmed: string): BypassRule | null { + const trimmed = trimAscii(rawUntrimmed); + if (asciiLower(trimmed) === '') return { kind: 'simple-hostnames' }; + if (asciiLower(trimmed) === '<-loopback>') return { kind: 'subtract-implicit' }; + let raw = trimmed; + let scheme = ''; + const schemeEnd = raw.indexOf('://'); + if (schemeEnd !== -1) { + scheme = raw.slice(0, schemeEnd); + raw = raw.slice(schemeEnd + 3); + if (!scheme) return null; + } + if (!raw) return null; + if (raw.includes('/')) { + // `ip_address.cc` `ParseCIDRBlock`: exactly one slash, an IP literal and a bit count within its size. + // The scheme of an IP block rule is compared as written (not lower-cased), as in Chromium. + const parts = raw.split('/').map(trimAscii); + if (parts.length !== 2) return null; + const prefix = parseIpLiteral(parts[0]!); + if (!prefix || !/^\d+$/.test(parts[1]!)) return null; + const bits = Number(parts[1]); + if (bits > prefix.length * 8) return null; + return { kind: 'ip-block', scheme, prefix, bits }; + } + const hostAndPort = parseHostAndPort(raw); + if (hostAndPort) { + const ip = parseIpLiteral(hostAndPort.host); + if (ip) return { kind: 'ip-host', scheme: asciiLower(scheme), host: ipHostString(ip), port: hostAndPort.port === -1 ? 0 : hostAndPort.port }; + } + let port = -1; + const colon = raw.lastIndexOf(':'); + if (colon !== -1) { + const parsed = parsePort(raw.slice(colon + 1)); + if (parsed === null) return null; + port = parsed; + raw = raw.slice(0, colon); + } + const pattern = raw.startsWith('.') ? `*${raw}` : raw; + return { kind: 'hostname', scheme: asciiLower(scheme), pattern: asciiLower(pattern), port }; +} + +/** + * `base::MatchPattern` (`base/strings/pattern.cc`), ported step for step: `*` matches any run, `?` zero or + * one character, `\` escapes either; each literal run is searched for at the first place it fits. + */ +function matchPattern(evaluated: string, pattern: string): boolean { + const text = Array.from(evaluated); + const pat = Array.from(pattern); + let p = 0; + let s = 0; + do { + let questionMarks = 0; + let asterisk = false; + while (p < pat.length && (pat[p] === '?' || pat[p] === '*')) { + if (pat[p] === '?') questionMarks += 1; + else asterisk = true; + p += 1; + } + let maximumDistance = asterisk ? -1 : questionMarks; + const patternStart = p; + let stringStart = s; + let escape = false; + let found = false; + for (;;) { + if (p === pat.length) { + if (s === text.length) { + found = true; + break; + } + } else { + if (!escape && (pat[p] === '*' || pat[p] === '?')) { + found = true; + break; + } + if (!escape && pat[p] === '\\') { + escape = true; + p += 1; + continue; + } + escape = false; + if (s === text.length) return false; + if (pat[p] === text[s]) { + p += 1; + s += 1; + continue; + } + } + if (maximumDistance === 0) return false; + maximumDistance -= 1; + p = patternStart; + stringStart += 1; + s = stringStart; + } + if (!found) return false; + } while (p !== pat.length); + return true; +} + +interface UrlFacts { + scheme: string; + /** GURL `host()`: lower case, IPv6 in brackets. */ + host: string; + hostNoBrackets: string; + /** GURL `EffectiveIntPort()`: the port, or the scheme's default; -1 when there is none. */ + port: number; + ip: Uint8Array | null; +} + +const DEFAULT_PORTS: Record = { http: 80, https: 443, ws: 80, wss: 443, ftp: 21 }; + +function urlFacts(url: URL): UrlFacts { + const scheme = url.protocol.slice(0, -1); + const host = url.hostname; + const hostNoBrackets = host.startsWith('[') ? host.slice(1, -1) : host; + const ip = host.startsWith('[') ? parseIpLiteral(hostNoBrackets) : /^\d+\.\d+\.\d+\.\d+$/.test(host) ? parseIpLiteral(host) : null; + return { scheme, host, hostNoBrackets, port: url.port ? Number(url.port) : (DEFAULT_PORTS[scheme] ?? -1), ip }; +} + +/** `ProxyHostMatchingRules::MatchesImplicitRules` on macOS (Chromium 148: no 0.0.0.0 / [::] rule yet). */ +function matchesImplicitRules(url: UrlFacts): boolean { + // `url_util.cc` `HostStringIsLocalhost`: a loopback IP (127/8, ::1), or localhost, localhost., *.localhost. + if (url.ip) { + if (url.ip.length === 4 ? url.ip[0] === 127 : url.ip.subarray(0, 15).every(b => b === 0) && url.ip[15] === 1) return true; + } else { + const name = url.hostNoBrackets.endsWith('.') ? url.hostNoBrackets.slice(0, -1) : url.hostNoBrackets; + if (asciiLower(name) === 'localhost' || name.endsWith('.localhost')) return true; + } + // `IsIPv4MappedLoopback`: [::ffff:127.x.x.x]. + if (url.host.startsWith('[::ffff') && url.ip && isIpv4Mapped(url.ip) && url.ip[12] === 127) return true; + // `IsLinkLocalIP`: 169.254/16, [::ffff:169.254.0.0]/112, [fe80::]/10 (`IPAddress::IsLinkLocal`). + if ((url.host.startsWith('169.254.') || url.host.startsWith('[')) && url.ip) { + if (url.ip.length === 4) return url.ip[0] === 169 && url.ip[1] === 254; + if (isIpv4Mapped(url.ip)) return url.ip[12] === 169 && url.ip[13] === 254; + return url.ip[0] === 0xfe && (url.ip[1]! & 0xc0) === 0x80; + } + return false; +} + +type RuleResult = 'include' | 'exclude' | 'no-match'; + +function evaluateRule(rule: BypassRule, url: UrlFacts): RuleResult { + switch (rule.kind) { + case 'simple-hostnames': + return !url.host.includes('.') && !url.ip ? 'include' : 'no-match'; + case 'subtract-implicit': + return matchesImplicitRules(url) ? 'exclude' : 'no-match'; + case 'hostname': + if (rule.port !== -1 && url.port !== rule.port) return 'no-match'; + if (rule.scheme && url.scheme !== rule.scheme) return 'no-match'; + return matchPattern(url.host, rule.pattern) ? 'include' : 'no-match'; + case 'ip-host': + if (rule.port !== 0 && url.port !== rule.port) return 'no-match'; + if (rule.scheme && url.scheme !== rule.scheme) return 'no-match'; + // `SchemeHostPortMatcherIPHostRule`: MatchPattern on two canonical IP strings, i.e. equality. + return url.host === rule.host ? 'include' : 'no-match'; + case 'ip-block': + if (!url.ip) return 'no-match'; + if (rule.scheme && url.scheme !== rule.scheme) return 'no-match'; + return matchesPrefix(url.ip, rule.prefix, rule.bits) ? 'include' : 'no-match'; + } +} + +/** + * `ProxyHostMatchingRules::Matches` (not reversed): later rules override earlier ones + * (`scheme_host_port_matcher.cc` `Evaluate`), and without an explicit match the implicit rules apply. + */ +function bypasses(rules: readonly BypassRule[], url: UrlFacts): boolean { + for (let i = rules.length - 1; i >= 0; i -= 1) { + const result = evaluateRule(rules[i]!, url); + if (result === 'include') return true; + if (result === 'exclude') return false; + } + return matchesImplicitRules(url); +} + +/** + * A proxy host as `ProxyServer::FromSchemeHostAndPort` takes it: trimmed, an IPv6 literal bracketed, then + * canonicalised; empty, or failing canonicalisation, is invalid and the entry is ignored (null). A host with + * characters whose canonicalisation in Chromium is not checked (white space, `/ \ ? # @ %`) is not guessed + * at: the reading fails. + */ +function canonicalProxyHost(value: string): string | null { + const host = trimAscii(value); + if (!host) return null; + const bracketed = !host.startsWith('[') && host.includes(':') ? `[${host}]` : host; + if (/[\s/\\?#@%]/.test(bracketed)) throw new SystemProxySettingsError('unrecognised proxy host in the system proxy settings'); + try { + return new URL(`http://${bracketed}/`).hostname || null; + } catch { + return null; + } +} + +/** + * The settings Chromium reads from the dictionary (`proxy_config_service_mac.cc` `GetCurrentProxyConfig`), + * from scutil's output. Keys outside this list (FTP, Gopher, RTSP, scoped services, inline PAC JavaScript, + * which Chromium ignores too) are skipped. + */ +function parseScutilProxyOutput(text: string): MacSystemProxySettings { + const dictionary = parseScPrint(text); + const settings: MacSystemProxySettings = { pacUrl: false, autoDiscovery: false, http: null, https: null, socks: null, bypass: [] }; + if (!dictionary) return settings; + // `GetValueFromDictionary` / `` / `` give null for a value of another + // type, and Chromium then reads the key as missing. In the text a number is an integer, a string a scalar. + const number = (key: string): number | undefined => { + const value = dictionary.get(key); + return typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : undefined; + }; + // `GetBoolFromDictionary`: a number, non-zero is true; missing is false. + const flag = (key: string) => (number(key) ?? 0) !== 0; + const stringValue = (key: string): string | undefined => { + const value = dictionary.get(key); + return typeof value === 'string' ? value : undefined; + }; + // `ProxyDictionaryToProxyChain`: the host key missing makes the entry invalid (ignored); the port key + // missing means the scheme's default (HTTP 80, SOCKS5 1080). + const manual = (prefix: 'HTTP' | 'HTTPS' | 'SOCKS'): ManualProxy | null => { + if (!flag(`${prefix}Enable`)) return null; + const hostValue = stringValue(`${prefix}Proxy`); + if (hostValue === undefined) return null; + const pacScheme = prefix === 'SOCKS' ? 'SOCKS5' : 'PROXY'; + const port = number(`${prefix}Port`) ?? (pacScheme === 'SOCKS5' ? 1080 : 80); + // Chromium narrows the integer to a 16-bit port; ports outside 1–65535 are not guessed at. + if (port < 1 || port > 0xffff) throw new SystemProxySettingsError(`unexpected ${prefix}Port in the system proxy settings`); + const host = canonicalProxyHost(hostValue); + if (host === null) return null; + const user = dictionary.get(`${prefix}User`); + // A blank user names no one; any other value counts, whatever its type. + return { pacScheme, host, port, namesUser: user !== undefined && !(typeof user === 'string' && trimAscii(user) === '') }; + }; + settings.autoDiscovery = flag('ProxyAutoDiscoveryEnable'); + // `set_pac_url(GURL(…))`, and `has_pac_url()` is the GURL being valid: otherwise the manual settings apply. + settings.pacUrl = flag('ProxyAutoConfigEnable') && URL.canParse(trimAscii(stringValue('ProxyAutoConfigURLString') ?? '')); + settings.http = manual('HTTP'); + settings.https = manual('HTTPS'); + settings.socks = manual('SOCKS'); + const exceptions = dictionary.get('ExceptionsList'); + if (Array.isArray(exceptions)) { + for (const item of exceptions) { + // Chromium skips an item that is not a string. + if (typeof item !== 'string') continue; + const rule = parseBypassRule(item); + if (!rule) continue; + if (rule.kind !== 'hostname' || !/[,;]/.test(item)) { + settings.bypass.push(rule); + continue; + } + // The macOS reader adds the whole item as one rule. Copying the config then serializes + // and reparses its rules on commas and semicolons (ProxyHostMatchingRules::operator=). + const scheme = rule.scheme ? `${rule.scheme}://` : ''; + const port = rule.port === -1 ? '' : `:${rule.port}`; + for (const entry of `${scheme}${rule.pattern}${port}`.split(/[,;]/)) { + const copiedRule = parseBypassRule(entry); + if (copiedRule) settings.bypass.push(copiedRule); + } + } + } + // `PrependRuleToBypassSimpleHostnames`: `` goes first, so every listed rule overrides it. + if (flag('ExcludeSimpleHostnames')) settings.bypass.unshift({ kind: 'simple-hostnames' }); + return settings; +} + +/** + * The PAC result Chromium gives this URL under these settings (`proxy_config.cc` `ProxyRules::Apply`, + * `MapUrlSchemeToProxyList`): no manual proxy → DIRECT; a bypass match → DIRECT; otherwise the proxy for + * the URL's scheme, else the SOCKS proxy, else DIRECT. A manual result has exactly one entry and no DIRECT + * after it. Throws (logged by the resolver core, which then goes direct) for what the Host does not do. + */ +function systemProxyResultFor(settings: MacSystemProxySettings, upstreamUrl: string): string { + if (settings.pacUrl) { + throw new SystemProxySettingsError('the system proxy settings use a proxy auto-config (PAC) URL, and the Chromium proxy helper had no answer'); + } + const { http, https, socks } = settings; + if (!http && !https && !socks) return 'DIRECT'; + const url = urlFacts(new URL(upstreamUrl)); + if (bypasses(settings.bypass, url)) return 'DIRECT'; + const proxy = url.scheme === 'http' ? (http ?? socks) + : url.scheme === 'https' ? (https ?? socks) + // `GetProxyListForWebSocketScheme`: SOCKS, then the HTTPS proxy, then the HTTP proxy. + : url.scheme === 'ws' || url.scheme === 'wss' ? (socks ?? https ?? http) + : socks; + if (!proxy) return 'DIRECT'; + if (proxy.namesUser) { + throw new SystemProxySettingsError('the system proxy for this request requires authentication; its password is in the keychain, which the Host does not read'); + } + return `${proxy.pacScheme} ${proxy.host}:${proxy.port}`; +} + +/** Reads the system proxy settings as scutil prints them. */ +export type ReadSystemProxySettings = () => Promise; + +/** What the resolver core asks per upstream (its `getProxySession` port). */ +export interface SystemProxySession { + resolveProxy(url: string): Promise; +} + +/** + * The Host's system proxy session: one reading of the settings serves every request for + * SYSTEM_PROXY_SETTINGS_TTL_MS, and concurrent requests share one reading. A failed reading is not kept: + * the resolver core already holds its unresolved verdict for 5 s per upstream. + */ +export function createMacSystemProxySession(readSettings: ReadSystemProxySettings, chromium?: SystemProxySession | null): SystemProxySession & { needsChromium(): Promise } { + let current: { settings: MacSystemProxySettings; expiresAt: number } | null = null; + let reading: Promise | null = null; + let reportedAutoDiscovery = false; + + function noteAutoDiscovery(settings: MacSystemProxySettings): void { + const skipped = settings.autoDiscovery && !settings.pacUrl; + if (skipped && !reportedAutoDiscovery) { + log.warn('system proxy auto-discovery (WPAD) is not tried on the Host — using the manual proxy settings', {}); + } + reportedAutoDiscovery = skipped; + } + + function settingsNow(): Promise { + if (current && current.expiresAt > Date.now()) return Promise.resolve(current.settings); + reading ??= (async () => { + try { + const settings = parseScutilProxyOutput(await readSettings()); + current = { settings, expiresAt: Date.now() + SYSTEM_PROXY_SETTINGS_TTL_MS }; + return settings; + } finally { + reading = null; + } + })(); + return reading; + } + + return { + async needsChromium() { + const settings = await settingsNow(); + return settings.pacUrl || settings.autoDiscovery; + }, + async resolveProxy(url) { + const settings = await settingsNow(); + // On demand (28c): Chromium only for PAC and auto-discovery; static settings never start the helper. + if (chromium && (settings.pacUrl || settings.autoDiscovery)) { + try { + return await chromium.resolveProxy(url); + } catch { + // No answer in time: the static reading below (28b), as before the helper. + } + } + noteAutoDiscovery(settings); + return systemProxyResultFor(settings, url); + }, + }; +} + +/** + * The production reader: `/usr/sbin/scutil --proxy`. `BYPASS_GLOBAL_PROXY` is removed from its + * environment (it makes scutil skip the global proxies, configd `do_showProxyConfiguration`). Failures name + * the exit code or signal only; stdout and stderr are never logged. + */ +export const readScutilProxyOutput: ReadSystemProxySettings = () => { + const env = { ...process.env }; + delete env.BYPASS_GLOBAL_PROXY; + return new Promise((resolve, reject) => { + execFile(SCUTIL_PATH, ['--proxy'], { + encoding: 'utf8', env, timeout: SCUTIL_TIMEOUT_MS, killSignal: 'SIGKILL', maxBuffer: SCUTIL_MAX_OUTPUT_BYTES, windowsHide: true, + }, (error, stdout) => { + if (error) { + const reason = (error as NodeJS.ErrnoException).code ?? error.signal ?? 'error'; + reject(new SystemProxySettingsError(`scutil --proxy failed (${String(reason)})`)); + return; + } + resolve(stdout); + }); + }); +}; diff --git a/apps/host/src/main.ts b/apps/host/src/main.ts index 85b6e7aa984..2ab4a9871ac 100644 --- a/apps/host/src/main.ts +++ b/apps/host/src/main.ts @@ -3,10 +3,11 @@ import './boot-env.js'; // Second: keeps unreadable user settings files instead of deleting them. import './boot-settings.js'; import { resolveAutomaticProjectIcon } from '../../desktop/src/main/projectAutomaticIcon.js'; -import type { ProjectInfoAuthorization } from '../../desktop/src/main/projectInfoAuthorization.js'; -import { readProjectIconImage, readProjectInfo, updateProjectInfo } from '../../desktop/src/main/projectInfoCore.js'; +import { readProjectIconImage, readProjectInfo } from '../../desktop/src/main/projectInfoCore.js'; +import { createHostProjectInfoUpdate } from './project-info.js'; import { reconcileDeletedTaskViewState } from '../../desktop/src/main/mcp-apps/viewStateStore.js'; import { clientMigrationContract } from './client-migration-contract.mjs'; +import { runLegacyPluginMigrationPreflight } from './plugins/legacy-approvals.js'; import { createRightSidebarTabsService } from '../../desktop/src/main/localDb/ipc/rightSidebarTabs.js'; import { createHostPlatformTools } from './platform/tools.js'; import { createHostCodexRuntime, createHostSubscriptionFastPolicies } from './agent/codex-runtime.js'; @@ -14,6 +15,10 @@ import { createHostClaudeProxyRuntime } from './agent/claude-proxy-runtime.js'; import { createAvailabilityPolicy } from '../../desktop/src/main/device-link/providerShareAvailabilityPolicyCore.js'; import { configureWindowsAtomicRename } from '../../desktop/src/main/windowsAtomicRename.js'; import { isDefinitiveRefreshError } from '../../desktop/src/main/authRefreshError.js'; +import type { HostStartFailureReason } from '../../desktop/src/shared/hostStartFailure.js'; +import { classifyHostStartFailure, HostAccountMismatchError, HostSignInRequiredError } from './start-failure.js'; +import { AuthRefreshBackoff } from '../../desktop/src/main/authRefreshBackoff.js'; +import { AUTH_ACCOUNT_VAULT_LOCK_FILE } from '../../desktop/src/main/authRefreshCommit.js'; import { createUserSession } from '../../desktop/src/main/localDb/ipc/createUserSession.js'; import { setSessionOpeningModelAdmission } from '../../desktop/src/main/localDb/sessionOpening.js'; import { resolveSessionExecutionSelection } from '../../desktop/src/main/maker-ipc/sessionExecutionSelection.js'; @@ -27,8 +32,17 @@ import { resolveSessionDevice, canRegisterHostDevice } from './auth/device-ident import { AUTH_SESSION_KEY } from '../../desktop/src/main/authCredentialKeys.js'; import { createHostDeviceLink } from './device-link.js'; import { createHostService } from './service.mjs'; -import { readHostCreateSessionOpts } from './create-session-request.js'; -import { ensureDialogueWorkspaceDir } from '../../desktop/src/main/localDb/dialogueWorkspace.js'; +import { createHostRuntimeSession, type HostRuntimeSessionCreatePorts } from './agent/create-runtime-session.js'; +import { + createHostProfileCoexistenceMonitor, createDesktopScanner, HOST_PROFILE_IN_USE_BY_DESKTOP, HostProfileInUseError, + type CoexistenceMonitor, type CoexistenceState, +} from './agent/profile-coexistence.js'; +import { createHostProviderExecutionCheck } from './agent/send-preflight.js'; +import { explicitPorts } from './agent/explicit-ports.js'; +import { createSkillProjectionBoundaryObserver, readSkillProjectionBoundaryStatus } from './agent/skill-projection-boundary.js'; +import { refuseSkillProjectionOwnerCommit, sweepOwnerSkillProjectionsAtLogout } from './agent/skill-projection-owner.js'; +import { createHostSharedGlobalSkills } from './agent/shared-global-skills.js'; +import { createHostAgentSkillList } from './agent/agent-skills.js'; import { resolveRuntimeDeviceId } from '../../desktop/src/main/deviceId.js'; import os from 'node:os'; import path from 'node:path'; @@ -43,7 +57,7 @@ import { createDefaultLayout } from '../../desktop/src/shared/layoutTree.ts'; import { createHash, randomBytes, randomUUID } from 'node:crypto'; import { hostRuntimeLayout } from './runtime-layout.mjs'; import { createHostServerApi } from './server-api.js'; -import { decodeAccessTokenOrgSlug } from '../../desktop/src/main/authTokenClaims.js'; +import { accessTokenRefreshDelayMs, decodeAccessTokenOrgSlug } from '../../desktop/src/main/authTokenClaims.js'; import { parseGhostSetupInteractionCommand } from '../../desktop/src/main/cindy-brain/ghostSetupInteractionBridge.js'; import { openSystemBrowser, openHostBrowser } from './browser-open.mjs'; @@ -52,20 +66,19 @@ import { OwnerSessionStorage } from '../../desktop/src/main/localDb/sessionStora import { getDbClient, setCurrentDbClient, clearCurrentDbClient, getCurrentDbClientSnapshot } from '../../desktop/src/main/localDb/client/current.ts'; import { waitForRetainedDbClient } from '../../desktop/src/main/localDb/client/pendingOperations.ts'; import { loadAgentInputQueueSnapshot, saveAgentInputQueueSnapshot, getPersistedInputClientIds } from '../../desktop/src/main/localDb/agentInputQueueSnapshots.ts'; -import { touchUserSendRow } from '../../desktop/src/main/localDb/sessionQueries.ts'; import { markSessionTurnStartedDurable, markSessionTurnEnded, drainSessionActiveTurnWrites, ackSessionTurnEndedDurable, hasAssistantProgressAfterMessage, getRecoveryContextSnapshot, } from '../../desktop/src/main/localDb/sessionActiveTurn.ts'; import { readSessionExtraDirsFromDb, readSessionWritableDirsFromDb } from '../../desktop/src/main/maker-host/session-storage.js'; import { createProviderGroupStore } from '../../desktop/src/main/provider-group/storeCore.js'; import { createProviderGroupBindings } from '../../desktop/src/main/provider-group/bindings.js'; -import { AGENT_BINARY_LAYOUT, readCachedBinaryStatus } from '../../desktop/src/main/agent-binaries/binaryStatus.js'; +import { createHostHarnessBinaries, HOST_HARNESS_KINDS } from './agent/harness-binary.js'; import { openOwnerDatabase, OwnerDatabaseError } from '../../desktop/src/main/localDb/startupCore.js'; import { discoverHostOwner, ownerDatabasePath, resolveHostDataDir, resolveHostRegion, resolveHostAppDataDir } from './profile-path.mjs'; import { acquireHostRuntimeLease, acquireHostServiceLease, type HostRuntimeLease } from './runtime-lock.js'; import { publishHostEndpoint, readHostProcessStatus, requestHostStop, requestHostRemote } from './control.mjs'; import { readAdoptedSessionState } from './credentials/session.mjs'; -import { refreshHostSession } from './auth/refresh.mjs'; +import { hostAccountVaultLock, HostRefreshDeferredError, HostSessionMissingError, refreshHostSession } from './auth/refresh.mjs'; import { configureHostOwner, readClaudeSubscriptionState } from './agent/claude-auth.mjs'; import { attachAgentsToMakerMemory, createHostMemoryManager, createHostMemoryMcpProviders } from './agent/memory.mjs'; import { createHostAgentGraph } from './agent/runtime.js'; @@ -73,6 +86,7 @@ import { createHostReviewContextResolver } from './agent/review-context.js'; import { createHostGitSnapshot, type HostGitSnapshot } from './agent/git-snapshot.js'; import { removeTurnChangeSetsForSession } from '../../desktop/src/main/turn-change-set/store.js'; import { removeSessionModelInterface } from '../../desktop/src/main/maker-host/session-model-interface.js'; +import { cleanupSessionRuntimeForTerminalStatus } from '../../desktop/src/main/localDb/sessionRuntimeCleanup.js'; import { reconcileSavepointRefsForDeletedSessions } from '../../desktop/src/main/git-snapshot/savepointCleanup.js'; import { createHostMcpRuntime } from './agent/mcp-runtime.js'; import { createHostAgentAuth } from './agent/auth-service.js'; @@ -82,6 +96,8 @@ import { createHostIpcRoute } from './ipc-route.mjs'; import { createHostIpcBindings } from './ipc-bindings/index.js'; import { projectHostAuthState } from './auth-state.js'; import { createHostModelAccess } from './agent/model-access.js'; +import { createHostUsagePricing } from './agent/usage-pricing.ts'; +import { createHostUsageRecording } from './agent/usage-recording.ts'; import { MODEL_ACCESS_STATUS_CHANNEL } from '../../desktop/src/shared/modelAccess.js'; import { createProviderCatalog } from './agent/providers.mjs'; import { closeCliProxyBridge } from '../../desktop/src/main/maker-host/cli-proxy-bridge.js'; @@ -97,6 +113,7 @@ import { hostAuthFetch } from './auth-fetch.mjs'; import type { Effort, PermissionMode } from '@cindy/maker-core'; import { createRequire } from 'node:module'; import { readAuthEndpoints } from './auth/endpoints.mjs'; +import { assertHostSessionRegion, HostCrossRegionPersonalAccountError, hostPackageRegion } from './auth/region-policy.js'; import { logoutHostSession } from './auth/logout.mjs'; import { listInstalledPlugins } from './plugins.mjs'; import { createHostGhostManager } from './plugins-installed.ts'; @@ -128,21 +145,38 @@ import { createSnapshotProcess } from './snapshot-process.mjs'; import { configureGhostSnapshotProcess } from '../../desktop/src/main/cindy-brain/ghostSnapshotCapability.js'; import { withCrossProcessLock } from '../../desktop/src/main/device-link/crossProcessLock.js'; import { createChatHandler } from './chat.mjs'; +import { createOwnerBoundaryStop, runOwnerBoundary } from './agent/owner-boundary.ts'; import { createEventHub } from './events.mjs'; import { createTaskTagService } from '../../desktop/src/main/localDb/ipc/taskTagService.js'; import { executeConversationSearch } from '../../desktop/src/main/localDb/ipc/search.js'; import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from '../../desktop/src/main/device-link/broadcast-tap.js'; import { createInputQueue } from './agent/input-queue.mjs'; +import { createHostSessionActivity } from './agent/session-activity.ts'; +import { readClaudeIdleMinutesFrom } from '../../desktop/src/main/maker-host/claudeIdleReleaseSettingsCore.js'; import { createHostAgentHandoffPending } from './agent/handoff-pending.ts'; +import { createHostRuntimePluginSettings, createHostTaskRuntimePlugins } from './agent/task-runtime-plugins.js'; +import { setGhostToolApprovalResolver } from '../../desktop/src/main/maker-host/mcp-tool-approval-policy.js'; +import { warmRuntimePluginSettings } from '../../desktop/src/main/maker-host/runtime-plugin-settings.js'; +import { bindHostSessionRuntimeHooks, createHostRuntimeSelection, hostRuntimeSelectionQueueHooks } from './agent/runtime-selection.ts'; +import { throwIpcError } from '../../desktop/src/main/utils/ipcValidate.js'; import type { ContextRecoveryKind } from './agent/context-recovery.ts'; import { createHostContextRecoveryWiring } from './agent/context-recovery-wiring.ts'; import { lockSessionRoute } from './agent/session-route-lock.mjs'; import { listPiRuntimePaletteCommands, mergePiPackageCommands, shouldListPiPackageCommands } from '../../desktop/src/shared/piPackages.js'; -import { createHostSessionUpdate, type HostModelSelectionApply } from './agent/session-update.ts'; -import { readDeviceLinkModelSelectionOrigin, getDeviceLinkInvokeContext } from '../../desktop/src/main/device-link/invoke-context.js'; -import { throwIpcError } from '../../desktop/src/main/utils/ipcValidate.js'; -import { withRehydrateCloseSuppressed } from '../../desktop/src/main/maker-host/rehydrateCloseSuppression.js'; -import { assertHostTaskExecutionSupported } from './agent/send-preflight.ts'; +import { createHostSessionUpdate } from './agent/session-update.ts'; +import { createHostSessionMovePorts, createRecentWorkdirsChangedPush } from './agent/session-move.ts'; +import { createHostTouchUserSend } from './agent/touch-user-send.ts'; +import { setLiveCcSessionBridge } from '../../desktop/src/main/maker-host/claude-transcript-relocation.ts'; +import { bindTaskRestoreRetention, createHostTaskRestore } from './agent/task-restore.ts'; +import { bindHostUiText } from './ui-text.ts'; +import { createHostGeneratedImages } from './agent/generated-images.ts'; +import { reconcileGeneratedImageRecovery, recoverGeneratedImagesForHistory } from '../../desktop/src/main/cindy-media/generatedImageRecovery.js'; +import { bindHostProjectIconRuntime } from './project-icon.ts'; +import { createUserInputEnqueue } from './agent/user-input.ts'; +import { resolveSessionReferencesWithPorts } from '../../desktop/src/main/maker-ipc/sessionReferenceResolverCore.ts'; +import { readSwitchOptionsAgentDeviceId, readSwitchOptionsConfirmedContextWindow } from '../../desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts'; +import { setSessionRouteLockImplementation } from '../../desktop/src/main/localDb/sessionRouteLock.ts'; +import { withSendToSessionLock } from '../../desktop/src/main/maker-ipc/sendToSessionLock.ts'; import { createInteractionBroker } from './agent/interactions.mjs'; import { messageToCamel, sessionToCamel } from '../../desktop/src/main/localDb/mapper.ts'; import { readHostSessionList, readHostSession } from './session-reads.js'; @@ -151,6 +185,7 @@ import { createHostAttachments } from './attachments.js'; import { createSubagentReadService } from '../../desktop/src/main/localDb/ipc/subagentReadService.js'; import { configureUserDataDir, configureAppDataDir, getUserDataDir } from '../../desktop/src/main/userDataPath.js'; import { botSessionLinks, messages as messageTable, projectAliases as projectAliasTable, sessions as sessionTable } from '../../desktop/src/main/localDb/schema.js'; +import { describeHostOutboundProxy, describeOutboundProxyLine, startHostSystemProxySettings, stopHostSystemProxySettings } from './outbound-proxy.ts'; import { and, eq, isNull } from 'drizzle-orm'; import { projectHistoryView } from '@cindy/maker-shared/message-window'; import { isDefaultDraftSessionTitle, normalizeAutoTitle } from '@cindy/maker-shared/session-title'; @@ -173,8 +208,32 @@ function parsePermissionMode(value: unknown): PermissionMode | undefined { } const command = process.argv[2]; +const usage = 'cindy-host [serve|login [--region=cn|global] [--method=]|open|status [--json]|migration-preflight |remote [status|enable|disable|revoke |agent-net-on|agent-net-off]|stop]'; + +/** The status command's boundary category: the running Host's, else a lock-free read of the profile. */ +function readStatusSkillProjectionBoundary(processStatus: { running: boolean | null; runtime?: { skillProjectionBoundary?: string } }) { + if (processStatus.running) return processStatus.runtime?.skillProjectionBoundary ?? null; + const owner = process.env.CINDY_HOST_OWNER?.trim() || discoverHostOwner(resolveHostDataDir()).ownerId; + if (!owner) return null; + configureUserDataDir(resolveHostDataDir()); + return readSkillProjectionBoundaryStatus(owner); +} + +// Every command, before it reads a profile: a release refuses a CINDY_HOST_REGION that names the other +// edition (profile-path.mjs resolveHostRegion) instead of running as the wrong one. +try { + resolveHostRegion(); +} catch (error) { + console.error(`cindy-host: ${error instanceof Error ? error.message : String(error)}`); + process.exit(1); +} +// open, status, stop and remote only contact a local loopback endpoint. +const proxyWarmup = command === undefined || command === 'serve' || command === 'login' + ? startHostSystemProxySettings().catch((error: unknown) => { + console.warn('[host] system proxy warmup failed:', error instanceof Error ? error.name : 'UnknownError'); + }) : undefined; if (command === '--help' || command === '-h') { - console.log('Usage: cindy-host [serve|login [--region=cn|global] [--method=]|open|status [--json]|remote [status|enable|disable|revoke |agent-net-on|agent-net-off]|stop]'); + console.log(`Usage: ${usage}`); } else if (command === 'open') { try { await openHostBrowser(resolveHostDataDir()); @@ -190,7 +249,9 @@ if (command === '--help' || command === '-h') { userDataDir: resolveHostDataDir(), keyringApplication: process.env.CINDY_HOST_KEYRING_APPLICATION?.trim() || undefined, }).catch(() => ({ authenticated: null, realm: null, credentialStoreUnavailable: true })); - const state = { ...login, ...await readHostProcessStatus(resolveHostDataDir()) }; + const processStatus = await readHostProcessStatus(resolveHostDataDir()); + const state = { ...login, ...processStatus, + skillProjectionBoundary: readStatusSkillProjectionBoundary(processStatus) }; const json = process.argv.includes('--json'); if (json) { console.log(JSON.stringify(state)); @@ -198,14 +259,32 @@ if (command === '--help' || command === '-h') { console.log(`authenticated: ${state.authenticated}`); console.log(`realm: ${state.realm ?? 'none'}`); console.log(`running: ${state.running === null ? 'unreachable' : state.running}`); + if ('region' in state && state.region) console.log(`region: ${state.region}`); if (state.baseUrl) console.log(`address: ${state.baseUrl}`); + if ('outboundProxy' in state && state.outboundProxy) console.log(`outbound proxy: ${describeOutboundProxyLine(state.outboundProxy)}`); + if ('legacyPluginApprovals' in state) { + const report = state.legacyPluginApprovals; + console.log(`legacy plugins missing approval receipts: ${report ? report.count : 'unchecked'}`); + for (const id of report?.installIds ?? []) console.log(` ${id}`); + } if (state.error) console.error(state.error); + // Row 25 (25b): an install signed in before the login published the projection owner. + if (state.authenticated && (state.skillProjectionBoundary === 'missing-or-invalid' || state.skillProjectionBoundary === 'other-owner')) { + console.log('Run cindy-host login again to finish setting up this account\'s Skills.'); + } if ('credentialStoreUnavailable' in login) console.error('Credential store is unavailable; unlock it to inspect sign-in status.'); } } catch (error) { console.error(`cindy-host status failed: ${error instanceof Error ? error.message : String(error)}`); process.exitCode = 1; } +} else if (command === 'migration-preflight') { + try { + process.exitCode = await runLegacyPluginMigrationPreflight(process.argv.slice(3)); + } catch (error) { + console.error(`cindy-host migration-preflight failed: ${error instanceof Error ? error.message : String(error)}`); + process.exitCode = 1; + } } else if (command === 'stop') { try { const result = await requestHostStop(resolveHostDataDir()); @@ -226,6 +305,7 @@ if (command === '--help' || command === '-h') { } } else if (command === 'login') { try { + await proxyWarmup; await runLoginCommand(process.argv.slice(3)); } catch (error) { console.error(`cindy-host login failed: ${error instanceof Error ? error.message : String(error)}`); @@ -233,7 +313,7 @@ if (command === '--help' || command === '-h') { } } else if (command !== undefined && command !== 'serve') { console.error( - `unknown command: ${command}\nusage: cindy-host [serve|login [--region=cn|global] [--method=]|open|status [--json]|remote [status|enable|disable|revoke ]|stop]`, + `unknown command: ${command}\nusage: ${usage}`, ); process.exitCode = 2; } else { @@ -242,6 +322,13 @@ if (!Number.isInteger(PORT) || PORT < 0 || PORT > 65535) throw new Error('CINDY_ const profileDir = resolveHostDataDir(); configureUserDataDir(profileDir); configureAppDataDir(resolveHostAppDataDir()); +// Release table row 25 (25b, decision (a)): serve never publishes the Skill projection owner; the +// window, or `cindy-host login` on a Host's own profile, does. Before anything can commit. +refuseSkillProjectionOwnerCommit(); +// Background copy in the locale before the owner database opens (its startup failure is one), as +// bootstrap-electron.ts configureUiText. +bindHostUiText(); +bindHostProjectIconRuntime(); configureWindowsAtomicRename({ packagedBinary: hostRuntimeLayout().atomicRenameBinary ?? undefined, sourceFile: hostRuntimeLayout().atomicRenameSource ?? undefined, @@ -270,48 +357,78 @@ interface RuntimeState { agents?: string[]; agentLane?: string; detail?: string; + /** + * Coexistence plan A (agent/profile-coexistence.ts): whether a desktop that opens this profile's + * database runs beside the Host (PIDs only). `waiting-for-turns`: it is gone, and the Host opens + * again once its running turns end. + */ + coexistence?: { state: CoexistenceState['state'] | 'waiting-for-turns'; desktops: number[] }; + /** + * Why the last start failed or was refused (start-failure.ts), the code the windows are given in the auth + * state and the 409 of an owner request; never the text of `detail`. Null for an ordinary signed-out start, + * and cleared once a runtime opens, the account signs out or a sign-in completes; a disposal does not clear it. + */ + unavailable?: HostStartFailureReason | null; } const runtime: RuntimeState = { state: 'uninitialized', owner: null, storage: 'unopened' }; +// Row 25 (25a): read-only diagnostic of the Skill projection owner boundary, read per call. +const observeSkillProjectionBoundary = createSkillProjectionBoundaryObserver(createLogger('host-skill-projection')); +// Row 25 (25b): the desktop's shared global Skill preparation, skipped while a desktop holds the profile. +const sharedGlobalSkills = createHostSharedGlobalSkills({ + isProfileHeld: () => inputQueue.isHeldForDesktop(), + bundledSystemSkillsRoot: () => hostRuntimeLayout().systemSkillsDir, +}); -/** Resolved dev checkout binary for one harness, or null when absent. */ -function harnessBinaryPath(kind: 'claude-code' | 'codex' | 'pi'): string | null { - const layout = kind === 'claude-code' - ? { dir: 'claude-code-bin', file: AGENT_BINARY_LAYOUT['claude-code'].binaryName } - : kind === 'codex' - ? { dir: 'codex-package-bin', file: AGENT_BINARY_LAYOUT.codex.binaryName } - : { dir: 'pi-bin', file: AGENT_BINARY_LAYOUT.pi.binaryName }; - const status = readCachedBinaryStatus({ - kind, - isPackaged: false, - userDataDir: resolveHostDataDir(), - devCandidates: [path.join(hostRuntimeLayout().harnessRoot, layout.dir, platformKey, layout.file)], - }); - return status.binaryPath ?? null; -} +/** + * The engine binary of each harness, chosen once when an owner runtime starts with the desktop's rules + * (agent/harness-binary.ts): Pi's explicit selection, then the bundled or dev checkout binary, then the + * profile install that reports the highest version. The harness status reports the same choice. + */ +const harnessBinaries = createHostHarnessBinaries({ + userDataDir: () => resolveHostDataDir(), + harnessRoot: () => hostRuntimeLayout().harnessRoot, + onUnavailable: (kind, error) => hostLog.warn('harness binary unavailable', { kind, error }), +}); -/** Dev checkout binaries, in the same order the Desktop dev lookup uses. */ -const HARNESS_KINDS = ['claude-code', 'codex', 'pi'] as const; -const platformKey = `${process.platform}-${process.arch}`; +/** The refusal a new send gets while a desktop uses this profile, in the system language. */ +const profileInUseMessage = () => `${HOST_PROFILE_IN_USE_BY_DESKTOP}: ${ + createMainI18n(() => [Intl.DateTimeFormat().resolvedOptions().locale]).t('logic.errors.hostProfileInUseByDesktop')}`; +/** The same, for a start that was refused: quit the desktop, then restart the Host. */ +const profileInUseAtStartMessage = () => createMainI18n(() => [Intl.DateTimeFormat().resolvedOptions().locale]) + .t('logic.errors.hostProfileInUseByDesktopAtStart'); +let coexistenceMonitor: CoexistenceMonitor | null = null; +let resumeGeneratedImageRecovery: () => Promise; -function harnessStatus(): Record { - return Object.fromEntries(HARNESS_KINDS.map((kind) => { - const layout = kind === 'claude-code' - ? { dir: 'claude-code-bin', file: AGENT_BINARY_LAYOUT['claude-code'].binaryName } - : kind === 'codex' - ? { dir: 'codex-package-bin', file: AGENT_BINARY_LAYOUT.codex.binaryName } - : { dir: 'pi-bin', file: AGENT_BINARY_LAYOUT.pi.binaryName }; - const status = readCachedBinaryStatus({ - kind, - isPackaged: false, - userDataDir: resolveHostDataDir(), - devCandidates: [ - path.join(hostRuntimeLayout().harnessRoot, layout.dir, platformKey, layout.file), - ].map((candidate) => path.resolve(candidate)), - }); - return [kind, status.binaryReady]; - })); +/** + * Rescan the profile while the runtime runs. A desktop that opens the database holds the input + * queue (new sends refused, nothing queued starts); once it is gone, the queue opens again after the + * running turns end, rebuilt from the database (input-queue.mjs releaseDesktopHold). + */ +function startProfileCoexistence(dataDir: string, scan: () => Promise): void { + coexistenceMonitor?.stop(); + const monitor = createHostProfileCoexistenceMonitor({ + scan, registryDir: path.join(dataDir, '.dev-instances'), log: hostLog, + message: profileInUseMessage(), isCurrent: () => coexistenceMonitor === monitor, + input: { + isHeldForDesktop: () => inputQueue.isHeldForDesktop(), + holdForDesktop: message => inputQueue.holdForDesktop(message), + releaseDesktopHold: () => inputQueue.releaseDesktopHold(), + }, + getPlugins: () => plugins, refreshPlugins: () => pluginGateway?.refresh(), + setState: state => { runtime.coexistence = state; }, + onInputReleased() { + // A Pi receipt retry held while the desktop used the profile runs now (agent/usage-recording.ts). + usageRecording.onProfileReleased(); + void resumeGeneratedImageRecovery(); + hostLog.info('the desktop left this profile; sends are accepted again'); + }, + }); + coexistenceMonitor = monitor; + runtime.coexistence = { state: 'clear', desktops: [] }; + monitor.start(); } + /** * The Desktop's `AuthState.user` projection, resolved from the same adopted * session so the browser identifies the account exactly like the client does. @@ -344,11 +461,22 @@ async function resolveAccountUser(expectedOwner: string | null = runtime.owner): const { sessionToken } = await refreshHostSession({ store, refresh: (token) => client.refresh(token), + withVaultLock: hostAccountVaultLock(resolveHostDataDir()), + buildRegion: hostPackageRegion(), }); const me = await client.getMe(sessionToken); const membership = me?.membership; if (!membership || typeof membership.id !== 'string' || !membership.id) return null; - if (expectedOwner && expectedOwner !== membership.id) throw new Error('The signed-in account does not match the active Host profile'); + // H-2, as the Desktop's cold start and runtime refresh: a rotated token stays in the record of its + // own region, but a personal session of another region is never adopted (treated as signed out). + try { + assertHostSessionRegion({ packageRegion: hostPackageRegion(), sessionRealm: realm, membershipKind: membership.kind }); + } catch (error) { + // As the Desktop's resetActiveAuthRealmToBuild: the refused realm is not kept as the account's. + account = { authenticated: false, realm: null }; + throw error; + } + if (expectedOwner && expectedOwner !== membership.id) throw new HostAccountMismatchError(); currentSessionToken = sessionToken; currentDeviceId = verifiedDeviceId; remoteIdentityReady = canRegisterHostDevice(store.read(AUTH_SESSION_KEY), () => resolveRuntimeDeviceId(machineIdSync, '')); @@ -369,30 +497,94 @@ let refreshTimer: NodeJS.Timeout | null = null; let authClosed = false; let authRefreshFlight: Promise | null = null; -async function refreshAuthSession(): Promise { +/** Advanced when the session ends or the runtime is disposed: a later timer or result of the old one does nothing. */ +let authRefreshEpoch = 0; +const authRefreshBackoff = new AuthRefreshBackoff(); +/** + * The one renewal of the account session (auth/refresh.mjs). Its callers: the renewal timer + * (scheduleAuthRefresh), the server API's 401 retry, Device Link's auth failure, the first startup, + * /api/auth/refresh. As the desktop's refresh(): one at a time, a caller during a retry's wait gets + * false instead of a request, and the server API's 401 after a network failure may bring the retry + * forward (`serverRejectedToken`, AuthRefreshBackoff). Not refused while a desktop holds the profile + * (the exception C); /api/auth/refresh is in the service gate's list of paths allowed then. + */ +async function refreshAuthSession(options?: { serverRejectedToken?: boolean }): Promise { if (authClosed) return false; + const epoch = authRefreshEpoch; + if (options?.serverRejectedToken && authRefreshBackoff.serverRejectedToken(epoch)) + armAuthRefreshTimer(epoch, authRefreshBackoff.runtimeRemaining(epoch)); if (authRefreshFlight) return authRefreshFlight; + if (authRefreshBackoff.runtimeRemaining(epoch) > 0) return false; + clearAuthRefreshTimer(); + authRefreshBackoff.startRuntimeAttempt(epoch); authRefreshFlight = performAuthRefresh().finally(() => { authRefreshFlight = null; }); return authRefreshFlight; } +function clearAuthRefreshTimer(): void { + if (refreshTimer) { clearTimeout(refreshTimer); refreshTimer = null; } +} +const MAX_TIMER_DELAY_MS = 2_147_483_647; +/** An access token already due when it arrives (a skewed clock) renews after this, not in a loop. */ +const DUE_ACCESS_TOKEN_RENEWAL_DELAY_MS = 60_000; +/** + * The desktop's scheduleRefresh: renew at the access token's exp minus 300 s (authTokenClaims.ts + * accessTokenRefreshDelayMs; the token lives about 60 minutes, inferred, not verified on the + * server). A token that is not a JWT with an exp schedules nothing, as on the desktop. + */ +function scheduleAuthRefresh(epoch = authRefreshEpoch): void { + if (authClosed || epoch !== authRefreshEpoch) return; + authRefreshBackoff.clear(); + clearAuthRefreshTimer(); + if (!currentSessionToken) return; + let delay: number; + try { delay = accessTokenRefreshDelayMs(currentSessionToken, Date.now()); } catch { return; } + if (!Number.isFinite(delay)) return; + armAuthRefreshTimer(epoch, delay > 0 ? delay : DUE_ACCESS_TOKEN_RENEWAL_DELAY_MS); +} +/** The desktop's scheduleRefreshRetryAfterTransientFailure: retry with its jittered backoff. */ +function deferAuthRefresh(epoch: number, error: unknown): void { + if (authClosed || epoch !== authRefreshEpoch) return; + const deferred = error instanceof HostRefreshDeferredError ? error : null; + const delay = authRefreshBackoff.defer(epoch, deferred?.retryAt, deferred?.networkFailure ?? false); + armAuthRefreshTimer(epoch, delay); +} +function armAuthRefreshTimer(epoch: number, delay: number): void { + clearAuthRefreshTimer(); + const due = Date.now() + delay; + const fire = () => { + refreshTimer = null; + if (authClosed || epoch !== authRefreshEpoch) return; + // A long wait is armed in chunks the timer can hold, without moving its deadline. + const remaining = Math.max(due - Date.now(), authRefreshBackoff.runtimeRemaining(epoch)); + if (remaining > 0) { refreshTimer = setTimeout(fire, Math.min(remaining, MAX_TIMER_DELAY_MS)); refreshTimer.unref(); return; } + void refreshAuthSession(); + }; + refreshTimer = setTimeout(fire, Math.min(delay, MAX_TIMER_DELAY_MS)); + refreshTimer.unref(); +} async function performAuthRefresh(): Promise { + const epoch = authRefreshEpoch; try { const user = await resolveAccountUser(); if (user) { accountUser = user; account = { authenticated: true, realm: account.realm ?? resolveHostRegion() }; eventHub.publish({ type: 'auth_changed', ...projectAuthState() }); + scheduleAuthRefresh(epoch); return true; } + deferAuthRefresh(epoch, null); return false; } catch (error) { - if (isDefinitiveRefreshError(error)) { + // Only a definitive rejection of the token still stored, or a stored session that is gone, ends + // the session (in this process; no stored credential is deleted). Anything else renews again later. + if (isDefinitiveRefreshError(error) || error instanceof HostSessionMissingError || error instanceof HostCrossRegionPersonalAccountError) { // Refresh may belong to an admitted HTTP request. Raise the boundary now, // but let that request unwind before waiting for the HTTP drain. void invalidateHostSession('account-unavailable').catch(error => { console.warn('[host] expired-account cleanup failed:', error instanceof Error ? error.message : 'cleanup failed'); }); - } + } else deferAuthRefresh(epoch, error); console.warn('[host] auth refresh failed:', error instanceof Error ? error.message : String(error)); return false; } @@ -401,12 +593,18 @@ async function performAuthRefresh(): Promise { let invalidation: Promise | null = null; function invalidateHostSession(_reason: string): Promise { if (invalidation) return invalidation; - const release = beginAppSessionBoundary(); - account = { authenticated: false, realm: account.realm, error: 'Sign in again with cindy-host login' }; - currentSessionToken = null; - remoteIdentityReady = false; - invalidation = Promise.resolve().then(async () => { - try { + let release = () => {}; + // The owner boundary's stop first (agent/owner-boundary.ts), then this path's teardown. Everything before + // the first await below runs before this returns: the boundary is raised synchronously, as before. + invalidation = runOwnerBoundary(ownerBoundary, { + beforeDispose: async () => { + release = beginAppSessionBoundary(); + account = { authenticated: false, realm: account.realm, error: 'Sign in again with cindy-host login' }; + endAuthRefreshes(); + currentSessionToken = null; + remoteIdentityReady = false; + // A refresh that called this belongs to an admitted request: let it unwind before the drain. + await Promise.resolve(); const requestsDrained = server.pauseOwnerRequests(); // Cancel user waits before draining HTTP handlers. A pending confirmation // must not keep expired-account requests (and their database) alive forever. @@ -417,14 +615,14 @@ function invalidateHostSession(_reason: string): Promise { interactionBroker.dispose(); await pluginGateway?.host.reset(); await requestsDrained; - await disposeOwnerRuntime(); - } finally { - commitVolatileAppSession('signed-out', null, true); - release(); - runtime.state = 'uninitialized'; runtime.owner = null; runtime.storage = 'unopened'; - runtime.detail = 'Sign-in expired. Stop the Host, sign in again, then start it.'; - eventHub.clear(); - } + }, + dispose: disposeOwnerRuntime, + }).then(({ errors }) => { if (errors.length) throw errors[0]; }).finally(() => { + commitVolatileAppSession('signed-out', null, true); + release(); + runtime.state = 'uninitialized'; runtime.owner = null; runtime.storage = 'unopened'; + runtime.detail = 'Sign-in expired. Stop the Host, sign in again, then start it.'; + eventHub.clear(); }).finally(() => { invalidation = null; }); return invalidation; } @@ -433,17 +631,19 @@ const serverApi = createHostServerApi({ invalidate: invalidateHostSession, locale: () => Intl.DateTimeFormat().resolvedOptions().locale, }); -function schedulePeriodicRefresh(): void { - if (refreshTimer) clearInterval(refreshTimer); - refreshTimer = setInterval(() => { - void refreshAuthSession(); - }, 30 * 60 * 1000); - refreshTimer.unref(); +/** No renewal of the ended session or disposed runtime runs or is armed again. */ +function endAuthRefreshes(): void { + authRefreshEpoch += 1; + clearAuthRefreshTimer(); + authRefreshBackoff.clear(); } /** Claude subscription state read once per boot; never on the health path. */ let claudeState: Record | null = null; /** Real maker-core agents registered in this process. */ let agentGraph: ReturnType | null = null; +let taskRuntimePlugins: ReturnType | null = null; +/** The maker's session-closed subscription of the current agent graph (runtime-selection.ts). */ +let offMakerSessionClosed: (() => void) | null = null; /** The desktop Git snapshot coordinator for this owner's tasks (agent/git-snapshot.ts). */ let gitSnapshot: HostGitSnapshot | null = null; const hostLog = createLogger('host'); @@ -452,6 +652,22 @@ let codexRuntime: ReturnType | null = null; let claudeProxy: ReturnType | null = null; let mcpRuntime: ReturnType | null = null; let agentAuth: ReturnType | null = null; +/** The XD gateway prices and reference prices of this process's account (release table row 13, 3a). */ +const usagePricing = createHostUsagePricing({ + profileDir, + modelAccessApiBaseUrl: () => readAuthEndpoints((account.realm ?? resolveHostRegion()) as 'cn' | 'global').modelAccessApiBaseUrl, +}); +/** + * The desktop's turn usage recorders over this process's owner database (release table row 13, 3d; + * agent/usage-recording.ts). Reads only in-memory credentials: the gateway key and the Codex proxy mode. + */ +const usageRecording = createHostUsageRecording({ + pricing: usagePricing, + isOpenAiSubscriptionProviderId: id => providerConfig?.codexAccounts.isOpenAiSubscriptionProviderId(id) ?? false, + readGatewayKey: () => currentGateway()?.credential ?? null, + codexProxyAuthInjection: () => codexRuntime?.proxy.getCodexProxyAuthInjection() ?? 'env-key', + isProfileHeld: () => inputQueue.isHeldForDesktop(), +}); const listProviders = createProviderCatalog({ readProviders: connected => providerConfig?.publicViews(connected) ?? Promise.resolve([]), // Keep each engine's model list in step with the account's models (the desktop refreshes on catalog change). @@ -475,6 +691,12 @@ const listProviders = createProviderCatalog({ return parsed.models; }, readOwner: () => ({ ...getActiveAppSession(), pending: isAppSessionBoundaryPending() }), + // The desktop's applyGatewayModels replaces the XD prices from the same /models response, and its + // model sync registers each round so billing waits briefly for it (model-access/index.ts). + applyPricedModels: (models, ownerId) => { usagePricing.replaceGatewayModelPricing(models, ownerId); }, + trackModelsSync: sync => usagePricing.trackGatewayModelPricingSync(sync), + // Coexistence plan A: no /models round while a desktop uses this profile (agent/providers.mjs). + isProfileHeld: () => inputQueue.isHeldForDesktop(), }); let stopPluginAuthorization: (() => void) | null = null; let platformClient: ReturnType | null = null; @@ -489,7 +711,6 @@ let modelAccess: ReturnType | null = null; const currentGateway = () => modelAccess?.gateway.credential && modelAccess.gateway.endpoint ? modelAccess.gateway : null; /** Owner-scoped Maker Memory; null until the runtime owns an account. */ let makerMemory: ReturnType | null = null; -const hostHistoryReader = createHostHistoryReader(isProvisionalSession); /** Non-secret projection of the adopted Desktop login; never tokens. */ let account: { authenticated: boolean; realm: string | null; error?: string } = { authenticated: false, realm: null }; @@ -513,6 +734,34 @@ async function ensureRuntime(ownerId: string): Promise { } runtimeLease = lease; + // Coexistence plan A: the runtime lease only stops a second Host. A desktop that opens this + // profile's database refuses the start: the lease is released and the Host stays blocked until it + // is restarted (no automatic retry). A scan that cannot read the registry refuses as well. + const scanProfile = createDesktopScanner(dataDir); + let desktops: number[]; + try { + desktops = await scanProfile((round, elapsedMs, result) => { + if (round > 1 || result === 'unknown' || result === 'deadline') { + hostLog.info('startup desktop identity check', { round, elapsedMs, result }); + } + }); + } + catch (error) { + runtimeLease = null; lease.release(); + runtime.state = 'blocked'; runtime.owner = ownerId; runtime.storage = 'unopened'; + runtime.coexistence = { state: 'desktop-running', desktops: [] }; + // The error code only: the message would carry the profile path into the status. + runtime.detail = `cannot tell whether a Cindy desktop app uses this profile (${(error as NodeJS.ErrnoException)?.code ?? 'unreadable'}); quit it and start cindy-host again`; + throw new HostProfileInUseError(runtime.detail); + } + if (desktops.length) { + runtimeLease = null; lease.release(); + runtime.state = 'blocked'; runtime.owner = ownerId; runtime.storage = 'unopened'; + runtime.coexistence = { state: 'desktop-running', desktops }; + runtime.detail = `a Cindy desktop app (pid ${desktops.join(', ')}) is running on this profile; quit it and start cindy-host again`; + throw new HostProfileInUseError(runtime.detail); + } + // Verify the credential owner under the profile lease, before opening any // database or constructing an agent. Refresh errors here must not be swallowed // by the periodic refresh path: an account B login cannot run on A's data. @@ -522,7 +771,7 @@ async function ensureRuntime(ownerId: string): Promise { keyringApplication: process.env.CINDY_HOST_KEYRING_APPLICATION?.trim() || undefined, }); account = { authenticated: false, realm: state.realm }; - if (!state.authenticated) throw new Error('Sign in with `cindy-host login` before opening account data'); + if (!state.authenticated) throw new HostSignInRequiredError(); if (state.authenticated) { const user = await resolveAccountUser(ownerId); if (!user) throw new Error('Unable to verify the signed-in Host account'); @@ -532,6 +781,8 @@ async function ensureRuntime(ownerId: string): Promise { } configureHostOwner({ userDataDir: dataDir, ownerId }); + // Option A: the window commits the owner, the Host only reads it (logs when it is not stable). + observeSkillProjectionBoundary(ownerId); const opened = await openOwnerDatabase({ userDataDir: dataDir, ownerId, @@ -560,10 +811,24 @@ async function ensureRuntime(ownerId: string): Promise { }; configureProvisionalSessions(dataDir, { onSwept: sessionId => eventHub.publish({ type: 'session_changed', action: 'delete', sessionId }) }); await sweepLeftoverProvisionalSessions(); + // As the desktop at startup (bootstrap-electron.ts): Cindy-owned Skill activation and the home-level + // projections, through the stable-owner boundary. Not awaited: the core logs failures, and every launch + // and Skill list runs it again before it needs the result, so startup does not wait on its locks. + void sharedGlobalSkills.ensureSharedGlobalSkills(); // Desktop runs this repair once the account DB is ready (bootstrap-electron.ts): // savepoint refs of tasks this DB marks deleted are removed from their repos. void reconcileSavepointRefsForDeletedSessions().catch(error => hostLog.warn('savepoint reconcile postponed', { error: error instanceof Error ? error.message : String(error) })); + // As the desktop once the account DB is ready (localDb/ipc/registerAll.ts): generated images' cleanup + // receipts resume (agent/generated-images.ts binds the recovery). + void reconcileGeneratedImageRecovery().catch(() => hostLog.warn('native image cleanup reconciliation deferred')); + // As the desktop once the account DB is ready (bootstrap-electron.ts): the account currency and the + // last price snapshot come back from disk before the first /models round. + // Usage recording resumes for this owner database; then, as the desktop (bootstrap-electron.ts :10384), + // pending Pi receipts are priced once the prices are back. + usageRecording.open(); + void usagePricing.prewarmModelPricing().then(() => usageRecording.retryPending()).catch(error => + hostLog.warn('model pricing prewarm failed', { error: error instanceof Error ? error.message : String(error) })); runtime.owner = ownerId; runtime.storage = 'ready'; delete runtime.detail; @@ -571,10 +836,14 @@ async function ensureRuntime(ownerId: string): Promise { const pluginOwner = activeOwnerScopeKey(); const credentials = await createCredentialStore({ userDataDir: dataDir, keyringApplication: process.env.CINDY_HOST_KEYRING_APPLICATION?.trim() || undefined }); + // The engine binaries this owner runtime uses, read once (the model settings use the same ones). + const harnessBinaryPaths = await harnessBinaries.resolve(); providerConfig = createHostProviderConfig({ profileDir: dataDir, ownerId, credentials, + // Coexistence plan A: the xAI login is neither renewed nor signed out while held (agent/xai-held-login.ts). + isProfileHeld: () => inputQueue.isHeldForDesktop(), gatewayConnected: () => Boolean(currentGateway()), - getCodexBinary: () => harnessBinaryPath('codex'), - getClaudeBinary: () => harnessBinaryPath('claude-code'), + getCodexBinary: () => harnessBinaryPaths.codex, + getClaudeBinary: () => harnessBinaryPaths['claude-code'], publish: (channel, payload) => eventHub.publish({ type: 'plugin_push', channel, payload }), openExternal: async url => { await openSystemBrowser(url); } }); await providerConfig.loadCatalog({ @@ -592,7 +861,12 @@ async function ensureRuntime(ownerId: string): Promise { if (!baseUrl) throw new Error('Model access endpoint is unavailable'); return serverApi(route, { baseUrl, method, redactErrorDetails: true }); }, - publish: status => eventHub.publish({ type: 'plugin_push', channel: MODEL_ACCESS_STATUS_CHANNEL, payload: status }), + publish: status => { + eventHub.publish({ type: 'plugin_push', channel: MODEL_ACCESS_STATUS_CHANNEL, payload: status }); + // As the desktop's onStatusChange (model-access/index.ts): a failed account's prices go, and + // come back with the next /models round after ok. Price changes are not pushed yet (row 13, 3f). + listProviders.noteCredentialStatus(status); + }, onKeyChanged: () => agentGraph?.gatewayRestart.schedule(), }); await modelAccess.start(); @@ -606,6 +880,7 @@ async function ensureRuntime(ownerId: string): Promise { }, onChanged: ghosts => { if (activeOwnerScopeKey() !== pluginOwner || isAppSessionBoundaryPending()) return; + if (inputQueue.isHeldForDesktop() || plugins?.pluginPauseFailure()) return; eventHub.publish({ type: 'plugin_push', channel: 'ghosts:changed', payload: { ghosts } }); void plugins?.reconcile().then(() => pluginGateway?.refresh()) .catch(error => console.warn('[host] plugin reconciliation failed:', error.message)); @@ -615,6 +890,7 @@ async function ensureRuntime(ownerId: string): Promise { const i18n = createMainI18n(() => [Intl.DateTimeFormat().resolvedOptions().locale]); hostConfirmations = createHostConfirmations({ current: toolOwnerCurrent }); hostTools = createHostToolService({ profileDir: dataDir, ownerId, + profileHold: () => inputQueue.isHeldForDesktop() ? profileInUseMessage() : null, deviceId: () => currentDeviceId ?? 'local', onProjectsChanged: catalogChanged => eventHub.publish({ type: 'project_aliases_changed', catalogChanged }), owner: () => ({ dataOwnerId: getActiveAppSession().dataOwnerId, ownerGeneration: getActiveAppSession().generation }), @@ -627,6 +903,12 @@ async function ensureRuntime(ownerId: string): Promise { }, }); plugins = await createHostPluginRuntime({ profileDir: dataDir, ownerId, manager: pluginManager, credentials, + modelRouteSources: () => ({ + localViews: () => providerConfig?.publicViews(Boolean(currentGateway()?.credential)) ?? Promise.resolve([]), + localAgents: () => agentGraph?.maker.listAvailableAgents() ?? [], + }), + // Coexistence plan A: plugin OAuth renews and writes nothing while held (plugins/authorization.ts). + isProfileHeld: () => inputQueue.isHeldForDesktop(), hostToolRequest: hostTools.request, onPluginStopped: hostTools.stopPlugin, getLoginEmail: () => accountUser?.email ?? null, getUser: () => accountUser, @@ -659,8 +941,9 @@ async function ensureRuntime(ownerId: string): Promise { } else eventHub.publish({ type: 'plugin_push', channel, payload }); }, }); + if (inputQueue.isHeldForDesktop()) plugins.pauseForDesktop(profileInUseMessage()); - if (pluginManager.hasPendingMutationRecovery()) await pluginManager.retryInterruptedMutationsAfterDbReady(); + if (!plugins.pluginPauseFailure() && pluginManager.hasPendingMutationRecovery()) await pluginManager.retryInterruptedMutationsAfterDbReady(); pluginGateway = createHostPluginGateway({ runtime: plugins, profileDir: dataDir, ownerId, version: layout.version, credentials, fileConfirmation, @@ -701,6 +984,20 @@ async function ensureRuntime(ownerId: string): Promise { }, }); + const taskPlugins = plugins.taskPlugins; + warmRuntimePluginSettings(); + setGhostToolApprovalResolver(taskPlugins.resolveToolApproval); + taskRuntimePlugins = createHostTaskRuntimePlugins({ + getMaker: () => { + if (!agentGraph) throw new Error('Agent runtime is unavailable'); + return agentGraph.maker; + }, + pluginHost: taskPlugins, selection: runtimeSelection, log: hostLog, + publish: event => { + if (plugins?.taskPlugins === taskPlugins && toolOwnerCurrent()) eventHub.publish(event); + }, + }); + stopPluginAuthorization = initializeHostPluginRemoteAuthorization({ authorization: plugins.authorization, root: (...parts) => ownerScopedPath(dataDir, ownerId, ...parts), credentials, identity: () => currentDeviceId && remoteIdentityReady && account.authenticated && accountUser?.id === ownerId @@ -726,14 +1023,19 @@ async function ensureRuntime(ownerId: string): Promise { hostTools.providers.push(...platformTools.providers); hostTools.services.replace(hostTools.providers); - const claudeBinary = harnessBinaryPath('claude-code'); - const codexBinary = harnessBinaryPath('codex'); - const piBinary = harnessBinaryPath('pi'); + const claudeBinary = harnessBinaryPaths['claude-code']; + const codexBinary = harnessBinaryPaths.codex; + const piBinary = harnessBinaryPaths.pi; if (claudeBinary || codexBinary || piBinary) { const gateway = modelAccess!.gateway; + const memoryProfileHold = () => inputQueue.isHeldForDesktop() ? profileInUseMessage() : null; // Memory uses the same owner-scoped store Desktop reads, so a task started // here sees the same memories as a task started there. - makerMemory = createHostMemoryManager({ userDataDir: dataDir, ownerId, getMaker: () => agentGraph?.maker ?? null }); + let memoryReview: ReturnType['autoReview']['memoryReview']> | undefined; + makerMemory = createHostMemoryManager({ userDataDir: dataDir, ownerId, profileHold: memoryProfileHold, review: { + isOneShotRouteDisabled: agent => memoryReview?.isOneShotRouteDisabled(agent) ?? Promise.resolve(true), + reviewOneShot: (...args) => memoryReview?.reviewOneShot(...args) ?? Promise.resolve(null), + } }); // Flip the flag before the agents are built: their runtimeConfig snapshots it // at construction, and native-agent syncoff needs the agents that do not exist yet. if (makerMemory.isEnabled()) await makerMemory.enable({ skipAgentSync: true }); @@ -742,6 +1044,8 @@ async function ensureRuntime(ownerId: string): Promise { if (codexBinary) codexRuntime = createHostCodexRuntime({ profileDir: dataDir, binaryPath: codexBinary, config: providerConfig, modelAccess: modelAccess!, availabilityPolicy: availabilityPolicy!, mcp: mcpRuntime, publish: (channel, payload) => eventHub.publish({ type: 'plugin_push', channel, payload }), + // Coexistence plan A: the subscription bridge neither reconciles nor renews (agent/codex-runtime.ts). + isProfileHeld: () => inputQueue.isHeldForDesktop(), }); if (claudeBinary || piBinary) { claudeProxy = createHostClaudeProxyRuntime({ profileDir: dataDir, @@ -757,13 +1061,20 @@ async function ensureRuntime(ownerId: string): Promise { await claudeProxy.ready(); } agentGraph = createHostAgentGraph({ - onSessionClose: (id: string) => platformTools?.closeSession(id), + onSessionClose: (id, close) => { + if (!close.transient && (close.reason === 'requested' || close.reason === 'unexpected')) + taskRuntimePlugins?.forgetSession(id); + return platformTools?.closeSession(id); + }, + toolLifecycleControl: taskPlugins.ghostToolLifecycleControl, codexRuntime, claudeProxy, providerConfig, mcpRuntime, isSessionInTurn: (id: string) => inputQueue.isTurnRunning(id), wakeSession: (id: string, reason: string) => inputQueue.wakeSession(id, reason), + // Coexistence plan A: reading a login state writes nothing the desktop shares (agent/runtime.ts). + isProfileHeld: () => inputQueue.isHeldForDesktop(), // A task restored at startup waits for the account's models, as on the desktop. ensureProviderCatalog: () => listProviders({ gateway: currentGateway(), ownerId: runtime.owner }), getGhostRosterPrompt: pluginGateway.rosterPrompt, @@ -785,14 +1096,20 @@ async function ensureRuntime(ownerId: string): Promise { makerMemory, reportGatewayKeyRejected: key => modelAccess?.reportRejectedKey(key), readAuthRealm: () => account.realm, - mcpProviders: await pluginGateway.prepareMcpProviders([...hostTools.providers, ...createHostMemoryMcpProviders(makerMemory), pluginGateway.provider]), + sharedGlobalSkills, + mcpProviders: await pluginGateway.prepareMcpProviders([...hostTools.providers, ...createHostMemoryMcpProviders(makerMemory, { readsAccountHistory: hostTools.readsAccountHistory, deviceId: () => currentDeviceId ?? '', searchProviders: taskPlugins.searchGhostRuntimeMemories, profileHold: memoryProfileHold }), pluginGateway.provider]), userDataDir: dataDir, }); + memoryReview = agentGraph.autoReview.memoryReview(memoryProfileHold); // The desktop's Auto-review authorization context (review-context.ts). agentGraph.autoReview.setContextResolver(createHostReviewContextResolver({ acceptedInput: (id: string) => inputQueue.acceptedInputProvenance(id), })); attachAgentsToMakerMemory(makerMemory, agentGraph.instances); + // Every runtime close of a task, whichever path closed it (idle release, engine switch, rebuild, + // delete, shutdown): the Maker emits it from the session's own close, as the desktop's per-session + // status listener finalizes it (sessionBindingLifecycle.ts). + offMakerSessionClosed = runtimeSelection.attachMaker(agentGraph.maker); gitSnapshot = createHostGitSnapshot(agentGraph.maker); agentAuth = createHostAgentAuth({ maker: agentGraph.maker, readApiKey: () => gateway?.credential ?? null, publish: (channel, payload) => eventHub.publish({ type: 'plugin_push', channel, payload }) }); @@ -800,6 +1117,8 @@ async function ensureRuntime(ownerId: string): Promise { if (makerMemory.isEnabled()) await makerMemory.enable(); runtime.agents = [...agentGraph.agents]; runtime.agentLane = currentGateway() ? 'gateway-key' : 'claude-subscription'; + // Idle ordinary tasks release their runtimes from here on, as on the desktop (idle-release.ts). + inputQueue.startIdleRelease(); } if (claudeBinary) { @@ -812,7 +1131,9 @@ async function ensureRuntime(ownerId: string): Promise { } await plugins.reconcile(); await pluginGateway.refresh(); + startProfileCoexistence(dataDir, scanProfile); runtime.state = 'ready'; + runtime.unavailable = null; } const eventHub = createEventHub(); @@ -851,6 +1172,8 @@ const hostProviderGroups = createProviderGroupStore({ withAvailabilityPolicyMutation: async () => { throw new Error('[UNSUPPORTED_CAPABILITY] Host cannot change provider groups'); }, }); const hostProviderBindings = createProviderGroupBindings(hostProviderGroups); +// The send path and the Device Link create entry refuse provider group tasks with this one check. +const assertProviderExecutionSupported = createHostProviderExecutionCheck({ hostProviderBindings, hostProviderGroups }); const readSessionForRun = async (sessionId: string) => { const db = getDbClient(); const rows = await db.drizzle.select().from(sessionTable) @@ -874,96 +1197,6 @@ const readSessionForRun = async (sessionId: string) => { fastMode: row.fastMode, planModeEnabled: row.planModeEnabled, }; }; -/** Runtime choices applied at dispatch (Device Link) or on enqueue (legacy web engine switches). */ -const pendingAgentSwitches = new Map(); - -function projectAgentSwitchIntent(intent: { - targetAgentKind: 'claude-code' | 'codex' | 'pi'; - model: string; - providerId: string | null; - effort?: string; - fastMode?: boolean | 'ultrafast'; -} | undefined): Record | null { - if (!intent) return null; - return { - targetAgentKind: intent.targetAgentKind, - model: intent.model, - providerId: intent.providerId, - ...(intent.effort ? { effort: intent.effort } : {}), - ...(intent.fastMode !== undefined ? { fastMode: intent.fastMode } : {}), - }; -} - -function stageAgentSwitch(sessionId: string, intent: NonNullable>) { - pendingAgentSwitches.set(sessionId, intent); - eventHub.publish({ type: 'session_changed', sessionId, patch: { agentSwitchIntent: projectAgentSwitchIntent(intent) } }); -} - -function captureModelSelectionOwner() { - const owner = captureDataOwnerBroadcastScope(); - const epoch = getCurrentDbClientSnapshot()?.clientEpoch; - return { - assertCurrent() { - if (epoch === undefined || !isDataOwnerBroadcastScopeCurrent(owner) || getCurrentDbClientSnapshot()?.clientEpoch !== epoch) { - throwIpcError('PRECONDITION_FAILED', 'Host account changed; runtime selection was not changed'); - } - }, - }; -} - -// Enqueue takes the route lock here. The send and explicit Pi Skill preparation -// paths already hold that same lock and call the unlocked application. -const applyPendingAgentSwitch = lockSessionRoute((sessionId: string) => applyPendingAgentSwitchUnlocked(sessionId)); -async function applyPendingAgentSwitchUnlocked( - sessionId: string, - prepare?: Pick & { - assertPreparationCurrent?(): void; - }, - assertLegacyPreparationCurrent?: () => void, -): Promise { - const intent = pendingAgentSwitches.get(sessionId); - if (!intent || Boolean(intent.deviceLinkOwner) !== Boolean(prepare)) return; - const assertIntentCurrent = () => { - if (pendingAgentSwitches.get(sessionId) !== intent) throw new Error('The selected route changed; retry the send'); - }; - const assertCurrent = () => { - intent.deviceLinkOwner?.assertCurrent(); - prepare?.signal?.throwIfAborted(); - prepare?.assertPreparationCurrent?.(); - assertLegacyPreparationCurrent?.(); - assertIntentCurrent(); - }; - assertCurrent(); - const patch = { - model: intent.model, - providerId: intent.providerId, - ...(intent.effort ? { effort: intent.effort } : {}), - ...(intent.fastMode !== undefined ? { fastMode: intent.fastMode } : {}), - }; - if (intent.deviceLinkOwner && prepare) { - const before = await readSessionForRun(sessionId); - assertHostTaskExecutionSupported(before); - if (before.agentKind !== intent.targetAgentKind) { - throwIpcError('PRECONDITION_FAILED', 'the task Harness changed; select the model again'); - } - await updateHostSession(sessionId, patch, { - assertCurrent, signal: prepare.signal, nextInputChars: prepare.nextInputChars, - prepareModelWindowSwitch: prepare.prepareModelWindowSwitch, - }); - } else { - await updateHostSession(sessionId, { agentKind: intent.targetAgentKind, ...patch }, undefined, assertCurrent); - } - assertIntentCurrent(); - pendingAgentSwitches.delete(sessionId); - eventHub.publish({ type: 'session_changed', sessionId, patch: { agentSwitchIntent: null } }); -} const interactionBroker = createInteractionBroker({ hub: eventHub }); const fileConfirmation = new GhostGrantConfirmBridge({ broadcast: (channel, payload) => eventHub.publish({ @@ -1000,10 +1233,27 @@ const interactions = { }; const insertSessionMessage = createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: (event: unknown) => eventHub.publish(event) }); +// Codex generated images, stored and delivered as on the desktop (agent/generated-images.ts). +const generatedImages = createHostGeneratedImages({ + createMessage: (sessionId, body, opts) => insertSessionMessage(sessionId, body, opts), + publish: (event: unknown) => eventHub.publish(event), + isProfileHeld: () => inputQueue.isHeldForDesktop(), + registerProfileRelease: resumeRecovery => { resumeGeneratedImageRecovery = resumeRecovery; }, +}); const messageRecovery = createHostMessageRecovery({ getOwner: getCurrentDbClientSnapshot, publish: (event: unknown) => eventHub.publish(event) }); +// Shared database writers that change a task's route (restoring an archived task) take the task's send +// lock through this bridge, as on the desktop (localDb/ipc/registerAll.ts installs the same lock). +setSessionRouteLockImplementation(withSendToSessionLock); +// Making an archived task active: sending to it, and the task list's restore (task-restore.ts); the +// restore is recorded for idle archiving, as the desktop's task management records it. +bindTaskRestoreRetention(); +const taskRestore = createHostTaskRestore({ getOwner: getCurrentDbClientSnapshot, + isHeldForDesktop: () => inputQueue.isHeldForDesktop(), + publish: event => eventHub.publish(event) }); + // The pending handoff summary: one registry for the Host process, as the desktop's singleton. const pendingHandoff = createHostAgentHandoffPending({ getOwner: getCurrentDbClientSnapshot, publish: event => eventHub.publish(event), log: createLogger('agent-handoff-pending') }); @@ -1021,21 +1271,35 @@ const contextRecovery = createHostContextRecoveryWiring({ publish: event => eventHub.publish(event), pendingHandoff, log: createLogger('context-recovery'), -}); -const updateHostSession = createHostSessionUpdate({ - getLiveSession: (sessionId: string) => agentGraph?.maker.getSession(sessionId), - closeRejectedPiRuntime: (sessionId, expected) => withRehydrateCloseSuppressed(sessionId, async () => { - const maker = agentGraph?.maker; - const live = maker?.getSession(sessionId); - if (live && live === expected) await maker?.closeSessionIfCurrent(live, 'runtime-refresh'); - }), - readSessionForRun, - publish: event => eventHub.publish(event), - modelWindow: () => agentGraph?.modelWindow ?? null, + rehydrateColdPiRuntimeForWindowVerification: sessionId => runtimeSelection.rehydrateColdPiRuntimeForWindowVerification(sessionId), }); const inputQueue = createInputQueue({ - applyPendingAgentSwitch: applyPendingAgentSwitchUnlocked, + getTaskRuntimePlugins: () => taskRuntimePlugins, getOwner: getCurrentDbClientSnapshot, + // The turn usage recorders (agent/usage-recording.ts), fed by the turn executor. + usage: usageRecording, + // The task list's activity time when a person's turn is dispatched or steered (register.ts + // touchSessionActivityInDb, the same write: agent/session-activity.ts). + touchSessionActivity: createHostSessionActivity({ getOwner: getCurrentDbClientSnapshot, publish: event => eventHub.publish(event) }), + // The runtime selection's hooks (runtime-selection.ts): a model or engine the user picked lands when + // the message is sent; as register.ts, the coordinator holds a task's queue while a credential switch + // waits for its turn to end or a gateway Codex restart is running (deferredRestartQueueWiring.ts), and + // idle release only looks at the pending switch (claudeIdleReleaseWatcher's isHostBusy); at a turn's + // end the pending credential switch, then the gateway restart; a runtime's own Plan change is saved. + ...hostRuntimeSelectionQueueHooks(() => runtimeSelection, { + isSessionRestarting: (id: string) => agentGraph?.gatewayRestart.isSessionRestarting(id) ?? false, + afterTurnSettled: () => agentGraph?.gatewayRestart.onSessionSettled(), + }), + restoreArchivedSessionForSend: taskRestore.restoreArchivedSessionForSend, + // Another device's task is read over Device Link, which the Host does not have: it answers as the + // desktop does when no link is connected (the reference is reported unavailable). + resolveSessionReferences: (refs: Parameters[1], options: Parameters[2]) => + resolveSessionReferencesWithPorts({ + getSelfDeviceId: () => currentDeviceId ?? '', + invokeRemote: async () => ({ ok: false, error: { code: 'NOT_CONNECTED', message: 'Host has no Device Link' } }), + } as Parameters[0], refs, options), + // The profile root's claude-idle-release.json, which the desktop window reads too (read-only here). + readClaudeIdleMinutes: () => readClaudeIdleMinutesFrom(profileDir), pendingHandoff, ...contextRecovery, createAttachments: ({ assertCurrent }: { assertCurrent(): void }) => createHostAttachments({ @@ -1048,16 +1312,9 @@ const inputQueue = createInputQueue({ }, getGitSnapshot: () => gitSnapshot, hub: eventHub, - hasPendingCredentialSwitch: (id: string) => agentGraph?.gatewayRestart.isSessionRestarting(id) ?? false, reportAgentCindyGatewayKeyRejected: () => modelAccess?.reportCurrentKeyRejected(), - onSessionSettled: () => agentGraph?.gatewayRestart.onSessionSettled(), readSession: readSessionForRun, - assertProviderExecutionSupported: (id: string, providerId?: string | null) => { - if (hostProviderBindings.readProviderGroupBinding(id) - || (providerId && hostProviderGroups.readProviderGroup(providerId))) { - throw new Error('[UNSUPPORTED_CAPABILITY] Host does not yet support provider groups'); - } - }, + assertProviderExecutionSupported, readSessionExtraDirs: readSessionExtraDirsFromDb, readSessionWritableDirs: readSessionWritableDirsFromDb, readMcpAppModelContext: async (id: string) => (await pluginGateway?.modelContext(id)) @@ -1065,6 +1322,7 @@ const inputQueue = createInputQueue({ ackInterruptedTurnDispatched: ackSessionTurnEndedDurable, ...messageRecovery, persistMessage: insertSessionMessage, + deliverCodexGeneratedImage: generatedImages.deliverCodexGeneratedImage, persistQueueSnapshot: saveAgentInputQueueSnapshot, loadQueueSnapshot: loadAgentInputQueueSnapshot, getPersistedClientIds: getPersistedInputClientIds, @@ -1081,17 +1339,66 @@ const inputQueue = createInputQueue({ if (!row) throw new Error('session not found'); return row.clearedAt; }, - touchUserSend: async (sessionId: string, atMs?: number) => { - const owner = getCurrentDbClientSnapshot(); - if (!owner) throw new Error('DbClient not ready'); - const ts = typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0 ? Math.floor(atMs) : Date.now(); - const [row] = await touchUserSendRow(owner.client.drizzle, sessionId, ts); - if (row && getCurrentDbClientSnapshot() === owner) eventHub.publish({ type: 'session_changed', sessionId, - patch: { userSendAt: new Date(row.userSendAt!).toISOString(), - lastActivityAt: new Date(row.lastActivityAt!).toISOString(), updatedAt: new Date(row.updatedAt).toISOString() } }); - }, + // The desktop's touchUserSendInDb, with its recent project record (touch-user-send.ts). + touchUserSend: createHostTouchUserSend({ + getOwner: getCurrentDbClientSnapshot, + publish: event => eventHub.publish(event), + broadcastRecentWorkdirsChanged: createRecentWorkdirsChangedPush(event => eventHub.publish(event)), + }), sent: (sessionId: string) => commitProvisionalSession(sessionId, sessionDraftPorts), }); +// The first step of every owner boundary: logout, session invalidation, shutdown (agent/owner-boundary.ts). +const ownerBoundary = createOwnerBoundaryStop({ beginStop: () => inputQueue.beginStop() }); +// The history view and work details: the desktop's reader, with the turn state and the in-flight rows +// of this input queue (agent/history.ts). +const hostHistoryReader = createHostHistoryReader({ + running: id => inputQueue.isTurnRunning(id), + live: id => inputQueue.liveHistory(id), +}); + +// A client's new input (the input route and /api/chat) waits for the task's permission changes first, +// as the desktop's maker:send and INPUT_ENQUEUE (agent/user-input.ts). +const enqueueUserInput = createUserInputEnqueue({ + getOwner: getCurrentDbClientSnapshot, + enqueue: (sessionId: string, input: unknown) => inputQueue.enqueue(sessionId, input), +}); + +// A task's model and engine changes, with the desktop's steps (runtime-selection.ts): the shared +// pending-switch registry (one for the Host process, as the desktop's), the desktop's set-model and +// engine switch, and the send transaction's landing. +const runtimeSelection = createHostRuntimeSelection({ + getMaker: () => { + if (!agentGraph) throw new Error('agent runtime is not ready'); + return agentGraph.maker; + }, + getMakerIfReady: () => agentGraph?.maker ?? null, + publish: event => eventHub.publish(event), + createDbMessage: (sessionId, body) => insertSessionMessage(sessionId, body), + pendingHandoff, + listProviderViews: async () => (await listProviders({ gateway: currentGateway(), ownerId: runtime.owner })).providers, + userDataDir: profileDir, + resolveConfiguredContextWindow: (...args) => { + if (!agentGraph) throw new Error('agent runtime is not ready'); + return agentGraph.modelWindow.resolveConfiguredContextWindow(...args); + }, + readStoredSessionContextWindowBudget: sessionId => { + if (!agentGraph) throw new Error('agent runtime is not ready'); + return agentGraph.modelWindow.readStoredSessionContextWindowBudget(sessionId); + }, + contextWindowBudgetChangesEffectiveWindow: input => { + if (!agentGraph) throw new Error('agent runtime is not ready'); + return agentGraph.modelWindow.contextWindowBudgetChangesEffectiveWindow(input); + }, + // No Codex runtime (no binary): no proxy, so no injection, as the desktop's proxy host before start. + codexProxyAuthInjectionState: () => codexRuntime?.proxy.getCodexProxyAuthInjectionState() ?? null, + // The input queue's API is the current owner runtime's, forwarded by name (input-queue.mjs). + inputQueue: inputQueue as unknown as Parameters[0]['inputQueue'], + readProviderGroupBinding: sessionId => hostProviderBindings.readProviderGroupBinding(sessionId), + readProviderGroup: providerId => hostProviderGroups.readProviderGroup(providerId), + log: createLogger('runtime-selection'), +}); +// The desktop's process-wide runtime selection slots (runtime-selection.ts), before any owner commit. +bindHostSessionRuntimeHooks(runtimeSelection); const subagentReads = createSubagentReadService({ getUserDataDir, @@ -1139,8 +1446,41 @@ const ipcRoute = createHostIpcRoute({ log: event => (event.outcome === 'ok' ? ipcLog.debug('ipc call', event) : ipcLog.warn('ipc call', event)), }); +// The working-directory move's ports (session-move.ts): the desktop's worktree registry (worktrees.json +// in the profile root, read only), an idle runtime closed through the executor, the recent project push, +// and the live Claude bridge the shared transcript move reads (register.ts setLiveCcSessionBridge). +const sessionMove = createHostSessionMovePorts({ + profileDir, + getMakerIfReady: () => agentGraph?.maker ?? null, + isTurnRunning: (id: string) => inputQueue.isTurnRunning(id), + closeRuntime: (id: string) => inputQueue.closeRuntime(id), + publish: event => eventHub.publish(event), +}); +setLiveCcSessionBridge(sessionMove.liveCcSessionBridge); + +const runtimePluginSettings = createHostRuntimePluginSettings({ + maker: { getSessionMeta: id => { + if (!agentGraph) throw new Error('Host runtime not ready'); + return agentGraph.maker.getSessionMeta(id); + } }, + selection: runtimeSelection, + resolveGhostControlPointPlugin: (point, id) => { + if (!plugins) throw new Error('Host plugin runtime not ready'); + return plugins.taskPlugins.resolveGhostControlPointPlugin(point, id); + }, + profileHold: () => inputQueue.isHeldForDesktop() ? profileInUseMessage() : null, + holdGeneration: () => inputQueue.profileHoldGeneration(), + publish: event => eventHub.publish(event), +}); const serverDeps = { + runtimePluginSettings, + legacyPluginApprovals: () => plugins?.legacyPluginApprovals() ?? null, ipcRoute, + // The HTTP logout's first step, before it closes the platform client and drains requests (server.mjs). + beginOwnerBoundaryStop: () => ownerBoundary.begin(), + // Coexistence plan A: while a desktop uses this profile, only reads, stops and answers reach the + // handlers (service.mjs HOST_PATHS_ALLOWED_WHILE_HELD); the rest get this refusal. + profileHold: () => (inputQueue.isHeldForDesktop() ? profileInUseMessage() : null), browserBackend: (handler: keyof NonNullable['browserSettings'], payload: unknown) => { if (!platformTools) throw new Error('HOST_RUNTIME_NOT_READY'); return platformTools.browserSettings[handler](undefined, payload); @@ -1153,6 +1493,12 @@ const serverDeps = { }), instanceId, isOwnerReady: () => runtime.state === 'ready' && account.authenticated && !isAppSessionBoundaryPending(), + // Why the start failed or was refused (start-failure.ts), the same code as the auth state's + // `hostUnavailable`. A start refused by a desktop on this profile (coexistence plan A) also says what to do. + ownerUnavailableReason: () => (!runtime.unavailable ? null + : runtime.unavailable === HOST_PROFILE_IN_USE_BY_DESKTOP + ? { reason: runtime.unavailable, message: profileInUseAtStartMessage() } + : { reason: runtime.unavailable }), requestStop: () => stop(), subagentRuns: subagentReads, token: apiToken, @@ -1169,9 +1515,10 @@ const serverDeps = { osRelease: os.release(), locale: Intl.DateTimeFormat().resolvedOptions().locale, voiceInput: profile.voiceInput, - harness: harnessStatus(), + harness: harnessBinaries.status(), auth: account.authenticated && accountUser - ? { user: accountUser, ownerId: runtime.owner } + // realm: the web shim lets usage statistics leave only for this region (甲-1). + ? { user: accountUser, ownerId: runtime.owner, realm: account.realm } : {}, appearance: profile.appearance, layout: profile.layout, @@ -1220,10 +1567,14 @@ const serverDeps = { pid: process.pid, region: resolveHostRegion(), dataDir: resolveHostDataDir(), - runtime, + // How this Host finds its outbound proxy (row 28): never an address or a setting. + outboundProxy: describeHostOutboundProxy(), + runtime: activeOwner === null + ? runtime + : { ...runtime, skillProjectionBoundary: observeSkillProjectionBoundary(activeOwner) }, remote: deviceLink?.state() ?? { enabled: false, status: 'offline' }, account, - harness: harnessStatus(), + harness: harnessBinaries.status(), claude: claudeState, maker: agentGraph ? { agents: agentGraph.agents } : null, sessions: sessionStorage ? (await listActiveSessions(sessionStorage)).length : null, @@ -1236,12 +1587,12 @@ const serverDeps = { }), getAuthState: async () => { await startup; return projectAuthState(); }, agentAuthState: async (kind: 'claude-code' | 'codex' | 'pi') => { - if (!HARNESS_KINDS.includes(kind)) throw new Error('Invalid agent kind'); + if (!HOST_HARNESS_KINDS.includes(kind)) throw new Error('Invalid agent kind'); if (!agentGraph?.instances[kind]) return { authenticated: false, errorReason: 'runtime_unavailable' }; return agentGraph.maker.getAgentAuthState(kind); }, agentStatus: async (kind: 'claude-code' | 'codex' | 'pi') => { - if (!HARNESS_KINDS.includes(kind)) throw new Error('Invalid agent kind'); + if (!HOST_HARNESS_KINDS.includes(kind)) throw new Error('Invalid agent kind'); return agentGraph?.maker.getAgentStatus(kind) ?? { binaryReady: false, binaryPath: null, authReady: false }; }, agentAuthInvoke: (channel: string, args: unknown[], caller: string) => { @@ -1265,39 +1616,64 @@ const serverDeps = { logout: async () => { await startup; authClosed = true; + const outgoingOwner = activeOwner; + // Read before the runtime is disposed (disposal releases the hold with the input queue). + const heldAtLogout = inputQueue.isHeldForDesktop(); + // The signed-in account, read before disposal clears it: signing out names it in the saved accounts. + const outgoingUser = accountUser; + let loggedOut = false; const releaseBoundary = beginAppSessionBoundary(); try { - await authRefreshFlight; - const realm = (account.realm ?? resolveHostRegion()) as 'cn' | 'global'; - const endpoints = readAuthEndpoints(realm); - const store = await createCredentialStore({ - userDataDir: resolveHostDataDir(), - keyringApplication: process.env.CINDY_HOST_KEYRING_APPLICATION?.trim() || undefined, - }); - const { machineIdSync } = createRequire(import.meta.url)('node-machine-id'); - const client = new CindyAuthClient({ - baseUrl: endpoints.authApiBaseUrl, - region: realm, - deviceId: resolveSessionDevice(store.read(AUTH_SESSION_KEY), () => resolveRuntimeDeviceId(machineIdSync, '')), - clientType: 'desktop', - fetch: (input, init) => hostAuthFetch(input, init), - }); - const result = await withCrossProcessLock( - path.join(resolveHostDataDir(), '.cindy-auth-accounts-v1.lock'), - { label: 'auth-account-vault', waitMs: 5000 }, - async (lock) => { - if (!lock.held) throw new Error('Saved account credentials are busy; retry logout'); - return logoutHostSession({ - store, ownerId: accountUser?.id, passportId: accountUser?.passportId, - refresh: (token) => client.refresh(token), - logout: (accessToken) => client.logout(accessToken), - }); - }, - ); - return result; + // As the desktop's logout (authManager.ts): stop and tear down locally first, then sign out the stored + // session; the server revoke is best effort (auth/logout.mjs), a failed revoke does not fail the logout. + const { result, errors } = await runOwnerBoundary(ownerBoundary, { + beforeDispose: () => authRefreshFlight, + dispose: disposeOwnerRuntime, + afterDispose: async () => { + const realm = (account.realm ?? resolveHostRegion()) as 'cn' | 'global'; + const endpoints = readAuthEndpoints(realm); + const store = await createCredentialStore({ + userDataDir: resolveHostDataDir(), + keyringApplication: process.env.CINDY_HOST_KEYRING_APPLICATION?.trim() || undefined, + }); + const { machineIdSync } = createRequire(import.meta.url)('node-machine-id'); + const client = new CindyAuthClient({ + baseUrl: endpoints.authApiBaseUrl, + region: realm, + deviceId: resolveSessionDevice(store.read(AUTH_SESSION_KEY), () => resolveRuntimeDeviceId(machineIdSync, '')), + clientType: 'desktop', + fetch: (input, init) => hostAuthFetch(input, init), + }); + const signedOut = await withCrossProcessLock( + path.join(resolveHostDataDir(), AUTH_ACCOUNT_VAULT_LOCK_FILE), + { label: 'auth-account-vault', waitMs: 5000 }, + async (lock) => { + if (!lock.held) throw new Error('Saved account credentials are busy; retry logout'); + return logoutHostSession({ + store, ownerId: outgoingUser?.id, passportId: outgoingUser?.passportId, + refresh: (token) => client.refresh(token), + logout: (accessToken) => client.logout(accessToken), + }); + }, + ); + loggedOut = true; + return signedOut; + }, + }); + if (errors.length) throw errors.length === 1 ? errors[0] : new AggregateError(errors, 'Logout did not complete cleanly'); + return result; } finally { - try { await disposeOwnerRuntime(); } + try { + // Row 25 (25b, decision (ii)): clear the outgoing owner's Skill projections as the desktop does at + // sign-out, without a commit; skipped while a desktop holds the profile. Never fails the logout. + if (loggedOut && outgoingOwner) { + await sweepOwnerSkillProjectionsAtLogout({ userDataDir: resolveHostDataDir(), ownerId: outgoingOwner, + isProfileHeld: () => heldAtLogout, warn: (message, fields) => hostLog.warn(message, fields) }); + } + } finally { + // An explicit sign-out ends what the last failed start reported (disposal keeps it). + if (loggedOut) runtime.unavailable = null; commitVolatileAppSession('signed-out', null, true); releaseBoundary(); eventHub.clear(); @@ -1316,28 +1692,11 @@ const serverDeps = { readProjectInfo, readProjectIconImage, resolveAutomaticProjectIcon, - updateProjectInfo: async (input: unknown, source: { desktopRequest?: string; legacyDesktop?: boolean } = {}) => { - const platform = platformClient; - let authorization: ProjectInfoAuthorization | undefined = { kind: 'host' }; - if (source.desktopRequest) { - const requestId = source.desktopRequest; - authorization = { kind: 'renderer', async check(check) { - if (!platform || !platform.status().attached) throw Error('Desktop project window unavailable'); - try { - const answer = await platform.call({ method: 'project.check', requestId, check }); - if (answer !== true) throw Error('Project authorization unavailable'); - } catch (error) { - if ((error as { code?: string }).code === 'MUTATION_CANCELLED') throw Error('[MUTATION_CANCELLED] Project action cancelled'); - throw error; - } - } }; - } else if (source.legacyDesktop) { - authorization = undefined; - } - const result = await updateProjectInfo(input, authorization); - eventHub.publish({ type: 'project_aliases_changed', catalogChanged: !!result.createdProjectKey }); - return result; - }, + updateProjectInfo: createHostProjectInfoUpdate({ + platform: () => platformClient, + profileHold: () => inputQueue.isHeldForDesktop() ? profileInUseMessage() : null, + changed: catalogChanged => eventHub.publish({ type: 'project_aliases_changed', catalogChanged }), + }), listProjectAliases: async () => { const rows = await getDbClient().drizzle.select().from(projectAliasTable); return rows.map((row: Record) => ({ @@ -1379,72 +1738,69 @@ const serverDeps = { activity: row.lastToolUse?.toolName ?? null, })); }, - updateSession: lockSessionRoute(async (sessionId: string, patch: Record) => { - if (getDeviceLinkInvokeContext()?.channel !== 'maker:set-model' || - readDeviceLinkModelSelectionOrigin() !== 'owner') return updateHostSession(sessionId, patch); - const deviceLinkOwner = captureModelSelectionOwner(); - const before = await readSessionForRun(sessionId); - assertHostTaskExecutionSupported(before); - deviceLinkOwner.assertCurrent(); - if (typeof patch.model !== 'string' || !patch.model.trim()) throwIpcError('INVALID_PARAMS', 'model is required'); - const targetAgentKind = before.agentKind; - stageAgentSwitch(sessionId, { - targetAgentKind, - model: patch.model, - providerId: Object.hasOwn(patch, 'providerId') ? patch.providerId as string | null : before.providerId, - ...(typeof patch.effort === 'string' ? { effort: patch.effort } : {}), - ...(patch.fastMode === true || patch.fastMode === false || patch.fastMode === 'ultrafast' ? { fastMode: patch.fastMode } : {}), - deviceLinkOwner, - }); - return { deferred: true, superseded: false, pendingUntilSend: true }; - }), + updateSession: lockSessionRoute(createHostSessionUpdate({ + restoreTaskToActive: taskRestore.restoreTaskToActive, + publish: event => eventHub.publish(event), + setModel: (sessionId, model, providerId, revision, selection) => + runtimeSelection.setModel(sessionId, model, providerId, revision, selection), + persistSessionFields: (sessionId, patch) => runtimeSelection.persistSessionFields(sessionId, patch), + move: sessionMove.move, + })), /** * Register a switch under the route lock for enqueue or the dispatch boundary. */ - switchSessionAgent: lockSessionRoute(async ( + /** + * A model change a client asks for: the desktop's set-model (runtime-selection.ts). A user's pick is + * an intent until the next send; the arguments are the desktop IPC's (the web client passes them + * through unchanged). + */ + setSessionModel: (sessionId: string, model: unknown, providerId: unknown, revision: unknown, selection: unknown) => + runtimeSelection.setModel(sessionId, model, providerId, revision, selection), + /** + * The desktop's set-effort, set-fast-mode and set-thinking-enabled (runtime-selection.ts, the shared + * handler bodies of sessionRuntimeAxisSettings.ts), with the desktop IPC's arguments. + */ + setSessionEffort: (sessionId: unknown, effort: unknown) => runtimeSelection.setEffort(sessionId, effort), + setSessionFastMode: (sessionId: unknown, requestedSpeed: unknown) => runtimeSelection.setFastMode(sessionId, requestedSpeed), + setSessionThinkingEnabled: (sessionId: unknown, enabled: unknown) => runtimeSelection.setThinkingEnabled(sessionId, enabled), + /** + * The desktop's set-permission-mode and set-plan-mode (runtime-selection.ts, the shared bodies of + * sessionPermissionSettings.ts), with the desktop IPC's arguments. Not under the task's send lock, as + * on the desktop: a permission change waits in the task's permission queue, which comes before the + * send lock (a holder of the send lock must never wait for it). + */ + setSessionPermissionMode: (sessionId: unknown, mode: unknown) => runtimeSelection.setPermissionMode(sessionId, mode), + setSessionPlanMode: (sessionId: unknown, enabled: unknown) => runtimeSelection.setPlanMode(sessionId, enabled), + /** + * An engine change a client asks for: the desktop's switch-session-agent (an intent until the next + * send), with its arguments: the options (confirmedContextWindow; agentDeviceId) and the thinking + * choice. Moving the Agent to another computer is refused as the Host refuses remote execution + * (send-preflight.ts); null keeps it on this computer, as on the desktop. + */ + switchSessionAgent: async ( sessionId: string, targetAgentKind: string, model: string, providerId: string | null, - effort?: string, - fastMode?: boolean | 'ultrafast', + effort?: unknown, + fastMode?: unknown, + options?: unknown, + thinking?: unknown, ) => { - const origin = readDeviceLinkModelSelectionOrigin(); - if (origin === 'scoped') throwIpcError('PRECONDITION_FAILED', 'remote agent switching requires an owner controller'); - const deviceLinkOwner = origin === 'owner' ? captureModelSelectionOwner() : undefined; - if (deviceLinkOwner) { - const row = await readSessionForRun(sessionId); - assertHostTaskExecutionSupported(row); - if (row.agentKind !== targetAgentKind) { - throwIpcError('UNSUPPORTED_CAPABILITY', 'Host does not yet support switching Harness over Device Link'); - } - deviceLinkOwner.assertCurrent(); - } else { - const [row] = await getDbClient().drizzle.select({ id: sessionTable.id }).from(sessionTable) - .where(eq(sessionTable.id, sessionId)).limit(1); - if (!row) throw new Error('session not found'); + // The desktop handler's readers of its 7th argument (sessionAgentSwitchHandler.ts). + const confirmedContextWindow = readSwitchOptionsConfirmedContextWindow(options); + const agentDeviceId = readSwitchOptionsAgentDeviceId(options); + if (agentDeviceId !== undefined && agentDeviceId !== null) { + throwIpcError('UNSUPPORTED_CAPABILITY', 'Host does not yet support remote execution'); } - if (!model) throwIpcError('INVALID_PARAMS', 'model is required'); - const intent = { - targetAgentKind: targetAgentKind === 'codex' ? 'codex' : targetAgentKind === 'pi' ? 'pi' : 'claude-code', - model, - providerId: providerId ?? null, - ...(typeof effort === 'string' && effort ? { effort } : {}), - ...(fastMode === true || fastMode === false || fastMode === 'ultrafast' ? { fastMode } : {}), - ...(deviceLinkOwner ? { deviceLinkOwner } : {}), - } as const; - stageAgentSwitch(sessionId, intent); - return { - switched: false, - agentKind: intent.targetAgentKind, - model: intent.model, - engineReady: true, - deferred: true, - }; - }), - getSessionAgentSwitchIntent: (sessionId: string) => ( - projectAgentSwitchIntent(pendingAgentSwitches.get(sessionId)) - ), + return runtimeSelection.switchAgent({ + sessionId, targetAgentKind, model, providerId, effort, fastMode, + ...(confirmedContextWindow !== undefined ? { confirmedContextWindow } : {}), + ...(agentDeviceId !== undefined ? { agentDeviceId } : {}), + thinking, + }); + }, + getSessionAgentSwitchIntent: (sessionId: string) => runtimeSelection.projectIntent(sessionId), /** * Auto-title step 1 (Codex-style immediate placeholder): persist the * normalized first user text while the title is still the default sentinel. @@ -1456,6 +1812,7 @@ const serverDeps = { const text = typeof input.text === 'string' ? input.text : ''; const seed = normalizeAutoTitle(text); if (!sessionId || !seed) return { applied: false, done: false }; + if (plugins?.taskPlugins.hasEnabledUserMessageHookGhost()) return { applied: false, done: false }; const rows = await getDbClient().drizzle.select({ title: sessionTable.title }).from(sessionTable) .where(eq(sessionTable.id, sessionId)).limit(1); const current = rows[0]?.title ?? null; @@ -1479,8 +1836,14 @@ const serverDeps = { const existing = await sessionStorage.get(sessionId); if (!existing) return { deleted: false, sessionId }; await inputQueue.disposeSession(sessionId); - pendingAgentSwitches.delete(sessionId); + runtimeSelection.clearIntent(sessionId); await sessionStorage.delete(sessionId); + // As the desktop's status writer for a deleted task (localDb/ipc/sessions.ts removeHookAttachmentDir): + // its generated images are released. + void recoverGeneratedImagesForHistory(sessionId).catch(() => undefined); + // As the desktop's status writers, under the task's route lock: a deleted task's runtime override and + // axes go (the runtime cleanup bindHostSessionRuntimeHooks installs). + cleanupSessionRuntimeForTerminalStatus(sessionId, 'deleted'); // Desktop cleanup for a deleted task (localDb/ipc/sessions.ts cleanupSessionTerminalArtifacts). try { removeSessionModelInterface(sessionId); } catch (error) { hostLog.warn('session interface snapshot cleanup failed', { sessionId, error: String(error) }); @@ -1498,7 +1861,7 @@ const serverDeps = { return { discarded: false, remaining: Boolean(await sessionStorage?.get(sessionId)) }; } await inputQueue.disposeSession(sessionId); - pendingAgentSwitches.delete(sessionId); + runtimeSelection.clearIntent(sessionId); const discarded = await discardProvisionalSessionRow(sessionId, sessionDraftPorts); return { discarded, remaining: Boolean(await sessionStorage?.get(sessionId)) }; }), @@ -1535,11 +1898,14 @@ const serverDeps = { }, chat: createChatHandler({ readSession: (id: string) => sessionStorage?.get(id), + profileHold: () => (inputQueue.isHeldForDesktop() ? profileInUseMessage() : null), createSession: (body: Record) => serverDeps.createSession(body), - enqueue: (id: string, input: unknown) => inputQueue.enqueue(id, input), + enqueue: enqueueUserInput, inputStatus: (id: string, clientId: string) => inputQueue.inputStatus(id, clientId), events: eventHub, defaultModel: process.env.CINDY_HOST_MODEL?.trim(), + // An owner boundary ends the open streams with the interrupted receipt (agent/owner-boundary.ts). + onBoundaryStop: ownerBoundary.onStop, }), providers: () => listProviders({ gateway: currentGateway(), ownerId: runtime.owner }), // The agent's own capability descriptor; no second catalog is invented here. @@ -1567,48 +1933,47 @@ const serverDeps = { if (!codexRuntime) throw new Error('Codex runtime is not available'); return codexRuntime.readRoute(); }, - modelPricing: async () => null, - referenceModelPricing: () => ({}), + // `maker:usage:model-pricing-v2`, which the renderer's getModelPricing asks (preload.ts): the native + // XD quotes. The v1 channel shares this path; only device-link reaches it (device-link.ts). + modelPricing: () => usagePricing.getGatewayModelPricing(), + referenceModelPricing: () => usagePricing.readReferenceModelPricing(), agents: () => agentGraph?.agents ?? [], events: eventHub, input: { ...inputQueue, + enqueue: enqueueUserInput, projection: (sessionId: string) => inputQueue.getProjection(sessionId), - enqueue: async (sessionId: string, item: Record) => { - await applyPendingAgentSwitch(sessionId); - return inputQueue.enqueue(sessionId, item); - }, }, interactions, agentCommands: async (input: { agentKind?: string; sessionId?: string }) => { const rawKind = String(input.agentKind ?? ''); const kind = rawKind === 'codex' ? 'codex' : rawKind === 'pi' ? 'pi' : 'claude-code'; - const agent = agentGraph?.instances?.[kind]; - if (!agent) return { success: false, error: `Agent '${kind}' is not registered` }; + const graph = agentGraph; + const agent = graph?.instances?.[kind]; + if (!graph || !agent) return { success: false, error: `Agent '${kind}' is not registered` }; const builtins = agent.listAgentCommands(); if (kind !== 'pi' || !input.sessionId) return { success: true, commands: builtins }; + const owner = getCurrentDbClientSnapshot(); const meta = await sessionStorage?.get(input.sessionId); + if (graph !== agentGraph || owner !== getCurrentDbClientSnapshot() || isAppSessionBoundaryPending()) + throw new Error('Host account changed'); if (!meta) throw new Error('session not found'); if (!shouldListPiPackageCommands(kind, true, meta)) return { success: true, commands: builtins }; - const manifest = agentGraph?.maker.getSessionRuntimeCapabilities(input.sessionId); + const manifest = graph.maker.getSessionRuntimeCapabilities(input.sessionId); const extra = manifest?.status === 'loaded' ? listPiRuntimePaletteCommands(manifest.commands, manifest.authorizedSlashCommandNames ?? manifest.managedPackageCommandNames) : []; return { success: true, commands: mergePiPackageCommands(kind, builtins, extra), runtimeStatus: manifest?.status ?? 'pending' }; }, - agentSkills: async (input: { agentKind?: string; workingDir?: string; sessionId?: string; forceReload?: boolean }) => { - const rawKind = String(input.agentKind ?? ''); - const kind = rawKind === 'codex' ? 'codex' : rawKind === 'pi' ? 'pi' : 'claude-code'; - const agent = agentGraph?.instances?.[kind]; - if (!agent) return { success: false, error: `Agent '${kind}' is not registered` }; - const stored = input.sessionId ? await sessionStorage?.get(input.sessionId) : null; - if (input.sessionId && !stored) throw new Error('session not found'); - const workingDir = stored?.workDir || input.workingDir || undefined; - if (workingDir && !path.isAbsolute(workingDir)) throw new Error('workingDir must be absolute'); - const result = kind === 'pi' && agentGraph - ? await agentGraph.maker.listAgentSkills(kind, { workingDir, sessionId: input.sessionId, forceReload: input.forceReload === true }) - : await agent.listAgentSkills({ workingDir }); - return { success: true, skills: result.skills ?? [] }; - }, + agentSkills: createHostAgentSkillList({ + maker: () => agentGraph?.maker ?? null, + hasAgent: kind => Boolean(agentGraph?.instances?.[kind as 'claude-code' | 'codex' | 'pi']), + readStoredWorkDir: async (sessionId) => { + const stored = await sessionStorage?.get(sessionId); + return { found: Boolean(stored), workDir: stored?.workDir }; + }, + isProfileHeld: () => inputQueue.isHeldForDesktop(), + ensureSharedGlobalSkills: () => sharedGlobalSkills.ensureSharedGlobalSkills(), + }), capabilities: async (agentKind: string) => { const kind = agentKind === 'codex' ? 'codex' : agentKind === 'pi' ? 'pi' : 'claude-code'; const baseCaps = agentGraph?.capabilitiesByAgent?.[kind]; @@ -1689,7 +2054,7 @@ const serverDeps = { function projectAuthState() { return projectHostAuthState({ account, accountUser, owner: runtime.owner, - generation: getActiveAppSession().generation, deviceId: currentDeviceId }); + generation: getActiveAppSession().generation, deviceId: currentDeviceId, unavailable: runtime.unavailable ?? null }); } /** Ordered disposal also runs after partial startup or a failed sign-out. */ @@ -1697,7 +2062,8 @@ async function disposeOwnerRuntime(): Promise { const remote = deviceLink; deviceLink = null; remoteIdentityReady = false; - if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; } + endAuthRefreshes(); + coexistenceMonitor?.stop(); coexistenceMonitor = null; const errors: unknown[] = []; const attempt = async (operation: () => unknown) => { try { await operation(); } catch (error) { errors.push(error); } @@ -1713,6 +2079,8 @@ async function disposeOwnerRuntime(): Promise { await attempt(() => modelAccess?.close()); agentGraph?.gatewayRestart.clear(); await attempt(() => providerConfig?.close()); + taskRuntimePlugins = null; + setGhostToolApprovalResolver(null); const stopPlugins = plugins?.close(); const stopApps = pluginGateway?.close(); // Attach a rejection handler immediately while other services drain. @@ -1723,7 +2091,6 @@ async function disposeOwnerRuntime(): Promise { // Client-owned OS sessions are released by its authenticated socket teardown. platformClient?.close(); await attempt(() => inputQueue.dispose()); - pendingAgentSwitches.clear(); await attempt(() => (agentGraph?.maker as { shutdown?: () => Promise } | undefined)?.shutdown?.()); // Stop watching this profile's Pi packages once Maker no longer runs Pi. agentGraph?.piPackages.close(); @@ -1737,6 +2104,9 @@ async function disposeOwnerRuntime(): Promise { await attempt(() => drainedPlugins); await attempt(() => drainedApps); pluginManager?.disposeNotificationIndex(); + // The usage writes started for this owner finish in its database, and no new one starts + // (agent/usage-recording.ts drain; the desktop flushes the Pi writes there, bootstrap-electron.ts :2639). + await attempt(() => usageRecording.drain()); await attempt(() => closeStorage?.()); } finally { platformTools = null; @@ -1745,6 +2115,8 @@ async function disposeOwnerRuntime(): Promise { pluginManager = null; hostTools = null; hostConfirmations = null; + offMakerSessionClosed?.(); + offMakerSessionClosed = null; agentGraph = null; gitSnapshot = null; mcpRuntime = null; @@ -1768,6 +2140,11 @@ async function disposeOwnerRuntime(): Promise { runtime.state = 'uninitialized'; runtime.storage = 'unopened'; runtime.owner = null; + // runtime.unavailable is not cleared here (甲, 2026-11-18): a refresh that ends a session the failed start + // never adopted (none saved, or rejected) disposes again, and the window must keep seeing why the start + // failed instead of a sign-in form. It ends only when the database opens (ensureRuntime), at an explicit + // sign-out (logout below), or at a completed sign-in; sign-in completes outside serve today (cindy-host + // login), so the next start reports anew. } if (errors.length) throw new AggregateError(errors, 'Owner runtime cleanup failed'); } @@ -1838,39 +2215,6 @@ function startDeviceLink(): void { if (deviceLink) return; const endpoint = readAuthEndpoints(account.realm === 'cn' ? 'cn' : 'global').deviceLinkApiBaseUrl; if (!endpoint) throw new Error('The endpoint manifest does not contain a Device Link relay'); - const preparePiSkillRuntime = lockSessionRoute(async ( - id: string, dir: string, route: { model: string; nextInputChars?: number } | undefined, assertPreparationCurrent: () => void, - ) => { - assertPreparationCurrent(); - if (route) { - const owner = activeOwnerScopeKey(); - const checkOwner = () => { - assertPreparationCurrent(); - if (activeOwnerScopeKey() !== owner || isAppSessionBoundaryPending()) throw new Error('Host account changed'); - }; - const row = await readSessionForRun(id); - checkOwner(); - const intent = pendingAgentSwitches.get(id); - const maker = agentGraph?.maker; - const live = maker?.getSession(id); - if (!maker || row.source === 'review' || row.workingDir !== dir || row.remoteHostId || row.agentDeviceId || row.orcaRole - || intent?.targetAgentKind !== 'pi' || intent.model !== route.model || live?.isTurnRunning()) { - throw new Error('[PRECONDITION_FAILED] The selected Pi route is not ready'); - } - if (intent.deviceLinkOwner) { - await inputQueue.preparePiSkillRuntime(id, dir, { - applyPendingOwnerSelection: true, nextInputChars: route.nextInputChars, assertPreparationCurrent, - }); - checkOwner(); - return; - } - await applyPendingAgentSwitchUnlocked(id, undefined, checkOwner); - checkOwner(); - if (live && live.agentKind !== 'pi') await maker.closeSessionIfCurrent(live, 'runtime-refresh'); - checkOwner(); - } - await inputQueue.preparePiSkillRuntime(id, dir, { assertPreparationCurrent }); - }); deviceLink = createHostDeviceLink({ profileDir, version: layout.version, mcpApps: pluginGateway ?? undefined, @@ -1886,26 +2230,23 @@ function startDeviceLink(): void { onProjectTaskStatus: (sessionId, status) => { eventHub.publish({ type: 'session_changed', sessionId, status, patch: { status } }); }, - preparePiSkillRuntime: (id, dir, route) => preparePiSkillRuntime(id, dir, route, inputQueue.capturePiSkillPreparation(id)), - createRuntimeSession: async input => { - const scope = activeOwnerScopeKey(); - const opts = readHostCreateSessionOpts(input, ensureDialogueWorkspaceDir); - // These routes need separate execution services; never reinterpret a remote - // task or Orca worker as an ordinary local task. - if (opts.remoteHostId || opts.agentDeviceId || opts.orcaRole) - throw new Error('[NOT_SUPPORTED] This execution route is not assembled in the Host yet'); - const row = await serverDeps.createSession({ - id: opts.id, agentKind: opts.agentKind, workingDir: opts.workingDir, - workspaceKind: opts.workspaceKind, model: opts.model, - permissionMode: opts.permissionMode, effort: opts.effort, providerId: opts.providerId, - fastMode: opts.fastMode, planModeEnabled: opts.planMode, - extraDirs: opts.extraDirs, writableDirs: opts.writableDirs, - }); - if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending() || !agentGraph) throw new Error('Host account changed'); - const session = await agentGraph.maker.createSession({ ...opts, id: row.id }); - if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending()) throw new Error('Host account changed'); - return { sessionId: session.id, agentKind: session.agentKind, workDir: session.workDir, - capabilities: session.capabilities, usedProjectContext: false }; + preparePiSkillRuntime: (id, workingDir, route) => { + const assertPreparationCurrent = inputQueue.capturePiSkillPreparation(id); + return withSendToSessionLock(id, () => inputQueue.preparePiSkillRuntime(id, workingDir, { + assertPreparationCurrent, + ...(route ? { applyPendingOwnerSelection: true, expectedPiModel: route.model, nextInputChars: route.nextInputChars } : {}), + })); + }, + // The Device Link create entry, with the runtime start admission (agent/create-runtime-session.ts). + // Coexistence plan A: a new task's runtime and a plugin page's calls are refused while held (device-link.ts). + profileHold: () => (inputQueue.isHeldForDesktop() ? profileInUseMessage() : null), + createRuntimeSession: input => { + return createHostRuntimeSession(explicitPorts({ + serverDeps, + getAgentGraph: () => agentGraph, + assertProviderExecutionSupported, + admitLocalRoute: opts => runtimeSelection.admitLocalRoute(opts), + }), input); }, availabilityPolicy: availabilityPolicy ?? undefined, disableShareAvailability, @@ -1946,13 +2287,16 @@ server.listen(PORT, '127.0.0.1', () => { // supervisors still need the non-secret loopback readiness address on stdout. process.stdout.write(`cindy-host listening on ${baseUrl}\n`); startup = (async () => { + // The loopback endpoint already answers /health while a cold PAC loads. + await proxyWarmup; + if (shuttingDown) return; let owner = process.env.CINDY_HOST_OWNER?.trim() || ''; let initialUser: AccountUser | null = null; if (!owner) { const discovered = discoverHostOwner(resolveHostDataDir()); if (discovered.ownerId) { owner = discovered.ownerId; - if (!existsSync(ownerDatabasePath(resolveHostDataDir(), owner))) throw new Error('owner database is missing'); + if (!existsSync(ownerDatabasePath(resolveHostDataDir(), owner))) throw new OwnerDatabaseError('DB_INIT_FAILED', 'owner database is missing'); } else { // A newly signed-in preview has credentials but no database yet. Resolve // the authenticated membership before creating its first owner database; @@ -1970,13 +2314,14 @@ server.listen(PORT, '127.0.0.1', () => { } await ensureRuntime(owner); startDeviceLink(); - if (account.authenticated) { schedulePeriodicRefresh(); return; } + if (account.authenticated) { scheduleAuthRefresh(); return; } const state = await readAdoptedSessionState({ userDataDir: resolveHostDataDir(), keyringApplication: process.env.CINDY_HOST_KEYRING_APPLICATION?.trim() || undefined, }); account = { authenticated: false, realm: state.realm }; - if (state.authenticated && await refreshAuthSession()) schedulePeriodicRefresh(); + // A renewal that succeeds schedules the next one; one that fails for now retries with backoff. + if (state.authenticated) await refreshAuthSession(); })().catch(async (error: unknown) => { const blocked = runtime.state === 'blocked'; try { await disposeOwnerRuntime(); } @@ -1984,6 +2329,7 @@ server.listen(PORT, '127.0.0.1', () => { finally { commitVolatileAppSession('signed-out', null, true); } runtime.state = blocked ? 'blocked' : 'error'; runtime.detail = error instanceof Error ? error.message : String(error); + runtime.unavailable = classifyHostStartFailure(error); console.error('cindy-host initialization failed:', runtime.detail); }); }); @@ -1993,21 +2339,34 @@ const stop = () => { if (shuttingDown) return; shuttingDown = true; authClosed = true; - if (refreshTimer) clearInterval(refreshTimer); - const requestsDrained = server.stopAccepting(); - const releaseOwnerBoundary = beginAppSessionBoundary(); - // As the desktop's quit ('reap-codex-tool-trees', a sync step before the Maker shutdown): - // once the app-servers close, the parent chain proving these trees are the Host's is gone. - // Only on this exit; an owner change or a window handoff leaves the Host running. - try { reapCodexToolTreesSync(); } - catch (error) { console.error('cindy-host codex tool tree reap failed:', error instanceof Error ? error.message : String(error)); } - void (async () => { - try { + endAuthRefreshes(); + let releaseOwnerBoundary = () => {}; + const errors: unknown[] = []; + // The owner boundary's stop first (agent/owner-boundary.ts): as the desktop's quit freezes the turn markers, + // a turn still running ends as an interruption. Everything before the first await in beforeDispose runs + // synchronously here, in the previous order. + const boundary = runOwnerBoundary(ownerBoundary, { + beforeDispose: async () => { + const requestsDrained = server.stopAccepting(); + releaseOwnerBoundary = beginAppSessionBoundary(); + // As the desktop's quit ('reap-codex-tool-trees', a sync step before the Maker shutdown): + // once the app-servers close, the parent chain proving these trees are the Host's is gone. + // Only on this exit; an owner change or a window handoff leaves the Host running. + try { reapCodexToolTreesSync(); } + catch (error) { console.error('cindy-host codex tool tree reap failed:', error instanceof Error ? error.message : String(error)); } // Always drain every in-flight writer before releasing the profile lease, // including when another startup/auth operation rejected. const settled = await Promise.allSettled([startup, authRefreshFlight, requestsDrained]); - const errors = settled.filter(result => result.status === 'rejected').map(result => result.reason); - try { await disposeOwnerRuntime(); } catch (error) { errors.push(error); } + errors.push(...settled.filter(result => result.status === 'rejected').map(result => result.reason)); + }, + // After the reap above (the guard in hostDesktopSourceContracts.guard.test.ts pins the order). + dispose: async () => { await disposeOwnerRuntime(); }, + }); + void (async () => { + try { + errors.push(...(await boundary).errors); + // The Chromium proxy helper (row 28c), by its handle; it also quits on its own once this process is gone. + try { await stopHostSystemProxySettings(); } catch (error) { errors.push(error); } if (errors.length) throw new AggregateError(errors, 'Host shutdown did not complete cleanly'); } finally { server.closeAllConnections(); diff --git a/apps/host/src/message-store.ts b/apps/host/src/message-store.ts index dbbd18198fc..5299eb760c7 100644 --- a/apps/host/src/message-store.ts +++ b/apps/host/src/message-store.ts @@ -1,7 +1,9 @@ import { createMessageClearRecovery } from '../../desktop/src/main/localDb/messageClearRecovery.js'; +import { supersedeRetriedUserTurnWithPorts } from '../../desktop/src/main/localDb/retriedUserTurnSupersede.js'; import { readVisiblePiUserEntry, patchMessageAgentMetaWithResultRow } from '../../desktop/src/main/localDb/messageMutations.js'; import { removeRefs as removeMediaRefs, removeSessionAttachmentRefIfUnreferencedByLiveMessage } from '../../desktop/src/main/cindy-media/ledger.js'; import { recomputePrRefsForSession } from '../../desktop/src/main/git-context/prRefsStore.js'; +import { trackMessagePrRefs } from '../../desktop/src/main/localDb/messagePrRefs.js'; import { createLogger } from '../../desktop/src/main/logger.js'; import { messageToCamel } from "../../desktop/src/main/localDb/mapper.js"; import { @@ -27,6 +29,9 @@ export function createHostMessageStore(deps: { input: Record, options?: MessageWriteOptions & { shouldBroadcast?: () => boolean; + /** As the desktop's createMessage: generated-image delivery commits its own media reference + * after its guarded content update (generatedImageDelivery.ts). */ + deferMediaRefs?: boolean; }, ) => { const owner = deps.getOwner(); @@ -78,13 +83,16 @@ export function createHostMessageStore(deps: { if (!pending) pendingPublication.set(owner.client, (pending = new Set())); if (created) pending.add(row.id); if (deps.getOwner() !== owner) throw new Error("message owner changed"); - await (deps.commitMediaRefs ?? hostChatAttachments.commitMessageMediaRefs)( - { sessionId, role: row.role, content: row.content }, - owner.client.drizzle, - ); - if (deps.getOwner() !== owner) throw new Error("message owner changed"); + if (!options?.deferMediaRefs) { + await (deps.commitMediaRefs ?? hostChatAttachments.commitMessageMediaRefs)( + { sessionId, role: row.role, content: row.content }, + owner.client.drizzle, + ); + if (deps.getOwner() !== owner) throw new Error("message owner changed"); + } const message = messageToCamel(row); - if (pending.has(row.id) && options?.shouldBroadcast?.() !== false) { + const publishing = pending.has(row.id); + if (publishing && options?.shouldBroadcast?.() !== false) { deps.publish({ type: "message_created", sessionId, @@ -92,6 +100,9 @@ export function createHostMessageStore(deps: { message, }); } + // The desktop createMessage hook (localDb/ipc/messages.ts): every published row records its PR + // references, broadcast or not, without waiting; corrections settle it first (messagePrRefs.ts). + if (publishing) trackMessagePrRefs(owner.client, message); pending.delete(row.id); return message; }; @@ -128,6 +139,16 @@ export function createHostMessageRecovery(deps: { }); return { rewindPersistedUserMessageAfterClear, + /** A zero-output retry replaced its failed turn: hide the old user row and its error row, as the + * desktop does (localDb/retriedUserTurnSupersede.ts), and tell clients they were deleted. */ + supersedeRetriedUserTurn: (sessionId: string, args: { supersededUserClientId: string; retryUserClientId: string }) => + supersedeRetriedUserTurnWithPorts(sessionId, args, { + captureOwnerBroadcastScope: capture, + isOwnerBroadcastScopeCurrent: owner => !!owner && isCurrent(owner), + broadcastMessageDeleted: (payload, owner) => { + if (owner && isCurrent(owner)) deps.publish({ type: 'message_deleted', ...payload }); + }, + }), async readPiUserEntry(sessionId: string, clientId: string) { const owner = capture(); const id = await readVisiblePiUserEntry(owner.client, sessionId, clientId); diff --git a/apps/host/src/outbound-proxy.test.mjs b/apps/host/src/outbound-proxy.test.mjs new file mode 100644 index 00000000000..1c23b0f9972 --- /dev/null +++ b/apps/host/src/outbound-proxy.test.mjs @@ -0,0 +1,77 @@ +/* + * 测试价值 + * - 生产入口与可观察结果:Host 的出站代理解析器 resolveHostOutboundProxy(outbound-proxy.ts,hostOutbound、 + * 回环代理、Claude 命令行网络环境都用它)对每个上游给出的代理地址,以及它记下的出站路径判定 + * (getHostOutboundPathSnapshotFor,Codex 后端不可达时报给用户的那句话的来源)。 + * - 规则依据:放行表第 28 行 28a。Host 从只读环境变量的解析器改成桌面的共用解析核心加“无系统代理” + * 的端口,转发结果必须不变;没有代理环境变量时,判定只能记成没问出来(unknown,session_unavailable), + * 不能记成确认直连——Host 没有读系统代理,报成 direct 是谎报(第二节“Codex 后端不可达时的出站路径”)。 + * - 现有覆盖缺口:auth-fetch.test.mjs 只覆盖 HTTP_PROXY 与 HTTPS_PROXY 同设、经代理的那一种配置; + * codex-proxy-gate.test.mjs 的上游都是本机地址,解析器在包里就被跳过。没有设置组合、NO_PROXY、 + * 一个变量都不设的用例,也没有判定的用例。 + * - 最小失败输入:设了 HTTP_PROXY、上游是 https(应直连);只设 NO_PROXY(应直连);没有代理环境变量 + * 时把判定记成 direct(Host 端口改成返回 'DIRECT')。 + * - tier:unit(只调解析器,不发请求、不连网)。 + * - 实测耗时:见 PR(单独运行本文件)。 + */ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { getHostOutboundPathSnapshotFor, resolveHostOutboundProxy } from './outbound-proxy.ts'; + +const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy', 'NO_PROXY', 'no_proxy']; + +/** Runs fn with exactly the given proxy variables set (the runner's own proxy variables removed). */ +async function withProxyEnv(t, env, fn) { + const saved = Object.fromEntries(PROXY_ENV_KEYS.map(key => [key, process.env[key]])); + t.after(() => { + for (const key of PROXY_ENV_KEYS) { + if (saved[key] === undefined) delete process.env[key]; else process.env[key] = saved[key]; + } + }); + for (const key of PROXY_ENV_KEYS) delete process.env[key]; + Object.assign(process.env, env); + return fn(); +} + +// Each row: proxy variables → upstream → the address the Host forwards through (null = direct). These +// are the results the environment-only resolver gave before 28a; the forwarding verdict must not move. +const ENV_ROWS = [ + ['credentialed HTTPS_PROXY, returned verbatim', { HTTPS_PROXY: 'http://user:secret@127.0.0.1:7890' }, 'https://api.example.test/v1', 'http://user:secret@127.0.0.1:7890'], + ['lowercase https_proxy', { https_proxy: 'http://127.0.0.1:7890' }, 'https://api.example.test/v1', 'http://127.0.0.1:7890'], + ['HTTP_PROXY does not cover an https upstream', { HTTP_PROXY: 'http://127.0.0.1:7890' }, 'https://api.example.test/v1', null], + ['HTTP_PROXY covers an http upstream', { HTTP_PROXY: 'http://127.0.0.1:7890' }, 'http://api.example.test/v1', 'http://127.0.0.1:7890'], + ['ALL_PROXY as the fallback', { ALL_PROXY: 'socks5://127.0.0.1:7891' }, 'https://api.example.test/v1', 'socks5://127.0.0.1:7891'], + ['NO_PROXY exempts the upstream domain', { HTTPS_PROXY: 'http://127.0.0.1:7890', NO_PROXY: 'example.test' }, 'https://api.example.test/v1', null], + ['a loopback upstream is never proxied', { HTTPS_PROXY: 'http://127.0.0.1:7890' }, 'https://127.0.0.1:8443/v1', null], + ['no proxy variable at all', {}, 'https://api.example.test/v1', null], + ['only NO_PROXY', { NO_PROXY: 'other.example' }, 'https://api.example.test/v1', null], +]; + +test('the Host forwards through the same proxy for every proxy-variable setting as before', async t => { + for (const [name, env, upstream, expected] of ENV_ROWS) { + await t.test(name, st => withProxyEnv(st, env, async () => { + assert.equal(await resolveHostOutboundProxy(upstream), expected); + })); + } +}); + +test('without proxy variables the Host records an unresolved path, not a confirmed direct one', async t => { + for (const [name, env, upstream] of [ + ['no proxy variable at all', {}, 'https://none.example.test/v1'], + ['only NO_PROXY', { NO_PROXY: 'other.example' }, 'https://no-proxy-only.example.test/v1'], + ]) { + await t.test(name, st => withProxyEnv(st, env, async () => { + assert.equal(await resolveHostOutboundProxy(upstream), null); + const { at, ...snapshot } = getHostOutboundPathSnapshotFor([upstream]); + assert.equal(typeof at, 'number'); + assert.deepEqual(snapshot, { source: 'system', kind: 'unknown', reason: 'session_unavailable', upstream: new URL(upstream).origin }); + })); + } + // With a proxy variable the judgement is the environment's, with the address redacted. + await withProxyEnv(t, { HTTPS_PROXY: 'http://user:secret@127.0.0.1:7890' }, async () => { + await resolveHostOutboundProxy('https://env.example.test/v1'); + const { at: _at, ...snapshot } = getHostOutboundPathSnapshotFor(['https://env.example.test']); + assert.deepEqual(snapshot, { source: 'env', kind: 'proxy', proxy: 'http://127.0.0.1:7890', upstream: 'https://env.example.test' }); + }); +}); diff --git a/apps/host/src/outbound-proxy.ts b/apps/host/src/outbound-proxy.ts new file mode 100644 index 00000000000..9fe9067770b --- /dev/null +++ b/apps/host/src/outbound-proxy.ts @@ -0,0 +1,119 @@ +/** + * The Host's outbound proxy resolver: the desktop's resolver core (outboundProxyResolverCore.ts), + * bound to Host ports. Proxy environment variables come first, as on the desktop; without them the core asks + * the system proxy session set here (release table row 28): + * - macOS: the static system proxy settings (28b, macos-system-proxy.ts); when they use PAC or auto-discovery, + * the Chromium proxy helper (28c, chromium-proxy.ts) answers, falling back to the static reading; + * - Windows: the Chromium proxy helper, prewarmed before the first request (28c); without an answer in time the request + * goes direct and its path is recorded as `unknown` (resolve_failed); + * - other platforms (Linux): none; only the proxy environment variables are read, and a request without them goes + * direct with its path recorded as `unknown` (session_unavailable), not as a confirmed direct route. + * Only main.ts starts the system settings (startHostSystemProxySettings); a process that did not, such as a test + * or an acceptance script importing outbound.mjs, reads the proxy environment variables only. + */ +import { hasProxyEnvConfig } from '@cindy/anthropic-compat-proxy'; + +import { + createOutboundProxyResolver, + type OutboundProxyResolverPorts, +} from '../../desktop/src/main/maker-host/outboundProxyResolverCore.ts'; +import { explicitPorts } from './agent/explicit-ports.ts'; +import { createChromiumProxyHelper, type ChromiumProxyHelper, type ChromiumProxyHelperState } from './chromium-proxy.ts'; +import { + createMacSystemProxySession, + readScutilProxyOutput, + type ReadSystemProxySettings, + type SystemProxySession, +} from './macos-system-proxy.ts'; +import { resolveHostDataDir } from './profile-path.mjs'; + +let systemProxySession: SystemProxySession | null = null; +let chromiumHelper: ChromiumProxyHelper | null = null; + +const hostOutboundProxyResolver = createOutboundProxyResolver(explicitPorts({ + // No Electron app whose readiness gates the system proxy session. + isAppReady: () => true, + // The platform's system proxy session once started; none otherwise (release table row 28). + getProxySession: () => systemProxySession, +})); + +export const resolveHostOutboundProxy = hostOutboundProxyResolver.resolveDesktopOutboundProxy; +/** The resolver's per-upstream outbound path judgement (diagnostics only), as on the desktop. */ +export const getHostOutboundPathSnapshotFor = hostOutboundProxyResolver.getOutboundPathSnapshotFor; + +/** + * Reads the macOS system proxy settings with the given reader from now on, asking `chromium` for PAC and + * auto-discovery; null stops reading them. Production passes scutil and the Chromium proxy helper once at startup + * (startHostSystemProxySettings); tests pass fixed scutil output and a stand-in helper, so no test reads the + * settings of the machine it runs on. Verdicts the resolver core already holds for an upstream stay until they + * expire (30 s; 5 s when unresolved), as after a settings change. + */ +export function useHostSystemProxySettings(readSettings: ReadSystemProxySettings | null, chromium: SystemProxySession | null = null): void { + systemProxySession = readSettings ? createMacSystemProxySession(readSettings, chromium) : null; +} + +/** Windows (28c): every resolution without proxy environment variables asks `chromium`; null stops it. */ +export function useHostChromiumProxySession(chromium: SystemProxySession | null): void { + systemProxySession = chromium; +} + +/** Prepare the system session before login or startup can send its first request. */ +export async function startHostSystemProxySettings({ + platform = process.platform, + readSettings = readScutilProxyOutput, + makeHelper = () => createChromiumProxyHelper({ profileDir: resolveHostDataDir() }), +}: { + platform?: NodeJS.Platform; + readSettings?: ReadSystemProxySettings; + makeHelper?: () => ChromiumProxyHelper; +} = {}): Promise { + if (platform !== 'darwin' && platform !== 'win32') return; + let helper: ChromiumProxyHelper; + try { + helper = chromiumHelper = makeHelper(); + } catch (error) { + // The static macOS settings remain usable even if the helper profile cannot be created. + if (platform === 'darwin') useHostSystemProxySettings(readSettings); + throw error; + } + if (platform === 'darwin') { + const session = createMacSystemProxySession(readSettings, helper); + systemProxySession = session; + if (hasProxyEnvConfig() || !await session.needsChromium().catch(() => false)) return; + } else { + systemProxySession = helper; + if (hasProxyEnvConfig()) return; + } + await helper.warmUp(); +} + +/** At Host shutdown: stops the Chromium proxy helper, if it runs, by its handle. */ +export async function stopHostSystemProxySettings(): Promise { + await chromiumHelper?.close(); +} + +/** How this Host finds its outbound proxy, for `cindy-host status` (never a proxy address or a setting). */ +export function describeHostOutboundProxy(): { + environmentVariables: boolean; + systemSettings: 'static-and-chromium-helper' | 'chromium-helper' | 'not-read'; + helper: ChromiumProxyHelperState | 'none'; +} { + return { + environmentVariables: hasProxyEnvConfig(), + systemSettings: process.platform === 'darwin' ? 'static-and-chromium-helper' + : process.platform === 'win32' ? 'chromium-helper' : 'not-read', + helper: chromiumHelper?.state() ?? 'none', + }; +} + +/** The `cindy-host status` line for a running Host's describeHostOutboundProxy(). */ +export function describeOutboundProxyLine(value: unknown): string { + const state = value as Partial> | null; + const environment = state?.environmentVariables ? 'proxy environment variables (used first)' : 'no proxy environment variables'; + const system = state?.systemSettings === 'static-and-chromium-helper' + ? `system settings (static; PAC and auto-discovery through the Chromium helper, ${state.helper ?? 'none'})` + : state?.systemSettings === 'chromium-helper' + ? `system settings through the Chromium helper (${state.helper ?? 'none'})` + : 'system proxy settings and PAC are not read on this platform'; + return `${environment}; ${system}`; +} diff --git a/apps/host/src/outbound.d.mts b/apps/host/src/outbound.d.mts index ffbe7538daf..14522d8ec31 100644 --- a/apps/host/src/outbound.d.mts +++ b/apps/host/src/outbound.d.mts @@ -1,7 +1,7 @@ import type { Agent } from 'node:http'; import type { createOutboundTransport } from '../../desktop/src/main/maker-host/outbound-fetch.js'; -import type { createEnvOutboundProxyResolver } from '@cindy/anthropic-compat-proxy'; +import type { OutboundProxyResolver } from '@cindy/anthropic-compat-proxy'; export const hostOutbound: ReturnType; -export const resolveHostOutboundProxy: ReturnType; +export const resolveHostOutboundProxy: OutboundProxyResolver; export function createHostWebSocketAgent(url: string | URL): Promise; diff --git a/apps/host/src/outbound.mjs b/apps/host/src/outbound.mjs index 38211ed68ad..ec4336bf425 100644 --- a/apps/host/src/outbound.mjs +++ b/apps/host/src/outbound.mjs @@ -1,17 +1,17 @@ import { createOutboundTransport } from '../../desktop/src/main/maker-host/outbound-fetch.js'; import { createLogger } from '../../desktop/src/main/logger.js'; -/** Headless network adapter: explicit service-account proxy environment, with - * the same HTTP CONNECT / SOCKS implementation used by desktop. There is no - * graphical session from which a system PAC policy could be read. */ -import { createEnvOutboundProxyResolver, isLoopbackHostname, parseOutboundProxyUrl, +/** Headless network adapter: the desktop's outbound proxy resolver (proxy environment variables + * first, then the platform system proxy session from outbound-proxy.ts), with + * the same HTTP CONNECT / SOCKS implementation used by desktop. */ +import { isLoopbackHostname, parseOutboundProxyUrl, Socks5HttpAgent, Socks5HttpsAgent, TunnelingHttpsAgent } from '@cindy/anthropic-compat-proxy'; -const resolveProxy = createEnvOutboundProxyResolver(); -export const resolveHostOutboundProxy = resolveProxy; +import { resolveHostOutboundProxy } from './outbound-proxy.ts'; +export { resolveHostOutboundProxy }; export async function createHostWebSocketAgent(url) { const upstream = new URL(url); upstream.protocol = upstream.protocol === 'wss:' ? 'https:' : upstream.protocol === 'ws:' ? 'http:' : upstream.protocol; if (isLoopbackHostname(upstream.hostname)) return undefined; - const raw = await resolveProxy(upstream.href); + const raw = await resolveHostOutboundProxy(upstream.href); if (!raw) return undefined; const proxy = parseOutboundProxyUrl(raw); if (!proxy) throw new Error('Unsupported Host proxy configuration'); @@ -22,4 +22,4 @@ export async function createHostWebSocketAgent(url) { // Plugin, model and auth traffic share the same DNS pinning, redirect and proxy // machinery as Desktop. Headless only changes how proxy settings are obtained. -export const hostOutbound = createOutboundTransport(resolveProxy, createLogger('host-outbound')); +export const hostOutbound = createOutboundTransport(resolveHostOutboundProxy, createLogger('host-outbound')); diff --git a/apps/host/src/platform/assets.mjs b/apps/host/src/platform/assets.mjs index c48a8cd0f21..6bb688526ae 100644 --- a/apps/host/src/platform/assets.mjs +++ b/apps/host/src/platform/assets.mjs @@ -1,9 +1,8 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import os from 'node:os'; -import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; -import { hostRuntimeLayout } from '../runtime-layout.mjs'; +import { hostRuntimeLayout, resolveSourceElectronBinary } from '../runtime-layout.mjs'; /** A trusted OS-facts worker; it has no task store, renderer or listening port. */ export async function preparePowerWorker() { @@ -12,13 +11,14 @@ export async function preparePowerWorker() { if (!layout.electronBinary) throw new Error('PLATFORM_MONITOR_UNAVAILABLE'); return { binary: layout.electronBinary, script: layout.powerWorker, close: async () => {} }; } + const binary = resolveSourceElectronBinary(); + if (!binary) throw new Error('PLATFORM_MONITOR_UNAVAILABLE'); const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-host-platform-')); try { const { build } = await import('esbuild'); const script = path.join(root, 'power-worker.cjs'); await build({ entryPoints: [fileURLToPath(new URL('../../../desktop/src/main/host-platform/power-worker.desktop.ts', import.meta.url))], outfile: script, bundle: true, platform: 'node', format: 'cjs', target: 'node22', external: ['electron'] }); - const binary = createRequire(new URL('../../../desktop/package.json', import.meta.url))('electron'); return { binary, script, close: () => fs.rm(root, { recursive: true, force: true }) }; } catch (error) { await fs.rm(root, { recursive: true, force: true }); throw error; } } diff --git a/apps/host/src/plugins.test.mjs b/apps/host/src/plugins.test.mjs index 8ca60804328..334f3360f40 100644 --- a/apps/host/src/plugins.test.mjs +++ b/apps/host/src/plugins.test.mjs @@ -27,6 +27,7 @@ import { createGhostKvStore } from '../../desktop/src/main/cindy-brain/ghostKvSt import { defaultPtySpawn } from '../../desktop/src/main/terminal/ptyFactory.ts'; import { createHostToolService } from './agent/host-tools.ts'; import { createHostConfirmations } from './host-confirmations.ts'; +import { heldCredentialError, holdCredentialFetch } from './agent/held-credentials.ts'; import { createLiziMcpProviders } from '@cindy/mcps'; import { setCurrentDbClient, clearCurrentDbClient } from '../../desktop/src/main/localDb/client/current.ts'; @@ -143,11 +144,89 @@ test('Host assembly injects an existing saved credential and rejects its revoked } finally { await api.network.disposeAll(); } }); +// Coexistence plan A (reviewer, 2026-11-17): while a Cindy desktop app running on its own uses the +// profile, plugin OAuth renews and writes nothing (plugins/authorization.ts, held-credentials.ts). +// Unit, through the same production assembly as above: an expired access token is not renewed (no +// token request leaves), the account vault is unchanged, and the tool fails with a refused renewal +// carrying the reason, not "reconnect"; released, the same request renews and goes out. +test('while a desktop uses the profile, plugin OAuth renews and writes nothing', async () => { + const records = new Map([ + ['target:account-accounts', JSON.stringify({ accounts: [{ id: 'acc1', status: 'connected' }], defaultAccountId: 'acc1' })], + ['target:account-rt-acc1', 'synthetic-refresh-token'], + ]); + const secret = { + readGhostSecret: (id, key) => records.get(id + ':' + key) ?? null, + readGhostSecretStrict: (id, key) => records.get(id + ':' + key) ?? null, + storeGhostSecret: (id, key, value) => { records.set(id + ':' + key, value); return true; }, + removeGhostSecret: (id, key) => records.delete(id + ':' + key), readGhostSecretTail: () => null, + listGhostAccountReferenceKeys: ids => ids.map(instanceKey => ({ instanceKey, keys: [] })), + }; + const oauthDecl = { authorizeUrl: 'https://accounts.example.test/authorize', tokenUrl: 'https://accounts.example.test/token', + scopes: ['read'], clientId: 'fixture-client' }; + const ghosts = [{ enabled: true, dir: '/fixture/target', approval: { state: 'approved', revision: 'held-oauth-fixture' }, + manifest: { id: 'target', name: 'target', version: '1.0.0', network: { hosts: ['api.example.test'], + secrets: [{ key: 'account', label: 'Account', source: 'oauth', inject: { header: 'Authorization', format: 'Bearer {value}', + hosts: ['api.example.test'] }, oauth: oauthDecl }] } } }]; + const requests = []; + const noop = () => {}; + const imports = new Proxy({ + GhostSavedCredentialManager, GhostConnectionManager, GhostNetworkSlot, GhostOauthAccountManager, heldCredentialError, holdCredentialFetch, + withGhostOauthMutationLock: async (_owner, _id, _path, run) => run(), + installedGhostMutationTargetToken, installedGhostStoragePart, + activeOwnerScopeKey: () => 'owner:1', isAppSessionBoundaryPending: () => false, + createLogger: () => ({ warn: noop, info: noop }), hostRuntimeLayout: () => ({ packaged: false }), + createHostPluginSecrets: () => secret, createHostPluginIdentity: () => ({}), + createHeadlessPluginSandbox: () => ({ adapter: {}, deliver: noop }), + hostBlobStore: {}, hostOutbound: { outboundFetch: async (url, init) => { + requests.push(String(url)); + return String(url).startsWith('https://accounts.example.test/token') + ? Response.json({ access_token: 'synthetic-access-token', token_type: 'Bearer', expires_in: 3600 }) + : Response.json({ accepted: true }); + } }, + }, { get: (target, name) => name in target ? target[name] : /^[A-Z]/.test(String(name)) ? class {} : () => ({}) }); + const load = compiled => { + const module = { exports: {} }; + compiled(name => name === 'node:module' ? { createRequire: () => ({ resolve: () => '/fixture/sqlite' }) } + : name.startsWith('node:') ? createRequire(import.meta.url)(name) : imports, module, module.exports); + return module.exports; + }; + imports.createHostPluginAuthorization = load(credentialAssembly[0]).createHostPluginAuthorization; + let held = true; + const api = await load(credentialAssembly[1]).createHostPluginRuntime({ + profileDir: '/fixture/host', ownerId: 'owner', credentials: {}, getLoginEmail: () => null, isProfileHeld: () => held, + manager: { list: () => ghosts, findInstalledInstance: id => ghosts.find(ghost => ghost.manifest.id === id) }, + publish: noop, assets: { nodeWorker: '/fixture/worker', close: noop }, + }); + try { + const before = JSON.stringify([...records]); + const refused = await api.network.handleFetchRequest('target', { url: 'https://api.example.test/account' }); + assert.equal(refused.ok, false); + const text = JSON.stringify(refused); + assert.match(text, /HOST_PROFILE_IN_USE_BY_DESKTOP: this plugin sign-in is not renewed while a Cindy desktop app/); + assert.doesNotMatch(text, /重新连接/, 'a refused renewal does not ask to reconnect'); + assert.deepEqual(requests, [], 'no token request and no API request left'); + assert.equal(JSON.stringify([...records]), before, 'the account vault is unchanged'); + // Held, no refresh token stored: the account is not marked expired either (that is a vault write). + records.delete('target:account-rt-acc1'); + const withoutToken = JSON.stringify([...records]); + assert.equal((await api.network.handleFetchRequest('target', { url: 'https://api.example.test/account' })).ok, false); + assert.equal(JSON.stringify([...records]), withoutToken, 'no expired mark while held'); + records.set('target:account-rt-acc1', 'synthetic-refresh-token'); + // Released: the same request renews the token and goes out. + held = false; + const renewed = await api.network.handleFetchRequest('target', { url: 'https://api.example.test/account' }); + assert.equal(renewed.ok, true, JSON.stringify(renewed)); + assert.deepEqual(requests, ['https://accounts.example.test/token', 'https://api.example.test/account']); + } finally { await api.network.disposeAll(); } +}); + // Rebase #9496 onto #9621: execute the real gateway's registered page-tool // callback with process/database boundaries injected. A null task must not be // restored, while task-bound calls must retain their original source context. -test('page tools accept a null task without changing task-bound context', async () => { +test('page tools accept a null task without changing task-bound context', async t => { let runPageTool; + let held = false; + let completeTool = async () => ({ ok: true, result: { content: [{ type: 'text', text: 'delivered' }] } }); const contexts = [], restored = []; const session = { id: 'task', instanceId: 'instance', agentKind: 'codex', workDir: '/workspace' }; const boundaries = { @@ -164,7 +243,7 @@ test('page tools accept a null task without changing task-bound context', async createImageCacheStore: () => ({}), hostChatAttachments: {}, createGhostGateway: () => ({ setPageControlGhostProvider() {}, getCindyGhostsMcpDeps(context) { contexts.push(context); - return { callGhostTool: async () => ({ ok: true, result: { content: [{ type: 'text', text: 'delivered' }] } }) }; + return { callGhostTool: (...args) => completeTool(...args) }; } }), pluginAppResult: value => value, }; @@ -174,7 +253,14 @@ test('page tools accept a null task without changing task-bound context', async new Function('require', 'module', 'exports', built.outputFiles[0].text)( name => name.startsWith('node:') ? localRequire(name) : boundaries, gatewayModule, gatewayModule.exports); gatewayModule.exports.createHostPluginGateway({ - runtime: { current: () => true, assertCurrent() {}, authorization: { i18n: {} } }, + runtime: { + current: () => true, + assertCurrent() {}, + assertPluginAvailable() { + if (held) throw Object.assign(new Error('profile held'), { code: 'PRECONDITION_FAILED' }); + }, + authorization: { i18n: {} }, + }, profileDir: '/unused', ownerId: 'owner', version: 'test', credentials: {}, cards: {}, restoreSession: async id => { assert.equal(id, session.id); restored.push(id); return session; }, }); @@ -186,6 +272,24 @@ test('page tools accept a null task without changing task-bound context', async assert.deepEqual(restored, [session.id]); assert.deepEqual(contexts, [undefined, { sessionId: session.id, sessionInstanceId: session.instanceId, agentKind: session.agentKind, workingDir: session.workDir }]); + held = true; + await assert.rejects(runPageTool({ sessionId: session.id, instance: 'plugin', tool: 'read', assertCurrent: async () => {} }, + {}, new AbortController().signal), { code: 'PRECONDITION_FAILED' }); + assert.deepEqual(restored, [session.id], 'held page tools must stop before task restore'); + assert.equal(contexts.length, 2); + + await t.test('page tools preserve an uncertain outcome when a hold interrupts dispatch', async () => { + held = false; + const interrupted = { ok: false, errorCode: 'PLUGIN_DELIVERY_UNKNOWN', message: 'synthetic pause interruption' }; + completeTool = async () => { + held = true; // admitted above, as in a desktop hold during dispatch + return interrupted; + }; + const result = await runPageTool({ sessionId: null, instance: 'plugin', tool: 'read', assertCurrent: async () => {} }, + {}, new AbortController().signal); + assert.equal(result.isError, true); + assert.deepEqual(JSON.parse(result.content[0].text), interrupted); + }); }); function tempProfile(t) { diff --git a/apps/host/src/plugins/authorization.ts b/apps/host/src/plugins/authorization.ts index 976fe800d32..aaedc6d9eaf 100644 --- a/apps/host/src/plugins/authorization.ts +++ b/apps/host/src/plugins/authorization.ts @@ -26,6 +26,7 @@ import { ConnectionTokenProvider, type IssuedConnectionToken } from '../../../de import { createMainI18n } from '../../../desktop/src/main/i18n.js'; import { createLogger } from '../../../desktop/src/main/logger.js'; import { hostOutbound } from '../outbound.mjs'; +import { heldCredentialError, holdCredentialFetch } from '../agent/held-credentials.js'; export interface PluginAccountPorts { hasLogin(): boolean; @@ -49,8 +50,16 @@ export function createHostPluginAuthorization(options: { account: PluginAccountPorts; publish(channel: string, payload: unknown): void; signal: AbortSignal; + /** Coexistence plan A: whether a Cindy desktop app running on its own uses this profile. */ + isProfileHeld?(): boolean; }) { const { owner, root, current, assertCurrent, getGhost, secret, identity, account } = options; + // Plugin OAuth while a desktop uses the profile (held-credentials.ts): its token requests (renewal, + // forced renewal after a 401, identity backfill) and broker calls are answered without the network, + // and its account vault writes nothing (no rotated token, no expired mark, no removed token, no + // insufficient scopes). A tool then fails with "…刷新令牌失败:,请稍后重试", not "reconnect". + const held = () => options.isProfileHeld?.() === true; + const heldWhat = 'this plugin sign-in is not renewed'; const log = createLogger('host-plugin-auth'); const i18n = createMainI18n(() => [Intl.DateTimeFormat().resolvedOptions().locale]); const changes = new GhostSetupChangeBus(log); @@ -81,15 +90,20 @@ export function createHostPluginAuthorization(options: { const oauth = new GhostOauthAccountManager({ connectionSources, connectionSource, vault: { read: secret.readGhostSecret, readStrict: secret.readGhostSecretStrict, - store: secret.storeGhostSecret, remove: secret.removeGhostSecret }, - fetchImpl: (url, init) => hostOutbound.outboundFetch(url, { ...init, - signal: AbortSignal.any([...(init?.signal ? [init.signal] : []), options.signal]) }), + store: (...args) => (held() ? false : secret.storeGhostSecret(...args)), + remove: (...args) => { if (!held()) secret.removeGhostSecret(...args); } }, + fetchImpl: holdCredentialFetch((url: Parameters[0], init?: RequestInit) => hostOutbound.outboundFetch(url, { ...init, + signal: AbortSignal.any([...(init?.signal ? [init.signal] : []), options.signal]) }), held, heldWhat), fetchAvatarHop: (url, init) => hostOutbound.guardedOutboundFetch(url, { ...init, credentials: 'omit', signal: AbortSignal.any([...(init?.signal ? [init.signal] : []), options.signal]) }, assertCurrent), openExternal: url => { assertCurrent(); return account.openExternal(url); }, broker: createGhostOauthBrokerClient({ hasLoginToken: account.hasLogin, - apiPost: (path, body) => { assertCurrent(); return account.post('oauthBrokerApiBaseUrl', path, body); }, logger: log, + apiPost: (path, body) => { + assertCurrent(); + if (held()) throw heldCredentialError(heldWhat); + return account.post('oauthBrokerApiBaseUrl', path, body); + }, logger: log, }), resolveBrokerPublicUrl: path => `${account.endpoint('oauthBrokerApiBaseUrl').replace(/\/+$/, '')}${path}`, captureConnectTarget: target, diff --git a/apps/host/src/plugins/chromium-sandbox.ts b/apps/host/src/plugins/chromium-sandbox.ts index ba1c33619fa..d1df4377bc3 100644 --- a/apps/host/src/plugins/chromium-sandbox.ts +++ b/apps/host/src/plugins/chromium-sandbox.ts @@ -6,6 +6,7 @@ import { installedGhostStoragePart } from '../../../desktop/src/shared/pluginIde import type { SandboxHandle, SandboxHostAdapter } from '../../../desktop/src/main/cindy-brain/runtime/GhostRuntime.js'; import { GHOST_BOOT_PATH, GHOST_MAIL_SDK_PATH } from '../../../desktop/src/main/cindy-brain/runtime/ghostFiles.js'; import { GHOST_HTML_CSP } from '../../../desktop/src/main/cindy-brain/runtime/ghostPageHandler.js'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; export interface HeadlessPluginSandboxPorts { /** Captured by the launcher, never selected by plugin data. */ @@ -13,6 +14,7 @@ export interface HeadlessPluginSandboxPorts { bridgeSource: string; ownerKey: () => string; isCurrent: (ghost: InstalledGhost, ownerKey: string) => boolean; + profileHoldMessage?(): string | null; pageHandler: (ghost: InstalledGhost, origin: string, current: () => boolean) => (request: Request) => Promise; send: (ghost: InstalledGhost, payload: unknown) => Promise; } @@ -35,6 +37,10 @@ export function createHeadlessPluginSandbox(ports: HeadlessPluginSandboxPorts) { const partitions = new Map>(); const logic = new Map(); const closing = new Set>(); + const assertNotHeld = () => { + const held = ports.profileHoldMessage?.(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + }; function closeContext(context: BrowserContext) { const pending = context.close().catch(() => undefined).finally(() => closing.delete(pending)); closing.add(pending); @@ -74,7 +80,9 @@ export function createHeadlessPluginSandbox(ports: HeadlessPluginSandboxPorts) { } if (!pending) { pending = (async () => { - const context = await (await browser()).newContext({ + const instance = await browser(); + assertNotHeld(); + const context = await instance.newContext({ acceptDownloads: false, serviceWorkers: 'block', permissions: [], bypassCSP: false, ignoreHTTPSErrors: false, }); @@ -94,14 +102,22 @@ export function createHeadlessPluginSandbox(ports: HeadlessPluginSandboxPorts) { const request = route.request(); let url: URL; try { url = new URL(request.url()); } catch { await route.abort('blockedbyclient'); return; } - if (url.origin !== origin) { - // The existing page contract allows external HTTPS images only. - if (url.protocol === 'https:' && request.resourceType() === 'image') await route.continue(); - else await route.abort('blockedbyclient'); - return; - } - if (url.username || url.password) { await route.abort('blockedbyclient'); return; } + const refuseWhileHeld = (held: string) => { + if (url.origin === origin) { + return route.fulfill({ status: 409, json: { ok: false, errorCode: 'PRECONDITION_FAILED', message: held } }); + } + return route.abort('blockedbyclient'); + }; try { + const held = ports.profileHoldMessage?.(); + if (held) { await refuseWhileHeld(held); return; } + if (url.origin !== origin) { + // The existing page contract allows external HTTPS images only. + if (url.protocol === 'https:' && request.resourceType() === 'image') await route.continue(); + else await route.abort('blockedbyclient'); + return; + } + if (url.username || url.password) { await route.abort('blockedbyclient'); return; } const body = request.postDataBuffer(); // Page configuration endpoints already have a 64 KiB body contract. if (body && body.length > 65_536) { await route.fulfill({ status: 413 }); return; } @@ -109,6 +125,8 @@ export function createHeadlessPluginSandbox(ports: HeadlessPluginSandboxPorts) { method: request.method(), headers: request.headers(), ...(body && !['GET', 'HEAD'].includes(request.method()) ? { body: new Uint8Array(body) } : {}), })); + const nowHeld = ports.profileHoldMessage?.(); + if (nowHeld) { await response.body?.cancel(); await refuseWhileHeld(nowHeld); return; } if (!current()) { await response.body?.cancel(); await route.abort('blockedbyclient'); return; } const bytes = Buffer.from(await response.arrayBuffer()); if (!current()) { await route.abort('blockedbyclient'); return; } @@ -138,43 +156,60 @@ export function createHeadlessPluginSandbox(ports: HeadlessPluginSandboxPorts) { create(ghost): SandboxHandle { let destroyed = false; let page: Page | undefined; + let stopLoading: (() => void) | undefined; let gone: ((details: { reason: string }) => void) | undefined; const id = installedGhostStoragePart(ghost); + const loadPage = async () => { + assertNotHeld(); + const partition = await partitionFor(ghost); + assertNotHeld(); + if (destroyed) throw new Error('PLUGIN_RUNTIME_STOPPED'); + page = await partition.context.newPage(); + const livePage = page; + if (destroyed || !partition.current()) { await page.close(); throw new Error('PLUGIN_PAGE_UNAVAILABLE'); } + page.on('crash', () => { if (!destroyed) gone?.({ reason: 'crashed' }); }); + page.on('close', () => { if (!destroyed) gone?.({ reason: 'closed' }); }); + const valid = () => !destroyed && partition.current() && !livePage.isClosed(); + await page.exposeBinding('__cindyPluginRequest', async (source, kind, payload) => { + if (!partition.current() || source.page !== livePage || source.frame !== livePage.mainFrame() || + new URL(source.frame.url()).origin !== partition.origin) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + assertNotHeld(); + if (!valid()) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + if (kind === 'ping') return { ok: true, id }; + if (kind !== 'send') throw new Error('PLUGIN_REQUEST_INVALID'); + const result = await ports.send(ghost, payload); + if (!valid()) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + return result; + }); + // Initialize the private delivery handle before loading plugin code. + // Unlike a global callback it cannot be replaced or called by a panel. + await page.route(`${partition.origin}${GHOST_BOOT_PATH}`, route => route.fulfill({ + status: 200, contentType: 'text/html', headers: { 'Content-Security-Policy': GHOST_HTML_CSP }, + body: '', + })); + await page.goto(`${partition.origin}${GHOST_BOOT_PATH}`); + const bridge = await page.evaluateHandle(`(() => { ${ports.bridgeSource}\nconst bridge = CindyPluginBridge.createGhostPageBridge({ ping: () => window.__cindyPluginRequest('ping'), send: payload => window.__cindyPluginRequest('send', payload) }); Object.defineProperty(window, 'cindy', { value: bridge.api, writable: false, configurable: false }); return bridge; })()`); + if (!valid()) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + logic.set(id, { page, partition, bridge }); + await page.addScriptTag({ url: `${partition.origin}${GHOST_MAIL_SDK_PATH}` }); + await page.addScriptTag({ url: `${partition.origin}/${ghost.manifest.entry}` }); + if (!valid()) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + }; return { async load() { - const partition = await partitionFor(ghost); - if (destroyed) throw new Error('PLUGIN_RUNTIME_STOPPED'); - page = await partition.context.newPage(); - const livePage = page; - if (destroyed || !partition.current()) { await page.close(); throw new Error('PLUGIN_PAGE_UNAVAILABLE'); } - page.on('crash', () => { if (!destroyed) gone?.({ reason: 'crashed' }); }); - page.on('close', () => { if (!destroyed) gone?.({ reason: 'closed' }); }); - const valid = () => !destroyed && partition.current() && !livePage.isClosed(); - await page.exposeBinding('__cindyPluginRequest', async (source, kind, payload) => { - if (!valid() || source.page !== livePage || source.frame !== livePage.mainFrame() || - new URL(source.frame.url()).origin !== partition.origin) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); - if (kind === 'ping') return { ok: true, id }; - if (kind !== 'send') throw new Error('PLUGIN_REQUEST_INVALID'); - const result = await ports.send(ghost, payload); - if (!valid()) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); - return result; + const stopped = new Promise((_resolve, reject) => { + stopLoading = () => reject(new Error('PLUGIN_RUNTIME_STOPPED')); }); - // Initialize the private delivery handle before loading plugin code. - // Unlike a global callback it cannot be replaced or called by a panel. - await page.route(`${partition.origin}${GHOST_BOOT_PATH}`, route => route.fulfill({ - status: 200, contentType: 'text/html', headers: { 'Content-Security-Policy': GHOST_HTML_CSP }, - body: '', - })); - await page.goto(`${partition.origin}${GHOST_BOOT_PATH}`); - const bridge = await page.evaluateHandle(`(() => { ${ports.bridgeSource}\nconst bridge = CindyPluginBridge.createGhostPageBridge({ ping: () => window.__cindyPluginRequest('ping'), send: payload => window.__cindyPluginRequest('send', payload) }); Object.defineProperty(window, 'cindy', { value: bridge.api, writable: false, configurable: false }); return bridge; })()`); - logic.set(id, { page, partition, bridge }); - await page.addScriptTag({ url: `${partition.origin}${GHOST_MAIL_SDK_PATH}` }); - await page.addScriptTag({ url: `${partition.origin}/${ghost.manifest.entry}` }); - if (!valid()) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + // A context can close during newPage() before the page handle arrives. + // Stop releases the startup waiter immediately. loadPage still checks + // destroyed before using or retaining any late-arriving page. + try { await Promise.race([loadPage(), stopped]); } + finally { stopLoading = undefined; } }, destroy() { if (destroyed) return; destroyed = true; + stopLoading?.(); if (logic.get(id)?.page === page) logic.delete(id); if (page) void page.close().catch(() => undefined); }, @@ -187,7 +222,19 @@ export function createHeadlessPluginSandbox(ports: HeadlessPluginSandboxPorts) { }; return { adapter, + /** A gateway request has one delivery attempt. Once submitted, only the plugin's + * verdict or the gateway deadline can settle it, even if its page then closes. */ + acceptGatewayDelivery(id: string, message: unknown): true { + assertNotHeld(); + const target = logic.get(id); + if (!target || target.partition.id !== id || !target.partition.current() || target.page.isClosed()) { + throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + } + void target.bridge.evaluate((bridge, payload) => bridge.deliver(payload), message).catch(() => {}); + return true; + }, async deliver(id: string, message: unknown, options: { failOnUncertain?: boolean } = {}): Promise { + if (ports.profileHoldMessage?.()) return false; const target = logic.get(id); if (!target?.partition.current() || target.page.isClosed()) return false; try { await target.bridge.evaluate((bridge, payload) => bridge.deliver(payload), message); return target.partition.current(); } @@ -195,12 +242,15 @@ export function createHeadlessPluginSandbox(ports: HeadlessPluginSandboxPorts) { }, /** A zero-bridge page in the exact same owner × installation partition. */ async openPage(ghost: InstalledGhost, pathname: string): Promise { + assertNotHeld(); const partition = await partitionFor(ghost); + assertNotHeld(); const url = new URL(pathname, partition.origin); if (url.origin !== partition.origin) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); const page = await partition.context.newPage(); try { await page.goto(url.href); + assertNotHeld(); if (!partition.current()) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); return page; } catch (error) { await page.close(); throw error; } diff --git a/apps/host/src/plugins/gateway-delivery.test.mjs b/apps/host/src/plugins/gateway-delivery.test.mjs new file mode 100644 index 00000000000..c869003b9f1 --- /dev/null +++ b/apps/host/src/plugins/gateway-delivery.test.mjs @@ -0,0 +1,115 @@ +// Integration (§3.2, release table 8i). Use the production logic-page adapter and shared gateway. +// Losing a page before admission and losing its reply after admission have different native-tool +// outcomes. Only the Playwright process boundary is replaced. No Chromium or profile is opened. +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { setImmediate as nextTurn } from 'node:timers/promises'; +import { chromium } from 'playwright-core'; +import { createHeadlessPluginSandbox } from './chromium-sandbox.ts'; +import { createSubscriptionGatewayReader } from '../../../desktop/src/main/cindy-brain/runtimePluginHostCore.ts'; +import { installedGhostStoragePart } from '../../../desktop/src/shared/pluginIdentity.ts'; + +const plugin = { manifest: { id: 'fixture', name: 'Fixture', version: '1.0.0', entry: 'main.js', + subscribe: { hooks: ['will-tool-call'] } }, dir: '/fixture', enabled: true, + approval: { state: 'approved', revision: 'one' } }; + +function createGateway(ghost, sendToGhostLogic, log = []) { + return createSubscriptionGatewayReader({ + availableGhosts: () => [ghost], listGhostNotificationCandidates: async () => [ghost], + findGhostNotificationTarget: id => id === installedGhostStoragePart(ghost) ? ghost : null, + getGhostRuntime: () => ({ stateOf: () => 'running' }), sendToGhostLogic, + broadcastGhostWindowPush() {}, log: { info() {}, warn: (_message, fields) => log.push(fields.why) }, + }).getGhostSubscriptionGateway(); +} + +function fixture(t) { + t.mock.timers.enable({ apis: ['Date', 'setTimeout'] }); + const sandbox = createHeadlessPluginSandbox({ ownerKey: () => 'test', isCurrent: () => true, + bridgeSource: '', pageHandler: () => () => new Response(), send: async () => ({ ok: true }) }); + t.after(() => sandbox.close()); + const log = []; + const gateway = createGateway(plugin, sandbox.acceptGatewayDelivery, log); + const screen = () => gateway.screenControlPoint('will-tool-call', { sessionId: 'unit', engine: 'pi', + phase: 'call', toolName: 'fixture', toolCallId: 'unit', input: {} }, + { pluginId: installedGhostStoragePart(plugin), onFailure: 'block' }, 100); + return { sandbox, screen, log }; +} + +function stubLogicPage(t, evaluate, isClosed = () => false) { + const page = { on() {}, exposeBinding() {}, route() {}, goto() {}, addScriptTag() {}, isClosed, + evaluateHandle: async () => ({ evaluate }) }; + const browser = { once() {}, close() {}, isConnected: () => true, async newContext() { return { + once() {}, on() {}, route() {}, routeWebSocket() {}, async close() {}, browser: () => browser, newPage: async () => page, + }; } }; + t.mock.method(chromium, 'launch', async () => browser); +} + +test('an absent logic page immediately applies the native hook delivery failure policy', async t => { + const { screen, log } = fixture(t); + let action; + const answer = screen().then(result => { action = result.action; }); + await nextTurn(); + assert.equal(action, 'block'); + assert.ok(log.includes('deliver: PLUGIN_PAGE_UNAVAILABLE')); + await answer; +}); + +test('a lost reply after logic-page admission follows the native hook deadline once', async t => { + const { sandbox, screen, log } = fixture(t); + const envelopes = []; + let closed = false; + stubLogicPage(t, async (_deliver, payload) => { + envelopes.push(payload); + closed = true; + throw Error('Page closed after submission'); + }, () => closed); + await sandbox.adapter.create(plugin).load(); + let action; + const answer = screen().then(result => { action = result.action; }); + await nextTurn(); + assert.deepEqual(envelopes.map(event => event.name), ['will-tool-call']); + t.mock.timers.tick(99); + await nextTurn(); + assert.equal(action, undefined); + t.mock.timers.tick(1); + await answer; + assert.equal(action, 'allow'); + assert.deepEqual(log, ['timeout']); + assert.equal(envelopes.length, 1); +}); + +// §3.2, integration: compare both control points under all three task policies. +// Electron's port reports synchronous admission. A renderer error after that +// admission and a silent renderer both leave the original deadline pending. +test('Host control failure directions match the desktop gateway', async t => { + const { sandbox } = fixture(t); + let failureMode, delivered; + stubLogicPage(t, async () => { + delivered = true; + if (failureMode === 'handler error') throw Error('fixture handler error'); + }); + const points = ['will-compose-context', 'will-start-turn']; + const installed = { ...plugin, manifest: { ...plugin.manifest, subscribe: { hooks: points } } }; + await sandbox.adapter.create(installed).load(); + for (const point of points) { + for (failureMode of ['silent', 'handler error', 'unsubscribed']) { + const ghost = failureMode === 'unsubscribed' + ? { ...installed, manifest: { ...installed.manifest, subscribe: { hooks: [] } } } : installed; + for (const onFailure of ['allow', 'skip', 'block']) { + delivered = false; + const host = createGateway(ghost, sandbox.acceptGatewayDelivery); + const desktop = createGateway(ghost, () => true); + const data = { sessionId: 'matrix', text: 'input', route: { agentKind: 'pi', model: 'm', providerId: 'p' } }; + const target = { pluginId: installedGhostStoragePart(ghost), onFailure }; + const actual = host.screenControlPoint(point, data, target, 100); + const expected = desktop.screenControlPoint(point, data, target, 100); + await nextTurn(); + t.mock.timers.tick(100); + assert.equal(delivered, failureMode !== 'unsubscribed', `${point}: ${failureMode}`); + const baseline = await expected; + assert.equal(baseline.action, onFailure); + assert.deepEqual(await actual, baseline, `${point}: ${failureMode}: ${onFailure}`); + } + } + } +}); diff --git a/apps/host/src/plugins/gateway.ts b/apps/host/src/plugins/gateway.ts index b70c8c1d428..6f4e0360cfa 100644 --- a/apps/host/src/plugins/gateway.ts +++ b/apps/host/src/plugins/gateway.ts @@ -114,9 +114,10 @@ export function createHostPluginGateway(options: GatewayOptions) { }, }; registry.setPluginPageToolRunner(async (grant, args, signal) => { - const assertCurrent = async () => { - signal.throwIfAborted(); runtime.assertCurrent(); await grant.assertCurrent(); - runtime.assertCurrent(); signal.throwIfAborted(); + const assertCurrent = async (interrupted = false) => { + const checkHost = interrupted ? runtime.assertCurrent : runtime.assertPluginAvailable; + signal.throwIfAborted(); checkHost(); await grant.assertCurrent(); + checkHost(); signal.throwIfAborted(); }; await assertCurrent(); const session = grant.sessionId === null ? undefined : await options.restoreSession(grant.sessionId, assertCurrent); @@ -125,7 +126,7 @@ export function createHostPluginGateway(options: GatewayOptions) { const deps = gateway.getCindyGhostsMcpDeps(session ? { sessionId: session.id, sessionInstanceId: session.instanceId, agentKind: session.agentKind, workingDir: session.workDir } : undefined, hostDeps, grant); const result = await deps.callGhostTool({ ghostId: grant.instance, tool: grant.tool, args, signal }); - await assertCurrent(); + await assertCurrent(!result.ok && result.errorCode === 'PLUGIN_DELIVERY_UNKNOWN'); return result.ok ? pluginAppResult(result.result) : { isError: true, content: [{ type: 'text', text: JSON.stringify(result) }] }; }); @@ -137,7 +138,11 @@ export function createHostPluginGateway(options: GatewayOptions) { isEnabled: runtime.current, toClaudeSdkConfig: context => { runtime.assertCurrent(); - return { type: 'sdk', name: 'cindy', instance: createCindyGhostsMcpServer(gateway.getCindyGhostsMcpDeps(context, hostDeps)) }; + const deps = gateway.getCindyGhostsMcpDeps(context, hostDeps); + return { type: 'sdk', name: 'cindy', instance: createCindyGhostsMcpServer({ + ...deps, + callGhostTool: async input => runtime.pluginPauseFailure() ?? deps.callGhostTool(input), + }) }; }, }; return { diff --git a/apps/host/src/plugins/legacy-approvals.ts b/apps/host/src/plugins/legacy-approvals.ts new file mode 100644 index 00000000000..b64ae50d803 --- /dev/null +++ b/apps/host/src/plugins/legacy-approvals.ts @@ -0,0 +1,82 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; + +import { isMissing } from '../../../desktop/src/main/concurrentInstanceScan.js'; +import { classifyGhostDirEntry } from '../../../desktop/src/main/cindy-brain/ghostContentTree.js'; +import { GhostInstallReceiptStore } from '../../../desktop/src/main/cindy-brain/ghostInstallReceipt.js'; +import { readInstalledGhostManifestSnapshotAsync } from '../../../desktop/src/main/installedGhostManifest.js'; +import { listLegacyOwnerProjectionRoots } from '../../../desktop/src/main/ownerProjectionRoots.js'; +import { GHOST_MANIFEST_FILE, GHOST_MANIFEST_MAX_BYTES, isValidGhostId, type InstalledGhost } from '../../../desktop/src/shared/ghost.js'; +import { installedGhostPhysicalRelId, installedGhostStoragePart } from '../../../desktop/src/shared/pluginIdentity.js'; + +export interface LegacyPluginApprovals { + count: number; + installIds: string[]; +} + +export function summarizeLegacyPluginApprovals(installed: readonly InstalledGhost[]): LegacyPluginApprovals { + const installIds = installed + .filter(ghost => ghost.approval.state === 'legacy-unapproved' && isValidGhostId(installedGhostPhysicalRelId(ghost))) + .map(installedGhostStoragePart).sort(); + return { count: installIds.length, installIds }; +} + +async function entryKind(file: string) { + try { + return await classifyGhostDirEntry(file); + } catch (error) { + if (isMissing(error)) return null; + throw error; + } +} + +async function directoryExists(dir: string): Promise { + const kind = await entryKind(dir); + if (kind !== null && kind !== 'directory') throw new Error(`Not a regular profile directory: ${path.basename(dir)}`); + return kind === 'directory'; +} + +/** Offline migration gate. Inspect every owner plus the two unclaimed content roots. + * The desktop's one-time backfill applies to bare install directories, not `_ns` entries. + * Read receipt facts without constructing GhostManager, whose listing can repair its index. + */ +async function checkLegacyPluginMigration(profile: string) { + if (!path.isAbsolute(profile)) throw new Error('Pass the absolute path of the desktop profile'); + const root = await fs.realpath(profile); + if (!await directoryExists(root)) throw new Error('Desktop profile not found'); + await directoryExists(path.join(root, 'owners')); + + const installIds: string[] = []; + const contentRoots = listLegacyOwnerProjectionRoots(root).filter(dir => path.basename(dir) !== 'ghost-install-state'); + for (const dir of contentRoots) { + if (!await directoryExists(dir)) continue; + const stateRoot = path.join(path.dirname(dir), 'ghost-install-state'); + await directoryExists(stateRoot); + const receipts = new GhostInstallReceiptStore(() => stateRoot); + for (const id of await fs.readdir(dir)) { + if (!isValidGhostId(id)) continue; + const install = path.join(dir, id); + const kind = await entryKind(install); + if (kind === 'file') continue; + if (kind !== 'directory') throw new Error(`Cannot verify plugin directory: ${id}`); + if (await entryKind(path.join(install, GHOST_MANIFEST_FILE)) === null) continue; + const receipt = await receipts.readAsync(id); + if (receipt.state === 'approved') continue; + if (receipt.state === 'invalid') throw new Error(`Cannot verify plugin approval receipt: ${id}`); + const manifest = await readInstalledGhostManifestSnapshotAsync(install, GHOST_MANIFEST_MAX_BYTES); + if (!manifest.ok || manifest.snapshot.manifest.id !== id) throw new Error(`Cannot verify installed plugin: ${id}`); + installIds.push(path.relative(root, install).split(path.sep).join('/')); + } + } + + return { allowed: installIds.length === 0, count: installIds.length, installIds: installIds.sort() }; +} + +export async function runLegacyPluginMigrationPreflight(args: readonly string[], output: Pick = console): Promise { + if (args.length !== 1) throw new Error('Usage: cindy-host migration-preflight '); + const report = await checkLegacyPluginMigration(args[0]); + output.log(JSON.stringify(report)); + if (report.allowed) return 0; + output.error('Open this profile in Cindy Desktop v0.1.48 or later, then close Desktop and rerun the preflight.'); + return 1; +} diff --git a/apps/host/src/plugins/managed-skills.test.mjs b/apps/host/src/plugins/managed-skills.test.mjs index 1a7a4ee7ce0..ed05b8445a9 100644 --- a/apps/host/src/plugins/managed-skills.test.mjs +++ b/apps/host/src/plugins/managed-skills.test.mjs @@ -21,14 +21,18 @@ import os from 'node:os'; import path from 'node:path'; import test from 'node:test'; import { fileURLToPath } from 'node:url'; +import { chromium } from 'playwright-core'; import { configureHostOwner } from '../agent/claude-auth.mjs'; import { createSnapshotProcess } from '../snapshot-process.mjs'; import { createHostGhostManager } from '../plugins-installed.ts'; import { createHostPluginRuntime } from './runtime.ts'; +import { runLegacyPluginMigrationPreflight } from './legacy-approvals.ts'; import { createHostPluginIdentity } from './identity.ts'; import { configureGhostSnapshotProcess } from '../../../desktop/src/main/cindy-brain/ghostSnapshotCapability.ts'; import { prepareBuiltInSkills } from '../../../desktop/src/main/maker-host/built-in-skills.ts'; +import { getDesktopMcpToolApprovalPolicy, setGhostToolApprovalResolver } from '../../../desktop/src/main/maker-host/mcp-tool-approval-policy.ts'; +import { writeRuntimePluginSettings } from '../../../desktop/src/main/maker-host/runtime-plugin-settings.ts'; import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; import { commitVolatileAppSession, LOCAL_DATA_OWNER_ID } from '../../../desktop/src/main/appSessionState.ts'; import { getAppCapabilities } from '../../../desktop/src/main/appCapabilities.ts'; @@ -70,13 +74,13 @@ async function profileFor(t, mode, ownerId) { return { profile, owner, manager }; } -async function install(manager, profile, { id, namespace, account }) { +async function install(manager, profile, { id, namespace, account, manifest = {} }) { const zip = new JSZip(); zip.file('ghost.json', JSON.stringify({ schemaVersion: 3, minCindyVersion: '0.1.61', id, name: `Fixture ${id}`, kind: 'chip', version: '1.0.0', entry: 'main.js', tools: [{ name: 'noop', description: 'fixture tool', parameters: { type: 'object' } }], ...(account ? { network: { hosts: ['api.example.com'], secrets: [{ key: 'email', label: 'Email', source: 'login-email', inject: { header: 'X-User', format: '{value}' } }] } } : {}), - skill: { items: [{ dir: 'skills/demo', name: 'demo', description: `Skill of ${id}` }] } })); + skill: { items: [{ dir: 'skills/demo', name: 'demo', description: `Skill of ${id}` }] }, ...manifest })); zip.file('main.js', '// fixture'); zip.file('skills/demo/SKILL.md', `---\nname: demo\ndescription: Skill of ${id}\n---\n\nApproved body\n`); const archive = path.join(profile, `${id}-${namespace ?? 'root'}.cindy`); @@ -104,11 +108,13 @@ async function installAll(manager, profile, owner, plugins = PLUGINS) { return parts; } -async function hostRuntime(t, { profile, owner, manager }, user = null) { +async function hostRuntime(t, { profile, owner, manager }, user = null, log) { const secrets = new Map(); const runtime = await createHostPluginRuntime({ profileDir: profile, ownerId: owner, manager, credentials: { read: key => secrets.get(key) ?? null, write: (key, value) => { secrets.set(key, value); }, remove: key => { secrets.delete(key); } }, getLoginEmail: () => user?.email ?? null, getUser: () => user, + modelRouteSources: () => ({ localViews: async () => [], localAgents: () => [] }), + log, appContext: () => ({ ok: false, error: 'unavailable' }), getSession: () => undefined, requestFileConfirmation: async () => false, publish() {}, // No plugin process is started here; the worker assets are never read. @@ -118,6 +124,79 @@ async function hostRuntime(t, { profile, owner, manager }, user = null) { return runtime; } +async function writeLegacyPlugin(dir, id) { + const manifest = JSON.stringify({ id, schemaVersion: 3, minCindyVersion: '0.1.61', kind: 'chip', + name: 'Legacy fixture', version: '1.0.0', entry: 'main.js' }); + await fs.mkdir(dir, { recursive: true }); + await fs.writeFile(path.join(dir, 'ghost.json'), manifest); + await fs.writeFile(path.join(dir, 'main.js'), '// fixture'); + return manifest; +} + +async function preflight(profile) { + const stdout = []; + const stderr = []; + const exitCode = await runLegacyPluginMigrationPreflight([profile], { log: value => stdout.push(value), error: value => stderr.push(value) }); + return { exitCode, report: JSON.parse(stdout[0]), stderr }; +} + +// §3.2 integration, migration release table §5: use the real startup plugin +// reconciliation and offline preflight on one unapproved bare install. A migrated +// copy alone cannot prove either the block or the safe discovery of an old profile. +test('legacy plugin startup reports missing approvals and preflight only passes after desktop backfill', async t => { + t = lifoCleanup(t); + const env = await profileFor(t, 'local', null); + const { profile, owner, manager } = env; + const id = 'legacy-fixture'; + const dir = ownerScopedPath(profile, owner, 'cindy-brain', id); + const receipt = ownerScopedPath(profile, owner, 'ghost-install-state', `${id}.json`); + const manifest = await writeLegacyPlugin(dir, id); + const report = { count: 1, installIds: [id] }; + const preflightReport = { ...report, allowed: false, installIds: [path.relative(profile, dir).split(path.sep).join('/')] }; + const refused = await preflight(profile); + assert.equal(refused.exitCode, 1); + assert.deepEqual(refused.report, preflightReport); + assert.match(refused.stderr.join('\n'), /Cindy Desktop v0\.1\.48 or later/); + + const logs = []; + const runtime = await hostRuntime(t, env, null, { info: (...args) => logs.push(args), trace() {}, debug() {}, warn() {}, error() {}, fatal() {} }); + const censusLogs = () => logs.filter(([message]) => message === 'legacy plugin approval census: %j'); + assert.equal(runtime.legacyPluginApprovals(), null); + await runtime.reconcile(); + assert.deepEqual(runtime.legacyPluginApprovals(), report); + assert.deepEqual(censusLogs(), [['legacy plugin approval census: %j', report]]); + assert.equal((await runtime.list()).find(ghost => ghost.manifest.id === id)?.approval.state, 'legacy-unapproved'); + await assert.rejects(fs.stat(receipt), { code: 'ENOENT' }); + assert.equal(await fs.readFile(path.join(dir, 'ghost.json'), 'utf8'), manifest); + assert.equal(await fs.readFile(path.join(dir, 'main.js'), 'utf8'), '// fixture'); + + assert.deepEqual((await manager.migrateLegacyApprovalsOnce()).migrated, [id]); + const approved = await fs.readFile(receipt); + assert.deepEqual(await preflight(profile), { exitCode: 0, report: { allowed: true, count: 0, installIds: [] }, stderr: [] }); + await runtime.reconcile(); + assert.deepEqual(runtime.legacyPluginApprovals(), { count: 0, installIds: [] }); + assert.equal(censusLogs().length, 1); + assert.deepEqual(await fs.readFile(receipt), approved); + assert.equal((await runtime.list()).find(ghost => ghost.manifest.id === id)?.enabled, true); +}); + +// §3.2 integration: an active-owner-only or cindy-brain-only scan can incorrectly +// clear the profile gate. Include the older flat and inactive owner layouts. +test('legacy plugin preflight includes unclaimed and dormant owner roots and rejects an incomplete census', async t => { + const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-host-legacy-preflight-')); + t.after(() => fs.rm(profile, { recursive: true, force: true })); + const dormant = ownerScopedPath(profile, 'dormant-owner', 'brain', 'dormant-fixture'); + await writeLegacyPlugin(dormant, 'dormant-fixture'); + await writeLegacyPlugin(path.join(profile, 'brain', 'shared-fixture'), 'shared-fixture'); + const refused = await preflight(profile); + assert.equal(refused.exitCode, 1); + assert.deepEqual(refused.report, { allowed: false, count: 2, + installIds: ['brain/shared-fixture', path.relative(profile, dormant).split(path.sep).join('/')] }); + const unknownRoot = ownerScopedPath(profile, 'unreadable-owner'); + await fs.writeFile(unknownRoot, 'not a directory'); + await assert.rejects(preflight(profile), /owner projection namespace is not a regular directory/); +}); + /** The identity as it was before 3c: the runtime's own lookup (manager.findInstalledInstance, then the list). */ function previousIdentity({ profile, owner, manager }, user = null) { return createHostPluginIdentity({ manager, root: (...parts) => ownerScopedPath(profile, owner, ...parts), @@ -196,3 +275,87 @@ test('with account services unavailable, a plugin that needs an account is left } assert.equal(runtime.identity.isVerifiedPublicMarket(parts.accountOfficial), true); }); + +// §3.2, integration: a pre-existing desktop installation must answer a runtime +// point without a second approval. Exercise real install facts, gateway wake, +// sandbox admission, host-request binding and verdict delivery. Only Chromium's +// process boundary is a fixture. The legacy variant starts with no receipt and +// takes the existing desktop backfill before handing its profile to the Host. +for (const layout of ['receipt', 'desktop backfill']) { + test(`Host hook delivery uses the existing ${layout} approval and the plugin’s each-call policy`, async t => { + t = lifoCleanup(t); + const env = await profileFor(t, 'local', null); + const id = 'approved-hook'; + const installed = () => env.manager.list().find(ghost => ghost.manifest.id === id); + const manifest = { id, schemaVersion: 3, minCindyVersion: '0.1.61', kind: 'chip', + name: 'Approved hook', version: '1.0.0', entry: 'main.js', + subscribe: { hooks: ['will-compose-context', 'will-tool-call', 'did-tool-result'] }, + tools: [{ name: 'noop', description: 'fixture tool', parameters: { type: 'object' }, approval: 'each-call' }] }; + if (layout === 'desktop backfill') { + const dir = ownerScopedPath(env.profile, env.owner, 'cindy-brain', id); + await fs.mkdir(dir, { recursive: true }); + await fs.writeFile(path.join(dir, 'ghost.json'), JSON.stringify(manifest)); + await fs.writeFile(path.join(dir, 'main.js'), '// fixture'); + assert.equal(installed()?.approval.state, 'legacy-unapproved'); + assert.deepEqual((await env.manager.migrateLegacyApprovalsOnce()).migrated, [id]); + } else { + await install(env.manager, env.profile, { id, namespace: null, manifest }); + } + const ghost = installed(); + assert.ok(ghost); + assert.equal(ghost.approval.state, 'approved'); + let onRequest, href; + const delivered = []; + const replies = []; + const verdicts = { + 'will-compose-context': { action: 'context', blocks: [{ id: 'reference', text: 'approved reference' }] }, + 'will-tool-call': { action: 'tool', tool: { decision: 'deny', reason: 'fixture denied call' } }, + 'did-tool-result': { action: 'tool', tool: { result: { details: { edited: true } } } }, + }; + const frame = { url: () => href }; + const page = { + on() {}, close: async () => {}, isClosed: () => false, mainFrame: () => frame, + exposeBinding(_name, handler) { onRequest = handler; }, + route: async () => {}, goto: async url => { href = url; }, addScriptTag: async () => {}, + evaluateHandle: async () => ({ + async evaluate(_deliver, message) { + delivered.push(message.name); + const result = await onRequest({ page, frame }, 'send', { type: 'event-verdict', + hookId: message.hookId, ...verdicts[message.name] }); + replies.push(result); + }, + }), + }; + const browser = { once() {}, close: async () => {}, isConnected: () => true, newContext: async () => ({ + once() {}, on() {}, route: async () => {}, routeWebSocket: async () => {}, close: async () => {}, + browser: () => browser, newPage: async () => page, + }) }; + t.mock.method(chromium, 'launch', async () => browser); + const runtime = await hostRuntime(t, env); + const installation = installedGhostStoragePart(ghost); + const screen = await runtime.taskPlugins.screenGhostControlPoint('will-compose-context', { sessionId: 'task', text: 'work' }, + { pluginId: installation, onFailure: 'block' }); + assert.equal(screen.action, 'context'); + const selection = [{ pluginId: installation, onFailure: 'block' }]; + await writeRuntimePluginSettings('task', { 'will-tool-call': selection, 'did-tool-result': selection }); + const lifecycle = runtime.taskPlugins.ghostToolLifecycleControl; + const call = { engine: 'pi', phase: 'call', toolName: 'noop', toolCallId: 'call', input: {} }; + assert.deepEqual(await lifecycle.run('task', call), { decision: 'deny', reason: 'fixture denied call' }); + assert.deepEqual(await lifecycle.run('task', { ...call, phase: 'result', + result: { content: [{ type: 'text', text: 'original' }], details: {} } }), { + result: { content: [{ type: 'text', text: 'original' }], details: { edited: true } }, + }); + assert.deepEqual(delivered, ['will-compose-context', 'will-tool-call', 'did-tool-result']); + await new Promise(resolve => setImmediate(resolve)); + assert.deepEqual(replies, [{ ok: true }, { ok: true }, { ok: true }]); + assert.deepEqual(installed()?.approval, ghost.approval); + setGhostToolApprovalResolver(runtime.taskPlugins.resolveToolApproval); + try { + const invocation = { serverName: 'cindy', toolName: 'ghost_call', toolParams: { ghost_id: id, tool: 'noop' } }; + assert.deepEqual([getDesktopMcpToolApprovalPolicy(invocation), getDesktopMcpToolApprovalPolicy(invocation)], + ['prompt-each-time', 'prompt-each-time']); + } finally { + setGhostToolApprovalResolver(null); + } + }); +} diff --git a/apps/host/src/plugins/profile-pause.test.mjs b/apps/host/src/plugins/profile-pause.test.mjs new file mode 100644 index 00000000000..ed6568b5849 --- /dev/null +++ b/apps/host/src/plugins/profile-pause.test.mjs @@ -0,0 +1,549 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import fs from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { chromium } from 'playwright-core'; + +import { beginAppSessionBoundary, commitVolatileAppSession, LOCAL_DATA_OWNER_ID } from '../../../desktop/src/main/appSessionState.ts'; +import { ownerScopedPath } from '../../../desktop/src/main/dataOwnerPath.ts'; +import { configureAppDataDir } from '../../../desktop/src/main/userDataPath.ts'; +import { configureGhostSnapshotProcess } from '../../../desktop/src/main/cindy-brain/ghostSnapshotCapability.ts'; +import { GhostRuntime } from '../../../desktop/src/main/cindy-brain/runtime/GhostRuntime.ts'; +import { installedGhostStoragePart } from '../../../desktop/src/shared/pluginIdentity.ts'; +import { configureHostOwner } from '../agent/claude-auth.mjs'; +import { createHostProfileCoexistenceMonitor } from '../agent/profile-coexistence.ts'; +import { hostOutbound } from '../outbound.mjs'; +import { createHostGhostManager } from '../plugins-installed.ts'; +import { createSnapshotProcess } from '../snapshot-process.mjs'; +import { lifoCleanup } from '../test-support/cleanup.mjs'; +import { chromiumUnavailable, testChromiumExecutable } from '../test-support/hook-plugin-fixture.mjs'; +import { prepareHostPluginAssets } from './assets.mjs'; +import { createHeadlessPluginSandbox } from './chromium-sandbox.ts'; +import { createHostPluginRuntime } from './runtime.ts'; + +const require = createRequire(new URL('../../../desktop/package.json', import.meta.url)); +const JSZip = require('jszip'); +const holdMessage = 'HOST_PROFILE_IN_USE_BY_DESKTOP: fixture profile in use'; +const held = { ok: false, errorCode: 'PRECONDITION_FAILED', message: holdMessage }; +const executablePath = testChromiumExecutable(); +const realPage = { skip: !executablePath && chromiumUnavailable, timeout: 20_000 }; + +// §3.2 integration. Use the installed-plugin Host assembly, the production +// gateway and genuine approval files. The earlier gateway-only tests cannot +// catch a changed owner/active target, restart, config route, or accepted +// upload. The first three cases substitute the browser API, no Chromium process. +// The last five require a dedicated headless Chromium and a temporary profile. +const logic = ` + cindy.onHostMessage(async message => { + if (message.type === 'event') { + const events = JSON.parse(localStorage.getItem('events') ?? '[]'); + events.push(message.data?.sessionId); + localStorage.setItem('events', JSON.stringify(events)); + if (message.hookId) localStorage.setItem('hookId', message.hookId); + return; + } + if (message.type !== 'tool-call') return; + let result; + if (message.args.request) result = await cindy.send({ ...message.args.request, callId: message.callId }); + else if (message.args.node) result = await cindy.node.request({ + method: message.args.node === 'pending' ? 'pending' : 'echo', + params: message.args.marker, + }); + else result = true; + if (message.args.loseReceipt) { + localStorage.setItem('staged', JSON.stringify(result)); + return; + } + await cindy.send({ type: 'tool-result', callId: message.callId, ok: true, result }); + }); +`; +const nodeWorker = String.raw` + require('node:readline').createInterface({ input: process.stdin }).on('line', line => { + const request = JSON.parse(line); + if (request.method === 'pending') { + require('node:fs').writeFileSync(request.params, 'started'); + return; + } + if (request.id !== undefined) process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: process.pid }) + '\n'); + }); +`; + +async function fixture(t, { executable, resident = true, node = false } = {}) { + const cleanup = lifoCleanup(t); + const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-plugin-pause-')); + cleanup.after(() => fs.rm(profile, { recursive: true, force: true })); + configureHostOwner({ userDataDir: profile, ownerId: null }); + commitVolatileAppSession('local', null, true); + configureAppDataDir(path.join(profile, 'app-data')); + configureGhostSnapshotProcess(createSnapshotProcess); + const ownerId = LOCAL_DATA_OWNER_ID; + const root = (...parts) => ownerScopedPath(profile, ownerId, ...parts); + const manager = createHostGhostManager({ userDataDir: profile, ownerId }); + cleanup.after(() => manager.disposeNotificationIndex()); + const zip = new JSZip(); + zip.file('ghost.json', JSON.stringify({ + schemaVersion: 3, minCindyVersion: '0.1.61', id: 'pause-fixture', + name: 'Pause fixture', kind: 'chip', version: '1.0.0', entry: 'main.js', + settingsHtml: 'panel.html', ...(resident ? { launch: 'resident' } : {}), + subscribe: { hooks: ['will-tool-call', 'did-tool-result'], topics: ['session'] }, + tools: [{ name: 'echo', description: 'synthetic tool', parameters: { type: 'object' } }], + network: { hosts: ['example.invalid'] }, library: true, notify: true, + ...(node ? { node: { entry: 'worker.cjs', protocol: 'json-rpc-stdio', lifecycle: 'resident' } } : {}), + })); + zip.file('main.js', logic); + zip.file('panel.html', 'Isolation fixture'); + if (node) zip.file('worker.cjs', nodeWorker); + const archive = path.join(profile, 'pause.cindy'); + await fs.writeFile(archive, await zip.generateAsync({ type: 'nodebuffer' })); + const installed = await manager.install(archive, { namespace: null, uiCapabilityApproved: true }); + assert.ok(installed.ghost, JSON.stringify(installed)); + const id = installedGhostStoragePart(installed.ghost); + const assets = executable ? { ...await prepareHostPluginAssets(), executablePath: executable } + : { bridgeSource: '', executablePath: null, nodeWorker: '', libraryWorker: '', close: async () => {} }; + cleanup.after(() => assets.close()); + const pushes = []; + const warnings = []; + const terminalCleanup = []; + const log = { trace() {}, debug() {}, info() {}, warn(message) { warnings.push(message); }, error() {}, fatal() {}, child() { return this; } }; + const runtime = await createHostPluginRuntime({ + profileDir: profile, ownerId, manager, assets, log, + credentials: { read: () => null, write() {}, remove() {} }, + getLoginEmail: () => null, getSession: () => undefined, requestFileConfirmation: async () => false, + modelRouteSources: () => ({ localViews: async () => [], localAgents: () => [] }), + appContext: () => ({ ok: true, context: { region: 'global', locale: 'en' } }), + onPluginStopped: id => terminalCleanup.push(id), + publish: (channel, payload) => pushes.push({ channel, payload }), + }); + cleanup.after(() => runtime.close()); + const gateway = runtime.taskPlugins.getGhostSubscriptionGateway(); + const call = args => runtime.callTool({ ghostId: id, tool: 'echo', args: args ?? {}, timeoutMs: 2_500 }); + const control = () => runtime.taskPlugins.screenGhostControlPoint('will-tool-call', + { engine: 'pi', phase: 'call', sessionId: 'task', toolName: 'read', toolCallId: 'tool', input: {} }, + { pluginId: id, onFailure: 'block' }); + return { root, manager, runtime, id, gateway, call, control, pushes, warnings, terminalCleanup, + hold: () => runtime.pauseForDesktop(holdMessage) }; +} + +function installBrowserSubstitute(t, { beforePage, beforeToolAnswer } = {}) { + const pages = []; + let contextCount = 0; + let closeObserver; + const received = []; + t.mock.method(chromium, 'launch', async () => { + const browser = { + once() {}, isConnected: () => true, async close() {}, + async newContext() { + contextCount++; + return { + once() {}, on() {}, route() {}, routeWebSocket() {}, async close() {}, browser: () => browser, + async newPage() { + await beforePage?.(); + let closed = false; + let binding, loadUrl; + const frame = { url: () => loadUrl }; + const page = { + on() {}, isClosed: () => closed, mainFrame: () => frame, route() {}, + async close() { closed = true; closeObserver?.(); }, + exposeBinding(_name, handler) { binding = handler; }, + async goto(url) { loadUrl = url; }, + async addScriptTag() {}, + async evaluateHandle() { + return { async evaluate(_deliver, envelope) { + received.push(envelope); + if (envelope.type === 'tool-call') { + const request = envelope.args.request; + const result = request ? await page.send('send', { ...request, callId: envelope.callId }) : true; + await beforeToolAnswer?.(result); + await page.send('send', { type: 'tool-result', callId: envelope.callId, ok: true, result }); + } + return true; + } }; + }, + send(kind, payload) { return binding({ page, frame }, kind, payload); }, + }; + pages.push(page); + return page; + }, + }; + }, + }; + return browser; + }); + return { pages, received, contexts: () => contextCount, observeClose: observer => { closeObserver = observer; } }; +} + +async function filesIn(root) { + const paths = await fs.readdir(root, { recursive: true, withFileTypes: true }); + return Object.fromEntries(await Promise.all(paths.filter(item => item.isFile()).map(async item => { + const file = path.join(item.parentPath, item.name); + return [path.relative(root, file), await fs.readFile(file, 'base64')]; + }))); +} + +test('Host pauses an approved install without changing receipt or KV, and restarts on demand in the same partition', async t => { + const browser = installBrowserSubstitute(t); + const f = await fixture(t, { resident: false }); + const kvFile = f.root('ghost-kv', f.id + '.json'); + await fs.mkdir(path.dirname(kvFile), { recursive: true }); + await fs.writeFile(kvFile, '{"saved":"before"}'); + const receipts = await filesIn(f.root('ghost-install-state')); + assert.ok(Object.keys(receipts).length > 0); + await f.runtime.reconcile(); + assert.equal(browser.pages.length, 0); + assert.deepEqual(await f.call(), { ok: true, result: true }); + + f.hold(); + assert.equal(browser.pages[0].isClosed(), true); + assert.deepEqual(await f.call(), held); + assert.equal(f.runtime.getGhost(f.id).enabled, true); + await assert.rejects(f.runtime.openPage(f.id, 'panel.html'), { code: 'PRECONDITION_FAILED' }); + await f.runtime.resumeAfterDesktop(); + assert.equal(browser.pages.length, 1); + assert.deepEqual(await f.call(), { ok: true, result: true }); + assert.equal(browser.contexts(), 1); + assert.deepEqual(await filesIn(f.root('ghost-install-state')), receipts); + assert.equal(await fs.readFile(kvFile, 'utf8'), '{"saved":"before"}'); +}); + +test('Host drops held plugin notifications and observer events, then keeps the native block policy', async t => { + const browser = installBrowserSubstitute(t); + const f = await fixture(t); + await f.runtime.reconcile(); + assert.equal((await f.call()).ok, true); + const page = browser.pages[0]; + assert.equal((await page.send('send', { type: 'notify', text: 'before the hold' })).ok, true); + assert.ok(f.pushes.some(push => push.channel === 'ghosts:notify')); + f.pushes.length = 0; + const installed = f.runtime.getGhost(f.id); + browser.observeClose(() => f.gateway.publishIndexed([installed], 'session', 'did-session-switched', { sessionId: 'closing' })); + for (let round = 0; round < 3; round++) { + const pending = f.control(); + assert.equal(browser.received.at(-1)?.name, 'will-tool-call'); + f.hold(); + if (round === 0) { + await assert.rejects(page.send('send', { type: 'notify', text: 'while held' }), { code: 'PRECONDITION_FAILED' }); + await assert.rejects(page.send('send', { type: 'host-tool-request', server: 'cindy_helper', tool: 'terminal_start' }), + { code: 'PRECONDITION_FAILED' }); + assert.deepEqual(f.pushes, [], 'stopping a resident must not publish a plugin state notification'); + assert.deepEqual(f.terminalCleanup, [], 'pause preserves existing plugin terminals'); + } + assert.equal((await pending).action, 'block'); + for (let turn = 0; turn < 4; turn++) assert.equal((await f.control()).action, 'block'); + f.gateway.publishIndexed([installed], 'session', 'did-session-switched', { sessionId: 'held' }); + await f.runtime.resumeAfterDesktop(); + assert.equal((await f.call()).ok, true); + } + browser.observeClose(undefined); + f.gateway.publishIndexed([installed], 'session', 'did-session-switched', { sessionId: 'resumed' }); + assert.deepEqual(browser.received.filter(event => event.topic === 'session').map(event => event.data.sessionId), ['resumed']); + assert.ok(f.pushes.every(push => push.channel !== 'ghosts:notify')); + assert.equal(f.warnings.includes('ghost control point failed'), false); +}); + +function interruptibleUpload(t) { + let admitUpload, finishUpload; + let writes = 0; + const admitted = new Promise(resolve => { admitUpload = resolve; }); + const finished = new Promise(resolve => { finishUpload = resolve; }); + const fakeFetch = async (_url, init) => { + writes++; + admitUpload(); + return new Promise((_resolve, reject) => { + init.signal.addEventListener('abort', () => { finishUpload(); reject(new Error('simulated disconnect after acceptance')); }, { once: true }); + }); + }; + t.mock.method(hostOutbound, 'guardedOutboundFetch', fakeFetch); + t.mock.method(hostOutbound, 'outboundFetch', fakeFetch); + return { admitted, finished, count: () => writes }; +} + +const externalUpload = { request: { type: 'fetch-request', url: 'https://example.invalid/upload', method: 'POST', body: 'synthetic' } }; + +// Same monitor as main.ts. Supply scan results and the completion of the input +// rebuild, while the installed plugin, its cleanup and both gates stay real. +function profileMonitor(t, f) { + let desktops = []; + let inputHeld = false; + let rebuilt = 0; + let refreshed = 0; + const attempts = []; + const plugins = { + pauseForDesktop: f.runtime.pauseForDesktop, + pluginPauseFailure: f.runtime.pluginPauseFailure, + resumeAfterDesktop() { + assert.equal(inputHeld, false); + const attempt = f.runtime.resumeAfterDesktop(); + attempts.push(attempt); + return attempt; + }, + }; + const monitor = createHostProfileCoexistenceMonitor({ + scan: async () => desktops, registryDir: f.root('fixture-registry'), message: holdMessage, + isCurrent: () => true, setState() {}, log: { warn() {} }, + getPlugins: () => plugins, refreshPlugins: async () => { refreshed++; }, + onInputReleased: () => { rebuilt++; }, + input: { + isHeldForDesktop: () => inputHeld, + holdForDesktop() { inputHeld = true; }, + async releaseDesktopHold() { inputHeld = false; return true; }, + }, + }); + t.after(() => monitor.stop()); + return { + async scan(pids) { + desktops = pids; + const count = attempts.length; + await monitor.scanNow(); + return await Promise.all(attempts.slice(count)); + }, + rebuilt: () => rebuilt, refreshed: () => refreshed, + }; +} + +test('Host retries a failed pause cleanup and publishes one current list and state', async t => { + installBrowserSubstitute(t); + const f = await fixture(t, { resident: false }); + await f.runtime.reconcile(); + await f.call(); + const dispose = f.runtime.library.disposeGhost.bind(f.runtime.library); + let calls = 0; + t.mock.method(f.runtime.library, 'disposeGhost', async id => { + if (++calls === 1) throw new Error('temporary fixture cleanup failure'); + await dispose(id); + }); + const monitor = profileMonitor(t, f); + await monitor.scan([42]); + assert.deepEqual(await f.call(), held); + f.pushes.length = 0; + assert.deepEqual(await monitor.scan([]), []); + assert.deepEqual(await monitor.scan([]), [true]); + assert.equal(calls, 2); + assert.deepEqual(await monitor.scan([]), []); + assert.equal(monitor.rebuilt(), 1); + assert.equal(monitor.refreshed(), 1); + const events = f.pushes.filter(event => ['ghosts:changed', 'ghosts:runtime-changed'].includes(event.channel)); + assert.deepEqual(events.map(event => event.channel), ['ghosts:changed', 'ghosts:runtime-changed']); + assert.equal(installedGhostStoragePart(events[0].payload.ghosts[0]), f.id); + assert.deepEqual(events[1].payload, f.runtime.runtimeStates()); + assert.deepEqual(await f.call(), { ok: true, result: true }); +}); + +test('Host resumes on a later clear scan when the owner was briefly unavailable', async t => { + installBrowserSubstitute(t); + const f = await fixture(t, { resident: false }); + await f.runtime.reconcile(); + const monitor = profileMonitor(t, f); + await monitor.scan([42]); + await monitor.scan([]); + const release = beginAppSessionBoundary(); + try { + assert.deepEqual(await monitor.scan([]), [false]); + assert.deepEqual(f.runtime.pluginPauseFailure(), held); + } finally { + release(); + } + assert.deepEqual(await monitor.scan([]), [true]); + assert.equal(monitor.rebuilt(), 1); + assert.equal(monitor.refreshed(), 1); + assert.deepEqual(await f.call(), { ok: true, result: true }); +}); + +test('a completed external write is still uncertain when pause interrupts its tool result', async t => { + let observed; + const replied = new Promise(resolve => { observed = resolve; }); + installBrowserSubstitute(t, { beforeToolAnswer: async result => { + observed(result); + await new Promise(() => {}); // the plugin did not deliver its tool result + } }); + const send = t.mock.fn(async () => new Response('accepted')); + t.mock.method(hostOutbound, 'guardedOutboundFetch', send); + t.mock.method(hostOutbound, 'outboundFetch', send); + const f = await fixture(t); + const pending = f.call(externalUpload); + assert.equal((await replied).ok, true); + f.hold(); + assert.equal((await pending).errorCode, 'PLUGIN_DELIVERY_UNKNOWN'); + assert.equal(send.mock.callCount(), 1); +}); + +test('a plugin request keeps its unavailable-page error when the owner changes outside a hold', async t => { + const f = await fixture(t, { resident: false }); + let release; + t.mock.method(hostOutbound, 'outboundFetch', async () => { + release = beginAppSessionBoundary(); + return new Response('outgoing owner'); + }); + try { + const result = await f.runtime.network.handleFetchRequest(f.id, { url: 'https://example.invalid/read' }); + assert.equal(result.ok, false); + assert.match(result.message, /PLUGIN_PAGE_UNAVAILABLE/); + } finally { + release?.(); + } +}); + +test('stopping a still-loading logic page rejects its startup waiter', async t => { + let entered; + const pageStarting = new Promise(resolve => { entered = resolve; }); + installBrowserSubstitute(t, { beforePage: async () => { + entered(); + await new Promise(() => {}); + } }); + const f = await fixture(t, { resident: false }); + const sandbox = createHeadlessPluginSandbox({ + ownerKey: () => 'fixture', isCurrent: () => true, bridgeSource: '', + send: async () => ({ ok: true }), pageHandler: () => () => new Response(), + }); + t.after(() => sandbox.close()); + const runtime = new GhostRuntime({ adapter: sandbox.adapter, onStateChanged() {} }); + const loading = runtime.spawn(f.runtime.getGhost(f.id)); + await pageStarting; + runtime.stop(f.id); + assert.equal((await loading).ok, false); + assert.equal(runtime.stateOf(f.id), 'off'); +}); + +test('pause reports an in-flight Node tool as uncertain without an external fetch', realPage, async t => { + const f = await fixture(t, { executable: executablePath, node: true }); + await f.runtime.reconcile(); + const marker = f.root('node-tool-started'); + const pending = f.call({ node: 'pending', marker }); + for (;;) { + t.signal.throwIfAborted(); + try { await fs.access(marker); break; } + catch { await new Promise(resolve => setTimeout(resolve, 10)); } + } + f.hold(); + assert.equal((await pending).errorCode, 'PLUGIN_DELIVERY_UNKNOWN'); +}); + +test('Host reports an interrupted external write as uncertain and never resends it', { timeout: 5_000 }, async t => { + installBrowserSubstitute(t); + const transport = interruptibleUpload(t); + const f = await fixture(t); + await f.runtime.reconcile(); + const delivery = f.call(externalUpload); + await transport.admitted; + f.hold(); + await transport.finished; + assert.match((await delivery).errorCode ?? '', /^PLUGIN_DELIVERY_UNKNOWN$/); + await f.runtime.resumeAfterDesktop(); + assert.equal((await f.call()).ok, true); + assert.equal(transport.count(), 1); +}); + +test('resident logic and Node resume in the old partition without a replacement approval', realPage, async t => { + const f = await fixture(t, { executable: executablePath, node: true }); + await f.runtime.reconcile(); + assert.equal((await f.call()).ok, true); + const panel = await f.runtime.openPage(f.id, 'panel.html'); + await panel.evaluate(() => { localStorage.setItem('saved', 'before'); document.cookie = 'fixture=old; path=/'; }); + const before = await f.call({ node: true }); + assert.equal(before.ok, true, JSON.stringify(before)); + const receipts = await filesIn(f.root('ghost-install-state')); + f.hold(); + assert.equal(f.runtime.node.stateOf(f.id), 'off'); + assert.deepEqual(await f.call({ node: true }), held); + await f.runtime.resumeAfterDesktop(); + const after = await f.call({ node: true }); + assert.equal(after.ok, true, JSON.stringify(after)); + assert.equal(before.result.ok, true, JSON.stringify(before.result)); + assert.equal(after.result.ok, true, JSON.stringify(after.result)); + assert.notEqual(before.result.result, after.result.result); + assert.deepEqual(await panel.evaluate(() => [localStorage.getItem('saved'), document.cookie]), ['before', 'fixture=old']); + assert.deepEqual(await filesIn(f.root('ghost-install-state')), receipts); +}); + +test('a real in-flight hook blocks on three intentional stops and paused native targets stay visible', realPage, async t => { + const f = await fixture(t, { executable: executablePath }); + await f.runtime.reconcile(); + assert.equal((await f.call()).ok, true); + const panel = await f.runtime.openPage(f.id, 'panel.html'); + for (let round = 0; round < 3; round++) { + const before = await panel.evaluate(() => localStorage.getItem('hookId')); + const pending = f.control(); + await panel.waitForFunction(old => localStorage.getItem('hookId') !== old, before, { timeout: 900 }); + f.hold(); + assert.equal((await pending).action, 'block'); + for (let call = 0; call < 4; call++) assert.equal((await f.control()).action, 'block'); + await f.runtime.resumeAfterDesktop(); + assert.equal((await f.call()).ok, true); + } + assert.ok(!f.warnings.includes('ghost control point failed')); + assert.ok(!f.warnings.includes('ghost control points fused; failures follow user policy')); +}); + +test('an open settings page cannot wake a plugin or change KV during the hold', realPage, async t => { + const f = await fixture(t, { executable: executablePath }); + await f.runtime.reconcile(); + const panel = await f.runtime.openPage(f.id, 'panel.html'); + const write = value => panel.evaluate(async body => { + const response = await fetch('/kv', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); + return { status: response.status, json: response.status === 204 ? null : await response.json() }; + }, value); + assert.equal((await write({ value: 'before' })).status, 204); + f.hold(); + assert.deepEqual(await write({ value: 'during' }), { status: 409, json: held }); + const wake = await panel.evaluate(async () => { const response = await fetch('/wake'); return { status: response.status, json: await response.json() }; }); + assert.deepEqual(wake, { status: 409, json: held }); + await f.runtime.resumeAfterDesktop(); + assert.deepEqual(await panel.evaluate(async () => (await fetch('/kv')).json()), { value: 'before' }); +}); + +test('real observer delivery resumes on the next event without replaying a held event', realPage, async t => { + const f = await fixture(t, { executable: executablePath, resident: false }); + const panel = await f.runtime.openPage(f.id, 'panel.html'); + const installed = f.runtime.getGhost(f.id); + await f.runtime.reconcile(); + // Queue before the first logic page is ready, then enter the hold in the + // same turn. The next event should flush this one, but no held event. + f.gateway.publishIndexed([installed], 'session', 'did-session-switched', { sessionId: 'before' }); + f.hold(); + f.gateway.publishIndexed([installed], 'session', 'did-session-switched', { sessionId: 'held' }); + assert.equal(await f.gateway.preparePublish('session'), null); + await f.runtime.resumeAfterDesktop(); + assert.equal(await panel.evaluate(() => localStorage.getItem('events')), null); + f.gateway.publishIndexed([installed], 'session', 'did-session-switched', { sessionId: 'resumed' }); + await panel.waitForFunction(() => JSON.parse(localStorage.getItem('events') ?? '[]').includes('resumed')); + assert.deepEqual(await panel.evaluate(() => JSON.parse(localStorage.getItem('events'))), ['before', 'resumed']); +}); + +test('an interrupted external upload is not resent and committed staging remains discoverable', realPage, async t => { + const transport = interruptibleUpload(t); + const f = await fixture(t, { executable: executablePath }); + await f.runtime.reconcile(); + const panel = await f.runtime.openPage(f.id, 'panel.html'); + const staging = (op, extra, loseReceipt = false) => f.call({ request: { type: 'library-request', op: 'staging.' + op, ...extra }, loseReceipt }); + const data = Buffer.from('fixture'); + const begin = taskId => staging('begin', { taskId, sourceRevision: 'v1', totalBytes: data.length, + sha256: createHash('sha256').update(data).digest('hex'), mime: 'image/png', + recovery: { filename: 'fixture.png' } }); + const committed = (await begin('committed')).result; + const unfinished = (await begin('unfinished')).result; + assert.equal(committed.ok, true, JSON.stringify(committed)); + assert.equal(unfinished.ok, true, JSON.stringify(unfinished)); + assert.equal((await staging('chunk', { stagingId: committed.stagingId, seq: 1, content: data.toString('base64'), encoding: 'base64' })).result.ok, true); + const lost = staging('commit', { stagingId: committed.stagingId }, true); + await panel.waitForFunction(() => Boolean(localStorage.getItem('staged'))); + assert.equal(await panel.evaluate(() => JSON.parse(localStorage.getItem('staged')).ok), true); + + const upload = f.call(externalUpload); + await transport.admitted; + f.hold(); + await transport.finished; + const interrupted = await upload; + assert.equal(interrupted.ok, false, JSON.stringify(interrupted)); + assert.equal(interrupted.errorCode, 'PLUGIN_DELIVERY_UNKNOWN'); + assert.equal((await lost).errorCode, 'PLUGIN_DELIVERY_UNKNOWN'); + await f.runtime.resumeAfterDesktop(); + const listing = (await staging('list', {})).result; + assert.equal(listing.ok, true, JSON.stringify(listing)); + assert.deepEqual(listing.items.map(item => item.stagingId), [committed.stagingId]); + assert.equal((await staging('read', { stagingId: committed.stagingId })).result.ok, true); + assert.equal((await staging('chunk', { stagingId: unfinished.stagingId, seq: 1, content: data.toString('base64'), encoding: 'base64' })).result.ok, false); + assert.equal((await staging('commit', { stagingId: unfinished.stagingId })).result.ok, false); + assert.equal(transport.count(), 1); +}); diff --git a/apps/host/src/plugins/runtime.ts b/apps/host/src/plugins/runtime.ts index 59c9f35bbc2..fe254b8414f 100644 --- a/apps/host/src/plugins/runtime.ts +++ b/apps/host/src/plugins/runtime.ts @@ -1,4 +1,5 @@ import { createRequire } from 'node:module'; +import { setMaxListeners } from 'node:events'; import { GhostManager } from '../../../desktop/src/main/cindy-brain/GhostManager.js'; import { GhostBrowserExtensionSlot } from '../../../desktop/src/main/cindy-brain/browserExtensionSlot.js'; import { hostRuntimeLayout } from '../runtime-layout.mjs'; @@ -38,8 +39,9 @@ import { GhostHandoffStore } from '../../../desktop/src/main/cindy-brain/handoff import { spawnResidentGhost } from '../../../desktop/src/main/cindy-brain/residentGhost.js'; import { setPluginEnabled } from '../../../desktop/src/main/cindy-brain/pluginEnableService.js'; import { ghostInstallApprovalToken, type InstalledGhost, type GhostAppContextResult } from '../../../desktop/src/shared/ghost.js'; +import { throwIpcError } from '../../../desktop/src/main/utils/ipcValidate.js'; import { installedGhostStoragePart, findInstalledGhostByInstanceId } from '../../../desktop/src/shared/pluginIdentity.js'; -import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending, type ActiveAppSession } from '../../../desktop/src/main/appSessionState.js'; +import { activeOwnerScopeKey, getActiveAppSession, getActiveDataOwnerPushStamp, isAppSessionBoundaryPending, type ActiveAppSession } from '../../../desktop/src/main/appSessionState.js'; import { availableGhostsIn, findGhostForInstanceIdIn, @@ -49,7 +51,7 @@ import { } from '../../../desktop/src/main/cindy-brain/ghostAvailability.js'; import { createManagedSkills } from '../../../desktop/src/main/maker-host/managedSkillsCore.js'; import { ownerScopedPath } from '../../../desktop/src/main/dataOwnerPath.js'; -import { createLogger } from '../../../desktop/src/main/logger.js'; +import { createLogger, type Logger } from '../../../desktop/src/main/logger.js'; import { hostBlobStore, hostMediaIngest } from '../media-store.js'; import * as ledger from '../../../desktop/src/main/cindy-media/ledger.js'; import { createHeadlessPluginSandbox } from './chromium-sandbox.js'; @@ -64,7 +66,13 @@ import { hostOutbound } from '../outbound.mjs'; import { prepareHostPluginAssets } from './assets.mjs'; import type { GhostNodeRuntimeBrokerDeps } from '../../../desktop/src/main/cindy-brain/nodeRuntimeBroker.js'; +import { createRuntimePluginHost, type RuntimePluginHostPorts } from '../../../desktop/src/main/cindy-brain/runtimePluginHostCore.js'; +import { summarizeLegacyPluginApprovals, type LegacyPluginApprovals } from './legacy-approvals.js'; + interface PluginRuntimeOptions { + modelRouteSources: RuntimePluginHostPorts['modelRouteSources']; + /** Coexistence plan A: whether a Cindy desktop app running on its own uses this profile (plugin OAuth). */ + isProfileHeld?(): boolean; profileDir: string; ownerId: string; manager: GhostManager; @@ -79,6 +87,7 @@ interface PluginRuntimeOptions { publish(channel: string, payload: unknown): void; hostToolRequest?: GhostNodeRuntimeBrokerDeps['hostToolRequest']; onPluginStopped?(id: string): void; + log?: Logger; /** Built/release paths only, never plugin-provided. */ assets?: Awaited>; } @@ -89,7 +98,7 @@ interface PluginRuntimeOptions { export async function createHostPluginRuntime(options: PluginRuntimeOptions) { const assets = options.assets ?? await prepareHostPluginAssets(); const owner = activeOwnerScopeKey(); - const log = createLogger('host-plugins'); + const log = options.log ?? createLogger('host-plugins'); const root = (...parts: string[]) => ownerScopedPath(options.profileDir, options.ownerId, ...parts); const mutation = new GhostMutationCoordinator(); const handoff = new GhostHandoffStore({ root: () => root('ghost-handoff') }); @@ -97,12 +106,37 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { const pending = new Set>(); const known = new Map(); const suspended = new Set(); + const newDeliveryController = () => { + const controller = new AbortController(); + setMaxListeners(0, controller.signal); // one listener per pending hook + return controller; + }; + let delivery = newDeliveryController(); + type CleanupJob = { id: string; kind: 'node' | 'library'; run(): Promise }; + let desktopPause: { message: string; cleanup: Promise; resuming: boolean } | null = null; + const unknownDelivery = { + ok: false as const, errorCode: 'PLUGIN_DELIVERY_UNKNOWN', + message: 'This tool call was running when the plugin paused and may have taken effect. Check the outcome before retrying.', + }; let closed = false; let closing: Promise | undefined; let reconciliation: Promise = Promise.resolve(); + let legacyApprovals: LegacyPluginApprovals | null = null; let enableChanges: Promise = Promise.resolve(); const current = () => !closed && !isAppSessionBoundaryPending() && activeOwnerScopeKey() === owner; const assertCurrent = () => { if (!current()) throw new Error('PLUGIN_OWNER_CHANGED'); }; + const profileHoldMessage = () => desktopPause?.message ?? null; + const pluginPauseFailure = () => desktopPause + ? { ok: false as const, errorCode: 'PRECONDITION_FAILED' as const, message: desktopPause.message } + : null; + const assertPluginAvailable = () => { + assertCurrent(); + const held = profileHoldMessage(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + }; + const publish = (channel: string, payload: unknown) => { + if (!desktopPause) options.publish(channel, payload); + }; const findGhost = (id: string) => current() ? options.manager.findInstalledInstance(id) ?? findInstalledGhostByInstanceId(options.manager.list(), id) ?? null : null; const getGhost = (id: string) => { @@ -114,7 +148,12 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { const isCurrent = (ghost: InstalledGhost) => current() && ghost.enabled && revision(getGhost(installedGhostStoragePart(ghost))) === revision(ghost); const guard = (id: string) => { const ghost = getGhost(id); - return () => { if (!ghost || !isCurrent(ghost)) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); }; + const signal = delivery.signal; + return () => { + const held = profileHoldMessage(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + if (signal.aborted || !ghost || !isCurrent(ghost)) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + }; }; const track = (job: Promise) => { pending.add(job); @@ -157,10 +196,10 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { }); const unavailable = () => { throw new Error('PLUGIN_ACCOUNT_SERVICE_UNAVAILABLE'); }; const authorization = createHostPluginAuthorization({ owner, root, current, assertCurrent, - getGhost, list: () => options.manager.list(), secret, kv, identity, + getGhost, list: () => options.manager.list(), secret, kv, identity, isProfileHeld: options.isProfileHeld, account: options.account ?? { hasLogin: () => false, post: unavailable, endpoint: unavailable, openExternal: unavailable }, - publish: options.publish, signal: stopSignal.signal }); + publish, signal: stopSignal.signal }); const require = createRequire(import.meta.url); const library = new GhostLibrarySlot({ getGhost, captureOwnerScope: () => current() ? owner : null, @@ -186,7 +225,7 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { if (activeOwnerScopeKey() !== owner) throw new Error('PLUGIN_OWNER_CHANGED'); await upsertGhostCard(row); }, - broadcast: payload => { if (current()) options.publish('ghosts:card-updated', payload); }, log, + broadcast: payload => { if (current()) publish('ghosts:card-updated', payload); }, log, }); const fsSlot = new GhostFsSlot({ getGhost, dataRootDir: () => root('ghost-fs'), ownerKey: () => owner, resolvePickedDirectory: getGhostPickedDirectory, @@ -255,8 +294,8 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { const browserExtensions = new GhostBrowserExtensionSlot({ getGhost, policyDir: () => root('browser-extension'), ownerScopeKey: () => owner, isVerifiedOfficial: ghost => !hostRuntimeLayout().packaged || identity.isVerifiedPublicMarket(installedGhostStoragePart(ghost)), - sendToGhost: async (id, payload) => { assertCurrent(); return sandbox.deliver(id, payload, { failOnUncertain: true }); }, - wake: async id => { const ghost = getGhost(id); return Boolean(ghost?.enabled && (await runtime.spawn(ghost)).ok); }, + sendToGhost: async (id, payload) => { assertPluginAvailable(); return sandbox.deliver(id, payload, { failOnUncertain: true }); }, + wake: async id => { assertPluginAvailable(); const ghost = getGhost(id); return Boolean(ghost?.enabled && (await runtime.spawn(ghost)).ok); }, // No trusted native confirmation surface is attached to Node Host yet. A // conflicting native registration is retained; never approve a takeover. confirmNativeTakeover: async () => false, @@ -264,10 +303,20 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { }); const ownerScope = { capture: () => owner, isCurrent: (value: unknown) => value === owner && current(), isStable: (value: unknown) => value === owner && current() }; const disposeRuntimeHostServices = (id: string) => { - network.disposeGhost(id); fsSlot.disposePlugin(id); options.onPluginStopped?.(id); + network.disposeGhost(id); fsSlot.disposePlugin(id); + // A profile hold stops plugin runtimes. An existing plugin terminal is + // outside this boundary and keeps its original lifetime. + if (!desktopPause || closed) options.onPluginStopped?.(id); }; - const node = createHostNodeRuntimeBroker(assets.nodeWorker!, { getGhost, ownerScope, - hostToolRequest: options.hostToolRequest, onStopped: disposeRuntimeHostServices, + const hostToolRequest = options.hostToolRequest; + const requestHostTool: PluginRuntimeOptions['hostToolRequest'] = hostToolRequest && ((id, payload, isPageCurrent) => { + const refusal = pluginPauseFailure(); + if (refusal) return Promise.resolve(refusal); + const signal = delivery.signal; + return hostToolRequest(id, payload, () => !signal.aborted && isPageCurrent()); + }); + const node = createHostNodeRuntimeBroker(assets.nodeWorker!, { getGhost, ownerScope, startBlockedReason: profileHoldMessage, + hostToolRequest: requestHostTool, onStopped: disposeRuntimeHostServices, readSecret: secret.readGhostSecret, secretSaved: secret.ghostSecretSaved, resolveOauthSecret: async (id, key, accountId) => { const decl = getGhost(id)?.manifest.network?.secrets?.find(item => item.key === key && item.source === 'oauth')?.oauth; @@ -276,15 +325,17 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { }, getCallSignal: (id, callId) => dispatcher.getPendingCallSignal(id, callId), getCallSessionId: (id, callId) => dispatcher.getPendingCallSessionId(id, callId), - authenticatedFetch: (id, request, authorization, check, signal) => network.handleAuthenticatedNodeFetch(id, request, authorization, check, signal), - networkRequest: (id, request) => request.op === 'fetch' ? network.handleFetchRequest(id, request) : network.handleNetworkRequest(id, request), + authenticatedFetch: async (id, request, authorization, check, signal) => + pluginPauseFailure() ?? network.handleAuthenticatedNodeFetch(id, request, authorization, check, signal), + networkRequest: async (id, request) => pluginPauseFailure() ?? (request.op === 'fetch' + ? network.handleFetchRequest(id, request) : network.handleNetworkRequest(id, request)), sendToGhost: (id, payload) => { void sandbox.deliver(id, payload); }, log, }); const download = new PluginDownloadSlot({ getGhost, root: id => root('plugin-downloads', id), scope: () => owner, send: (id, event) => { void sandbox.deliver(id, event); }, download: createDownloader(), guardedFetch: hostOutbound.guardedOutboundFetch }); - const notify = new GhostNotifySlot({ getGhost, broadcast: payload => options.publish('ghosts:notify', payload), log }); + const notify = new GhostNotifySlot({ getGhost, broadcast: payload => publish('ghosts:notify', payload), log }); const pipe = createGhostExecutionPipe({ dispatcher: () => dispatcher, - hostTools: options.hostToolRequest, + hostTools: requestHostTool, fetch: (id, payload) => network.handleFetchRequest(id, payload), files: (id, payload, check) => fsSlot.handleFsRequest(id, payload, check), network: (id, payload) => network.handleNetworkRequest(id, payload), library: (id, payload) => library.handleLibraryRequest(id, payload), @@ -293,26 +344,35 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { warn: (message, details) => log.warn(message, details), }); const sandbox = createHeadlessPluginSandbox({ ...assets, executablePath: assets.executablePath ?? undefined, ownerKey: () => owner, - isCurrent: ghost => isCurrent(ghost), + isCurrent: ghost => isCurrent(ghost), profileHoldMessage, send(ghost, payload) { + const refusal = pluginPauseFailure(); + if (refusal) return Promise.resolve(refusal); + const signal = delivery.signal; const id = installedGhostStoragePart(ghost); - const result = pipe(id, payload, () => isCurrent(ghost)); + const result = pipe(id, payload, () => !signal.aborted && isCurrent(ghost)); if (result) return track(result); const request = payload as { type?: string; kind?: string } | null; if (request?.type === 'browser-extension-request') return track(browserExtensions.handleRequest(id, payload)); + if (request?.type === 'event-verdict') { + // The sandbox supplies the installation id. The shared gateway ignores stale or + // mismatched replies and returns no information about pending requests to the page. + taskPlugins.getGhostSubscriptionGateway().handleVerdict(id, payload); + return Promise.resolve({ ok: true }); + } if (request?.type === 'card-update') { cards.handleCardUpdate(id, payload); return Promise.resolve({ ok: true }); } if (request?.type === 'host-request' && request.kind === 'app-context') return Promise.resolve(options.appContext()); if (request?.type === 'notify') return Promise.resolve(notify.handleNotify(id, payload)); return Promise.reject(new Error('UNSUPPORTED_CAPABILITY: this Host service is not connected')); }, - pageHandler: (ghost, origin, pageCurrent) => createGhostPageHandler({ ghost, origin, isCurrent: pageCurrent, + pageHandler: (ghost, origin, pageCurrent) => createGhostPageHandler({ ghost, origin, isCurrent: () => !desktopPause && pageCurrent(), ghostKvStore: { read: id => { guard(id)(); return kv.read(id); }, write: (id, value) => { guard(id)(); kv.write(id, value); authorization.changes.emit(id, { source: 'kv' }); }, - captureTarget: id => revision(getGhost(id)), isTargetCurrent: (id, target) => current() && target === revision(getGhost(id)) }, - ghostWakeHandler: async id => { const item = getGhost(id); if (!item) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + captureTarget: id => revision(getGhost(id)), isTargetCurrent: (id, target) => !desktopPause && current() && target === revision(getGhost(id)) }, + ghostWakeHandler: async id => { assertPluginAvailable(); const item = getGhost(id); if (!item) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); const spawned = await runtime.spawn(item); return { state: spawned.ok ? spawned.state : runtime.stateOf(id) }; }, ghostAppContextProvider: options.appContext, ghostModelsHandler: input => handleGhostModelsRequest({ ...input, needs: () => getGhost(input.ghostId)?.manifest.models ?? null, - store: models, onChanged: () => options.publish('ghosts:changed', { ghosts: options.manager.list() }) }), + store: models, onChanged: () => publish('ghosts:changed', { ghosts: options.manager.list() }) }), ghostSecretsHandler: async input => { const item = getGhost(input.ghostId); if (!item) return { status: 404 }; const declared = item.manifest.network?.secrets ?? []; @@ -353,30 +413,82 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { }, log, }), }); - const runtime = new GhostRuntime({ adapter: sandbox.adapter, log, + const runtime = new GhostRuntime({ adapter: sandbox.adapter, log, startBlockedReason: profileHoldMessage, onStateChanged: (id, state) => { if (state !== 'running' && state !== 'starting') disposeRuntimeHostServices(id); - dispatcher?.onRuntimeState(id, state); options.publish('ghosts:runtime-changed', { states: runtime.listStates() }); + dispatcher?.onRuntimeState(id, state); publish('ghosts:runtime-changed', { states: runtime.listStates() }); } }); - const dispatcher = new GhostPipeDispatcher({ getGhost, runtimeStateOf: id => runtime.stateOf(id), + const withSuspension = (ghost: InstalledGhost) => + suspended.has(installedGhostStoragePart(ghost)) ? { ...ghost, enabled: false } : ghost; + const stampCurrent: RuntimePluginHostPorts['isGhostOwnerStampCurrent'] = stamp => { + if (!current() || !stamp) return false; + const active = getActiveDataOwnerPushStamp(); + return stamp.dataOwnerId === active.dataOwnerId && stamp.ownerGeneration === active.ownerGeneration; + }; + const taskPlugins = createRuntimePluginHost({ + getGhostRuntime: () => runtime, + availableGhosts: () => current() ? identityLookup.availableGhosts().map(withSuspension) : [], + listGhostNotificationCandidates: () => listAvailableGhostsFrom(() => listInstalledGhostsForOwner(listingScope, + () => ({ listAsync: () => options.manager.listNotificationCandidatesAsync() }))).then(items => items.map(withSuspension)), + findGhostNotificationTarget: id => { + if (!current()) return null; + const ghost = options.manager.findInstalledInstance(id); + return ghost && identityLookup.isGhostAvailableForActiveSession(id) ? withSuspension(ghost) : null; + }, + findGhostForInstanceId: (id, namespace) => { + const ghost = current() ? findGhostForInstanceIdIn(identityLookup, id, namespace) : null; + return ghost ? withSuspension(ghost) : null; + }, + sendToGhostLogic: sandbox.acceptGatewayDelivery, + // Discovery and the owner/approval checks still see the same exact plugin + // during a hold. Only the gateway's delivery is suspended. + hookDeliveryPauseSignal: () => delivery.signal, + ghostOwnerScope: { ...listingScope, onInvalidated: id => runtime.stop(id) }, + getGhostOwnerPushStamp: getActiveDataOwnerPushStamp, + isGhostOwnerStampCurrent: stampCurrent, + broadcastGhostWindowPush: (channel, payload, stamp) => { + if (current() && (!stamp || stampCurrent(stamp))) publish(channel, payload); + }, + modelRouteSources: options.modelRouteSources, + log, + }); + class HostGhostPipeDispatcher extends GhostPipeDispatcher { + override async callGhostTool(request: Parameters[0]) { + const refusal = pluginPauseFailure(); + if (refusal) return refusal; + const signal = delivery.signal; + const result = await super.callGhostTool(request); + // A stopped tool may already have made changes the host cannot observe. + // Calls refused at admission and tools that returned a result keep theirs. + return !result.ok && signal.aborted && current() ? unknownDelivery : result; + } + } + const dispatcher = new HostGhostPipeDispatcher({ getGhost, runtimeStateOf: id => runtime.stateOf(id), spawn: ghost => runtime.spawnForTool(ghost), sendToGhost: sandbox.deliver, ownerScope, log }); async function reconcileInstalled() { assertCurrent(); + if (desktopPause) return; const ghosts = await options.manager.listAsync(); assertCurrent(); + if (desktopPause) return; + const approvals = summarizeLegacyPluginApprovals(ghosts); + if (legacyApprovals === null) log.info('legacy plugin approval census: %j', approvals); + legacyApprovals = approvals; browserExtensions.reconcile(ghosts.map(ghost => getGhost(installedGhostStoragePart(ghost)) ?? { ...ghost, enabled: false })); for (const [id, previous] of known) { + if (desktopPause) return; if (previous === revision(getGhost(id))) continue; authorization.changes.emit(id, { source: 'manifest' }); - runtime.stop(id); await node.stopAndWait(id); await library.disposeGhost(id); known.delete(id); + taskPlugins.dropGhost(id); runtime.stop(id); await node.stopAndWait(id); await library.disposeGhost(id); known.delete(id); assertCurrent(); } await sandbox.revokeStale(); assertCurrent(); for (const ghost of ghosts) { const id = installedGhostStoragePart(ghost); + if (desktopPause) return; if (!known.has(id)) await authorization.reconcile(ghost); assertCurrent(); known.set(id, revision(ghost)); - spawnResidentGhost(ghost, { isAvailable: () => isCurrent(ghost), startNode: item => track(node.startResident(item)), + spawnResidentGhost(ghost, { isAvailable: () => !desktopPause && isCurrent(ghost), startNode: item => track(node.startResident(item)), spawnBrowser: item => track(runtime.spawn(item)), warn: (message, fields) => log.warn(message, fields) }); } } @@ -385,15 +497,87 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { reconciliation = next.catch(() => {}); return next; } - function setEnabled(id: string, enabled: boolean, approval?: string) { + async function cleanPausedPlugins(jobs: CleanupJob[]): Promise { + const results = await Promise.all(jobs.map(async job => { + try { + await job.run(); + return null; + } catch (error) { + log.warn('paused plugin cleanup failed', { + id: job.id, kind: job.kind, error: error instanceof Error ? error.message : String(error), + }); + return job; + } + })); + return results.filter(job => job !== null); + } + function pauseForDesktop(message: string): void { + if (closed || desktopPause) return; + const ids = new Set([...known.keys(), ...Object.keys(runtime.listStates())]); + const pause = { message, cleanup: Promise.resolve([]), resuming: false }; + desktopPause = pause; + // Mark this generation before any synchronous stop callback can report + // delivery failure. Aborting removes the gateway's pending verdicts. + delivery.abort(); + for (const id of ids) runtime.stop(id); + // The Node stop starts synchronously. Library teardown aborts open staging + // uploads and leaves committed receipts queryable by stagingId. + pause.cleanup = cleanPausedPlugins([ + ...[...ids].map(id => ({ id, kind: 'node' as const, run: () => node.stopAndWait(id) })), + ...[...ids].map(id => ({ id, kind: 'library' as const, run: () => library.disposeGhost(id) })), + ]); + download.abortAll(); + track(pause.cleanup); + } + async function resumeAfterDesktop(): Promise { + const pause = desktopPause; + const canResume = () => current() && !options.isProfileHeld?.(); + if (!pause || pause.resuming || !canResume()) return false; + pause.resuming = true; + try { + const failed = await pause.cleanup; + if (!canResume()) return false; + if (failed.length) { + // Retry only what failed. A Node stop timeout isn't proof of exit. + pause.cleanup = track(cleanPausedPlugins(failed)); + if ((await pause.cleanup).length || !canResume()) return false; + } + delivery = newDeliveryController(); + const resumedSignal = delivery.signal; + desktopPause = null; + try { + if (options.manager.hasPendingMutationRecovery()) await options.manager.retryInterruptedMutationsAfterDbReady(); + // Preserve the browser partition and the gateway fuses. The usual + // resident policy starts residents; on-demand plugins wait for a call. + await reconcile(); + const ghosts = await options.manager.listAsync(); + if (resumedSignal.aborted) return false; + if (!canResume()) { + pauseForDesktop(pause.message); + return false; + } + publish('ghosts:changed', { ghosts }); + publish('ghosts:runtime-changed', { states: runtime.listStates() }); + return true; + } catch (error) { + if (!resumedSignal.aborted) pauseForDesktop(pause.message); + throw error; + } + } finally { + pause.resuming = false; + } + } + async function setEnabled(id: string, enabled: boolean, approval?: string) { + assertPluginAvailable(); const next = enableChanges.then(() => setPluginEnabled({ - find: findGhost, requireAvailable: assertCurrent, + find: findGhost, requireAvailable: assertPluginAvailable, notFound: message => { throw new Error(message); }, - acquire: () => { assertCurrent(); return mutation.acquire(); }, + acquire: () => { assertPluginAvailable(); return mutation.acquire(); }, stop: async key => { // Requests from old pages lose authority immediately, even if writing the // disabled receipt fails. Re-enabling is an explicit new transaction. suspended.add(key); + taskPlugins.dropGhost(key); network.disposeGhost(key); browserExtensions.reconcile(options.manager.list().map(ghost => getGhost(installedGhostStoragePart(ghost)) ?? { ...ghost, enabled: false })); runtime.stop(key); @@ -407,7 +591,7 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { }, start: key => { suspended.delete(key); runtime.resetFuse(key); }, didChange: async () => { await reconcile(); }, - }, id, enabled, approval, assertCurrent)); + }, id, enabled, approval, assertPluginAvailable)); enableChanges = next.catch(() => {}); return next; } @@ -434,22 +618,32 @@ export async function createHostPluginRuntime(options: PluginRuntimeOptions) { } return { list: () => options.manager.listAsync(), reconcile, cards, library, fsSlot, storage, network, secret, node, authorization, - browserExtensions, - manager: options.manager, getGhost, current, assertCurrent, dispatcher, handoff, files, + browserExtensions, taskPlugins, + legacyPluginApprovals: () => current() ? legacyApprovals : null, + manager: options.manager, getGhost, current, assertCurrent, assertPluginAvailable, pluginPauseFailure, dispatcher, handoff, files, /** Built-in and approved plugin Skills, as Desktop's listCindyManagedSkills. */ listManagedSkills: () => managedSkills.listCindyManagedSkills(), identity, - captureMutationOwner() { assertCurrent(); return getActiveAppSession(); }, + captureMutationOwner() { assertPluginAvailable(); return getActiveAppSession(); }, acquireMutationLease(expected: ActiveAppSession) { - assertCurrent(); + assertPluginAvailable(); const active = getActiveAppSession(); if (active.mode !== expected.mode || active.dataOwnerId !== expected.dataOwnerId || active.generation !== expected.generation) throw new Error('PLUGIN_OWNER_CHANGED'); return mutation.acquire(); }, runtimeStates: () => ({ states: runtime.listStates() }), - callTool: (request: Parameters[0]) => { assertCurrent(); return track(dispatcher.callGhostTool(request)); }, - async openPage(id: string, file: string) { const ghost = getGhost(id); if (!ghost?.enabled) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); return sandbox.openPage(ghost, file); }, + callTool(request: Parameters[0]) { + assertCurrent(); + return track(dispatcher.callGhostTool(request)); + }, + async openPage(id: string, file: string) { + assertPluginAvailable(); + const ghost = getGhost(id); + if (!ghost?.enabled) throw new Error('PLUGIN_PAGE_UNAVAILABLE'); + return sandbox.openPage(ghost, file); + }, + pauseForDesktop, resumeAfterDesktop, setEnabled, close() { return closing ??= dispose(); }, }; diff --git a/apps/host/src/profile-path.mjs b/apps/host/src/profile-path.mjs index 9bba15c7c30..6756b452149 100644 --- a/apps/host/src/profile-path.mjs +++ b/apps/host/src/profile-path.mjs @@ -1,13 +1,27 @@ import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; +import { hostReleaseRegion } from './runtime-layout.mjs'; const DB_FILE_PREFIX = 'cindy'; -export function resolveHostRegion(raw = process.env.CINDY_HOST_REGION) { - if (raw === undefined || raw === null || raw === '') return 'global'; - if (raw === 'cn' || raw === 'global') return raw; - throw new Error(`CINDY_HOST_REGION must be "cn" or "global"; received ${JSON.stringify(raw)}`); +/** + * The Host's edition. A release is built for one (scripts/build.mjs --region) and answers that; a + * CINDY_HOST_REGION naming the other edition refuses to start rather than being ignored. From source + * CINDY_HOST_REGION chooses, global when unset, for development only. The account's realm is separate: + * it only picks the sign-in and service endpoints. + */ +export function resolveHostRegion(raw = process.env.CINDY_HOST_REGION, release = hostReleaseRegion()) { + const requested = raw === undefined || raw === null || raw === '' ? null : raw; + if (requested !== null && requested !== 'cn' && requested !== 'global') { + throw new Error(`CINDY_HOST_REGION must be "cn" or "global"; received ${JSON.stringify(raw)}`); + } + if (release === null) return requested ?? 'global'; + if (requested !== null && requested !== release) { + throw new Error(`HOST_REGION_MISMATCH: this Cindy Host release is the ${release} edition, but CINDY_HOST_REGION is ${requested}. ` + + `Install the ${requested} release, or remove CINDY_HOST_REGION (a release does not need it).`); + } + return release; } /** Source and installed Hosts default to an independent profile. Existing @@ -56,8 +70,21 @@ export function ownerDatabasePath(userDataDir, ownerId) { return path.join(userDataDir, `${DB_FILE_PREFIX}-${ownerId}.db`); } +/** + * The OS app-data root the Host shares with the desktop: the Skill mutation locks and the built-in + * Skill bundle live under `/Cindy`, so both sides must resolve the same directory or their + * cross-process exclusion silently splits. Electron's app.getPath('appData') does not follow $HOME on + * macOS (measured 2026-11-17, release table row 25) while os.homedir() does, so a desktop that launches + * the Host passes its own value in CINDY_HOST_APP_DATA_DIR and the Host uses it as given; only a Host + * installed on its own computes it. A value that is not absolute is refused rather than guessed. + */ export function resolveHostAppDataDir(options = {}) { const env = options.env ?? process.env; + const passed = env.CINDY_HOST_APP_DATA_DIR; + if (passed !== undefined && passed !== '') { + if (!path.isAbsolute(passed)) throw new Error('CINDY_HOST_APP_DATA_DIR must be an absolute directory'); + if (!options.appDataDir) return passed; + } return options.appDataDir ?? env.APPDATA ?? (process.platform === 'darwin' diff --git a/apps/host/src/profile-path.test.mjs b/apps/host/src/profile-path.test.mjs index 0aece2cdbeb..dc9781a246a 100644 --- a/apps/host/src/profile-path.test.mjs +++ b/apps/host/src/profile-path.test.mjs @@ -9,6 +9,7 @@ import { ownerDatabasePath, resolveHostDataDir, resolveHostRegion, + resolveHostAppDataDir, } from './profile-path.mjs'; test('defaults to the global profile and reuses Desktop DB naming', () => { @@ -21,6 +22,18 @@ test('accepts only explicit CN or global identities', () => { assert.throws(() => resolveHostRegion('dev'), /must be "cn" or "global"/); }); +// A release answers the edition it was built for (scripts/build.mjs --region; region row of +// docs/host/personal-migration-release-table.md). A CINDY_HOST_REGION naming the other edition refuses +// rather than being ignored: an operator who kept CINDY_HOST_REGION=global from an old systemd unit +// while installing the cn release must find out. Minimal failing input: release cn with +// CINDY_HOST_REGION=global returning cn (silently ignored) or global (env wins). +test('a release answers its build region and refuses a CINDY_HOST_REGION of the other edition', () => { + assert.equal(resolveHostRegion(undefined, 'cn'), 'cn'); + assert.equal(resolveHostRegion('cn', 'cn'), 'cn'); + assert.throws(() => resolveHostRegion('global', 'cn'), /HOST_REGION_MISMATCH: this Cindy Host release is the cn edition, but CINDY_HOST_REGION is global/); + assert.throws(() => resolveHostRegion('cn', 'global'), /HOST_REGION_MISMATCH/); +}); + test('explicit Host data dirs retain Desktop XDT_USER_DATA_DIR semantics', () => { const base = { XDG_CONFIG_HOME: path.join('/config-home') }; assert.equal(resolveHostDataDir({ env: base, appDataDir: '/appdata' }), path.join('/appdata', 'CindyHost', 'global')); @@ -57,3 +70,19 @@ test('discovers a single-account profile and refuses to guess across accounts', fs.rmSync(root, { recursive: true, force: true }); } }); + +// Release table row 25 (25b): the desktop's Electron appData does not follow $HOME on macOS (measured +// with the repo's Electron under a temp HOME: desktop lock dir outside it, Host lock dir inside), so +// a desktop launching the Host passes its appData and the Host must use exactly that; the Skill +// mutation locks and built-in bundle under /Cindy depend on it. Gap: no test covered the +// source of the Host's appData. Minimal failure: a passed value ignored in favour of $HOME/APPDATA. +// Tier: unit. +test('the Host uses the app-data root passed by its launcher, refuses a relative one, and computes it otherwise', () => { + const passed = path.join(os.tmpdir(), 'cindy-passed-app-data'); + assert.equal(resolveHostAppDataDir({ env: { CINDY_HOST_APP_DATA_DIR: passed, APPDATA: path.join(os.tmpdir(), 'other') } }), passed); + assert.equal(resolveHostDataDir({ env: { CINDY_HOST_APP_DATA_DIR: passed } }), path.join(passed, 'CindyHost', 'global')); + assert.throws(() => resolveHostAppDataDir({ env: { CINDY_HOST_APP_DATA_DIR: 'relative/app-data' } }), /must be an absolute directory/); + const computed = path.join(os.tmpdir(), 'cindy-computed-app-data'); + assert.equal(resolveHostAppDataDir({ env: { APPDATA: computed } }), computed); + assert.equal(resolveHostAppDataDir({ env: { CINDY_HOST_APP_DATA_DIR: '', APPDATA: computed } }), computed); +}); diff --git a/apps/host/src/project-icon.test.mjs b/apps/host/src/project-icon.test.mjs new file mode 100644 index 00000000000..a734a01e049 --- /dev/null +++ b/apps/host/src/project-icon.test.mjs @@ -0,0 +1,60 @@ +/* + * Test value + * - Production entry and observable result: the handler `/api/project-info/auto-icon` serves + * (resolveAutomaticProjectIcon, handed over by main.ts), after the startup binding bindHostProjectIconRuntime. + * The website request of a known project shows up in the Host outbound proxy decisions + * (getHostOutboundPathSnapshotFor), which only the Host outbound transport (outbound.mjs) records. + * - Rule, and which side is right: the desktop binds its guarded fetch for these requests + * (projectAutomaticIcon.desktop.ts); the Host binds its own (release table section 二, item 项目自动图标的出站请求, + * 甲, aligned). Without it the module used a transport that reads proxy environment variables only. + * - Coverage gap: no test reached the icon fetch through the Host; the setter guard listed the setter as unbound. + * - Minimal failing input: a project whose package.json homepage is https://203.0.113.9/ (a documentation + * address the guard refuses, so nothing leaves the machine) leaves no Host proxy decision for that origin. + * - Tier: unit (node:test, in-memory SQL, a temporary profile and project; no account, network or engine). + */ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/better-sqlite3'; +import { getTableColumns, getTableName } from 'drizzle-orm'; + +import { bindHostProjectIconRuntime } from './project-icon.ts'; +import { getHostOutboundPathSnapshotFor } from './outbound-proxy.ts'; +import { configureHostOwner } from './agent/claude-auth.mjs'; +import { resolveAutomaticProjectIcon } from '../../desktop/src/main/projectAutomaticIcon.js'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../desktop/src/main/localDb/client/current.ts'; +import { createDbClientForHandle } from '../../desktop/src/main/localDb/client/createDbClientForHandle.ts'; +import { sessions, recentWorkdirs } from '../../desktop/src/main/localDb/schema.ts'; +import { lifoCleanup } from './test-support/cleanup.mjs'; + +test('the Host fetches project icon websites through its own outbound transport', async t => { + t = lifoCleanup(t); + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-icon-profile-')); + t.after(() => fs.rmSync(profile, { recursive: true, force: true })); + const project = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-icon-project-'))); + t.after(() => fs.rmSync(project, { recursive: true, force: true })); + const website = 'https://203.0.113.9/'; + fs.writeFileSync(path.join(project, 'package.json'), JSON.stringify({ name: 'icon-fixture', homepage: website })); + + configureHostOwner({ userDataDir: profile, ownerId: 'icon-owner' }); + const sqlite = new Database(':memory:'); + t.after(() => sqlite.close()); + for (const table of [sessions, recentWorkdirs]) { + sqlite.exec(`CREATE TABLE "${getTableName(table)}" (${Object.values(getTableColumns(table)) + .map(column => `"${column.name}" ${column.getSQLType()}`).join(',')})`); + } + sqlite.prepare("INSERT INTO sessions(id,status,working_dir,created_at,updated_at) VALUES ('task','active',?,0,1)").run(project); + const client = createDbClientForHandle({ db: sqlite, drizzle: drizzle(sqlite) }); + setCurrentDbClient(client, 'icon-owner'); + t.after(() => clearCurrentDbClient(client)); + + bindHostProjectIconRuntime(); + const icon = await resolveAutomaticProjectIcon({ projectKey: `local:${project}` }); + assert.equal(icon.image, null, 'the refused website gives no icon'); + const decision = getHostOutboundPathSnapshotFor([website]); + assert.ok(decision, 'the icon request went through the Host outbound transport'); + assert.equal(decision.upstream, 'https://203.0.113.9'); +}); diff --git a/apps/host/src/project-icon.ts b/apps/host/src/project-icon.ts new file mode 100644 index 00000000000..8966669cad5 --- /dev/null +++ b/apps/host/src/project-icon.ts @@ -0,0 +1,14 @@ +import { configureProjectIconRuntime } from '../../desktop/src/main/projectAutomaticIcon.js'; +import { hostOutbound } from './outbound.mjs'; + +/** + * Project automatic icons (`/api/project-info/auto-icon`) fetch websites through the Host outbound transport, + * as the desktop binds its own (projectAutomaticIcon.desktop.ts, the desktop guardedOutboundFetch): the same + * DNS pinning, redirect and private-address guard, with the Host's proxy decision (outbound-proxy.ts). Unbound, + * the module falls back to a transport that reads proxy environment variables only. readRemote stays unset: + * the desktop reads remote workdir icons through the remote file browser, and the Host refuses remote workdirs. + * Called once by main.ts at startup. + */ +export function bindHostProjectIconRuntime(): void { + configureProjectIconRuntime({ fetch: hostOutbound.guardedOutboundFetch }); +} diff --git a/apps/host/src/project-info.ts b/apps/host/src/project-info.ts new file mode 100644 index 00000000000..c088ae2bf82 --- /dev/null +++ b/apps/host/src/project-info.ts @@ -0,0 +1,38 @@ +import { updateProjectInfo } from '../../desktop/src/main/projectInfoCore.js'; +import type { ProjectInfoAuthorization } from '../../desktop/src/main/projectInfoAuthorization.js'; +import { throwIpcError } from '../../desktop/src/main/utils/ipcValidate.js'; +import type { createPlatformClientBridge } from './platform/client-bridge.js'; + +export function createHostProjectInfoUpdate(deps: { + platform(): ReturnType | null; + profileHold(): string | null; + changed(catalogChanged: boolean): void; +}) { + const assertCurrent = () => { + const held = deps.profileHold(); + if (held) throwIpcError('PRECONDITION_FAILED', held); + }; + return async (input: unknown, source: { desktopRequest?: string; legacyDesktop?: boolean } = {}) => { + const platform = deps.platform(); + let authorization: ProjectInfoAuthorization | undefined = { kind: 'host', assertCurrent }; + if (source.desktopRequest) { + const requestId = source.desktopRequest; + authorization = { kind: 'renderer', assertCurrent, async check(check) { + if (!platform || !platform.status().attached) throw Error('Desktop project window unavailable'); + try { + const answer = await platform.call({ method: 'project.check', requestId, check }); + if (answer !== true) throw Error('Project authorization unavailable'); + } catch (error) { + if ((error as { code?: string }).code === 'MUTATION_CANCELLED') throw Error('[MUTATION_CANCELLED] Project action cancelled'); + throw error; + } + } }; + } else if (source.legacyDesktop) { + // Legacy windows supply no project grants. Preserve that admission rule. + authorization = undefined; + } + const result = await updateProjectInfo(input, authorization); + deps.changed(!!result.createdProjectKey); + return result; + }; +} diff --git a/apps/host/src/release-region.mjs b/apps/host/src/release-region.mjs new file mode 100644 index 00000000000..998a02391ed --- /dev/null +++ b/apps/host/src/release-region.mjs @@ -0,0 +1,66 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +/** + * A Host release is built for one edition, as the desktop is (region-and-editions.md §2.4: the + * installed build decides the region). The edition is fixed when the release is built and cannot be + * changed at startup. + */ +export const RELEASE_REGIONS = Object.freeze(['cn', 'global']); + +/** + * The release builder's region. There is no default: a missing or unknown value fails the build + * rather than producing a package of the wrong edition (the fail-closed exception of §2.2, as the + * desktop's versioned packaging requires `--region`). + * + * @param {string | undefined} value + * @returns {'cn' | 'global'} + */ +export function selectReleaseRegion(value) { + if (value === 'cn' || value === 'global') return value; + throw new Error(`A Host release needs --region cn or --region global; received ${value === undefined ? 'none' : JSON.stringify(value)}`); +} + +// The desktop renderer reads its region as `import.meta.env?.VITE_CINDY_AUTH_REGION` +// (shared/brandRegion.ts); for that optional access Vite inlines the whole env object, so every renderer +// build carries one `VITE_CINDY_AUTH_REGION:""`. +const WEB_REGION_MARKER = /VITE_CINDY_AUTH_REGION:"([a-z]+)"/g; + +function scriptFiles(dir) { + const files = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const file = path.join(dir, entry.name); + if (entry.isDirectory()) files.push(...scriptFiles(file)); + else if (entry.isFile() && entry.name.endsWith('.js')) files.push(file); + } + return files; +} + +/** + * The regions a renderer build was built for, read from its scripts. + * + * @param {string} webDir + * @returns {string[]} sorted, distinct + */ +export function readWebRegions(webDir) { + const regions = new Set(); + for (const file of scriptFiles(webDir)) { + for (const match of fs.readFileSync(file, 'utf8').matchAll(WEB_REGION_MARKER)) regions.add(match[1]); + } + return [...regions].sort(); +} + +/** + * A release must serve the renderer of its own edition. A renderer whose region cannot be read, or that + * carries another or more than one, is refused. + * + * @param {string} webDir + * @param {'cn' | 'global'} region + */ +export function assertWebRegion(webDir, region) { + const regions = readWebRegions(webDir); + if (regions.length === 1 && regions[0] === region) return; + throw new Error(regions.length === 0 + ? `Cannot read the region of the renderer build in ${webDir}; build it with VITE_CINDY_AUTH_REGION=${region}` + : `The renderer build in ${webDir} is for ${regions.join(', ')}, not ${region}; build it with VITE_CINDY_AUTH_REGION=${region}`); +} diff --git a/apps/host/src/release-region.test.mjs b/apps/host/src/release-region.test.mjs new file mode 100644 index 00000000000..8fb06b557b7 --- /dev/null +++ b/apps/host/src/release-region.test.mjs @@ -0,0 +1,109 @@ +/** + * The Host's edition: one release per region, fixed when it is built (region-and-editions.md §2.4). + * + * Test value + * - Production entries and observable results: from source, the desktop modules the Host loads follow + * CINDY_HOST_REGION through the loader (loaders/raw-hook.mjs): the active catalog's unverified XD + * embedding models (hidden for cn before /models first succeeds), the currency of a zero amount + * (regionalMoney.zeroUsageMoney, which localDb/mapper.ts uses for tasks and runs without a cost) and the + * voice input default language the web client boots with (profile-settings.mjs). The release builder + * (scripts/build.mjs) refuses a missing or unknown --region before any work, and a renderer build of + * another region (release-region.mjs assertWebRegion). + * - Rule: docs/host/personal-migration-release-table.md, the region row (甲类, 2026-11-17): the desktop + * constant was always global on the Host, so a mainland China account saw unverified XD models, USD + * zero amounts and an automatic voice language. + * - Coverage gap: no Host test ran a desktop module under another region; the release builder had no region. + * - Minimal failing input: CINDY_HOST_REGION=cn with the loader's define removed gives 7 embedding + * models, USD and auto; `build.mjs --output
` without --region starts building. + * - Tier: unit (Node test runner, child processes with an empty HOME; no account, network or engine). + * The source-mode children load the catalog module (under a second together on this machine); the + * builder children exit at argument checking. + */ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +import { assertWebRegion, readWebRegions } from './release-region.mjs'; + +const exec = promisify(execFile); +const hostDir = fileURLToPath(new URL('..', import.meta.url)); + +function childEnv(home, region) { + const env = { ...process.env, HOME: home, USERPROFILE: home, ELECTRON_SKIP_BINARY_DOWNLOAD: '1' }; + delete env.CINDY_HOST_REGION; + delete env.NODE_OPTIONS; + if (region !== undefined) env.CINDY_HOST_REGION = region; + // A desktop build variable some shells inherit; the Host must not read it. + env.VITE_CINDY_AUTH_REGION = region === 'cn' ? 'global' : 'cn'; + return env; +} + +async function sourceModeReadings(region) { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-region-')); + try { + const probe = [ + "const { getActiveCatalog } = await import('../desktop/src/main/maker-host/active-catalog.ts');", + "const { zeroUsageMoney } = await import('../desktop/src/shared/regionalMoney.ts');", + "const { readProfileSettings } = await import('./src/profile-settings.mjs');", + "const xd = getActiveCatalog().providers.find(provider => provider.id === 'xd');", + 'console.log(JSON.stringify({ embeddingModels: (xd?.embeddingModels ?? []).length, zeroCurrency: zeroUsageMoney().currency,', + ' voiceLanguage: readProfileSettings({ dataDir: process.argv[1], ownerId: null }).voiceInput.settings.language }));', + ].join('\n'); + const { stdout } = await exec(process.execPath, ['--import', 'tsx', '--import', './src/loaders/register-raw.mjs', + '--input-type=module', '-e', probe, home], { cwd: hostDir, env: childEnv(home, region) }); + return JSON.parse(stdout.trim().split('\n').at(-1)); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } +} + +test('from source the desktop modules follow CINDY_HOST_REGION, global when unset', async () => { + const [cn, unset] = await Promise.all([sourceModeReadings('cn'), sourceModeReadings(undefined)]); + assert.deepEqual(cn, { embeddingModels: 0, zeroCurrency: 'CNY', voiceLanguage: 'zh-CN' }); + assert.equal(unset.zeroCurrency, 'USD'); + assert.equal(unset.voiceLanguage, 'auto'); + assert.ok(unset.embeddingModels > 0, 'global keeps the unverified XD embedding models'); +}); + +test('a release build needs --region cn or global, checked before any output is written', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-region-build-')); + try { + for (const args of [[], ['--region', 'dev']]) { + const output = path.join(root, 'release'); + await assert.rejects( + exec(process.execPath, ['scripts/build.mjs', '--output', output, ...args], { cwd: hostDir, env: childEnv(root, undefined) }), + error => /A Host release needs --region cn or --region global/.test(error.stderr), + ); + assert.deepEqual(fs.readdirSync(root), [], `nothing written for ${JSON.stringify(args)}`); + } + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + +test('a release only takes the renderer build of its own region', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-region-web-')); + const web = (name, ...scripts) => { + const dir = path.join(root, name, 'assets'); + fs.mkdirSync(dir, { recursive: true }); + scripts.forEach((text, index) => fs.writeFileSync(path.join(dir, `chunk-${index}.js`), text)); + return path.dirname(dir); + }; + try { + // The shape Vite inlines for the renderer's import.meta.env (brandRegion.ts reads it optionally). + const cn = web('cn', 'const e={MODE:"production",VITE_CINDY_AUTH_REGION:"cn"};', 'export const x=1;'); + assert.deepEqual(readWebRegions(cn), ['cn']); + assert.doesNotThrow(() => assertWebRegion(cn, 'cn')); + assert.throws(() => assertWebRegion(cn, 'global'), /is for cn, not global/); + assert.throws(() => assertWebRegion(web('none', 'export const x=1;'), 'cn'), /Cannot read the region/); + assert.throws(() => assertWebRegion(web('mixed', 'a={VITE_CINDY_AUTH_REGION:"cn"}', 'b={VITE_CINDY_AUTH_REGION:"global"}'), 'cn'), + /is for cn, global, not cn/); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/host/src/runtime-layout.mjs b/apps/host/src/runtime-layout.mjs index 361a0085015..295bf223931 100644 --- a/apps/host/src/runtime-layout.mjs +++ b/apps/host/src/runtime-layout.mjs @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -9,6 +10,26 @@ const root = release ? fileURLToPath(new URL('..', import.meta.url)) : fileURLToPath(new URL('../../..', import.meta.url)); +/** The edition a release was built for (scripts/build.mjs --region); null when running from source. */ +export function hostReleaseRegion() { + return release?.region ?? null; +} + +// Electron's npm entry can synchronously run its installer. Read the installed +// package's marker directly so source commands never start a download. +// 源码方式不读 ELECTRON_OVERRIDE_DIST_PATH。 +export function resolveSourceElectronBinary() { + try { + const manifest = createRequire(new URL('../../desktop/package.json', import.meta.url)).resolve('electron/package.json'); + const directory = path.dirname(manifest); + const dist = path.join(directory, 'dist'); + const binary = path.resolve(dist, fs.readFileSync(path.join(directory, 'path.txt'), 'utf8').trim()); + return binary.startsWith(dist + path.sep) && fs.statSync(binary).isFile() ? binary : null; + } catch { + return null; + } +} + export function hostRuntimeLayout() { if (release && (release.platform !== process.platform || release.arch !== process.arch || release.modules !== process.versions.modules)) { @@ -22,6 +43,9 @@ export function hostRuntimeLayout() { version: release?.version ?? JSON.parse(fs.readFileSync(path.join(desktop, 'package.json'), 'utf8')).version, configDir: release ? resource('config') : path.join(root, 'config'), drizzleDir: release ? resource('drizzle') : path.join(desktop, 'drizzle'), + // The built-in Skill bundle the Host publishes (user decision: the personal Host ships its own + // copy; release table row 25). From source: the desktop's own development bundle. + systemSkillsDir: release ? resource('system-skills') : path.join(desktop, 'resources', 'system-skills'), sqliteVecPath: release ? resource('native', vec) : path.join(desktop, 'native', 'sqlite-vec', `${process.platform}-${process.arch}`, vec), webDir: release ? resource('web') : path.join(desktop, '.vite', 'renderer', 'main_window'), shimPath: release ? resource('web', 'shim.js') : path.join(root, 'apps', 'web', 'shim.js'), @@ -37,6 +61,8 @@ export function hostRuntimeLayout() { agentNetWorker: release ? path.join(root, 'bin', 'agent-net-worker.mjs') : path.join(root, 'packages', 'agent-net', 'dist', 'node-worker.mjs'), agentNetCore: release ? resource('agent-net', 'core.wasm') : path.join(root, 'packages', 'agent-net-core', 'dist', 'core.wasm'), credentialScript: release ? path.join(root, 'bin', 'electron-codec.cjs') : path.join(root, 'apps', 'host', 'src', 'credentials', 'electron-codec.cjs'), + // The Chromium proxy helper (chromium-proxy-worker.cjs, row 28c), run by electronBinary; macOS and Windows releases only. + proxyWorker: release?.electronBinary ? path.join(root, 'bin', 'chromium-proxy-worker.cjs') : null, electronBinary: release?.electronBinary ? path.join(root, release.electronBinary) : null, chromiumExecutable: release?.chromiumExecutable ? path.join(root, release.chromiumExecutable) : null, harnessRoot: release ? resource('harnesses') : path.join(root, 'apps'), diff --git a/apps/host/src/server-api.test.mjs b/apps/host/src/server-api.test.mjs new file mode 100644 index 00000000000..ebccc24f012 --- /dev/null +++ b/apps/host/src/server-api.test.mjs @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; + +import { hostOutbound } from './outbound.mjs'; +import { createHostServerApi } from './server-api.ts'; +import { configureUserDataDir } from '../../desktop/src/main/userDataPath.ts'; + +// 测试价值:生产入口 createHostServerApi(Host 给桌面请求合同的端口)。规则:服务端回 401 时,桌面的请求合同以 +// `serverRejectedToken: true` 调续期,Host 的续期据此在网络失败后的等待里提前一次(C,与桌面 AuthRefreshBackoff 相同)。 +// 缺口:Host 原来的端口不传参数,这个信号丢在半路;没有用例经过它。最小失败输入:一次 401。tier:unit(替换出站 fetch)。 +test('a 401 from the server reaches the Host renewal as server evidence', async (t) => { + // The request contract logs the 401; the log goes to a temporary profile. + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-server-api-')); + t.after(() => fs.rmSync(profile, { recursive: true, force: true })); + configureUserDataDir(profile); + t.mock.method(hostOutbound, 'outboundFetch', async () => + new Response(JSON.stringify({ error: { code: 'UNAUTHORIZED', message: 'expired' } }), { status: 401 })); + const renewals = []; + const request = createHostServerApi({ + token: () => 'synthetic-access', locale: () => 'en', invalidate: async () => {}, + refresh: async (options) => { renewals.push(options); return false; }, + }); + await assert.rejects(request('/api/fixture', { baseUrl: 'https://example.invalid' })); + assert.deepEqual(renewals, [{ serverRejectedToken: true }]); +}); diff --git a/apps/host/src/server-api.ts b/apps/host/src/server-api.ts index b6ca33b3f5c..6374faa7488 100644 --- a/apps/host/src/server-api.ts +++ b/apps/host/src/server-api.ts @@ -7,7 +7,7 @@ import { hostOutbound } from './outbound.mjs'; * captured account boundary covering requests, refresh and returned payloads. */ export function createHostServerApi(options: { token(): string | null; - refresh(): Promise; + refresh(options?: { serverRejectedToken?: boolean }): Promise; invalidate(reason: string): Promise; locale(): string; }) { @@ -26,7 +26,8 @@ export function createHostServerApi(options: { }, auth: { getAccessToken: () => { check(); return options.token(); }, - refresh: async () => { check(); const refreshed = await options.refresh(); check(); return refreshed; }, + // The desktop's request contract says whether the server rejected the token (a 401). + refresh: async (refreshOptions) => { check(); const refreshed = await options.refresh(refreshOptions); check(); return refreshed; }, invalidateSession: async reason => { check(); await options.invalidate(reason); }, }, }); diff --git a/apps/host/src/server.mjs b/apps/host/src/server.mjs index c8f6dd84178..02fdb119364 100644 --- a/apps/host/src/server.mjs +++ b/apps/host/src/server.mjs @@ -14,6 +14,8 @@ import path from 'node:path'; import { isAuthorized } from './api-token.mjs'; import { clientErrorMessage } from './client-error.mjs'; +import { createLogger } from '../../desktop/src/main/logger.ts'; +import { parseTypedError, typedErrorStatus } from './typed-error.mjs'; import { createWebAuth, isLoopbackRequest, CONNECT_PAGE, CONNECT_SCRIPT } from './web-auth.mjs'; import { buildWebShim } from './web-client-build.mjs'; import { HOST_IPC_MANIFEST_PATH, HOST_IPC_PATH_PREFIX } from '@cindy/maker-shared/host-ipc-registry'; @@ -95,14 +97,34 @@ export function createHostServer(input) { let authDrain; const cancelPendingAuth = () => authDrain ??= Promise.resolve().then(() => deps.cancelPendingAuth?.()); const unsubscribeSessions = deps.webAuth.onSessionRevoke?.(caller => deps.releaseAuthCaller?.(caller)); + const log = deps.serverLog ?? createLogger('host-server'); + // Only the step and the error's code or name: a message can carry account or sign-in details. + const signOutStep = (step, run) => { + const warn = (error) => { + const code = typeof error?.code === 'string' ? error.code : (error instanceof Error ? error.name : typeof error); + log.warn('a sign-out step failed; the sign-out continues', { step, error: code }); + }; + try { return Promise.resolve(run()).catch(warn); } + catch (error) { warn(error); return Promise.resolve(); } + }; const logout = () => { if (logoutFlight) return logoutFlight; - // Revoke browser streams immediately and drain existing database callers - // before the owner runtime closes. Concurrent sign-out clicks share a result. - deps.webAuth.clear(); - deps.platformClient?.()?.close(); - logoutFlight = cancelPendingAuth().then(() => Promise.all([...ownerRequests])).then(() => deps.logout()) - .finally(() => { logoutFlight = undefined; }); + // The owner boundary's stop comes first (agent/owner-boundary.ts): a turn that fails on the + // teardown below is an interruption, not an ended turn with an error row. Once begun, the boundary + // must reach dispose: whatever fails before it, deps.logout() still runs (its runOwnerBoundary + // disposes the stopped input runtime, which rebuilds it) and the stop is released. + const releaseStop = deps.beginOwnerBoundaryStop?.() ?? (() => {}); + // Revoke browser streams immediately and drain existing database callers before the owner runtime + // closes. Concurrent sign-out clicks share a result. As in runOwnerBoundary, each step runs whatever + // the one before it did: a failed revoke must not leave the platform client open, nor a sign-in in + // progress that completes after the sign-out. A step that fails is not the logout's failure: the user + // still signs out, and the logout's own result (or error) is what the caller gets. + const revoked = signOutStep('revoke web sessions', () => deps.webAuth.clear()); + const closed = signOutStep('close platform client', () => deps.platformClient?.()?.close()); + logoutFlight = Promise.all([revoked, closed]) + .then(() => signOutStep('cancel pending sign-in', () => cancelPendingAuth())) + .then(() => Promise.all([...ownerRequests])).then(() => deps.logout()) + .finally(() => { releaseStop(); logoutFlight = undefined; }); return logoutFlight; }; const server = createServer(async (request, response) => { @@ -145,7 +167,9 @@ export function createHostServer(input) { || ['/control/platform', '/control/remote', '/events', '/chat', '/sessions', '/plugins'].includes(url.pathname) || url.pathname.startsWith('/sessions/'); if (ownerRequest) { if (ownerPaused || logoutFlight || deps.isOwnerReady?.() === false) { - send(response, 409, { error: 'owner_runtime_unavailable' }); return; + // Why, when the Host can say it (coexistence plan A: its start was refused because a desktop + // uses this profile): a reason code and a sentence for the window. Older clients read only `error`. + send(response, 409, { error: 'owner_runtime_unavailable', ...(deps.ownerUnavailableReason?.() ?? {}) }); return; } const completion = new Promise(resolve => { finishOwnerRequest = resolve; }); ownerRequests.add(completion); @@ -245,7 +269,10 @@ export function createHostServer(input) { send(response, routed.status, routed.body); return; } - const result = await service(url.pathname, body, { caller }); + const trustedNativeClient = isLoopbackRequest(request) && !request.headers.origin + && isAuthorized(request.headers.authorization, deps.token) + && Boolean(deps.instanceId && request.headers['x-cindy-host-instance'] === deps.instanceId); + const result = await service(url.pathname, body, { caller, trustedNativeClient }); send(response, result.status, result.body); return; } @@ -322,7 +349,15 @@ export function createHostServer(input) { } if (request.method === 'GET' && url.pathname === '/health') { - send(response, 200, isWebAuthorized(request, deps) ? await deps.probe() : { status: 'ok', service: 'cindy-host' }); + if (!isWebAuthorized(request, deps)) { + send(response, 200, { status: 'ok', service: 'cindy-host' }); + return; + } + const health = await deps.probe(); + // Plugin identities are local diagnostics. Browser pairing does not grant this read. + const legacyPluginApprovals = request.headers.origin === undefined && isAuthorized(request.headers.authorization, deps.token) + ? deps.legacyPluginApprovals?.() : undefined; + send(response, 200, legacyPluginApprovals === undefined ? health : { ...health, legacyPluginApprovals }); return; } @@ -375,6 +410,13 @@ export function createHostServer(input) { response.end(); return; } + // A typed error whose code is in the shared table answers with its status and code + // (typed-error.mjs, as the IPC route). The message stays the whole `[CODE] message`: the web + // client reads the code from the response text (apps/web/shim.js requestHost). Anything else + // stays the 500 below. + const typed = parseTypedError(error); + const status = typed ? typedErrorStatus(typed.code) : null; + if (typed && status !== null) { send(response, status, { error: typed.code, message: clientErrorMessage(error) }); return; } send(response, 500, { error: 'internal_error', message: clientErrorMessage(error) }); } finally { finishOwnerRequest?.(); diff --git a/apps/host/src/server.test.mjs b/apps/host/src/server.test.mjs index 366867b8f04..ad66307ab62 100644 --- a/apps/host/src/server.test.mjs +++ b/apps/host/src/server.test.mjs @@ -10,6 +10,12 @@ import { createPlatformClientBridge } from './platform/client-bridge.ts'; import { createHostPlatformRpc } from '@cindy/maker-shared/host-platform-rpc'; import { createHostServer } from './server.mjs'; +import { publishHostEndpoint, readHostProcessStatus } from './control.mjs'; +import Database from 'better-sqlite3'; +import { drizzle } from 'drizzle-orm/better-sqlite3'; +import { createOwnerBoundaryStop, runOwnerBoundary } from './agent/owner-boundary.ts'; +import { markSessionTurnEnded, drainSessionActiveTurnWrites } from '../../desktop/src/main/localDb/sessionActiveTurn.ts'; +import { setCurrentDbClient, clearCurrentDbClient } from '../../desktop/src/main/localDb/client/current.ts'; const TOKEN = 'test-token-value'; @@ -103,6 +109,31 @@ test('health is public while task data requires the profile bearer', async (t) = assert.equal((await request('/sessions', { headers: { authorization: 'Bearer wrong' } })).status, 401); }); +// §3.2 integration, release table §5: the CLI reads the startup census through +// the real Host endpoint. Pairing a browser must not disclose the install IDs. +test('Host status carries the legacy plugin census without exposing it to paired browsers', async t => { + const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-status-legacy-')); + const webAuth = createWebAuth(); + const cookie = `cindy_host_web=${webAuth.exchange(webAuth.pair())}`; + const report = { count: 1, installIds: ['legacy-fixture'] }; + const instanceId = 'status-fixture'; + const server = createHostServer({ token: TOKEN, instanceId, webAuth, + probe: () => ({ status: 'ok', clientProtocol: 1, pid: process.pid, instanceId }), + legacyPluginApprovals: () => report }); + let removeEndpoint; + t.after(() => { removeEndpoint?.(); server.close(); fs.rmSync(profile, { recursive: true, force: true }); }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const baseUrl = `http://127.0.0.1:${server.address().port}`; + fs.writeFileSync(path.join(profile, 'host-api-token'), TOKEN); + removeEndpoint = publishHostEndpoint(profile, baseUrl, instanceId); + assert.deepEqual((await readHostProcessStatus(profile)).legacyPluginApprovals, report); + for (const headers of [{}, { cookie }, { authorization: `Bearer ${TOKEN}`, origin: baseUrl }]) { + const response = await fetch(`${baseUrl}/health`, { headers }); + assert.equal(response.status, 200); + assert.equal(Object.hasOwn(await response.json(), 'legacyPluginApprovals'), false); + } +}); + test('model-access retry performs synchronization and Codex route reads the actual runtime', async t => { let retries = 0; const ready = { state: 'ok', source: 'server', endpoint: 'https://fixture.invalid', accountTier: null }; @@ -250,6 +281,72 @@ test('expired browser sessions release only their own authenticated controller', // Account teardown must not close storage underneath another request or accept // more private work while two clients are concurrently signing out. +// 测试价值 +// - 生产入口:server.mjs 的 HTTP 退出登录(POST /logout),配 main.ts 同样的接线:beginOwnerBoundaryStop 是 +// createOwnerBoundaryStop 的 begin,logout 经 runOwnerBoundary 拆运行时;回合结束写入用真实的 markSessionTurnEnded。 +// - 规则:放行表第五节“甲:账号边界停止提前置位”与 agent/owner-boundary.ts 的不变式:begin 在关平台客户端之前; +// begin 之后必须到达 dispose,压制必须释放。 +// - 现有覆盖缺口:取消挂起的登录被拒、或关平台客户端同步抛错时,不调 deps.logout(停止态的输入运行时不会被重建, +// 之后每次发送都被拒),或连 release 都不调(之后所有回合都不写结束时间);撤销网页会话同步抛错时,连带跳过关平台 +// 客户端与取消挂起的登录(进行中的登录可能在退出之后才完成),前置步骤的错误也没有任何日志。 +// - 规则补充:前置三步各自执行,一步失败不跳过后面的步骤(同 runOwnerBoundary);每步失败记一条 warn,只带步骤名与 +// 错误码或 error.name,不带 message 原文。 +// - 最小失败输入:一次退出登录,前置的一步失败。 +// - tier:unit(真实 HTTP 回环与临时 SQLite,无真实等待)。 +for (const failure of ['cancelPendingAuth rejects', 'platformClient.close throws', 'webAuth.clear throws']) { + test(`logout, when ${failure}: the stop begins before the platform client closes, every other step still runs, the logout still reaches dispose, and the stop is released`, async t => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-host-logout-boundary-')); + const sqlite = new Database(path.join(root, 'markers.sqlite')); + sqlite.exec('CREATE TABLE sessions(id TEXT PRIMARY KEY, active_turn_started_at INTEGER, last_turn_ended_at INTEGER); INSERT INTO sessions(id) VALUES (\'after\')'); + setCurrentDbClient({ drizzle: drizzle(sqlite) }, 'logout-boundary-test'); + t.after(() => { clearCurrentDbClient(); sqlite.close(); fs.rmSync(root, { recursive: true, force: true }); }); + const order = []; + let stopping = false; + const boundary = createOwnerBoundaryStop({ beginStop: () => { stopping = true; order.push('begin'); } }); + const webAuth = createWebAuth(); + const clear = webAuth.clear; + webAuth.clear = () => { + clear(); + if (failure === 'webAuth.clear throws') throw new Error('revoke failed: secret-detail'); + }; + let cancels = 0; + const warnings = []; + const request = await withServer(t, { + webAuth, + serverLog: { warn: (message, fields) => warnings.push({ message, fields }) }, + beginOwnerBoundaryStop: () => boundary.begin(), + platformClient: () => ({ close: () => { + order.push('close'); + if (failure === 'platformClient.close throws') throw new Error('platform close failed: secret-detail'); + } }), + cancelPendingAuth: async () => { + cancels++; + if (failure === 'cancelPendingAuth rejects') throw new Error('login cancel failed: secret-detail'); + }, + // As main.ts: the logout's own boundary; its dispose replaces the stopped input runtime with a fresh one. + logout: async () => { + const { errors } = await runOwnerBoundary(boundary, { dispose: async () => { order.push('dispose'); stopping = false; } }); + if (errors.length) throw errors[0]; + return { signedOut: true }; + }, + }); + const response = await request('/logout', { method: 'POST', headers: { authorization: `Bearer ${TOKEN}` } }); + assert.equal(response.status, 200); + assert.equal(response.body.signedOut, true, 'signed out cleanly'); + assert.deepEqual(order, ['begin', 'close', 'begin', 'dispose']); + assert.equal(cancels, 1, 'the pending sign-in was cancelled'); + const step = { 'cancelPendingAuth rejects': 'cancel pending sign-in', 'platformClient.close throws': 'close platform client', + 'webAuth.clear throws': 'revoke web sessions' }[failure]; + assert.deepEqual(warnings.map(w => w.fields), [{ step, error: 'Error' }], 'one warning, with the step and the error name'); + assert.ok(!JSON.stringify(warnings).includes('secret-detail'), 'no error message in the log'); + assert.equal(stopping, false, 'the stopped input runtime was replaced'); + // The suppression is released: the next turn's end is written. + markSessionTurnEnded('after'); + await drainSessionActiveTurnWrites('after'); + assert.equal(typeof sqlite.prepare('SELECT last_turn_ended_at AS endedAt FROM sessions WHERE id = ?').get('after').endedAt, 'number'); + }); +} + test('logout drains owner requests, revokes streams and serializes concurrent callers', async (t) => { let enter; let release; @@ -347,6 +444,33 @@ test('unknown routes and internal failures stay JSON', async (t) => { assert.equal(failed.body.message, 'storage offline'); }); +// Rule: a typed error from an /api entry answers with the shared table's status, as the IPC route +// (typed-error.mjs); the message stays the whole `[CODE] message`, which the web client reads the +// code from. Gap: every failure here answered 500, a refused model change included. Only an exactly +// typed error in the table changes; a code mismatch, a code outside the table or a plain error stay 500. +test('typed errors from /api entries answer with their table status; anything else stays 500', async (t) => { + const typed = (code, text = `[${code}] refused`) => Object.assign(new Error(text), { code }); + let failure; + const request = await withServer(t, { updateSession: () => { throw failure; } }); + const call = () => request('/api/sessions/update', { method: 'POST', + headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }, + body: JSON.stringify({ sessionId: 's', patch: { model: 'small' } }) }); + for (const [code, status] of [['MODEL_WINDOW_PROTECTION_UNAVAILABLE', 409], ['PRECONDITION_FAILED', 409], + ['INVALID_PARAMS', 400], ['UNSUPPORTED_CAPABILITY', 501]]) { + failure = typed(code); + const answer = await call(); + assert.equal(answer.status, status, code); + assert.deepEqual(answer.body, { error: code, message: `[${code}] refused` }); + } + for (const untyped of [typed('NOT_IN_TABLE'), typed('INVALID_PARAMS', '[NOT_FOUND] mismatch'), + new Error('[INVALID_PARAMS] no code property')]) { + failure = untyped; + const answer = await call(); + assert.equal(answer.status, 500, untyped.message); + assert.deepEqual(answer.body, { error: 'internal_error', message: untyped.message }); + } +}); + // Only an Error's message is part of the client contract. Any other thrown value // may stringify to a stack or an internal path, so no error body may echo it. test('thrown values that are not errors are never serialised to the client', async (t) => { @@ -364,10 +488,40 @@ test('thrown values that are not errors are never serialised to the client', asy assert.deepEqual(capabilities.body, { error: 'agent_not_registered', message: 'Unexpected error' }); }); +// The desktop's set-effort, set-fast-mode, set-thinking-enabled, set-permission-mode and set-plan-mode +// reach their Host entries with the IPC arguments the web client passes (shim.js), and answer what the +// entry returns. +test('effort, Fast mode, thinking, permission and Plan routes pass the desktop IPC arguments to their entries', async (t) => { + const calls = []; + const request = await withServer(t, { + setSessionEffort: (...args) => { calls.push(['effort', ...args]); return { deferred: true, superseded: false, pendingUntilSend: true }; }, + setSessionFastMode: (...args) => { calls.push(['fast', ...args]); return undefined; }, + setSessionThinkingEnabled: (...args) => { calls.push(['thinking', ...args]); return undefined; }, + setSessionPermissionMode: (...args) => { calls.push(['permission', ...args]); return true; }, + setSessionPlanMode: (...args) => { calls.push(['plan', ...args]); return undefined; }, + }); + const headers = { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }; + const post = (path, body) => request(path, { method: 'POST', headers, body: JSON.stringify(body) }); + const effort = await post('/api/sessions/set-effort', { sessionId: 's1', effort: 'low' }); + assert.equal(effort.status, 200); + assert.deepEqual(effort.body, { deferred: true, superseded: false, pendingUntilSend: true }); + assert.equal((await post('/api/sessions/set-fast-mode', { sessionId: 's1', fastMode: 'ultrafast' })).status, 200); + assert.equal((await post('/api/sessions/set-thinking-enabled', { sessionId: 's1', enabled: false })).status, 200); + const permission = await post('/api/sessions/set-permission-mode', { sessionId: 's1', mode: 'auto' }); + assert.equal(permission.status, 200); + assert.equal(permission.body, true); + assert.equal((await post('/api/sessions/set-plan-mode', { sessionId: 's1', enabled: true })).status, 200); + assert.deepEqual(calls, [['effort', 's1', 'low'], ['fast', 's1', 'ultrafast'], ['thinking', 's1', false], + ['permission', 's1', 'auto'], ['plan', 's1', true]]); +}); + test('cross-engine switch returns a deferred intent and exposes it for the renderer', async (t) => { let intent = null; + let forwarded = null; const request = await withServer(t, { - switchSessionAgent: (sessionId, targetAgentKind, model, providerId) => { + switchSessionAgent: (...args) => { + forwarded = args; + const [, targetAgentKind, model, providerId] = args; intent = { targetAgentKind, model, providerId }; return { switched: false, agentKind: targetAgentKind, model, engineReady: true, deferred: true }; }, @@ -384,9 +538,13 @@ test('cross-engine switch returns a deferred intent and exposes it for the rende model: 'group/deepseek', providerId: 'magpie-debian', effort: 'high', + options: { confirmedContextWindow: 128_000 }, + thinking: false, }), }); assert.equal(switched.status, 200); + // The desktop IPC's arguments reach the entry, including its options and the thinking choice. + assert.deepEqual(forwarded, ['s1', 'pi', 'group/deepseek', 'magpie-debian', 'high', undefined, { confirmedContextWindow: 128_000 }, false]); assert.equal(switched.body.deferred, true); assert.equal(switched.body.switched, false); assert.equal(switched.body.agentKind, 'pi'); @@ -430,6 +588,30 @@ test('browser pairing gates boot data, cookies and API access', async (t) => { assert.equal((await request('/api/sessions/list', { method: 'POST', headers: { cookie } })).status, 401); }); +// Integration: the task plugin settings endpoint has a trusted-renderer +// contract. A paired browser has an owner cookie but no desktop capability. +test('task plugin settings require the pinned desktop client and obey the profile hold', async t => { + const calls = []; + let held = false; + const auth = createWebAuth(); + const cookie = `cindy_host_web=${auth.exchange(auth.pair())}`; + const request = await withServer(t, { webAuth: auth, instanceId: 'live', + runtimePluginSettings: (id, settings) => { calls.push([id, settings]); return settings ?? {}; }, + profileHold: () => held ? 'HOST_PROFILE_IN_USE_BY_DESKTOP: fixture hold' : null, + }); + const invoke = (headers, settings) => request('/api/runtime-plugins', + { method: 'POST', headers, body: JSON.stringify({ sessionId: 'task', value: settings }) }); + const trusted = { authorization: `Bearer ${TOKEN}`, 'x-cindy-host-instance': 'live' }; + assert.equal((await invoke({ cookie })).status, 403); + assert.equal((await invoke({ authorization: trusted.authorization })).status, 403); + assert.equal((await invoke(trusted)).status, 200); + assert.equal((await invoke(trusted, {})).status, 200); + held = true; + assert.equal((await invoke(trusted)).status, 409); + assert.equal((await invoke(trusted, {})).status, 409); + assert.deepEqual(calls, [['task', undefined], ['task', {}]]); +}); + test('expired pairing codes and browser sessions cannot authorize a client', () => { let now = 0; const auth = createWebAuth({ now: () => now }); @@ -505,3 +687,26 @@ for (const boundary of ['logout', 'expired-owner', 'stop']) { assert.equal(bridge.status().waiting, 0); }); } + +// 测试价值 +// - 生产入口:server.mjs 的 createHostServer(窗口与网页端的 owner 请求都经它)。 +// - 规则:并存方案 A 后续(审核方 2026-11-17 定)。Host 因桌面占用而启动被拒时,owner 请求的 409 要带原因码和一句 +// 能说清原因与做法的话,客户端据此显示人话,不再是笼统的 "not ready";Host 说不出原因时只有 `error`, +// 旧客户端照旧。 +// - 现有覆盖缺口:之前 409 只有 `{ error: 'owner_runtime_unavailable' }`。 +// - 最小失败输入:未就绪的 Host 收到一次 owner 请求。tier:unit(本机回环 HTTP)。 +test('a refused owner request says why when the Host knows, and stays a bare error otherwise', async t => { + const reason = { reason: 'HOST_PROFILE_IN_USE_BY_DESKTOP', message: 'Quit the desktop app, then restart the Host.' }; + const ask = async ownerUnavailableReason => { + const server = createHostServer({ token: TOKEN, instanceId: 'fixture-host', probe: () => ({}), isOwnerReady: () => false, + ...(ownerUnavailableReason ? { ownerUnavailableReason } : {}) }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => server.close()); + const response = await fetch(`http://127.0.0.1:${server.address().port}/api/sessions/list`, { + method: 'POST', headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' }, body: '{}' }); + return { status: response.status, body: await response.json() }; + }; + assert.deepEqual(await ask(() => reason), { status: 409, body: { error: 'owner_runtime_unavailable', ...reason } }); + assert.deepEqual(await ask(() => null), { status: 409, body: { error: 'owner_runtime_unavailable' } }); + assert.deepEqual(await ask(undefined), { status: 409, body: { error: 'owner_runtime_unavailable' } }); +}); diff --git a/apps/host/src/service.mjs b/apps/host/src/service.mjs index 1c43a7ffc2e..6fb19beeb49 100644 --- a/apps/host/src/service.mjs +++ b/apps/host/src/service.mjs @@ -1,5 +1,41 @@ import { clientErrorMessage } from './client-error.mjs'; import { HOST_BROWSER_SETTINGS_ACTIONS } from '@cindy/maker-shared/host-channel-contract'; +import { throwIpcError } from '../../desktop/src/main/utils/ipcValidate.ts'; + +/** + * What still runs while a desktop that opens this profile's database is live (coexistence plan A, + * agent/profile-coexistence.ts). Everything else is refused, typed, before its handler runs; a path + * added later is refused too until it is listed here. Allowed are reads, and what a running turn + * needs to end: stopping it, and answering its permission requests, questions and plugin prompts. + * Without those the turn would not end and the profile could never be released. + */ +export const HOST_PATHS_ALLOWED_WHILE_HELD = Object.freeze({ + // Reads: they answer from what this process holds or read the shared files; none writes. Not + // /api/browser-backend/get-health: a failed embedded-browser probe recovers the backend + // (health-service.ts getHealth), so it is refused like other writes. + read: Object.freeze([ + '/api/me', '/api/auth/state', '/api/profile', '/api/runtime/sessions', '/api/conversations/search', + '/api/sessions/list', '/api/sessions/get', '/api/sessions/messages', '/api/sessions/agent-switch-intent', + '/api/sessions/interrupted-pending', '/api/sessions/error-tail-pending', '/api/sessions/interrupted-candidates', + '/api/messages/list', '/api/messages/history-view', '/api/messages/work-details', '/api/messages/estimated-value', + '/api/turn-change-sets/list', '/api/project-info/get', '/api/project-info/image', '/api/project-aliases/list', + '/api/recent-workdirs/list', '/api/ghosts', '/api/ghosts/runtime-states', '/api/ghosts/card', '/api/ghosts/cards', + '/api/plugins/list', '/api/providers', '/api/agents', '/api/agents/auth-state', '/api/agents/status', + '/api/agents/codex-runtime-route', '/api/model-access', '/api/usage/model-pricing', '/api/usage/reference-model-pricing', + '/api/interactions/pending', '/api/input/projection', '/api/agent-commands', '/api/agent-skills', '/api/capabilities', + '/api/right-sidebar-tabs/list', '/api/browser-backend/get-state', + ]), + // Stopping or interrupting the running turn. + stop: Object.freeze(['/api/input/stop']), + // Answering the running turn: its permission requests and questions, and its plugin prompts. An + // install consent is answered only with a refusal (below): accepting installs into the shared profile. + answer: Object.freeze(['/api/interactions/respond', '/api/ghosts/confirm/resolve', '/api/ghosts/install-consent/resolve']), + // Renewing the account session (reviewer, 2026-11-17): the one shared credential the Host writes + // while held, because it would sign itself out otherwise (auth/refresh.mjs). A window in client + // mode asks the Host to renew through this path; refused, the window takes it as a failed renewal. + renew: Object.freeze(['/api/auth/refresh']), +}); +const ALLOWED_WHILE_HELD = new Set(Object.values(HOST_PATHS_ALLOWED_WHILE_HELD).flat()); /** Owner business operations shared by HTTP and authenticated Device Link. * Transport admission and owner leases belong to the caller. No synthetic HTTP @@ -8,6 +44,10 @@ import { HOST_BROWSER_SETTINGS_ACTIONS } from '@cindy/maker-shared/host-channel- export function createHostService(deps) { return async function invoke(pathname, body = {}, context = {}) { const url = { pathname }; + const held = deps.profileHold?.(); + if (held && !ALLOWED_WHILE_HELD.has(pathname)) throwIpcError('PRECONDITION_FAILED', held); + if (held && pathname === '/api/ghosts/install-consent/resolve' && body?.confirmed !== false) + throwIpcError('PRECONDITION_FAILED', held); for (const [action, handler] of Object.entries(HOST_BROWSER_SETTINGS_ACTIONS)) { if (pathname === `/api/browser-backend/${action}`) @@ -64,6 +104,10 @@ export function createHostService(deps) { if (url.pathname === '/api/sessions/list') { return { status: 200, body: await deps.listSessions(body) }; } + if (pathname === '/api/runtime-plugins') { + if (!context.trustedNativeClient) throwIpcError('PERMISSION_DENIED', 'A trusted desktop renderer is required'); + return { status: 200, body: await deps.runtimePluginSettings(body.sessionId, body.value) }; + } if (url.pathname === '/api/project-info/auto-icon') return { status: 200, body: await deps.resolveAutomaticProjectIcon(body) }; if (url.pathname === '/api/project-info/image') return { status: 200, body: await deps.readProjectIconImage(body) }; if (url.pathname === '/api/project-info/get') return { status: 200, body: await deps.readProjectInfo() }; @@ -95,8 +139,29 @@ export function createHostService(deps) { if (url.pathname === '/api/sessions/update') { return { status: 200, body: await deps.updateSession(String(body.sessionId ?? ''), body.patch ?? {}) }; } + if (url.pathname === '/api/sessions/set-effort') { + // The desktop's set-effort, set-fast-mode and set-thinking-enabled, with their IPC arguments. + return { status: 200, body: (await deps.setSessionEffort(body.sessionId, body.effort)) ?? null }; + } + if (url.pathname === '/api/sessions/set-fast-mode') { + return { status: 200, body: (await deps.setSessionFastMode(body.sessionId, body.fastMode)) ?? null }; + } + if (url.pathname === '/api/sessions/set-thinking-enabled') { + return { status: 200, body: (await deps.setSessionThinkingEnabled(body.sessionId, body.enabled)) ?? null }; + } + if (url.pathname === '/api/sessions/set-permission-mode') { + // The desktop's set-permission-mode and set-plan-mode, with their IPC arguments. + return { status: 200, body: (await deps.setSessionPermissionMode(body.sessionId, body.mode)) ?? null }; + } + if (url.pathname === '/api/sessions/set-plan-mode') { + return { status: 200, body: (await deps.setSessionPlanMode(body.sessionId, body.enabled)) ?? null }; + } + if (url.pathname === '/api/sessions/set-model') { + // The desktop's set-model, with its IPC arguments (the web client passes them through). + return { status: 200, body: await deps.setSessionModel(String(body.sessionId ?? ''), body.model, body.providerId, body.revision, body.selection) }; + } if (url.pathname === '/api/sessions/switch-agent') { - return { status: 200, body: await deps.switchSessionAgent(String(body.sessionId ?? ''), String(body.targetAgentKind ?? ''), String(body.model ?? ''), body.providerId ?? null, body.effort, body.fastMode) }; + return { status: 200, body: await deps.switchSessionAgent(String(body.sessionId ?? ''), String(body.targetAgentKind ?? ''), String(body.model ?? ''), body.providerId ?? null, body.effort, body.fastMode, body.options, body.thinking) }; } if (url.pathname === '/api/sessions/agent-switch-intent') { return { status: 200, body: await deps.getSessionAgentSwitchIntent(String(body.sessionId ?? '')) }; diff --git a/apps/host/src/service.test.mjs b/apps/host/src/service.test.mjs new file mode 100644 index 00000000000..86c66c6b684 --- /dev/null +++ b/apps/host/src/service.test.mjs @@ -0,0 +1,109 @@ +/* + * 测试价值 + * - 生产入口:service.mjs 的 createHostService(HTTP 的 /api/* 与 device-link 的契约通道都经它), + * main.ts 给它的 profileHold 在闸门关着时返回带原因标记的文案。 + * - 规则:并存方案 A 后续(审核方 2026-11-17 定)。闸门关着时,Host 一切会写库或改运行时的入口默认拒绝;只放行 + * 读取、停止正在跑的回合、回答它的权限询问与提问(以及插件确认)。新建任务、改任务设置、改模型、排队消息的 + * 编辑删除移动、设置写入都拒绝;以后新加的路径没登记也拒绝。 + * - 现有覆盖缺口:input-queue 的 "profile hold" 用例只覆盖输入队列;任务、设置、插件等写入口之前照常执行。 + * - 最小失败输入:闸门关着时调用任一写入路径。tier:unit(处理函数全是记录调用的桩,没有 IO)。 + */ +import test from 'node:test'; +import assert from 'node:assert/strict'; + +import { createHostService, HOST_PATHS_ALLOWED_WHILE_HELD } from './service.mjs'; + +const HELD = 'HOST_PROFILE_IN_USE_BY_DESKTOP: held for this test'; + +/** Every dependency the service reaches is a stub that records the call and answers `{}`. */ +function stubbedService(held) { + const calls = []; + const stub = (name) => new Proxy(async (...args) => { calls.push(name); return {}; }, { + get: (target, key) => (key === 'then' ? undefined : stub(`${name}.${String(key)}`)), + }); + const deps = new Proxy({ profileHold: () => held() }, { + get: (target, key) => (key in target ? target[key] : stub(String(key))), + }); + return { invoke: createHostService(deps), calls }; +} + +const isHeldRefusal = error => error?.code === 'PRECONDITION_FAILED' && error.message === `[PRECONDITION_FAILED] ${HELD}`; + +test('while held, reads, stops and answers to the running turn still reach their handlers', async () => { + const { invoke, calls } = stubbedService(() => HELD); + for (const [kind, paths] of Object.entries(HOST_PATHS_ALLOWED_WHILE_HELD)) { + for (const path of paths) { + const before = calls.length; + // `confirmed: false`: an install consent is answered only with a refusal while held (test below). + const result = await invoke(path, { sessionId: 'task', callId: 'call', agentKind: 'claude-code', request: {}, + requestId: 'request', confirmed: false }, { caller: 'device:test' }); + assert.equal(result.status, 200, `${kind} ${path} is answered`); + assert.ok(calls.length > before, `${kind} ${path} reaches its handler`); + } + } +}); + +// What a running turn needs to end, named here rather than read from the production list: if any of +// these were refused, the turn could not end and the profile could never be released. And the account +// renewal, the one shared credential written while held. +test('while held, stopping the running turn, answering it and renewing the account are never refused', async () => { + const { invoke, calls } = stubbedService(() => HELD); + for (const path of ['/api/input/stop', '/api/interactions/respond', '/api/ghosts/confirm/resolve', + '/api/ghosts/install-consent/resolve', + // The account renewal (reviewer, 2026-11-17): a client-mode window asks the Host to renew here. + '/api/auth/refresh']) { + const before = calls.length; + const result = await invoke(path, { sessionId: 'task', requestId: 'request', confirmed: false }, { caller: 'device:test' }); + assert.equal(result.status, 200, path); + assert.ok(calls.length > before, `${path} reaches its handler`); + } +}); + +// Rule (reviewer, 2026-11-17): accepting a plugin install consent installs into the profile the +// desktop shares, so while held only a refusal is answered; a plugin confirmation is answered either way. +test('while held, an install consent can be declined but not accepted; a plugin confirmation either way', async () => { + const { invoke, calls } = stubbedService(() => HELD); + const answer = (path, confirmed) => invoke(path, { requestId: 'request', confirmed }, { caller: 'device:test' }); + await assert.rejects(answer('/api/ghosts/install-consent/resolve', true), isHeldRefusal); + assert.deepEqual(calls, [], 'the acceptance reached no handler'); + assert.equal((await answer('/api/ghosts/install-consent/resolve', false)).status, 200); + assert.equal((await answer('/api/ghosts/confirm/resolve', true)).status, 200); + assert.equal((await answer('/api/ghosts/confirm/resolve', false)).status, 200); + assert.equal(calls.length, 3); +}); + +// Each category of write, one path or more each; the last one is a path no handler knows yet. +const REFUSED = { + sends: ['/api/input/enqueue', '/api/input/steer', '/api/input/resume', '/api/input/retry-last-error'], + 'queue edits': ['/api/input/remove', '/api/input/update-text', '/api/input/update-content', '/api/input/move', + '/api/input/clear-session', '/api/input/clear-error', '/api/input/set-interaction-lock', '/api/input/set-edit-lock', + '/api/input/set-expanded'], + 'tasks': ['/api/sessions/create', '/api/sessions/update', '/api/sessions/delete', '/api/sessions/discard', + '/api/sessions/commit', '/api/sessions/auto-title', '/api/messages/create'], + 'task settings and models': ['/api/sessions/set-model', '/api/sessions/set-effort', '/api/sessions/set-fast-mode', + '/api/sessions/set-thinking-enabled', '/api/sessions/set-permission-mode', '/api/sessions/set-plan-mode', + '/api/sessions/switch-agent'], + 'settings and profile files': ['/api/settings/appearance/set', '/api/settings/appearance/reset', '/api/settings/layout/set', + '/api/settings/layout/reset', '/api/settings/sidebar/set', '/api/settings/shortcuts/set', '/api/project-info/set', + '/api/project-info/auto-icon', '/api/project-aliases/set', '/api/project-aliases/delete', '/api/right-sidebar-tabs/upsert', + '/api/browser-backend/set-kind', '/api/task-tags/execute'], + // Reads that change something: a failed embedded-browser probe recovers the backend (health-service.ts). + 'reads that write': ['/api/browser-backend/get-health'], + 'plugins and accounts': ['/api/ghosts/set-enabled', '/api/agents/logout', '/api/model-visibility/claim', + '/api/model-access/retry'], + 'a path added later': ['/api/some-later-write'], +}; + +test('while held, every other path is refused, typed, before its handler runs; open, they run', async () => { + let held = HELD; + const { invoke, calls } = stubbedService(() => held); + for (const [category, paths] of Object.entries(REFUSED)) { + for (const path of paths) { + await assert.rejects(invoke(path, { sessionId: 'task' }), isHeldRefusal, `${category}: ${path}`); + } + } + assert.deepEqual(calls, [], 'no handler ran'); + held = null; + await invoke('/api/sessions/set-model', { sessionId: 'task' }); + assert.ok(calls.length > 0, 'the same path runs once the profile is released'); +}); diff --git a/apps/host/src/sessions.test.mjs b/apps/host/src/sessions.test.mjs index 8966be3b877..f296acdba77 100644 --- a/apps/host/src/sessions.test.mjs +++ b/apps/host/src/sessions.test.mjs @@ -8,6 +8,7 @@ import { listActiveSessions, listRunningSessions } from './sessions.mjs'; import { readHostSessionList, readHostSession } from './session-reads.ts'; import { createHostMessageStore, createHostMessageRecovery } from './message-store.ts'; import { createHostEventPersistence } from './agent/event-persistence.ts'; +import { createHostHistoryReader } from './agent/history.ts'; import { createInteractionBroker } from './agent/interactions.mjs'; import { OwnerSessionStorage } from '../../desktop/src/main/localDb/sessionStorageAdapter.ts'; import { setCurrentDbClient, clearCurrentDbClient, getCurrentDbClientSnapshot } from '../../desktop/src/main/localDb/client/current.ts'; @@ -331,3 +332,225 @@ test('Host Pi recovery preserves message metadata and excludes cleared or rewoun assert.equal(await recovery.readPiUserEntry('task', 'input'), undefined); assert.equal(await recovery.linkPiUserEntry('task', 'missing', 'pi-entry'), false); }); + +// The Host history view as main.ts binds it (agent/history.ts createHostHistoryReader, the desktop's +// localHistoryViewReader.ts) over a real in-memory owner database. +function hostHistoryFixture(t, rows) { + const { sqlite, db } = sessionListDb(t); + sqlite.exec(rows); + const client = createDbClientForHandle({ db: sqlite, drizzle: db }); + setCurrentDbClient(client, 'isolated'); + t.after(() => clearCurrentDbClient(client)); + return { sqlite }; +} + +// Contract of the shared reader (historyViewReader.ts:55): `anchor` must reject anchors in cleared +// or rewound history. The Host's own anchor once took a message from before the clear line: as a +// work-details range it handed back the cleared body (the /api/messages/work-details route, main.ts +// workDetails), as a page cursor it was taken instead of refused. The Host now uses the desktop's +// anchor (localHistoryViewReader.ts), which answers NOT_FOUND. Minimal failing input: one message +// before the task's clear line, one rewound message, each used as the anchor. Tier: unit, real +// in-memory SQL through the reader main.ts binds. +test('Host history refuses a message from before the clear line, or rewound, as an anchor', async t => { + hostHistoryFixture(t, `INSERT INTO sessions(id,source,status,created_at,updated_at,cleared_at) + VALUES ('task','desktop','active',0,300,200); + INSERT INTO messages(id,client_id,session_id,role,content,created_at,rewind_at) + VALUES ('old','c-old','task','assistant','"cleared reply"',100,NULL),('new','c-new','task','user','"after the clear"',300,NULL), + ('undone','c-undone','task','assistant','"rewound reply"',400,500);`); + const reader = createHostHistoryReader({ running: () => false, live: () => [] }); + const range = id => ({ key: 'work', firstMessageId: id, lastMessageId: id }); + assert.deepEqual((await reader.details('task', range('new'))).messages.map(row => row.id), ['new']); + for (const id of ['old', 'undone']) { + await assert.rejects(reader.details('task', range(id)), { code: 'NOT_FOUND' }); + await assert.rejects(reader.page('task', id, true), { code: 'NOT_FOUND' }); + } +}); + +// A clear while the page is being read: the reader re-checks the page's endpoints after the scan +// (historyViewReader.ts, "A clear/rewind during the scan invalidates the whole snapshot") and refuses +// the page. The Host's own anchor once ignored the clear line, so the page went out with the rows +// just cleared. Minimal failing input: the clear lands between the read and the projection (the +// reader asks for the in-flight rows in between). Tier: unit, as above. +test('Host history refuses a page whose rows were cleared while it was read', async t => { + const { sqlite } = hostHistoryFixture(t, `INSERT INTO sessions(id,source,status,created_at,updated_at) + VALUES ('task','desktop','active',0,300); + INSERT INTO messages(id,client_id,session_id,role,content,created_at) + VALUES ('m1','c-1','task','user','"question"',100),('m2','c-2','task','assistant','"answer"',200);`); + const reader = createHostHistoryReader({ running: () => false, live: () => { + sqlite.exec("UPDATE sessions SET cleared_at=250 WHERE id='task'"); + return []; + } }); + await assert.rejects(reader.page('task', undefined, true), { code: 'NOT_FOUND' }); +}); + +// Release table section 6, Host history reader ②: the Host's reader had no outline and hydrate, so +// a page scanned at most 2000 full rows (historyViewReader.ts MAX_HISTORY_SCAN_ROWS) and one long +// turn answered UNSUPPORTED_CAPABILITY. The desktop reads bodies-free outlines (budget 100000) and +// loads bodies on demand. Minimal failing input: one turn of 2100 thinking rows after its user row. +// Tier: unit, real in-memory SQL through the reader main.ts binds. +test('Host history reads a task longer than the full-row scan budget', async t => { + const { sqlite } = hostHistoryFixture(t, `INSERT INTO sessions(id,source,status,created_at,updated_at) + VALUES ('task','desktop','active',0,3000); + INSERT INTO messages(id,client_id,session_id,role,content,created_at) VALUES ('u','c-u','task','user','"go"',1);`); + const insert = sqlite.prepare("INSERT INTO messages(id,client_id,session_id,role,content,created_at) VALUES (?,?,'task','thinking',?,?)"); + sqlite.transaction(() => { for (let n = 0; n < 2100; n++) insert.run(`t${n}`, `c-t${n}`, JSON.stringify(`step ${n}`), 10 + n); })(); + const reader = createHostHistoryReader({ running: () => false, live: () => [] }); + const page = await reader.page('task', undefined, true); + assert.deepEqual(page.items.map(item => item.type === 'work' + ? [item.summary.firstMessageId, item.summary.lastMessageId, item.summary.messageCount] : item.messages.map(row => row.id)), + [['u'], ['t0', 't2099', 2100]]); + const work = page.items[1].summary; + const details = await reader.details('task', work); + assert.equal(details.messages[0].id, 't0'); + assert.equal(details.messages[0].content, 'step 0', 'the body is read when the work is opened'); +}); + +/* + * Task PR references (release table 甲, section 二 item 任务的 PR 关联). + * Test value + * - Production entries and observable results: createHostMessageStore (the Host's message write) and + * createHostEventPersistence's updateDbMessageContent / discardPersistedAssistantMessage, observed in the + * session_pr_refs rows of a real in-memory database. + * - Rule, and which side is right: the desktop's message paths (localDb/ipc/messages.ts createMessage, + * updateMessageContent, discardPersistedAssistantMessage) record and recompute these rows through + * localDb/messagePrRefs.ts; the Host must keep the same rows for the same history. + * - Coverage gap: the Host wrote messages without recording PR references and recomputed them only after a + * clear recovery, so a PR a Host task mentioned never reached session_pr_refs. + * - Minimal failing input: one user message naming https://github.com/o/r/pull/7 gives no row; an + * assistant reply updated to name pull/9 gives none; a retracted reply keeps its PR. + * - Tier: unit (node:test, in-memory SQL, the desktop PR store; no account, network or engine). + * The comparison uses the two calls the desktop createMessage makes for PR references (writeMessageRow, then + * trackMessagePrRefs): localDb/ipc/messages.ts itself imports Electron and does not load under Node. + */ +function prRefsDb(t) { + const database = sessionListDb(t); + for (const table of [sessionPrRefs, migrationMeta]) { + database.sqlite.exec(`CREATE TABLE "${getTableName(table)}" (${Object.values(getTableColumns(table)) + .map(column => `"${column.name}" ${column.getSQLType()}`).join(',')})`); + } + database.sqlite.exec(`CREATE UNIQUE INDEX pr_identity ON session_pr_refs(session_id,provider,host,owner,repo,pr_number); + CREATE UNIQUE INDEX message_delivery ON messages(session_id,client_id); + INSERT INTO sessions(id,source,status,created_at,updated_at) VALUES ('task','desktop','active',0,1)`); + const client = createDbClientForHandle({ db: database.sqlite, drizzle: database.db }); + const refs = () => database.sqlite.prepare(`SELECT provider,host,owner,repo,pr_number AS pr,url,association_source AS source + FROM session_pr_refs WHERE removed_at IS NULL ORDER BY provider,pr_number`).all(); + return { ...database, client, refs }; +} +// The record is fire-and-forget, as on the desktop; better-sqlite3 settles it within a few turns. +const settle = async () => { for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve)); }; +const prText = 'see https://github.com/o/r/pull/7 and https://gitlab.com/g/p/-/merge_requests/3, again https://github.com/o/r/pull/7'; + +test('Host message writes record task PR references as the desktop does, only into the writing owner', async t => { + const host = prRefsDb(t); + setCurrentDbClient(host.client, 'isolated'); + t.after(() => clearCurrentDbClient(host.client)); + const write = createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish: () => {} }); + await write('task', { clientId: 'u1', role: 'user', content: prText, createdAt: 1000 }, { shouldBroadcast: () => false }); + await write('task', { clientId: 't1', role: 'tool_result', content: 'https://github.com/o/r/pull/99', createdAt: 1001 }); + await settle(); + const hostRows = host.refs(); + assert.deepEqual(hostRows.map(row => `${row.provider}:${row.owner}/${row.repo}#${row.pr}`), ['github:o/r#7', 'gitlab:g/p#3']); + + // The desktop createMessage's PR steps on the same input, in another database. + const desktop = prRefsDb(t); + const { writeMessageRow } = await import('../../desktop/src/main/localDb/messageWrite.ts'); + const { messageToCamel } = await import('../../desktop/src/main/localDb/mapper.ts'); + const { trackMessagePrRefs } = await import('../../desktop/src/main/localDb/messagePrRefs.ts'); + clearCurrentDbClient(host.client); + setCurrentDbClient(desktop.client, 'isolated'); + t.after(() => clearCurrentDbClient(desktop.client)); + for (const input of [{ clientId: 'u1', role: 'user', content: prText, createdAt: 1000 }, + { clientId: 't1', role: 'tool_result', content: 'https://github.com/o/r/pull/99', createdAt: 1001 }]) { + const { row } = await writeMessageRow(desktop.client, 'task', input); + trackMessagePrRefs(desktop.client, messageToCamel(row)); + } + await settle(); + assert.deepEqual(hostRows, desktop.refs()); + + // A switch right after the write: the record stays with the owner that wrote, never the next one. + const next = prRefsDb(t); + clearCurrentDbClient(desktop.client); + setCurrentDbClient(host.client, 'isolated'); + await write('task', { clientId: 'u2', role: 'user', content: 'https://github.com/o/r/pull/8', createdAt: 1002 }); + clearCurrentDbClient(host.client); + setCurrentDbClient(next.client, 'next'); + t.after(() => clearCurrentDbClient(next.client)); + await settle(); + assert.deepEqual(next.refs(), []); +}); + +test('Host reply corrections and retractions recompute task PR references as the desktop does', async t => { + const db = prRefsDb(t); + setCurrentDbClient(db.client, 'isolated'); + t.after(() => clearCurrentDbClient(db.client)); + const owner = getCurrentDbClientSnapshot(); + const publish = () => {}; + const history = createHostEventPersistence({ getOwner: getCurrentDbClientSnapshot, + isCurrent: () => getCurrentDbClientSnapshot() === owner, + persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish }), + publish, onPersistenceError: error => { throw error; } }); + history.noteSessionAgentKind('task', 'cc'); + history.noteTurnStarted('task'); + const session = { id: 'task', workDir: '/tmp', remoteHostId: null }; + const emit = (type, data) => history.event(session, { type, data }); + const numbers = () => db.refs().map(row => row.pr); + + // The streamed draft names no PR (a tool call stores it); the final full text does: a correction of + // the original row. + emit('text', { text: 'working on it', agentMessageId: 'reply-1' }); + emit('tool_use', { toolUseId: 'read-1', toolName: 'Read', input: { path: 'file.txt' } }); + emit('tool_result', { toolUseIds: ['read-1'], summary: 'https://github.com/o/r/pull/99' }); + await history.drain(); + assert.equal(db.sqlite.prepare("SELECT count(*) AS n FROM messages WHERE role='assistant'").get().n, 1); + await settle(); + assert.deepEqual(numbers(), []); + emit('text', { text: 'opened https://github.com/o/r/pull/9', isFinal: true, isFullText: true, agentMessageId: 'reply-1' }); + await history.drain(); + assert.deepEqual(numbers(), [9]); + + // An empty authoritative final retracts the reply, and with it the PR only it mentioned. + emit('text', { text: '', isFinal: true, isFullText: true, agentMessageId: 'reply-1' }); + await history.drain(); + assert.equal(history.hasFailedWrites(), false); + assert.equal(db.sqlite.prepare("SELECT count(*) AS n FROM messages WHERE role='assistant'").get().n, 0); + assert.deepEqual(numbers(), []); +}); + +// Release table 甲 (the PR reference gap's family): the desktop updateMessageContent releases, on a final +// correction, the images of the original content that no live message uses any more +// (reconcileAssistantDerivedState → reconcileAssistantMediaRefs). The Host only committed the new content's +// references, so a picture the correction removed stayed on the task until it was deleted. Same unit tier +// and entry as above (the event stream); the image is a ledger row only, no blob is read. +test('a Host reply correction releases the images it no longer shows, as the desktop does', async t => { + const db = prRefsDb(t); + db.sqlite.exec(`CREATE TABLE "${getTableName(mediaRefs)}" (${Object.values(getTableColumns(mediaRefs)) + .map(column => `"${column.name}" ${column.getSQLType()}`).join(',')})`); + setCurrentDbClient(db.client, 'isolated'); + t.after(() => clearCurrentDbClient(db.client)); + const owner = getCurrentDbClientSnapshot(); + const publish = () => {}; + const history = createHostEventPersistence({ getOwner: getCurrentDbClientSnapshot, + isCurrent: () => getCurrentDbClientSnapshot() === owner, + persistMessage: createHostMessageStore({ getOwner: getCurrentDbClientSnapshot, publish }), + publish, onPersistenceError: error => { throw error; } }); + history.noteSessionAgentKind('task', 'cc'); + history.noteTurnStarted('task'); + const session = { id: 'task', workDir: '/tmp', remoteHostId: null }; + const emit = (type, data) => history.event(session, { type, data }); + const kept = 'b'.repeat(64), dropped = 'c'.repeat(64); + const attached = () => db.sqlite.prepare("SELECT hash FROM media_refs WHERE ref_kind='session-attachment' AND ref_id='task' ORDER BY hash").all() + .map(row => row.hash); + + emit('text', { text: `![a](cindy-media://blobs/${kept}.png) ![b](cindy-media://blobs/${dropped}.png)`, agentMessageId: 'reply-1' }); + emit('tool_use', { toolUseId: 'read-1', toolName: 'Read', input: { path: 'file.txt' } }); + emit('tool_result', { toolUseIds: ['read-1'], summary: 'done' }); + await history.drain(); + const ref = db.sqlite.prepare("INSERT INTO media_refs(id,hash,ref_kind,ref_id) VALUES (?,?,'session-attachment','task')"); + for (const hash of [kept, dropped]) if (!attached().includes(hash)) ref.run(`ref-${hash[0]}`, hash); + assert.deepEqual(attached(), [kept, dropped]); + + emit('text', { text: `![a](cindy-media://blobs/${kept}.png) only`, isFinal: true, isFullText: true, agentMessageId: 'reply-1' }); + await history.drain(); + assert.equal(history.hasFailedWrites(), false); + assert.deepEqual(attached(), [kept]); +}); diff --git a/apps/host/src/start-failure.ts b/apps/host/src/start-failure.ts new file mode 100644 index 00000000000..62def1c86c2 --- /dev/null +++ b/apps/host/src/start-failure.ts @@ -0,0 +1,49 @@ +import { AuthApiError } from '@cindy/auth-client'; +import { isDefinitiveRefreshError } from '../../desktop/src/main/authRefreshError.js'; +import { OwnerDatabaseError } from '../../desktop/src/main/localDb/startupCore.js'; +import type { HostStartFailureReason } from '../../desktop/src/shared/hostStartFailure.js'; +import { HostProfileInUseError } from './agent/profile-coexistence.js'; +import { HostRefreshDeferredError, HostSessionMissingError } from './auth/refresh.mjs'; +import { HostCrossRegionPersonalAccountError } from './auth/region-policy.js'; + +/** The saved session's account is not the account of the data this Host opens. */ +export class HostAccountMismatchError extends Error { + constructor() { + super('The signed-in account does not match the active Host profile'); + this.name = 'HostAccountMismatchError'; + } +} + +/** There is account data but no saved session: an ordinary signed-out start, not a failure. */ +export class HostSignInRequiredError extends Error { + constructor() { + super('Sign in with `cindy-host login` before opening account data'); + this.name = 'HostSignInRequiredError'; + } +} + +/** A transport failure of the auth client (no response): the sign-in service was not reached. */ +function isSignInServiceUnreachable(error: unknown): boolean { + if (error instanceof HostRefreshDeferredError) return error.networkFailure; + return error instanceof AuthApiError && error.statusCode === 0 + && (error.code === 'NETWORK_ERROR' || error.code === 'REQUEST_TIMEOUT'); +} + +/** + * Why a start failed, for the windows (auth state `hostUnavailable`), or null when the start ended as an + * ordinary signed-out state: no saved session, a session the server rejected or that is gone, a personal + * account of another region. The same three are what ends a session at runtime (main.ts refreshAuthSession). + * Decided only from error types and explicit codes, never from message text: the text can carry paths, + * pids or account details and stays in `runtime.detail`. + */ +export function classifyHostStartFailure(error: unknown): HostStartFailureReason | null { + if (error instanceof HostSignInRequiredError || error instanceof HostSessionMissingError + || error instanceof HostCrossRegionPersonalAccountError || isDefinitiveRefreshError(error)) return null; + if (error instanceof HostProfileInUseError) return 'HOST_PROFILE_IN_USE_BY_DESKTOP'; + if (error instanceof HostAccountMismatchError) return 'HOST_ACCOUNT_MISMATCH'; + if (error instanceof OwnerDatabaseError) { + return error.code === 'DB_SCHEMA_LOCKED' ? 'HOST_DATABASE_LOCKED' : 'HOST_DATABASE_UNAVAILABLE'; + } + if (isSignInServiceUnreachable(error)) return 'HOST_SIGN_IN_SERVICE_UNREACHABLE'; + return 'HOST_START_FAILED'; +} diff --git a/apps/host/src/startup-account.test.mjs b/apps/host/src/startup-account.test.mjs index 2164a1137a2..009220bba00 100644 --- a/apps/host/src/startup-account.test.mjs +++ b/apps/host/src/startup-account.test.mjs @@ -1,12 +1,35 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { readFileSync } from 'node:fs'; +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import ts from 'typescript'; import { mapMembershipToAuthUser } from '../../desktop/src/shared/authUser.ts'; import { resolveSessionDevice, canRegisterHostDevice } from './auth/device-identity.mjs'; import { AUTH_SESSION_KEY } from '../../desktop/src/main/authCredentialKeys.ts'; import { resolveRuntimeDeviceId } from '../../desktop/src/main/deviceId.ts'; -import { decodeAccessTokenOrgSlug } from '../../desktop/src/main/authTokenClaims.ts'; +import { accessTokenRefreshDelayMs, decodeAccessTokenOrgSlug } from '../../desktop/src/main/authTokenClaims.ts'; +import { createServer } from 'node:http'; +import { AuthApiError, CindyAuthClient as RealAuthClient, parseAuthSessionRecord, serializeAuthSessionRecord } from '@cindy/auth-client'; +import { assertHostSessionRegion } from './auth/region-policy.ts'; +import { HostRefreshDeferredError, HostSessionMissingError, refreshHostSession as realRefreshHostSession } from './auth/refresh.mjs'; +import { AuthRefreshBackoff } from '../../desktop/src/main/authRefreshBackoff.ts'; +import { isDefinitiveRefreshError } from '../../desktop/src/main/authRefreshError.ts'; +import { HostCrossRegionPersonalAccountError } from './auth/region-policy.ts'; +import { projectAdoptedSession } from './credentials/session.mjs'; +import { OwnerDatabaseError } from '../../desktop/src/main/localDb/startupCore.ts'; +import { createDesktopScanner, HostProfileInUseError, nodeProfileScanPorts } from './agent/profile-coexistence.ts'; +import { spawn } from 'node:child_process'; +import { request as httpRequest } from 'node:http'; +import { classifyHostStartFailure, HostAccountMismatchError, HostSignInRequiredError } from './start-failure.ts'; +import { projectHostAuthState } from './auth-state.ts'; +import { createHostServer } from './server.mjs'; +import { once } from 'node:events'; +import { createInterface } from 'node:readline'; +import { pathToFileURL } from 'node:url'; +import { createSourceElectronTree } from './test-support/source-electron-tree.mjs'; +import { lifoCleanup } from './test-support/cleanup.mjs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; import { retainDbClient, waitForRetainedDbClient } from '../../desktop/src/main/localDb/client/pendingOperations.ts'; // Unit regression: run the real startup/auth functions with in-memory network, @@ -48,31 +71,41 @@ let closeStorage = null, sessionStorage = null; let account = { authenticated: false, realm: 'global' }; const runtime = { owner: null }; ${functions.join('\n')} -return { start: ensureRuntime, resolve: resolveAccountUser, token: () => currentSessionToken, close: () => closeStorage() }; +return { start: ensureRuntime, resolve: resolveAccountUser, token: () => currentSessionToken, account: () => account, runtime, lease: () => runtimeLease, close: () => closeStorage() }; `, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText; function setup(overrides = {}) { const opens = []; + const steps = []; const deps = { mapMembershipToAuthUser, decodeAccessTokenOrgSlug, resolveRuntimeDeviceId, resolveSessionDevice, canRegisterHostDevice, AUTH_SESSION_KEY, + waitForRetainedDbClient, resolveHostDataDir: () => 'isolated-test-profile', - configureHostOwner: () => {}, + configureHostOwner: ({ ownerId }) => { steps.push(`owner:${ownerId}`); }, + // Row 25 (25a): the Host reads the Skill projection boundary for the owner it just configured. + observeSkillProjectionBoundary: (ownerId) => { steps.push(`boundary:${ownerId}`); return 'stable'; }, acquireHostRuntimeLease: () => ({ held: true, release() {} }), + // No desktop on the profile (coexistence plan A); the refusal below scans a real one. + createDesktopScanner: () => async () => [], hostLog: { info() {} }, OwnerDatabaseError, HostProfileInUseError, + HostAccountMismatchError, HostSignInRequiredError, readAdoptedSessionState: async () => ({ authenticated: true, realm: 'global' }), - openOwnerDatabase: async (args) => { opens.push(args); throw new Error('database opened'); }, + openOwnerDatabase: async (args) => { opens.push(args); steps.push('open'); throw new Error('database opened'); }, path: { join: (...parts) => parts.join('/') }, layout: { packaged: false, drizzleDir: 'desktop/drizzle', sqliteVecPath: 'desktop/vec0' }, process, resolveHostRegion: () => 'global', readAuthEndpoints: () => ({ authApiBaseUrl: 'https://example.invalid' }), createCredentialStore: async () => ({ read: () => null }), createRequire: () => () => ({ machineIdSync: () => 'test-device' }), CindyAuthClient: class { async getMe() { return { membership: { id: 'account-b' } }; } }, refreshHostSession: async () => ({ sessionToken: 'synthetic-test-value' }), + // The account-vault lock of the profile (auth/refresh.mjs); the cases here hold no other process. + hostAccountVaultLock: () => task => task(), ACCOUNT_DEFAULT_MODEL: 'test-model', ACCOUNT_DEFAULT_EFFORT: 'medium', // The former startup refresh swallowed mismatch errors and still opened storage. refreshAuthSession: async () => false, + assertHostSessionRegion, hostPackageRegion: () => 'global', hostAuthFetch: () => { throw new Error('no network in this harness'); }, ...overrides, }; // import.meta.url is only passed to the injected createRequire stub. const code = compiled.replaceAll('import.meta.url', "'file:///test/main.ts'"); - return { ...new Function(...Object.keys(deps), code)(...Object.values(deps)), opens }; + return { ...new Function(...Object.keys(deps), code)(...Object.values(deps)), opens, steps }; } test('startup rejects a different signed-in owner before opening storage', async () => { @@ -87,6 +120,8 @@ test('matching owner authentication proceeds to its own database', async () => { await assert.rejects(h.start('account-b'), /database opened/); assert.equal(h.opens.length, 1); assert.equal(h.opens[0].ownerId, 'account-b'); + // Read after the owner is configured (the boundary path follows that profile), before storage. + assert.deepEqual(h.steps, ['owner:account-b', 'boundary:account-b', 'open']); }); test('an explicit owner cannot open private data without a verified login', async () => { @@ -95,3 +130,742 @@ test('an explicit owner cannot open private data without a verified login', asyn assert.deepEqual(h.opens, []); assert.equal(h.token(), null); }); + +/* + * H-2 (release table; user decision 2026-11-17 “和桌面版一致”): adopting a stored session (a + * Desktop profile's `AUTH_SESSION_KEY` record) applies the Desktop's cold-start and runtime-refresh + * rule. Production entry: main.ts's ensureRuntime and resolveAccountUser, with the real + * CindyAuthClient, refreshHostSession and session projection against two fake auth servers. + * Gap: the cases above stub the auth client and never carry an account kind or a realm. + * Minimal failure: global package, stored cn personal session → must stay signed out, no database. + * Tier: unit (loopback HTTP only). + */ +async function adoptStoredSession(packageRegion, sessionRealm, kind) { + const hits = []; + const servers = {}; + const memberId = `fixture-${sessionRealm}-member`; + for (const region of ['cn', 'global']) { + const server = createServer((request, response) => { + hits.push(`${region} ${request.url}`); + const membership = { id: memberId, kind, role: 'owner', displayName: 'Fixture', email: null, + orgId: kind === 'org' ? 'fixture-org' : null, orgName: kind === 'org' ? 'Fixture Org' : null }; + const json = (value) => response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(value)); + if (request.url === '/api/auth/refresh') return json({ accessToken: 'fixture-access-value', refreshToken: `fixture-rotated-${region}`, membership }); + if (request.url === '/api/me') return json({ membership, passportId: 'fixture-passport', identities: [membership] }); + return response.writeHead(404).end('{}'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + servers[region] = { server, url: `http://127.0.0.1:${server.address().port}` }; + } + // The record exactly as the Desktop writes it (no Host device binding). + const records = new Map([[AUTH_SESSION_KEY, serializeAuthSessionRecord(sessionRealm, 'fixture-desktop-refresh')]]); + const store = { read: (key) => records.get(key) ?? null, write: (key, value) => records.set(key, value) }; + const h = setup({ + createCredentialStore: async () => store, + readAdoptedSessionState: async () => projectAdoptedSession(store), + readAuthEndpoints: (realm) => ({ authApiBaseUrl: servers[realm].url }), + CindyAuthClient: RealAuthClient, refreshHostSession: realRefreshHostSession, hostAuthFetch: (input, init) => fetch(input, init), + hostPackageRegion: () => packageRegion, + }); + const close = () => Promise.all(Object.values(servers).map(({ server }) => new Promise((resolve) => server.close(resolve)))); + return { h, hits, memberId, stored: () => parseAuthSessionRecord(records.get(AUTH_SESSION_KEY)), close }; +} + +test('an adopted cross-region personal session stays signed out; an organization session is used', async () => { + for (const [packageRegion, sessionRealm, kind, adopted] of [ + ['global', 'cn', 'personal', false], + ['cn', 'global', 'personal', false], + ['global', 'cn', 'org', true], + ['cn', 'global', 'org', true], + ['global', 'global', 'personal', true], + ]) { + const label = `package ${packageRegion}, stored ${sessionRealm} ${kind}`; + const run = await adoptStoredSession(packageRegion, sessionRealm, kind); + try { + if (adopted) { + await assert.rejects(run.h.start(run.memberId), /database opened/, label); + assert.equal(run.h.opens[0]?.ownerId, run.memberId, label); + assert.equal(run.h.token(), 'fixture-access-value', label); + assert.equal(run.h.account().realm, sessionRealm, label); + } else { + await assert.rejects(run.h.start(run.memberId), (error) => error.code === 'HOST_CROSS_REGION_PERSONAL_ACCOUNT', label); + assert.deepEqual(run.h.opens, [], `${label}: no account database is opened`); + assert.equal(run.h.token(), null, `${label}: the session is not adopted`); + // Cleared, as the Desktop resets to its build realm; an empty realm is what makes the web + // shim block every statistics collector (甲 21). + assert.deepEqual(run.h.account(), { authenticated: false, realm: null }, label); + } + // As the Desktop: the rotated token stays in the record of its own region either way. + assert.deepEqual([run.stored()?.realm, run.stored()?.refreshToken], [sessionRealm, `fixture-rotated-${sessionRealm}`], label); + assert.ok(run.hits.length > 0 && run.hits.every((hit) => hit.startsWith(`${sessionRealm} `)), label); + } finally { + await run.close(); + } + } +}); + +// 测试价值 +// - 生产入口:main.ts 的 ensureRuntime(本文件按源码取出并注入端口),用真的 createDesktopScanner 扫一个 +// 临时 profile 的 `.dev-instances`;登记的是一个活着的子进程。 +// - 规则:并存方案 A(审核方 2026-11-17 定)。运行时租约只挡第二个 Host;同一 profile 上有开库的桌面时, +// Host 启动被拒:释放租约、停在 blocked、不读账号、不开库,也不自动重试。没有 `runtime` 字段的记录(旧版桌面) +// 按开库处理;`runtime: 'client'` 的记录(Host 的客户端)不挡。 +// - 现有覆盖缺口:上面的用例只覆盖账号核对;之前 Host 看不到桌面。 +// - 最小失败输入:一份没有 runtime 字段、PID 活着的登记记录。tier:unit(一个空转子进程,按 PID 结束)。 +test('a desktop that opens the profile refuses the start: lease released, blocked, nothing read or opened', async t => { + const profile = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-coexistence-start-')); + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1 << 30)'], { stdio: 'ignore' }); + await once(child, 'spawn'); + t.after(async () => { + if (child.exitCode === null && child.signalCode === null) { const exited = once(child, 'exit'); child.kill(); await exited; } + rmSync(profile, { recursive: true, force: true }); + }); + mkdirSync(path.join(profile, '.dev-instances')); + const record = { schemaVersion: 1, pid: child.pid, startedAtMs: Date.now(), userDataDir: profile, state: 'ready', passive: false }; + const recordFile = path.join(profile, '.dev-instances', `${child.pid}.json`); + writeFileSync(recordFile, JSON.stringify(record)); + let released = 0; + let reads = 0; + const ports = { + resolveHostDataDir: () => profile, createDesktopScanner, + acquireHostRuntimeLease: () => ({ held: true, release() { released += 1; } }), + readAdoptedSessionState: async () => { reads += 1; return { authenticated: true, realm: 'global' }; }, + }; + const refused = setup(ports); + await assert.rejects(refused.start('account-b'), + error => error instanceof HostProfileInUseError && error.code === 'HOST_PROFILE_IN_USE_BY_DESKTOP' && error.message.includes(`pid ${child.pid}`)); + assert.equal(released, 1, 'the runtime lease is released'); + assert.equal(refused.lease(), null); + assert.equal(reads, 0, 'no account read'); + assert.deepEqual(refused.opens, [], 'no database opened'); + assert.equal(refused.runtime.state, 'blocked'); + assert.deepEqual(refused.runtime.coexistence, { state: 'desktop-running', desktops: [child.pid] }); + + // A client of a Host (runtime: 'client') on the same profile never opens its database: the start goes on. + writeFileSync(recordFile, JSON.stringify({ ...record, runtime: 'client' })); + const allowed = setup(ports); + await assert.rejects(allowed.start('account-b'), /database opened/); + assert.equal(allowed.opens.length, 1); +}); + +// A slow OS lookup is distinguishable from a live desktop only at startup. Run the real +// startup/lease path against changing profile records with an injected OS and clock. +function uncertainDesktopStart(t, betweenRounds, duringLookup) { + const profile = mkdtempSync(path.join(os.tmpdir(), 'host-startup-identity-')); + t.after(() => rmSync(profile, { recursive: true, force: true })); + const registry = path.join(profile, '.dev-instances'); + mkdirSync(registry); + const alive = new Set([41]); + const identities = new Map(); + const write = pid => writeFileSync(path.join(registry, `${pid}.json`), JSON.stringify({ pid, startedAtMs: 1000, userDataDir: profile })); + write(41); + const waits = [], queries = [], rounds = []; + let elapsed = 0, releases = 0; + // Advance both clocks so a wall-clock watchdog racing the scan also fires in these tests. + t.mock.timers.enable({ apis: ['setTimeout'] }); + const advance = ms => { elapsed += ms; t.mock.timers.tick(ms); }; + const fixture = { alive, identities, write, registry, advance }; + const clock = { now: () => elapsed, sleep: async ms => { + waits.push(ms); advance(ms); + betweenRounds?.(fixture); + } }; + const ports = { ...nodeProfileScanPorts, selfPid: () => 99, isPidAlive: pid => alive.has(pid), + readProcessIdentities: async pids => { + queries.push([...pids]); + duringLookup?.(fixture, queries.length); + return new Map(identities); + } }; + const h = setup({ resolveHostDataDir: () => profile, createDesktopScanner: dir => createDesktopScanner(dir, ports, clock), + acquireHostRuntimeLease: () => ({ held: true, release() { releases++; } }), + hostLog: { info: (_message, fields) => rounds.push(fields) } }); + return { h, waits, queries, rounds, releases: () => releases }; +} + +test('startup rechecks unknown identity and opens when the process has ended', async t => { + const f = uncertainDesktopStart(t, ({ alive }) => alive.delete(41)); + await assert.rejects(f.h.start('account-b'), /database opened/); + assert.equal(f.h.opens.length, 1); + assert.deepEqual(f.waits, [500]); + assert.equal(f.releases(), 0); +}); + +test('startup stops rechecking as soon as a desktop identity is confirmed', async t => { + const f = uncertainDesktopStart(t, ({ identities }) => identities.set(41, { startedAtMs: 1000, command: 'Cindy' })); + await assert.rejects(f.h.start('account-b'), { code: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }); + assert.deepEqual(f.queries, [[41], [41]]); + assert.deepEqual(f.waits, [500]); + assert.deepEqual(f.h.opens, []); + assert.equal(f.releases(), 1); +}); + +test('startup exhausts four unknown identities and releases the lease', async t => { + const f = uncertainDesktopStart(t); + await assert.rejects(f.h.start('account-b'), { code: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }); + assert.deepEqual(f.queries, [[41], [41], [41], [41]]); + assert.deepEqual(f.waits, [500, 1000, 2000]); + assert.equal(f.releases(), 1); + assert.equal(f.h.lease(), null); + assert.deepEqual(f.h.opens, []); + assert.deepEqual(f.rounds.map(r => r.result), Array(4).fill('unknown')); +}); + +test('startup refuses a new desktop registration between identity checks', async t => { + const f = uncertainDesktopStart(t, ({ alive, write }) => { alive.delete(41); alive.add(42); write(42); }); + await assert.rejects(f.h.start('account-b'), { code: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }); + assert.deepEqual(f.queries, [[41], [42]]); + assert.deepEqual(f.waits, [500]); + assert.deepEqual(f.h.runtime.coexistence.desktops, [42]); + assert.deepEqual(f.h.opens, []); +}); + +test('startup keeps a vanished record blocked until the OS proves PID reuse', async t => { + let count = 0; + const f = uncertainDesktopStart(t, ({ registry, identities }) => { + if (++count === 1) rmSync(path.join(registry, '41.json')); + else identities.set(41, { startedAtMs: 60_000, command: 'unrelated program' }); + }); + await assert.rejects(f.h.start('account-b'), /database opened/); + assert.deepEqual(f.waits, [500, 1000]); + assert.equal(f.h.opens.length, 1); +}); + +test('startup retains an unidentified PID if the record disappears during the first lookup', async t => { + const f = uncertainDesktopStart(t, undefined, ({ registry }) => rmSync(path.join(registry, '41.json'), { force: true })); + await assert.rejects(f.h.start('account-b'), { code: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }); + assert.equal(f.queries.length, 4); + assert.deepEqual(f.h.opens, []); + assert.equal(f.releases(), 1); +}); + +test('startup refuses without another lookup when a delayed wake exhausts the time budget', async t => { + const f = uncertainDesktopStart(t, ({ advance }) => advance(10_000)); + await assert.rejects(f.h.start('account-b'), { code: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }); + assert.deepEqual(f.queries, [[41]]); + assert.deepEqual(f.rounds.map(r => r.result), ['unknown', 'deadline']); + assert.equal(f.releases(), 1); +}); + +// A suspend or a slow OS lookup can finish after the retry budget. A completed +// scan still decides whether the real startup path opens storage or releases its lease. +test('startup opens after a slow first scan finds no desktop', async t => { + const f = uncertainDesktopStart(t, undefined, ({ advance, alive }) => { + advance(12_000); + alive.delete(41); + }); + await assert.rejects(f.h.start('account-b'), /database opened/); + assert.equal(f.h.opens.length, 1); + assert.deepEqual(f.waits, []); +}); + +test('startup reports the live desktop found by a slow first scan', async t => { + const f = uncertainDesktopStart(t, undefined, ({ advance, identities }) => { + advance(12_000); + identities.set(41, { startedAtMs: 1000, command: 'Cindy' }); + }); + await assert.rejects(f.h.start('account-b'), { code: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }); + assert.deepEqual(f.h.runtime.coexistence.desktops, [41]); + assert.equal(f.releases(), 1); + assert.deepEqual(f.h.opens, []); + assert.deepEqual(f.waits, []); +}); + +test('startup opens when a slow retry finds the process has ended', async t => { + const f = uncertainDesktopStart(t, undefined, ({ advance, alive }, round) => { + if (round === 2) { + advance(12_000); + alive.delete(41); + } + }); + await assert.rejects(f.h.start('account-b'), /database opened/); + assert.equal(f.h.opens.length, 1); + assert.deepEqual(f.waits, [500]); +}); + +test('startup refuses an unknown identity before sleeping past the retry budget', async t => { + const f = uncertainDesktopStart(t, undefined, ({ advance }) => advance(9_800)); + await assert.rejects(f.h.start('account-b'), { code: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }); + assert.deepEqual(f.waits, []); + assert.deepEqual(f.h.runtime.coexistence.desktops, [41]); + assert.equal(f.releases(), 1); +}); + +/* + * 测试价值(C,审核方 2026-11-17 定的第 6 步与“四个入口走同一个函数”) + * - 生产入口:main.ts 的 refreshAuthSession / performAuthRefresh / scheduleAuthRefresh / deferAuthRefresh + * 与 resolveAccountUser(按源码取出),用真的 refreshHostSession、AuthRefreshBackoff 与 + * accessTokenRefreshDelayMs,内存里的凭据记录,假的账号服务。 + * - 规则:续期排在 access token 的 exp 减 300 秒(与桌面 scheduleRefresh 同一个函数),不再是固定 30 分钟; + * 暂时失败按桌面的退避重试;只有确定失败才结束会话、不再排;同时到来的调用方共用一次续期。 + * - 现有覆盖缺口:之前每 30 分钟一次,失败后不重排;没有用例看排期。 + * - 最小失败输入:exp 在一小时后的 access token。tier:unit(node:test 的假时钟)。 + */ +const renewalSource = ['refreshAuthSession', 'clearAuthRefreshTimer', 'scheduleAuthRefresh', 'deferAuthRefresh', + 'armAuthRefreshTimer', 'performAuthRefresh', 'endAuthRefreshes', 'resolveAccountUser']; +const renewalConstants = ['MAX_TIMER_DELAY_MS', 'DUE_ACCESS_TOKEN_RENEWAL_DELAY_MS']; +const renewalParts = []; +(function visitRenewal(node) { + if (ts.isFunctionDeclaration(node) && renewalSource.includes(node.name?.text)) renewalParts.push(node.getText(source)); + else if (ts.isVariableStatement(node) && node.declarationList.declarations.some(d => renewalConstants.includes(d.name.getText(source)))) + renewalParts.push(node.getText(source)); + else ts.forEachChild(node, visitRenewal); +})(source); +// The source is only compiled and run, never asserted on; a renamed function fails the harness here. +if (renewalParts.length !== renewalSource.length + renewalConstants.length) throw new Error('a renewal function is missing from main.ts'); +const renewalCompiled = ts.transpileModule(` +let currentSessionToken = null, accountUser = null, currentDeviceId = null, remoteIdentityReady = false; +let account = { authenticated: true, realm: 'global' }; +const runtime = { owner: null }; +let refreshTimer = null, authClosed = false, authRefreshFlight = null, authRefreshEpoch = 0; +const authRefreshBackoff = new AuthRefreshBackoff(() => Date.now(), () => 0); +${renewalParts.join('\n').replaceAll('import.meta.url', "'file:///test/main.ts'")} +return { refresh: refreshAuthSession, schedule: scheduleAuthRefresh, end: endAuthRefreshes, adopt: (token) => { currentSessionToken = token; }, + token: () => currentSessionToken, timer: () => refreshTimer }; +`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText; + +const fakeJwt = (payload) => ['{"alg":"none"}', JSON.stringify(payload), 'sig'].map((part, i) => (i < 2 ? Buffer.from(part).toString('base64url') : part)).join('.'); + +function renewalHarness(t, server) { + t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1_800_000_000_000 }); + const records = new Map([[AUTH_SESSION_KEY, serializeAuthSessionRecord('global', server.current())]]); + const store = { read: (key) => records.get(key) ?? null, write: (key, value) => records.set(key, value) }; + const invalidated = []; + const deps = { + mapMembershipToAuthUser, decodeAccessTokenOrgSlug, resolveRuntimeDeviceId, resolveSessionDevice, canRegisterHostDevice, AUTH_SESSION_KEY, + waitForRetainedDbClient, + resolveHostDataDir: () => 'isolated-test-profile', resolveHostRegion: () => 'global', hostPackageRegion: () => 'global', + readAuthEndpoints: () => ({ authApiBaseUrl: 'https://example.invalid' }), assertHostSessionRegion, hostAuthFetch: () => assert.fail('no network'), + createCredentialStore: async () => store, createRequire: () => () => ({ machineIdSync: () => 'test-device' }), + CindyAuthClient: class { refresh(token) { return server.refresh(token); } async getMe() { return { membership: server.membership, passportId: 'passport-a' }; } }, + refreshHostSession: realRefreshHostSession, hostAccountVaultLock: () => task => task(), + AuthRefreshBackoff, accessTokenRefreshDelayMs, isDefinitiveRefreshError, HostSessionMissingError, HostRefreshDeferredError, + HostCrossRegionPersonalAccountError, + eventHub: { publish() {} }, projectAuthState: () => ({}), + invalidateHostSession: async (reason) => { invalidated.push(reason); }, + }; + const h = new Function(...Object.keys(deps), renewalCompiled)(...Object.values(deps)); + const settle = async () => { for (let i = 0; i < 20; i++) await new Promise(resolve => setImmediate(resolve)); }; + return { ...h, invalidated, settle, stored: () => parseAuthSessionRecord(records.get(AUTH_SESSION_KEY))?.refreshToken }; +} + +/** A fake auth server: each renewal rotates the refresh token and issues an access token valid for an hour. */ +function renewalServer() { + let current = 'fixture-r0'; + let next = 0; + let failure = null; + const requests = []; + return { + requests, membership: { id: 'member-a', kind: 'personal', role: 'owner', displayName: 'Fixture', email: null, orgId: null, orgName: null }, + current: () => current, + fail(error) { failure = error; }, + async refresh(token) { + requests.push(Date.now()); + if (failure) throw failure; + if (token !== current) throw new AuthApiError('INVALID_REFRESH_TOKEN', 401, 'rotated'); + current = `fixture-r${++next}`; + return { accessToken: fakeJwt({ exp: Math.floor(Date.now() / 1000) + 3600 }), refreshToken: current, membership: this.membership }; + }, + }; +} + +test('the next renewal is armed at the access token\'s exp minus 300 s and goes through the one renewal', async (t) => { + const server = renewalServer(); + const h = renewalHarness(t, server); + const start = Date.now(); + h.adopt(fakeJwt({ exp: Math.floor(start / 1000) + 3600 })); + h.schedule(); + t.mock.timers.tick(3300_000 - 1); + await h.settle(); + assert.equal(server.requests.length, 0, 'not before exp - 300 s'); + t.mock.timers.tick(1); + await h.settle(); + assert.deepEqual(server.requests, [start + 3300_000]); + assert.equal(h.stored(), 'fixture-r1'); + // The new access token arms the next one, again at its exp minus 300 s. + t.mock.timers.tick(3300_000); + await h.settle(); + assert.deepEqual(server.requests, [start + 3300_000, start + 6600_000]); + // Callers at the same moment (the 401 retry, Device Link, /api/auth/refresh) share one renewal. + await Promise.all([h.refresh(), h.refresh(), h.refresh()]); + assert.equal(server.requests.length, 3); +}); + +// d (reviewer, 2026-11-17): a token without a numeric exp arms nothing, as on the desktop; the server +// API's 401 path still renews it. +test('a token without a numeric exp arms no renewal; the server API\'s 401 still renews', async (t) => { + const server = renewalServer(); + const h = renewalHarness(t, server); + h.adopt(fakeJwt({ sub: 'member-a' })); + h.schedule(); + assert.equal(h.timer(), null, 'nothing is armed'); + t.mock.timers.tick(24 * 3600_000); + await h.settle(); + assert.equal(server.requests.length, 0); + assert.equal(await h.refresh({ serverRejectedToken: true }), true, 'the 401 retry renews'); + assert.equal(server.requests.length, 1); + assert.ok(h.timer(), 'the renewed token has an exp and arms the next renewal'); +}); + +test('a renewal failing for now retries with the desktop\'s backoff; a definitive one ends the session and arms nothing', async (t) => { + const server = renewalServer(); + const h = renewalHarness(t, server); + server.fail(new AuthApiError('NETWORK_ERROR', 0, 'offline')); + assert.equal(await h.refresh(), false); + assert.ok(h.timer(), 'a retry is armed'); + assert.equal(await h.refresh(), false, 'a caller during the wait gets false'); + assert.equal(server.requests.length, 1, 'and sends nothing'); + t.mock.timers.tick(60_000); + await h.settle(); + assert.equal(server.requests.length, 2, 'retried after the first backoff step (1 minute here)'); + // As the desktop: after a network failure, the server API's 401 brings one attempt forward. + assert.equal(await h.refresh({ serverRejectedToken: true }), false, 'the network is still down'); + assert.equal(server.requests.length, 3, 'the 401 evidence sent one attempt at once'); + assert.equal(await h.refresh(), false, 'without new evidence, the wait holds'); + assert.equal(server.requests.length, 3); + server.fail(null); + t.mock.timers.tick(120_000); + await h.settle(); + assert.equal(server.requests.length, 4, 'the second step is 2 minutes'); + assert.equal(h.stored(), 'fixture-r1'); + assert.deepEqual(h.invalidated, []); + + server.fail(new AuthApiError('INVALID_REFRESH_TOKEN', 401, 'revoked')); + const pending = h.refresh(); + // The desktop's re-reads of the stored sources before a rejection counts (250 ms, then 1 s). + for (const step of [250, 1000]) { await h.settle(); t.mock.timers.tick(step); } + assert.equal(await pending, false); + assert.deepEqual(h.invalidated, ['account-unavailable']); + assert.equal(h.timer(), null, 'nothing is armed after a definitive failure'); +}); + +/* + * 甲 (2026-11-17): a failed or refused start now tells the windows why, as one fixed code in the auth state + * (`hostUnavailable`), so a window does not offer its own sign-in beside a Host that stays down. + * Production entry: the real errors of ensureRuntime / resolveAccountUser (this harness), the real + * classification (start-failure.ts, what main.ts's startup catch stores), the real projection + * (auth-state.ts) and the real `/api/auth/state` route (server.mjs + service.mjs). Gap: before, every + * failed start projected the same signed-out state as "no session". Minimal input: one failing start per + * reason, with a sentinel in the error text; an ordinary signed-out start. Tier: unit (loopback HTTP only). + */ +const SENTINEL = 'sentinel-detail-/Users/someone/pid-4242'; +const TOKEN = 'start-failure-test-token'; + +async function authStateAfter(t, error) { + const unavailable = classifyHostStartFailure(error); + const server = createHostServer({ + token: TOKEN, + probe: () => ({ status: 'ok' }), + me: () => ({ authenticated: false }), + getAuthState: () => projectHostAuthState({ account: { authenticated: false, realm: 'global' }, accountUser: null, + owner: null, generation: 1, deviceId: null, unavailable }), + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + t.after(() => server.close()); + const { port } = server.address(); + return new Promise((resolve, reject) => { + const req = httpRequest(`http://127.0.0.1:${port}/api/auth/state`, + { method: 'POST', headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' } }, response => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', chunk => { text += chunk; }); + response.on('end', () => resolve({ status: response.statusCode, text, body: JSON.parse(text) })); + }); + req.on('error', reject); + req.end('{}'); + }); +} + +const failedStart = (overrides, owner = 'account-b') => setup(overrides).start(owner).then(() => null, error => error); + +for (const [reason, start] of [ + ['HOST_ACCOUNT_MISMATCH', () => failedStart({}, 'account-a')], + ['HOST_PROFILE_IN_USE_BY_DESKTOP', () => failedStart({ createDesktopScanner: () => async () => [4242] })], + ['HOST_DATABASE_LOCKED', () => failedStart({ acquireHostRuntimeLease: () => ({ held: false, reason: SENTINEL }) })], + ['HOST_DATABASE_UNAVAILABLE', () => failedStart({ openOwnerDatabase: async () => { throw new OwnerDatabaseError('MIGRATE_FAILED', SENTINEL); } })], + // The auth client's own transport failures, typed: a renewal that got no response, and /me without one. + ['HOST_SIGN_IN_SERVICE_UNREACHABLE', () => failedStart({ refreshHostSession: async () => { + throw new HostRefreshDeferredError(`the renewal failed for now: ${SENTINEL}`, { networkFailure: true }); + } })], + ['HOST_SIGN_IN_SERVICE_UNREACHABLE', () => failedStart({ + CindyAuthClient: class { async getMe() { throw new AuthApiError('NETWORK_ERROR', 0, SENTINEL); } }, + })], + // A renewal deferred for another reason is not "unreachable", whatever its text says. + ['HOST_START_FAILED', () => failedStart({ refreshHostSession: async () => { + throw new HostRefreshDeferredError('the network of the vault lock is busy', { networkFailure: false }); + } })], + ['HOST_START_FAILED', () => failedStart({ openOwnerDatabase: async () => { throw new Error(SENTINEL); } })], +]) { + test(`a start that fails as ${reason} tells the windows that code and nothing of its text`, async t => { + const error = await start(); + assert.ok(error, 'the start failed'); + const response = await authStateAfter(t, error); + assert.equal(response.status, 200); + assert.deepEqual(response.body.hostUnavailable, { reason }); + assert.equal(response.body.authenticated, false); + assert.ok(!response.text.includes(SENTINEL), 'no error text in /api/auth/state'); + }); +} + +for (const [name, start] of [ + ['no saved session', () => failedStart({ readAdoptedSessionState: async () => ({ authenticated: false, realm: 'global' }) })], + ['the saved session is gone', () => failedStart({ refreshHostSession: async () => { throw new HostSessionMissingError(); } })], + ['the server rejected the session', () => failedStart({ refreshHostSession: async () => { + throw new AuthApiError('INVALID_REFRESH_TOKEN', 401, SENTINEL); + } })], + ['a personal account of another region', () => failedStart({ hostPackageRegion: () => 'cn', + CindyAuthClient: class { async getMe() { return { membership: { id: 'account-b', kind: 'personal' } }; } } })], +]) { + test(`an ordinary signed-out start (${name}) carries no start-failure reason`, async t => { + const error = await start(); + assert.ok(error, 'the start ended signed out'); + const response = await authStateAfter(t, error); + assert.equal('hostUnavailable' in response.body, false); + assert.equal(response.body.mode, 'signed-out'); + }); +} + +/** + * The environment of a test's `cindy-host serve` child, so that it reaches no real profile, sign-in or setting + * whatever terminal runs the test (a Cindy task terminal carries XDT_* and CINDY_* variables such as + * XDT_OFFICIAL_SHARED_PROFILE). Drops every XDT_ / CINDY_ variable and NODE_OPTIONS / NODE_PATH (any case: Windows + * keys are case-insensitive), points every home, application-data and temporary directory into `root`, then sets + * back only what the test passes. `bin` goes first on PATH (stand-in programs). + */ +function isolatedServeEnv(root, bin, set) { + const env = {}; + for (const [key, value] of Object.entries(process.env)) { + if (/^(XDT_|CINDY_)/i.test(key) || /^NODE_(OPTIONS|PATH)$/i.test(key)) continue; + env[key] = value; + } + const put = (key, value) => { + for (const existing of Object.keys(env)) if (existing.toUpperCase() === key.toUpperCase()) delete env[existing]; + env[key] = value; + }; + const dir = (name) => { const full = path.join(root, name); mkdirSync(full, { recursive: true }); return full; }; + const pathKey = Object.keys(process.env).find(key => key.toUpperCase() === 'PATH') ?? 'PATH'; + put('PATH', `${bin}${path.delimiter}${process.env[pathKey] ?? ''}`); + const home = dir('home'); + for (const key of ['HOME', 'USERPROFILE']) put(key, home); + const temp = dir('temp'); + for (const key of ['TMPDIR', 'TEMP', 'TMP']) put(key, temp); + put('APPDATA', dir('app-data')); + put('LOCALAPPDATA', dir('local-app-data')); + for (const [key, name] of [['XDG_CONFIG_HOME', 'xdg-config'], ['XDG_DATA_HOME', 'xdg-data'], ['XDG_CACHE_HOME', 'xdg-cache'], + ['XDG_STATE_HOME', 'xdg-state']]) put(key, dir(name)); + for (const [key, value] of Object.entries(set)) put(key, value); + return env; +} + +// Allow cold source-mode startup the same 90 seconds as the lifecycle acceptance. +const SOURCE_SERVE_ENDPOINT_TIMEOUT_MS = 90_000; + +function serveTimeoutMessage(what, stderr) { + const stderrTail = stderr.slice(-8192).trimEnd() || '(empty)'; + return `timed out waiting for ${what}\ncindy-host stderr tail:\n${stderrTail}`; +} + +// Integration: unlike tests with injected binaries, run the default source +// workers against the installed JS package with no dist executable. +test('source proxy and power workers report unavailable without an Electron binary', async t => { + const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-workers-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const { host, electron } = createSourceElectronTree(root); + const { createChromiumProxyHelper } = await import(pathToFileURL(path.join(host, 'src/chromium-proxy.ts'))); + const { preparePowerWorker } = await import(pathToFileURL(path.join(host, 'src/platform/assets.mjs'))); + const proxy = createChromiumProxyHelper({ profileDir: root }); + try { + await proxy.warmUp(); + assert.equal(proxy.state(), 'unavailable'); + await assert.rejects(preparePowerWorker(), { message: 'PLATFORM_MONITOR_UNAVAILABLE' }); + assert.equal(existsSync(path.join(electron, 'entry-ran')), false); + } finally { await proxy.close(); } +}); + +// Source serve e2e: an empty native vault used to run Electron's npm installer +// synchronously after publishing the endpoint. Start the real CLI, time the +// first client request, and observe all child-process launches up to refresh. +test('source serve keeps health responsive and refreshes an empty native profile without child processes', { + skip: !['darwin', 'win32'].includes(process.platform) && 'Linux uses Secret Service instead of Electron', + timeout: 120_000, +}, async t => { + t = lifoCleanup(t); + const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-no-electron-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + const { host, electron } = createSourceElectronTree(root); + const profile = path.join(root, 'profile'); + const launches = path.join(root, 'child-launches'); + writeFileSync(launches, ''); + const env = isolatedServeEnv(root, path.join(root, 'bin'), { + CINDY_HOST_DATA_DIR: profile, CINDY_HOST_PORT: '0', XDT_DEVICE_ID_OVERRIDE: 'synthetic-host', + HTTP_PROXY: 'http://127.0.0.1:9', HTTPS_PROXY: 'http://127.0.0.1:9', NO_PROXY: '127.0.0.1,localhost', + }); + const preload = path.join(host, 'monitor.mjs'); + // Initialize tsx's compiler before observing the application, even with a + // cold cache. Block and record attempts before they can start any process. + writeFileSync(path.join(host, 'warm.ts'), 'export const n: number = 1;'); + writeFileSync(preload, ` + import './warm.ts'; + import cp from 'node:child_process'; + import { syncBuiltinESMExports } from 'node:module'; + import { appendFileSync } from 'node:fs'; + function unexpected(command) { + appendFileSync(${JSON.stringify(launches)}, String(command?.file ?? command) + '\\n'); + throw new Error('unexpected child process'); + } + cp.ChildProcess.prototype.spawn = unexpected; + cp.spawnSync = cp.execSync = cp.execFileSync = unexpected; + syncBuiltinESMExports(); + `); + const serveStarted = performance.now(); + const child = spawn(process.execPath, ['--import', 'tsx', '--import', './src/loaders/register-raw.mjs', + '--import', './monitor.mjs', 'src/main.ts', 'serve'], { cwd: host, env, stdio: ['ignore', 'pipe', 'pipe'] }); + const exited = once(child, 'exit'); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', chunk => { stderr += chunk; }); + t.after(async () => { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); + await exited; + }); + const lines = createInterface({ input: child.stdout }); + let endpointTimer; + const baseUrl = await new Promise((resolve, reject) => { + endpointTimer = setTimeout(() => reject(new Error(serveTimeoutMessage('the endpoint', stderr))), + SOURCE_SERVE_ENDPOINT_TIMEOUT_MS - (performance.now() - serveStarted)); + lines.on('line', line => { + const match = /^cindy-host listening on (http:\/\/127\.0\.0\.1:\d+)$/.exec(line); + if (match) resolve(match[1]); + }); + exited.then(() => reject(new Error('serve exited before listening: ' + stderr)), reject); + }).finally(() => clearTimeout(endpointTimer)); + t.diagnostic(`Source serve spawn to endpoint: ${Math.ceil(performance.now() - serveStarted)} ms`); + const headers = { authorization: 'Bearer ' + readFileSync(path.join(profile, 'host-api-token'), 'utf8').trim() }; + const start = performance.now(); + const deadline = AbortSignal.timeout(1000); + const health = await fetch(baseUrl + '/health', { headers, signal: deadline }).catch(error => { + if (deadline.aborted) assert.fail('First /health response exceeded its 1000 ms deadline'); + throw error; + }); + assert.equal(health.status, 200); + await health.json(); + const elapsed = performance.now() - start; + assert.ok(elapsed < 1000, `/health took ${elapsed} ms`); + t.diagnostic(`First /health response including its body: ${Math.ceil(elapsed)} ms`); + const refresh = await fetch(baseUrl + '/api/auth/refresh', { method: 'POST', + headers: { ...headers, 'content-type': 'application/json' }, body: '{}' }); + assert.equal(readFileSync(launches, 'utf8'), ''); + assert.equal(existsSync(path.join(electron, 'entry-ran')), false); + assert.equal(refresh.status, 200); + assert.equal((await refresh.json()).ok, false); + // The missing-session callback completes asynchronously after the response. + const teardown = AbortSignal.timeout(5000); + while (true) { + const { runtime } = await (await fetch(baseUrl + '/health', { headers, signal: teardown })).json(); + if (runtime.detail?.startsWith('Sign-in expired')) break; + await new Promise(resolve => setTimeout(resolve, 20)); + } +}); + +/* + * Test value (reviewer 2026-11-18): the serve child of the next test cannot reach real data from any terminal. + * Production entry: the environment isolatedServeEnv builds, as a real child process reads it. Minimal input: + * variables a Cindy task terminal carries. Tier: unit (one short child process). + */ +test('the serve child environment carries no XDT_ or CINDY_ variable of the terminal and no real directory', async t => { + const planted = { XDT_OFFICIAL_SHARED_PROFILE: '/should/not/leak', CINDY_SOMETHING: 'leak', CINDY_HOST_DATA_DIR: '/should/not/leak' }; + const before = Object.fromEntries(Object.keys(planted).map(key => [key, process.env[key]])); + Object.assign(process.env, planted); + const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-serve-env-')); + t.after(() => { + for (const [key, value] of Object.entries(before)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } + rmSync(root, { recursive: true, force: true }); + }); + const env = isolatedServeEnv(root, path.join(root, 'bin'), { CINDY_HOST_DATA_DIR: path.join(root, 'profile') }); + const child = spawn(process.execPath, ['-e', 'process.stdout.write(JSON.stringify(process.env))'], { env, stdio: ['ignore', 'pipe', 'inherit'] }); + let out = ''; + child.stdout.on('data', chunk => { out += chunk; }); + await once(child, 'exit'); + const seen = JSON.parse(out); + const upper = Object.fromEntries(Object.entries(seen).map(([key, value]) => [key.toUpperCase(), value])); + assert.deepEqual(Object.keys(upper).filter(key => /^(XDT_|CINDY_)/.test(key)), ['CINDY_HOST_DATA_DIR']); + assert.equal(upper.CINDY_HOST_DATA_DIR, path.join(root, 'profile')); + assert.ok(!out.includes('/should/not/leak'), 'no planted value reaches the child'); + for (const key of ['HOME', 'USERPROFILE', 'TMPDIR', 'TEMP', 'TMP', 'APPDATA', 'LOCALAPPDATA', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', + 'XDG_CACHE_HOME', 'XDG_STATE_HOME']) { + assert.ok(upper[key]?.startsWith(root), `${key} is inside the temporary directory`); + } + assert.ok(upper.PATH.startsWith(path.join(root, 'bin') + path.delimiter)); +}); + +/* + * Test value (甲, reviewer 2026-11-18): the reason of a failed start survives a refresh. + * - Bug: a window in client mode calls /api/auth/refresh as it starts (authManager initialize). With no + * saved session that refresh ends the session (HostSessionMissingError), and the session's teardown + * disposed the runtime again and cleared the reason: the window was given a sign-in form while the Host + * stayed down (walked through on 2026-11-18). A session the server rejects takes the same branch of + * performAuthRefresh (the renewal case above asserts it reaches invalidateHostSession). + * - Production entry: the real `cindy-host serve` (main.ts) in a child process on a temporary profile, its + * runtime lease held by this process, so the start is refused as HOST_DATABASE_LOCKED. + * - Gap: the cases above build the state from a classified error; none runs a refresh after a failed start. + * - Not covered: a rejected saved session end to end. A saved session needs the system credential store + * (keychain or keyring) and the auth endpoint must be https; neither belongs in a unit run. + * - Credentials: no saved session, so no record is ever decrypted. On macOS and Windows the store only checks + * that a record file exists (credentials/store.mjs read; the native codec runs only to decrypt). On Linux + * building the store looks up the keyring at once (store.mjs createCredentialStore, secret-tool); a stand-in + * `secret-tool` first on PATH answers instead, so no real keyring is read and the session ends as elsewhere. + * - Environment: isolatedServeEnv (asserted by the test above). + * - Tier: unit (loopback HTTP and one child process; no network, nothing outside the temporary directory). + */ +test('a refresh after a failed start keeps the start-failure reason (no saved session)', async t => { + const { acquireHostRuntimeLease } = await import('./runtime-lock.ts'); + const root = mkdtempSync(path.join(os.tmpdir(), 'cindy-host-start-reason-')); + const profile = path.join(root, 'profile'); + mkdirSync(profile, { recursive: true, mode: 0o700 }); + const bin = path.join(root, 'bin'); + mkdirSync(bin); + writeFileSync(path.join(bin, 'secret-tool'), `#!${['', 'bin', 'sh'].join('/')}\necho cindy-host-start-reason-test-secret\n`, { mode: 0o755 }); + const lease = acquireHostRuntimeLease(profile, 'owner-locked'); + assert.equal(lease.held, true); + const hostDir = fileURLToPath(new URL('..', import.meta.url)); + const serveStarted = performance.now(); + const child = spawn(process.execPath, ['--import', 'tsx', '--import', './src/loaders/register-raw.mjs', 'src/main.ts', 'serve'], { + cwd: hostDir, stdio: ['ignore', 'ignore', 'pipe'], + env: isolatedServeEnv(root, bin, { CINDY_HOST_DATA_DIR: profile, CINDY_HOST_APP_DATA_DIR: path.join(root, 'app-data'), + CINDY_HOST_OWNER: 'owner-locked', CINDY_HOST_PORT: '0', XDT_DEVICE_ID_OVERRIDE: 'synthetic-host', CINDY_HOST_KEYRING_APPLICATION: 'cindy-host-start-reason-test', + // Anything that leaves the machine fails at once. + HTTP_PROXY: 'http://127.0.0.1:9', HTTPS_PROXY: 'http://127.0.0.1:9', NO_PROXY: '127.0.0.1,localhost', NODE_USE_ENV_PROXY: '1' }), + }); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', chunk => { stderr += chunk; }); + t.after(async () => { + if (child.exitCode === null) { child.kill('SIGTERM'); await once(child, 'exit'); } + lease.release(); + rmSync(root, { recursive: true, force: true }); + }); + const until = async (read, what, deadline = null) => { + for (let i = 0; deadline === null ? i < 600 : performance.now() < deadline; i++) { + if (child.exitCode !== null) assert.fail(`cindy-host exited (${child.exitCode}) while waiting for ${what}: ${stderr}`); + const value = await read().catch(() => null); + if (value) return value; + await new Promise(resolve => setTimeout(resolve, 50)); + } + assert.fail(serveTimeoutMessage(what, stderr)); + }; + const { baseUrl } = await until(async () => JSON.parse(readFileSync(path.join(profile, 'host-endpoint.json'), 'utf8')), + 'the endpoint', serveStarted + SOURCE_SERVE_ENDPOINT_TIMEOUT_MS); + t.diagnostic(`Source serve spawn to endpoint: ${Math.ceil(performance.now() - serveStarted)} ms`); + const token = readFileSync(path.join(profile, 'host-api-token'), 'utf8').trim(); + const call = async (method, pathname) => { + const response = await fetch(`${baseUrl}${pathname}`, { method, headers: { authorization: `Bearer ${token}`, + 'content-type': 'application/json' }, ...(method === 'POST' ? { body: '{}' } : {}) }); + return { status: response.status, body: await response.json() }; + }; + await until(async () => (await call('POST', '/api/auth/state')).body.hostUnavailable, 'the start to fail'); + + const refreshed = await call('POST', '/api/auth/refresh'); + assert.equal(refreshed.status, 200); + assert.equal(refreshed.body.ok, false); + // The refresh ends the session in the background: wait until its teardown has finished. + await until(async () => /^Sign-in expired/.test((await call('GET', '/health')).body.runtime?.detail ?? ''), 'the session teardown'); + const state = await call('POST', '/api/auth/state'); + assert.deepEqual(state.body.hostUnavailable, { reason: 'HOST_DATABASE_LOCKED' }); + assert.equal(state.body.authenticated, false); +}); diff --git a/apps/host/src/test-support/hook-plugin-fixture.mjs b/apps/host/src/test-support/hook-plugin-fixture.mjs new file mode 100644 index 00000000000..a5c2e5ae8a0 --- /dev/null +++ b/apps/host/src/test-support/hook-plugin-fixture.mjs @@ -0,0 +1,115 @@ +// A hook-answering plugin for Host tests, run in the Host's own plugin sandbox (real headless +// Chromium, the shared GhostRuntime), as installed plugins run on the Host (plugins/runtime.ts). +// +// Hooks (will-user-message and the runtime control points) reach a plugin's logic page through +// cindy.onHostMessage, and the plugin answers with cindy.send({ type: 'event-verdict', hookId, ... }) +// (plugin-creator references: plugin-event-subscriptions.md, plugin-control-points.md). A Node worker +// cannot answer them: its events also go to the logic page. So the fixture is a logic plugin. +// +// What the plugin does for each hook name is fixed when it is written (`behaviors`): +// { action, ... } answer with that verdict for the hookId it was asked +// 'silent' never answer (the host's wait runs out) +// 'throw' throw inside the handler (a plugin error) +// { impersonate, ... } answer with another hookId (a verdict that is not this question's) +// Every message the page receives is also reported back as { type: 'fixture-received', message }. +// +// Chromium: CINDY_TEST_CHROMIUM, else Playwright's default build when it is installed. Without one +// the caller skips with `chromiumUnavailable` as the reason. Never a user's browser or profile. +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build } from 'esbuild'; +import { chromium } from 'playwright-core'; +import { createHeadlessPluginSandbox } from '../plugins/chromium-sandbox.ts'; +import { createGhostPageHandler } from '../../../desktop/src/main/cindy-brain/runtime/ghostPageHandler.ts'; +import { GhostRuntime } from '../../../desktop/src/main/cindy-brain/runtime/GhostRuntime.ts'; +import { installedGhostStoragePart } from '../../../desktop/src/shared/pluginIdentity.ts'; + +/** The Chromium a test may launch, or null. */ +export function testChromiumExecutable() { + const explicit = process.env.CINDY_TEST_CHROMIUM?.trim(); + if (explicit) return fs.existsSync(explicit) ? explicit : null; + try { + const bundled = chromium.executablePath(); + return bundled && fs.existsSync(bundled) ? bundled : null; + } catch { return null; } +} +export const chromiumUnavailable = 'no Chromium for the plugin sandbox: set CINDY_TEST_CHROMIUM to a headless Chromium build'; + +/** Write the fixture plugin into `dir` and return its installed-plugin record. */ +export function writeHookPlugin(dir, { id = 'hook-fixture', hooks = ['will-user-message'], behaviors = {}, manifest = {} } = {}) { + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify({ + schemaVersion: 3, id, name: 'Hook fixture', description: 'Synthetic hook answers for Host tests.', + version: '1.0.0', minCindyVersion: '0.0.0', entry: 'main.js', launch: 'resident', + subscribe: { hooks }, ...manifest, + }, null, 2)); + fs.writeFileSync(path.join(dir, 'main.js'), ` + const behaviors = ${JSON.stringify(behaviors)}; + cindy.onHostMessage(async message => { + await cindy.send({ type: 'fixture-received', message }); + if (!message || message.type !== 'event' || typeof message.hookId !== 'string') return; + const behavior = behaviors[message.name]; + if (behavior === undefined || behavior === 'silent') return; + if (behavior === 'throw') throw new Error('fixture plugin failure'); + const { impersonate, ...verdict } = behavior; + await cindy.send({ type: 'event-verdict', hookId: impersonate ?? message.hookId, ...verdict }); + }); + globalThis.fixtureReady = true; + `); + const manifestFile = JSON.parse(fs.readFileSync(path.join(dir, 'ghost.json'), 'utf8')); + return { manifest: manifestFile, dir, enabled: true, namespace: null, namespaceState: 'confirmed', + approval: { state: 'approved', revision: `${id}-fixture` } }; +} + +/** + * The Host's plugin sandbox and GhostRuntime over the given plugins. Everything a plugin sends + * reaches `onSend(id, payload)` (where plugins/runtime.ts routes it on the Host). `close()` stops the + * runtimes and the browser; register it on lifoCleanup. + */ +export async function startHookPluginSandbox({ ghosts, executablePath, onSend = () => {} }) { + const installed = new Map(ghosts.map(ghost => [installedGhostStoragePart(ghost), ghost])); + const enabled = new Set(installed.keys()); + const kv = new Map(); + const bridge = await build({ entryPoints: [fileURLToPath(new URL('../../../desktop/src/shared/ghostPageBridge.ts', import.meta.url))], + write: false, bundle: true, platform: 'browser', format: 'iife', globalName: 'CindyPluginBridge' }); + const platform = createHeadlessPluginSandbox({ + executablePath, bridgeSource: bridge.outputFiles[0].text, + ownerKey: () => 'hook-fixture-owner', + isCurrent: ghost => enabled.has(installedGhostStoragePart(ghost)), + send: async (ghost, payload) => { + await onSend(installedGhostStoragePart(ghost), payload); + return { ok: true }; + }, + pageHandler: (ghost, origin, isCurrent) => createGhostPageHandler({ + ghost, origin, isCurrent, + ghostKvStore: { read: id => kv.get(id) ?? {}, write: (id, value) => kv.set(id, value), + captureTarget: id => enabled.has(id) ? id : null, isTargetCurrent: id => enabled.has(id) }, + ghostWakeHandler: null, ghostAppContextProvider: null, ghostModelPickerProvider: null, + ghostAgentModelsProvider: null, ghostModelPreferencesProvider: null, ghostMediaModelsProvider: null, ghostModelsHandler: null, + ghostSecretsHandler: null, ghostOauthHandler: null, ghostConnectionsHandler: null, + serveGhostMedia: async () => new Response(null, { status: 404 }), + serveGhostLibraryFile: async () => new Response(null, { status: 404 }), + serveGhostGallery: async () => Response.json([]), log: { error() {}, warn() {} }, + }), + }); + const runtime = new GhostRuntime({ adapter: platform.adapter, onStateChanged: () => {} }); + return { + runtime, platform, installed, + id: ghost => installedGhostStoragePart(ghost), + spawn: ghost => runtime.spawn(ghost), + deliver: (ghost, message) => platform.deliver(installedGhostStoragePart(ghost), message), + async close() { + for (const id of installed.keys()) runtime.stop(id); + await platform.close(); + }, + }; +} + +/** Process ids whose command line runs `executablePath` (POSIX `ps`), for leak checks. */ +export async function processesRunning(executablePath) { + const { execFile } = await import('node:child_process'); + const out = await new Promise((resolve, reject) => execFile('ps', ['-axo', 'pid=,command='], { maxBuffer: 16 * 1024 * 1024 }, + (error, stdout) => error ? reject(error) : resolve(stdout))); + return new Set(out.split('\n').filter(line => line.includes(executablePath)).map(line => Number.parseInt(line, 10)).filter(Number.isFinite)); +} diff --git a/apps/host/src/test-support/hook-plugin-fixture.test.mjs b/apps/host/src/test-support/hook-plugin-fixture.test.mjs new file mode 100644 index 00000000000..c2d19ee0000 --- /dev/null +++ b/apps/host/src/test-support/hook-plugin-fixture.test.mjs @@ -0,0 +1,47 @@ +// Integration, real headless Chromium through the Host's plugin sandbox (plugins/chromium-sandbox.ts) +// and the shared GhostRuntime: the hook fixture the 8i tests will use (release table row 33). Rule: the +// fixture starts as a logic plugin, answers the hook it is asked with the verdict it was written with, +// takes no delivery once stopped, and closing the sandbox leaves no browser process behind. +// Gap: no Host test started a plugin that answers hooks; the 8i tests need one that comes and goes +// cleanly. Minimal input: one plugin, one will-user-message event. Skipped without a Chromium build +// (CINDY_TEST_CHROMIUM), never a user's browser. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { lifoCleanup } from './cleanup.mjs'; +import { chromiumUnavailable, processesRunning, startHookPluginSandbox, testChromiumExecutable, writeHookPlugin } from './hook-plugin-fixture.mjs'; + +const executablePath = testChromiumExecutable(); + +test('the hook fixture plugin answers the hook it is asked, takes nothing once stopped, and leaves no browser process', { + skip: executablePath ? false : chromiumUnavailable, timeout: 30_000, +}, async t => { + t = lifoCleanup(t); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-hook-fixture-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + const before = await processesRunning(executablePath); + const sent = []; + const ghost = writeHookPlugin(path.join(dir, 'plugin'), { + behaviors: { 'will-user-message': { action: 'rewrite', text: 'redacted text' } }, + }); + const sandbox = await startHookPluginSandbox({ ghosts: [ghost], executablePath, onSend: (id, payload) => { sent.push({ id, payload }); } }); + let closed = false; + t.after(() => closed ? undefined : sandbox.close()); + + assert.deepEqual(await sandbox.spawn(ghost), { ok: true, state: 'running' }); + const event = { type: 'event', name: 'will-user-message', hookId: 'hook-1', data: { sessionId: 'task-1', text: 'my secret' } }; + assert.equal(await sandbox.deliver(ghost, event), true); + const verdicts = () => sent.filter(item => item.payload?.type === 'event-verdict'); + for (let attempt = 0; attempt < 400 && verdicts().length === 0; attempt += 1) await new Promise(resolve => setTimeout(resolve, 5)); + assert.deepEqual(verdicts(), [{ id: sandbox.id(ghost), payload: { type: 'event-verdict', hookId: 'hook-1', action: 'rewrite', text: 'redacted text' } }]); + assert.deepEqual(sent.find(item => item.payload?.type === 'fixture-received')?.payload.message, event); + + sandbox.runtime.stop(sandbox.id(ghost)); + assert.equal(await sandbox.deliver(ghost, { ...event, hookId: 'hook-2' }), false); + await sandbox.close(); + closed = true; + const after = await processesRunning(executablePath); + assert.deepEqual([...after].filter(pid => !before.has(pid)), []); +}); diff --git a/apps/host/src/test-support/source-electron-tree.mjs b/apps/host/src/test-support/source-electron-tree.mjs new file mode 100644 index 00000000000..82ccd12993f --- /dev/null +++ b/apps/host/src/test-support/source-electron-tree.mjs @@ -0,0 +1,41 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +// Run the actual Host source with a private Desktop dependency tree. Other +// workspace packages stay at their usual versions; no installed files change. +export function createSourceElectronTree(root) { + const repo = fileURLToPath(new URL('../../../../', import.meta.url)); + const host = path.join(root, 'apps', 'host'); + const desktop = path.join(root, 'apps', 'desktop'); + const electron = path.join(desktop, 'node_modules', 'electron'); + fs.mkdirSync(path.join(host, 'node_modules'), { recursive: true }); + fs.mkdirSync(electron, { recursive: true }); + for (const file of ['package.json', 'apps/host/package.json', 'apps/host/tsconfig.json', + 'apps/desktop/package.json', 'apps/desktop/tsconfig.json']) { + fs.copyFileSync(path.join(repo, file), path.join(root, file)); + } + fs.cpSync(path.join(repo, 'apps/host/src'), path.join(host, 'src'), { recursive: true }); + for (const dir of ['node_modules', 'packages', 'config', 'apps/desktop/src', 'apps/desktop/resources']) { + fs.symlinkSync(path.join(repo, dir), path.join(root, dir), 'junction'); + } + fs.symlinkSync(electron, path.join(host, 'node_modules', 'electron'), 'junction'); + for (const app of ['host', 'desktop']) { + const deps = path.join('apps', app, 'node_modules'); + if (!fs.existsSync(path.join(repo, deps))) continue; + for (const name of fs.readdirSync(path.join(repo, deps))) { + if (name !== 'electron' && !name.startsWith('.')) { + fs.symlinkSync(path.join(repo, deps, name), path.join(root, deps, name), 'junction'); + } + } + } + fs.writeFileSync(path.join(electron, 'package.json'), JSON.stringify({ name: 'electron', main: 'index.cjs' })); + // Stand in for the npm entry's synchronous installer without using a network + // or installation program, even if a regression reaches it. + fs.writeFileSync(path.join(electron, 'index.cjs'), ` + require('node:fs').writeFileSync(require('node:path').join(__dirname, 'entry-ran'), ''); + require('node:child_process').spawnSync(process.execPath, ['-e', '']); + throw new Error('synthetic Electron installer'); + `); + return { host, electron }; +} diff --git a/apps/host/src/typed-error.mjs b/apps/host/src/typed-error.mjs new file mode 100644 index 00000000000..e195a9bd0d0 --- /dev/null +++ b/apps/host/src/typed-error.mjs @@ -0,0 +1,54 @@ +/** + * The HTTP status a typed error (createIpcError: `[CODE] message` with `error.code === CODE`) answers + * with on the Host's request entries: the IPC route (ipc-route.mjs) and the server's catch for the + * other /api, /sessions and /chat entries (server.mjs). One table and one decision for both. + * + * - The request itself was valid and the task's current state refuses it (its context window or + * usage, a turn running, a credential switch in progress, a route not usable now): 409, as + * PRECONDITION_FAILED. Clients handle it by its code; it is not a server failure. + * - Anything else, or an error that is not typed exactly, is the caller's 500. + */ +export const STATUS_BY_CODE = Object.freeze({ + INVALID_PARAMS: 400, + PERMISSION_DENIED: 403, + NOT_FOUND: 404, + PRECONDITION_FAILED: 409, + OWNER_CHANGED: 409, + UNSUPPORTED_CAPABILITY: 501, + // A model change refused by the task's state (sessionRuntimeSelectionApply.ts). + CREDENTIAL_SWITCH_BUSY: 409, + MODEL_CONTEXT_USAGE_UNKNOWN: 409, + MODEL_SELECTION_UNAVAILABLE: 409, + MODEL_SWITCH_TASK_RUNNING: 409, + MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN: 409, + MODEL_WINDOW_PREPARATION_IN_PROGRESS: 409, + MODEL_WINDOW_PROTECTION_UNAVAILABLE: 409, + MODEL_WINDOW_REMOTE_REBUILD_UNSUPPORTED: 409, + MODEL_WINDOW_TARGET_CONTEXT_UNKNOWN: 409, +}); + +const CODED_ERROR = /^\[([A-Z][A-Z0-9_]*)\] ([\s\S]*)$/; + +/** + * A typed error's code and message, or null. Typed means all of: `error.code` is a string, the message + * is `[CODE] message`, and the two codes are the same. Nothing else is serialised to a client. + * + * @param {unknown} error + * @returns {{ code: string, message: string } | null} + */ +export function parseTypedError(error) { + const code = typeof error?.code === 'string' ? error.code : null; + const match = error instanceof Error ? CODED_ERROR.exec(error.message) : null; + if (!code || !match || match[1] !== code) return null; + return { code, message: match[2] }; +} + +/** + * The status of a typed error whose code is in the table, or null (the caller's 500). + * + * @param {string} code + * @returns {number | null} + */ +export function typedErrorStatus(code) { + return Object.hasOwn(STATUS_BY_CODE, code) ? STATUS_BY_CODE[code] : null; +} diff --git a/apps/host/src/ui-text.test.mjs b/apps/host/src/ui-text.test.mjs new file mode 100644 index 00000000000..7e18ad13741 --- /dev/null +++ b/apps/host/src/ui-text.test.mjs @@ -0,0 +1,22 @@ +/** + * The Host's background copy in the locale (ui-text.ts bindHostUiText). + * - Rule: main-process copy that reaches the user from background services follows the locale, as + * bootstrap-electron.ts binds configureUiText; a key the catalog lacks keeps the English fallback + * (release table 甲 23). + * - Gap: the Host bound nothing, so the database startup failure, the one line a user most needs to + * read, was always the English fallback. + * - Minimal failing input: a Chinese system language and the schema lease failure title. + * - Tier: unit, through the reader the database startup failure uses (localDb/hostUiText.ts). + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { localDbText } from '../../desktop/src/main/localDb/hostUiText.ts'; +import { configureUiText } from '../../desktop/src/main/uiText.ts'; +import { bindHostUiText } from './ui-text.ts'; + +test('the database startup failure follows the system language once the Host binds its copy', t => { + t.after(() => configureUiText((_key, fallback) => fallback)); + assert.equal(localDbText('localDbFatal.schemaLease.title'), 'Local database is in use', 'unbound: the English fallback'); + bindHostUiText(() => ['zh-CN']); + assert.equal(localDbText('localDbFatal.schemaLease.title'), '本地数据暂时无法打开'); +}); diff --git a/apps/host/src/ui-text.ts b/apps/host/src/ui-text.ts new file mode 100644 index 00000000000..60cca3a2065 --- /dev/null +++ b/apps/host/src/ui-text.ts @@ -0,0 +1,18 @@ +import { createMainI18n } from '../../desktop/src/main/i18n.js'; +import { configureUiText } from '../../desktop/src/main/uiText.ts'; + +/** + * Main-process copy that reaches the user from background services (uiText.ts: the database startup + * failure, MCP app history titles), in the locale, as bootstrap-electron.ts binds it: a key the + * catalog lacks keeps the English fallback. The Host reads the process's system language, as its other + * main-side copy does (release table section 二, item Pi 提示与对话框的语言). + */ +export function bindHostUiText( + resolveSystemLanguages: () => string[] = () => [Intl.DateTimeFormat().resolvedOptions().locale], +): void { + const { t } = createMainI18n(resolveSystemLanguages); + configureUiText((key, fallback) => { + const localized = t(key); + return localized === key ? fallback : localized; + }); +} diff --git a/apps/host/src/web-client-build.mjs b/apps/host/src/web-client-build.mjs index 19a8c2ce5a9..3f71c59e7a6 100644 --- a/apps/host/src/web-client-build.mjs +++ b/apps/host/src/web-client-build.mjs @@ -3,6 +3,16 @@ import { fileURLToPath } from 'node:url'; /** Compile the browser adapter with the same shared contract as Desktop. * Returned in memory: no generated file, profile access, or renderer build. */ +/** + * The shim imports the Desktop's TapDB collector table (shared/endpoints.ts), whose module also + * reads two Vite build values. A browser IIFE has no `import.meta.env`; without these the shim + * would throw on load. The shim uses neither value. + */ +export const WEB_SHIM_DEFINE = { + 'import.meta.env.VITE_ENDPOINT_MANIFEST_BASE_URL': 'undefined', + 'import.meta.env.VITE_ENDPOINT_MANIFEST_PEER_BASE_URL': 'undefined', +}; + export async function buildWebShim(entry) { // Production serves a prebuilt shim. esbuild is a development dependency and // must not be loaded just to start an installed Host. @@ -17,6 +27,7 @@ export async function buildWebShim(entry) { // apps/web reuses the renderer and has no separate workspace install. nodePaths: [fileURLToPath(new URL('../node_modules', import.meta.url))], logLevel: 'silent', + define: WEB_SHIM_DEFINE, }); return result.outputFiles[0].text; } diff --git a/apps/host/src/web-shim.test.mjs b/apps/host/src/web-shim.test.mjs index ea9a791f982..0866e7705df 100644 --- a/apps/host/src/web-shim.test.mjs +++ b/apps/host/src/web-shim.test.mjs @@ -343,3 +343,128 @@ test('an expired browser pairing keeps the page and can reconnect after pairing assert.ok(b.calls.every(c => !c.url.includes('/enqueue'))); assert.deepEqual(b.redirects, []); }); + +/* + * 甲-1 (release table): the Host web page runs a prebuilt renderer whose TapDB collector was fixed + * when it was built; the Host must not add a cross-region upload of the signed-in account's usage. + * Production entry: the real shim bundle plus the real vendored TapDB SDK, initialized the way the + * renderer's tapdbClient does (ajax, device_login). The fake collector is the page's own + * XMLHttpRequest, navigator.sendBeacon and image pixel, recording what would leave the browser. + * Gap: the shim tests above stub no network primitives, and the renderer's TapDB tests run in + * Electron where the build region and the account region are checked by the Desktop. + * Minimal failure: account realm cn, renderer collector global: any recorded request is a leak. + * Tier: unit (vm, no sockets). + */ +// Bundled once, only by the test that needs it (the other shim tests do not pay for it). +let tapdbSdk; +async function loadTapdbSdk() { + const { build: bundle } = await import('esbuild'); + tapdbSdk ??= (await bundle({ + entryPoints: [fileURLToPath(new URL('../../desktop/src/renderer/vendor/tapdb/tapdb.esm.min.js', import.meta.url))], + bundle: true, write: false, format: 'iife', globalName: 'TapDBLib', platform: 'browser', logLevel: 'silent', + })).outputFiles[0].text; +} +const COLLECTOR = { cn: 'https://e.tapdb.com/event', global: 'https://e.tapdb.ap-sg.tapapis.com/event' }; + +function analyticsPage(auth, frames = [], authState = { authenticated: Boolean(auth), realm: auth?.realm ?? 'global' }) { + const sent = []; + class FakeXhr { + open(method, url) { this.url = url; } + setRequestHeader() {} + send() { sent.push(['xhr', this.url]); } + } + class FakeImage {} + Object.defineProperty(FakeImage.prototype, 'src', { configurable: true, set(value) { sent.push(['img', value]); }, get() { return ''; } }); + const storage = new Map(); + const timers = []; + const window = { addEventListener() {}, removeEventListener() {}, crypto: { randomUUID: () => 'test-id' }, __cindyBoot: { auth } }; + const context = vm.createContext({ + window, console, URL, URLSearchParams, TextDecoder, AbortController, JSON, Math, Date, encodeURIComponent, decodeURIComponent, + XMLHttpRequest: FakeXhr, HTMLImageElement: FakeImage, Image: FakeImage, + navigator: { language: 'en', languages: ['en', 'en'], userAgent: 'test', platform: 'test', clipboard: { writeText() {} }, + sendBeacon: (url) => { sent.push(['beacon', url]); return true; } }, + document: { referrer: '', title: 't', URL: 'http://127.0.0.1:1234/', cookie: '', addEventListener() {}, + createElement: () => ({ dataset: {} }), getElementsByTagName: () => [], head: { appendChild() {} } }, + location: { href: 'http://127.0.0.1:1234/', protocol: 'http:', host: '127.0.0.1:1234', hostname: '127.0.0.1', pathname: '/', search: '', hash: '', replace() {} }, + screen: { width: 1, height: 1 }, + localStorage: { getItem: (k) => storage.get(k) ?? null, setItem: (k, v) => storage.set(k, String(v)), removeItem: (k) => storage.delete(k) }, + sessionStorage: { getItem: () => null, setItem() {}, removeItem() {} }, + setTimeout: (fn) => { timers.push(fn); return timers.length; }, clearTimeout() {}, setInterval: () => 0, clearInterval() {}, + TextEncoder, ReadableStream, Response, + // The stream's opening /api/auth/state read answers authState; the event stream carries the + // frames (auth_changed); every other request stays pending. + fetch: (url) => { + if (String(url).startsWith('/api/auth/state')) { + return Promise.resolve({ ok: true, text: async () => JSON.stringify({ ...authState, user: null, dataOwnerId: null }) }); + } + if (String(url).startsWith('/events')) { + // Open (never closed), so the stream reaches its opening auth read for every case. + return Promise.resolve(new Response(new ReadableStream({ start(controller) { + if (frames.length) controller.enqueue(new TextEncoder().encode(frames.map((frame) => `data: ${JSON.stringify(frame)}\n\n`).join(''))); + } }))); + } + return new Promise(() => {}); + }, + }); + for (const key of ['XMLHttpRequest', 'HTMLImageElement', 'Image', 'navigator', 'document', 'location', 'localStorage', 'sessionStorage', 'screen']) window[key] = context[key]; + vm.runInContext(source, context); + vm.runInContext(`${tapdbSdk};globalThis.__tapdb = TapDBLib.default;`, context); + return { sent, tapdb: context.__tapdb, beacon: (url) => context.navigator.sendBeacon(url), pixel: (url) => { new FakeImage().src = url; } }; +} + +test('Host web usage statistics leave only for the signed-in account region', async () => { + await loadTapdbSdk(); + const signedOut = { seq: 1, type: 'auth_changed', authenticated: false, user: null, dataOwnerId: null, realm: 'global' }; + for (const [label, auth, renderer, leaves, frames] of [ + ['same region', { realm: 'global' }, 'global', true], + ['same region (cn)', { realm: 'cn' }, 'cn', true], + ['account cn, renderer global', { realm: 'cn' }, 'global', false], + ['account global, renderer cn', { realm: 'global' }, 'cn', false], + ['no signed-in account', undefined, 'global', false], + // auth_changed keeps the stored realm when signed out; the shim must not keep reporting. + ['signed out after boot', { realm: 'global' }, 'global', false, [signedOut]], + ]) { + const page = analyticsPage(auth, frames); + for (let n = 0; n < 40; n++) await Promise.resolve(); + page.tapdb.init({ appId: 'fixture-app', serverUrl: COLLECTOR[renderer], send_method: 'ajax', textContent: 'form', + isInitDeviceLogin: true, autoTrack: { pageShow: false, pageHide: false } }); + page.tapdb.optInTracking(); + page.tapdb.setUser('fixture-member'); + page.tapdb.track('fixture_event'); + page.beacon(COLLECTOR[renderer]); + page.pixel(COLLECTOR[renderer]); + const toCollector = page.sent.filter(([, url]) => String(url).startsWith(new URL(COLLECTOR[renderer]).origin)); + if (leaves) { + assert.ok(toCollector.some(([kind]) => kind === 'xhr'), `${label}: the SDK reports through XHR`); + assert.ok(toCollector.some(([kind]) => kind === 'beacon') && toCollector.some(([kind]) => kind === 'img'), label); + } else { + assert.deepEqual(toCollector, [], `${label}: nothing reaches the other region's collector`); + } + // Other origins are untouched by the guard. + page.beacon('https://example.invalid/collect'); + assert.deepEqual(page.sent.at(-1), ['beacon', 'https://example.invalid/collect'], label); + } +}); + +// 并存方案 A 的 W(审核方 2026-11-17 定):网页端把 Host 的 typed 错误体还原成 `[CODE] message`(带 code), +// 让 renderer 共用的解码(公共映射、发送失败横幅)按窗口那样认出“桌面版占用数据”的拒绝;之前用户看到的是 +// 一段 JSON。启动被拒的 409 带原因码时与窗口的 host-ipc-proxy 同样加标记。其余错误体与之前完全相同。 +test('typed Host errors reach the renderer as [CODE] message; other failures as before', async () => { + let reply; + const b = browser(() => reply()); + const answer = (status, body) => () => new Response(typeof body === 'string' ? body : JSON.stringify(body), { status }); + const running = '[PRECONDITION_FAILED] HOST_PROFILE_IN_USE_BY_DESKTOP: In use by the desktop app.'; + reply = answer(409, { error: 'PRECONDITION_FAILED', message: running }); + await assert.rejects(b.api.localDb.sessions.list(), { code: 'PRECONDITION_FAILED', message: running }); + reply = answer(409, { error: 'NOT_FOUND', message: 'Source task is unavailable' }); + await assert.rejects(b.api.localDb.sessions.list(), { code: 'NOT_FOUND', message: '[NOT_FOUND] Source task is unavailable' }); + reply = answer(409, { error: 'owner_runtime_unavailable', reason: 'HOST_PROFILE_IN_USE_BY_DESKTOP', message: 'Quit that app, then restart the Host.' }); + await assert.rejects(b.api.localDb.sessions.list(), { code: 'PRECONDITION_FAILED', + message: '[PRECONDITION_FAILED] HOST_PROFILE_IN_USE_BY_DESKTOP_AT_START: Quit that app, then restart the Host.' }); + for (const [status, body] of [[409, { error: 'owner_runtime_unavailable' }], [500, { error: 'internal_error', message: 'Unexpected error' }], + [502, 'Bad gateway'], [409, { error: 'PRECONDITION_FAILED' }]]) { + reply = answer(status, body); + const text = typeof body === 'string' ? body : JSON.stringify(body); + await assert.rejects(b.api.localDb.sessions.list(), { code: `HTTP_${status}`, message: text }); + } +}); diff --git a/apps/web/analytics-region-guard.js b/apps/web/analytics-region-guard.js new file mode 100644 index 00000000000..d5843b81920 --- /dev/null +++ b/apps/web/analytics-region-guard.js @@ -0,0 +1,86 @@ +/** + * Host web: usage statistics stay in the signed-in account's region (release table, 甲-1). + * + * The renderer this page runs is a prebuilt Desktop renderer, so its TapDB project and collector + * were fixed when that renderer was built. The Host serves one account, whose region may differ; + * the page must not add a cross-region upload. The renderer is reused unchanged, so the guard sits + * on the egress itself: a request to a TapDB collector leaves only when that collector is the + * signed-in account's own (`eventUrlByRegion[realm]`). An unknown realm (not signed in, or a value + * outside the table) blocks every TapDB collector. Other requests are untouched. + * + * Covered: the vendored SDK's three transports (XMLHttpRequest, navigator.sendBeacon, an image + * pixel through the `src` property) and fetch. Other ways to load a URL (`setAttribute('src')`, + * iframes, scripts) are not covered; an SDK update that adopts one must extend this guard, and the + * web-shim test drives the real SDK so a new transport shows up there. A blocked XHR send is a + * silent no-op: firing an error would only make the SDK retry against the same collector. + */ + +function originOf(url, base) { + try { return new URL(String(url), base).origin; } catch { return null; } +} + +/** + * @param {{ + * target: any, + * eventUrlByRegion: Readonly>, + * readRealm: () => string | null | undefined, + * }} options + * @returns {(url: unknown) => boolean} whether a request to `url` may leave + */ +export function installAnalyticsRegionGuard({ target, eventUrlByRegion, readRealm }) { + const base = target.location?.href; + const collectors = new Set(Object.values(eventUrlByRegion).map((url) => originOf(url)).filter(Boolean)); + const allowed = (url) => { + const origin = originOf(url, base); + if (!origin || !collectors.has(origin)) return true; + const realm = readRealm(); + const own = realm === 'cn' || realm === 'global' ? originOf(eventUrlByRegion[realm]) : null; + return own !== null && origin === own; + }; + + const XHR = target.XMLHttpRequest; + if (typeof XHR === 'function' && XHR.prototype) { + const open = XHR.prototype.open; + const send = XHR.prototype.send; + XHR.prototype.open = function guardedOpen(method, url, ...rest) { + this.__cindyAnalyticsBlocked = !allowed(url); + return open.call(this, method, url, ...rest); + }; + XHR.prototype.send = function guardedSend(...args) { + if (this.__cindyAnalyticsBlocked) return undefined; + return send.apply(this, args); + }; + } + + const navigator = target.navigator; + if (navigator && typeof navigator.sendBeacon === 'function') { + const sendBeacon = navigator.sendBeacon.bind(navigator); + try { + Object.defineProperty(navigator, 'sendBeacon', { + configurable: true, writable: true, + value: (url, data) => (allowed(url) ? sendBeacon(url, data) : false), + }); + } catch { + navigator.sendBeacon = (url, data) => (allowed(url) ? sendBeacon(url, data) : false); + } + } + + const Image = target.HTMLImageElement; + const srcDescriptor = Image?.prototype && Object.getOwnPropertyDescriptor(Image.prototype, 'src'); + if (srcDescriptor?.set && srcDescriptor.configurable) { + Object.defineProperty(Image.prototype, 'src', { + ...srcDescriptor, + set(value) { if (allowed(value)) srcDescriptor.set.call(this, value); }, + }); + } + + if (typeof target.fetch === 'function') { + const fetch = target.fetch; + target.fetch = function guardedFetch(input, init) { + const url = typeof input === 'string' || input instanceof URL ? input : input?.url; + if (!allowed(url)) return Promise.reject(new TypeError('Usage statistics stay in the account region')); + return fetch.call(this, input, init); + }; + } + return allowed; +} diff --git a/apps/web/shim.js b/apps/web/shim.js index 30107cbe56d..14956747519 100644 --- a/apps/web/shim.js +++ b/apps/web/shim.js @@ -10,6 +10,8 @@ import { createHostChannelHandlers, unsupportedHostChannel } from '@cindy/maker-shared/host-channel-contract'; import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; +import { TAPDB_EVENT_URL_BY_REGION } from '../desktop/src/shared/endpoints.ts'; +import { installAnalyticsRegionGuard } from './analytics-region-guard.js'; (function installCindyHostShim() { // Polyfill Web Crypto randomUUID in insecure contexts (e.g. plain HTTP over LAN IP). @@ -83,6 +85,12 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; * files through the host, which is why this is a mirror and not a store. */ const boot = window.__cindyBoot ?? {}; + // 甲-1: the prebuilt renderer's usage statistics leave only for the account's own region. + installAnalyticsRegionGuard({ + target: window, + eventUrlByRegion: TAPDB_EVENT_URL_BY_REGION, + readRealm: () => window.__cindyBoot?.auth?.realm ?? null, + }); const settingsMirror = { appearance: boot.appearance ?? {}, layout: boot.layout ?? null, @@ -107,6 +115,27 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; if (!ownerStamp().dataOwnerId) throw new Error('sidebar settings require an active account'); } + /** + * A typed Host error body as the desktop window receives it: `[CODE] message`, with `code` set, so + * the renderer's shared decoders (ipcError.ts, the send-failure banner) read it the same way. + * `{ error: 'CODE', message }` is a typed handler error (server.mjs); a start refused because a + * Cindy desktop app running on its own uses this data answers `owner_runtime_unavailable` with a + * reason (host-ipc-proxy.ts does the same for the window). Any other body stays as before. + */ + function typedHostError(detail) { + let body; + try { body = JSON.parse(detail); } catch { return null; } + if (!body || typeof body !== 'object') return null; + const message = typeof body.message === 'string' ? body.message.trim() : ''; + if (body.error === 'owner_runtime_unavailable' && body.reason === 'HOST_PROFILE_IN_USE_BY_DESKTOP') { + return Object.assign(new Error(`[PRECONDITION_FAILED] HOST_PROFILE_IN_USE_BY_DESKTOP_AT_START: ${message || 'a Cindy desktop app uses this data'}`), + { code: 'PRECONDITION_FAILED' }); + } + if (typeof body.error !== 'string' || !/^[A-Z][A-Z0-9_]*$/.test(body.error) || !message) return null; + const prefix = `[${body.error}]`; + return Object.assign(new Error(message.startsWith(prefix) ? message : `${prefix} ${message}`), { code: body.error }); + } + async function requestHost(path, args, method = 'POST', signal) { const headers = { 'content-type': 'application/json' }; const response = await fetch(path, { @@ -119,6 +148,8 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; if (!response.ok) { if (response.status === 401) eventConnection?.authorizationRequired(); const detail = await response.text().catch(() => ''); + const typed = typedHostError(detail); + if (typed) throw typed; throw Object.assign(new Error(detail || `host ${path} failed`), { code: `HTTP_${response.status}` }); } const text = await response.text(); @@ -370,26 +401,23 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; 'maker.input.setInteractionLock': (args) => rpc('/input/set-interaction-lock', { sessionId: args?.[0], lockId: args?.[1], locked: args?.[2] }), 'maker.input.setEditLock': (args) => rpc('/input/set-edit-lock', { sessionId: args?.[0], clientId: args?.[1], locked: args?.[2] }), 'maker.input.clearSession': (args) => rpc('/input/clear-session', { sessionId: args?.[0] }), - 'maker.setPermissionMode': (args) => { - const sessionId = args?.[0]; - const mode = args?.[1]; - if (!sessionId) return Promise.resolve(); - return rpc('/sessions/update', { sessionId, patch: { permissionMode: mode } }); - }, + // The desktop's set-permission-mode and set-plan-mode, with their IPC arguments (the Host runs the + // shared bodies: argument checks, the task's permission queue, rollback, grant revocation). + 'maker.setPermissionMode': (args) => rpc('/sessions/set-permission-mode', { sessionId: args?.[0], mode: args?.[1] }), + // The desktop's set-model with its own arguments; the answer is the Host's (a user's pick is an + // intent until the next send: { deferred: true, pendingUntilSend: true }). 'maker.setModel': (args) => { - const [sessionId, model, providerId, _rev, selection] = args ?? []; + const [sessionId, model, providerId, revision, selection] = args ?? []; if (!sessionId) return Promise.resolve({ deferred: false }); - const patch = { model }; - if (providerId !== undefined) patch.providerId = providerId; - if (selection?.effort) patch.effort = selection.effort; - if (selection?.fastMode !== undefined) patch.fastMode = selection.fastMode; - return rpc('/sessions/update', { sessionId, patch }).then(() => ({ deferred: false })); + return rpc('/sessions/set-model', { sessionId, model, providerId, revision, selection }); }, 'maker.switchSessionAgent': async (args) => { - const [sessionId, targetAgentKind, model, providerId, effort, fastMode] = args ?? []; + const [sessionId, targetAgentKind, model, providerId, effort, fastMode, options, thinking] = args ?? []; if (!sessionId || !model) { return { switched: false, agentKind: targetAgentKind, model, engineReady: true }; } + // The desktop IPC's arguments, including its options (agentDeviceId, confirmedContextWindow) and + // the thinking choice. return rpc('/sessions/switch-agent', { sessionId, targetAgentKind, @@ -397,27 +425,16 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; providerId: providerId ?? null, effort, fastMode, + options, + thinking, }); }, - 'maker.setEffort': (args) => { - const sessionId = args?.[0]; - const effort = args?.[1]; - if (!sessionId) return Promise.resolve(); - return rpc('/sessions/update', { sessionId, patch: { effort } }); - }, - 'maker.setFastMode': (args) => { - const sessionId = args?.[0]; - const fastMode = args?.[1]; - if (!sessionId) return Promise.resolve(); - return rpc('/sessions/update', { sessionId, patch: { fastMode } }); - }, - 'maker.setPlanMode': (args) => { - const sessionId = args?.[0]; - const planModeEnabled = args?.[1]; - if (!sessionId) return Promise.resolve(); - return rpc('/sessions/update', { sessionId, patch: { planModeEnabled } }); - }, - 'maker.setThinkingEnabled': () => unsupported('maker.setThinkingEnabled'), + // The desktop's set-effort and set-fast-mode, with their IPC arguments (the Host runs the shared + // handler bodies: a live change, or a change staged into a pending pick). + 'maker.setEffort': (args) => rpc('/sessions/set-effort', { sessionId: args?.[0], effort: args?.[1] }), + 'maker.setFastMode': (args) => rpc('/sessions/set-fast-mode', { sessionId: args?.[0], fastMode: args?.[1] }), + 'maker.setPlanMode': (args) => rpc('/sessions/set-plan-mode', { sessionId: args?.[0], enabled: args?.[1] }), + 'maker.setThinkingEnabled': (args) => rpc('/sessions/set-thinking-enabled', { sessionId: args?.[0], enabled: args?.[1] }), 'maker.listDesktopCommands': () => ({ success: true, commands: STATIC.emptyList }), 'maker.claimLegacyModelVisibilityOwner': () => ({ dataOwnerId: window.__cindyBoot?.auth?.ownerId ?? null, @@ -995,6 +1012,9 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; * subscribers receive them through the same fan-out the preload provides. */ let eventConnection = null; + // 甲-1: the account realm only while signed in (as the boot values); signed out blocks every + // usage-statistics collector. Host auth states always carry the stored realm. + const signedInRealm = (state) => (state?.authenticated === true ? state.realm ?? null : null); let connectionState = { status: 'connecting', connection: 0, recovery: 0 }; function ensureEventStream() { if (eventConnection) return; @@ -1004,7 +1024,7 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; beforeEvents: async (signal) => { const auth = await requestHost('/api/auth/state', null, 'POST', signal); if (signal.aborted) return; - (window.__cindyBoot ??= {}).auth = { user: auth.user, ownerId: auth.dataOwnerId }; + (window.__cindyBoot ??= {}).auth = { user: auth.user, ownerId: auth.dataOwnerId, realm: signedInRealm(auth) }; emit('onAuthStateChange', auth); }, onState: (state) => { @@ -1017,7 +1037,7 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; // Interaction traffic has its own preload channels; everything // else stays on the shared event stream. if (parsed.type === 'auth_changed') { - (window.__cindyBoot ??= {}).auth = { user: parsed.user, ownerId: parsed.dataOwnerId }; + (window.__cindyBoot ??= {}).auth = { user: parsed.user, ownerId: parsed.dataOwnerId, realm: signedInRealm(parsed) }; emit('onAuthStateChange', parsed); } else if (parsed.type === 'interaction_request') { emit('maker.onInteractionRequest', { sessionId: parsed.sessionId, request: parsed.request }); @@ -1033,6 +1053,9 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; 'ghosts:runtime-changed': 'ghosts.onRuntimeChanged', 'ghosts:card-updated': 'ghosts.onCardUpdated', 'ghosts:notify': 'ghosts.onNotify', + 'ghosts:user-message-blocked': 'ghosts.onUserMessageBlocked', + 'ghosts:user-message-rewritten': 'ghosts.onUserMessageRewritten', + 'ghosts:hook-fused': 'ghosts.onHookFused', 'ghosts:confirm-request': 'ghosts.onConfirmRequest', 'ghosts:confirm-dismissed': 'ghosts.onConfirmDismissed', 'ghosts:install-consent:request': 'ghosts.onInstallConsentRequest', @@ -1041,6 +1064,10 @@ import { startHostEventStream } from '@cindy/maker-shared/host-event-stream'; 'maker:auth:login-progress': 'maker.auth.onLoginProgress', 'model-access:status-change': 'modelAccess.onStatusChange', 'maker:codex-runtime-route-changed': 'maker.onCodexRuntimeRouteChanged', + 'maker:session-credential-switch-applied': 'maker.onSessionCredentialSwitchApplied', + 'maker:session-credential-switch-failed': 'maker.onSessionCredentialSwitchFailed', + 'maker:draft-pref:apply': 'onMakerDraftPrefApply', + 'local-db:recent-workdirs:changed': 'localDb.recentWorkdirs.onChanged', }[parsed.channel]; if (subscriber) emit(subscriber, parsed.payload); } else if (parsed.type === 'settings_changed') { diff --git a/docs/dev-rules/protocol-compatibility/host-web-adapter-experimental.md b/docs/dev-rules/protocol-compatibility/host-web-adapter-experimental.md index 3527bc44341..ba011c198a7 100644 --- a/docs/dev-rules/protocol-compatibility/host-web-adapter-experimental.md +++ b/docs/dev-rules/protocol-compatibility/host-web-adapter-experimental.md @@ -27,6 +27,8 @@ Host SSE v2 由 `protocol=2` 和 `x-cindy-event-protocol: 2` 双向确认,新 客户端模式追加可信窗口专用的 `maker:runtime-plugins`,映射到 `POST /api/runtime-plugins`,并转发插件拦截、改写、熔断三种既有窗口事件。旧窗口对新 Host 保持原调用和原事件处理,新窗口连旧 Host 时仅这条新通道收到沿用的 `404 not_found`,无需改动 Device Link 或中转。 +`GET /health` 对无浏览器 Origin 且具有本机 profile bearer 的请求追加可选的 `legacyPluginApprovals` 诊断,供 `cindy-host status` 使用。旧 Host 省略字段,旧客户端忽略字段,浏览器配对会话及 Device Link 仍无这项诊断。 + 同机原生客户端新增 `/control/platform/socket`,复用 profile bearer,并要求 `x-cindy-host-instance` 与 Host 当前实例一致。拒绝浏览器 Origin 连接,窗口身份绑定 账号、客户端 ID 和 PID。HTTP/SSE 的实例头为可选增量;旧显式客户端不带头时继续原协议, diff --git a/docs/handoff/debian-a1-plan.md b/docs/handoff/debian-a1-plan.md index e1207765c45..ecc8e71314f 100644 --- a/docs/handoff/debian-a1-plan.md +++ b/docs/handoff/debian-a1-plan.md @@ -207,11 +207,15 @@ flowchart TB 1. 停 `cindy-desktop.service`,并确认没有其他进程占用数据库。 2. 重新备份真实 profile 的数据库与 `safe-storage`(沿用既有备份命名,不覆盖旧备份)。 -3. 用 feat 分支构建的桌面产物替换 `cindy-desktop.service` 里的二进制,并让它以客户端模式启动 +3. 在 Host 和桌面都已退出时运行 `cindy-host migration-preflight "$PROFILE"`,传入本步骤使用的 + 真实 profile 绝对路径。仅在退出码为 0 且 `count` 为 0 时继续。非零时先用 Cindy Desktop + v0.1.48 或更新的版本以内嵌模式打开这个 profile,完成已有的一次性插件批准迁移,退出后复查。 + 仍有缺口或清点失败时停止切换。[插件预检边界](../host/client-handoff-foundation.md#迁移前的插件批准预检) +4. 用 feat 分支构建的桌面产物替换 `cindy-desktop.service` 里的二进制,并让它以客户端模式启动 (自动发现 `host-endpoint.json`,或设 `CINDY_HOST_API=http://127.0.0.1:3456`)。 -4. `systemctl --user enable --now cindy-host.service`,让 Host 持有 profile 并迁移到 seq 129。 -5. 先启动 Host,再启动桌面。 -6. 桌面版本号显示改为真实版本,不再是 `0.0.0-host`(读取桌面包版本)。 +5. `systemctl --user enable --now cindy-host.service`,让 Host 持有 profile 并迁移到 seq 129。 +6. 先启动 Host,再启动桌面。 +7. 桌面版本号显示改为真实版本,不再是 `0.0.0-host`(读取桌面包版本)。 - 完成判据:第 7 节全部通过。 ### S9 · 收尾 diff --git a/docs/host/README.md b/docs/host/README.md index 366ed384f02..c7c2c1c741e 100644 --- a/docs/host/README.md +++ b/docs/host/README.md @@ -31,12 +31,14 @@ | 文档 | 内容 | |---|---| +| [自有电脑验证 Host](owned-machine-verification.md) | 三个平台的任务内工具链、Host 门禁,以及发布前的 macOS 文件监听和桌面测试 | | [headless-runtime-plan.md](headless-runtime-plan.md) | 当前架构目标、能力缺口、分批交付与完整无界面验收 | | [architecture-and-status.md](architecture-and-status.md) | 原 PR 阶段的模块分析与实验记录;现状以基础网页版和当前计划为准 | | [maintenance-plan.md](maintenance-plan.md) | PR #9246 合并后的维护计划与逐批验收边界 | | [feature-parity.md](feature-parity.md) | 原 PR 阶段的逐项功能记录与审计,保留历史验证范围 | | [personal-migration-release-table.md](personal-migration-release-table.md) | 个人版迁移放行表:每项应保留能力的现状、与桌面的差异和证据(M1 起随检查点更新) | | [electron-client-mode.md](electron-client-mode.md) | Electron 以客户端模式运行:通道代理表、安全边界、未迁移清单 | +| [client-mode-account-switch.md](client-mode-account-switch.md) | 客户端模式下的账号切换与添加账号:定稿方案(Host 执行、窗口只当界面;安全小节、默认行为、改动与测试清单,未实现) | | [channel-coverage.md](channel-coverage.md) | 脚本生成:桌面主进程全部 IPC 通道的归属(A 后台/B 窗口/W 窗口设置/S 同步/R 回执/C 待定)、要 Host 做的总数与真实使用排行、客户端模式行为 | | [systemd.md](systemd.md) | user unit 安装与运维 | | [maker-assembly-extraction-plan.md](maker-assembly-extraction-plan.md) | Runtime 装配抽离计划 | diff --git a/docs/host/architecture-and-status.md b/docs/host/architecture-and-status.md index 5230b3abd4f..74c5ac61c29 100644 --- a/docs/host/architecture-and-status.md +++ b/docs/host/architecture-and-status.md @@ -99,7 +99,7 @@ flowchart LR | 真实 Maker/Agent Runtime | 已验证(Host 持有) | Host 进程独占持有真实 Maker/Session 运行时与数据库写锁;桌面客户端模式下通过 `setMakerClientMode(true)` 阻断本地装配,所有请求代理至 Host。 | | 现有 session/message SQLite 与历史恢复 | 已验证 | 生产 profile(owner `cmv9i0xz401c8yg013q3zkqb0`)全部 192 条存量任务与消息完整接管,数据库安全推至 seq 129,`fuser -v` 验证单写者,无数据丢失。 | | Cindy 登录(`cindy-host login`) | 部分 | 复用 Desktop 的 authorize URL、PKCE、托管回调轮询与 session 记录;实测已生成与 Desktop 同形的 authorize URL 并完成对真实 auth 服务的 `getProviders`。**用户交互后的 code 兑换尚未实测**。 | -| Cindy OAuth 与凭据持久化 | 已验证(单写者) | Host 接管凭据层与令牌刷新:直接读写 `safeStorage`(Chromium OSCrypt v11);后台每 30 分钟定时刷新,暴露 `/api/auth/refresh` 供 Desktop 代理调用,彻底解决多端并发 refresh token 轮转失效问题。 | +| Cindy OAuth 与凭据持久化 | 已验证(单写者) | Host 接管凭据层与令牌刷新:直接读写 `safeStorage`(Chromium OSCrypt v11);按 access token 的 exp 减 300 秒续期(与桌面同一个函数;access token 约 60 分钟(推算,未在服务端核实)),失败按桌面的退避重试,暴露 `/api/auth/refresh` 供 Desktop 代理调用,彻底解决多端并发 refresh token 轮转失效问题。 | | Claude 订阅判定(Host) | 部分 | Host 通过共享模块读出「CLI 是否订阅登录 + Cindy 是否获准使用」:真实 profile 与临时 profile 均实测返回 `{"cliLoggedIn":false,"allowed":false,"connected":false}`(本机 CLI 非订阅登录)。判定来源与 Desktop 同源,未读取或复制任何 Anthropic 凭证。 | | Claude Code / Codex / Pi Harness | 部分 | 二进制就绪查询已抽成 `agent-binaries/binaryStatus.ts`,Desktop 与 Host 共用同一判定;实测 Host `/health` 对三种 Harness 均报告可用。Agent 启动所需的认证适配、代理、目录与 MCP 注入尚未迁出。 | | Plugin 执行与状态 | 未实现 | `cindy-brain`/plugin manager 依赖 Main 宿主接口与 Electron IPC;存量 plugin 向下兼容是阻断条件。 | @@ -136,7 +136,7 @@ flowchart LR - 无 Secret Service 时抛 `CREDENTIAL_STORE_UNAVAILABLE`,不回退明文、不静默失败。 - 新写入使用 0600 与同目录临时文件 + rename 原子替换。 - 实现:`apps/host/src/credentials/{oscrypt,linux-keyring,store}.mjs`;测试 `store.test.mjs`(9 例)。 -- 令牌续期:`apps/host/src/auth/refresh.mjs` 复用 `@cindy/auth-client` 的刷新语义,服务端轮换时原子写回同一记录,access token 只留内存。单测覆盖轮换/不轮换/缺失三种分支。 +- 令牌续期:`apps/host/src/auth/refresh.mjs` 与桌面运行时续期对齐(被拒后经共用的 `runRefreshWithReplacementRetry` 改用别的进程写下的新令牌;只有盘上仍是被拒的那枚才判确定失败;在账号库跨进程锁里按桌面 `authRefreshCommit.ts` 的同一条规则写账号库、v1 记录与旧版独立令牌),access token 只留内存。细节与测试见个人版迁移放行表并存行“后续九”。 - 未覆盖:macOS Keychain 与 Windows DPAPI 分支;对真实账号发起刷新(会轮换真实凭据,需 Desktop 关闭后单独验证);重启续期与 Desktop 交替运行的端到端验证。 ## 明确排除的参考实现 diff --git a/docs/host/channel-coverage.md b/docs/host/channel-coverage.md index 571ccaa18fd..bf66020f0e7 100644 --- a/docs/host/channel-coverage.md +++ b/docs/host/channel-coverage.md @@ -1,7 +1,7 @@ # Host 通道覆盖清单(脚本生成) > 由 `node scripts/host-channel-coverage.mjs` 生成,不要手工修改;行号只在 `--json` 输出里。 -> 生成时的源码提交:`cadb0c4f1b`。归属规则见下方「归属规则」,正本在脚本的 `OWNERSHIP_RULES`。 +> 生成时的源码提交:`775077d232`。归属规则见下方「归属规则」,正本在脚本的 `OWNERSHIP_RULES`。 统计对象是桌面主进程(`apps/desktop/src/main`,不含测试)里所有 `ipcMain.handle/on` 及其包装函数注册的通道;注册、调用次数和排行均按 `(kind, channel)` 区分。 @@ -10,31 +10,31 @@ ## 总口径 -**真正要 Host 做的 = A + C-后台 + C-两段式 = 934 + 32 + 43 = 1009**;巡检实际调用到 **131** 个(666 次,其中 A 129)。 +**真正要 Host 做的 = A + C-后台 + C-两段式 = 930 + 32 + 49 = 1011**;巡检实际调用到 **131** 个(666 次,其中 A 129)。 同步通道(S)与回执通道(R)已单列,不在 A 里;C-窗口本地与 C-专项设计不计入。 | 分类 | 含义 | 通道数 | |---|---|---:| -| contract | 已在 Host 通道合同或通用路由登记表里,窗口做客户端时转发给 Host | 83(巡检调用 35) | +| contract | 已在 Host 通道合同或通用路由登记表里,窗口做客户端时转发给 Host | 84(巡检调用 35) | | client | 客户端模式自己的通道(连接状态、重连) | 2(巡检调用 1) | -| **A** | 必须由后台处理:读写后台持有的数据或运行状态 | 934(巡检调用 128) | +| **A** | 必须由后台处理:读写后台持有的数据或运行状态 | 930(巡检调用 128) | | **B** | 永久留在窗口:只能在 Electron/图形界面里做 | 359(巡检调用 70) | | **W** | 窗口本地设置:窗口直接读写同一份 profile,不经 Host | 5(巡检调用 1) | | **S** | 同步通道(给 `event.returnValue` 赋值):不能转发给 Host | 14(巡检调用 11) | |  S·本地 | 同步·本地(窗口读 profile:界面设置与首帧提示) | 8(巡检调用 8) | |  S·镜像 | 同步·数据归 Host(需窗口缓存镜像) | 6(巡检调用 3) | | **R** | 回执通道:主进程向界面要数据,界面回执;先不排期 | 6(巡检调用 2) | -| **C** | 跨两边,按处理方式分四种 | 90(巡检调用 4) | +| **C** | 跨两边,按处理方式分四种 | 96(巡检调用 4) | |  C-后台 | | 32(巡检调用 2) | -|  C-两段式(窗口做界面动作,数据调 Host) | | 43(巡检调用 0) | +|  C-两段式(窗口做界面动作,数据调 Host) | | 49(巡检调用 0) | |  C-窗口本地 | | 11(巡检调用 2) | |  C-专项设计(安全边界) | | 4(巡检调用 0) | -| 合计 | | 1493 | +| 合计 | | 1496 | **窗口类**(B + W + S·本地 + C-窗口本地)在客户端模式下: 已注册 **373**(其中 10 个只有源码判定,客户端快照里还没有)、未注册 **0**(今天被拒或无人监听,见下文)、快照无法判断 10。 -判定依据:A:default 125、A:rule 809、B:rule 359、C:dependency 20、C:rule 70、R:rule 6、S:dependency 14、W:rule 5(rule = 规则表,dependency = 窗口 API 或同步返回值判定,default = 未登记前缀且没用窗口 API)。 +判定依据:A:default 122、A:rule 808、B:rule 359、C:dependency 26、C:rule 70、R:rule 6、S:dependency 14、W:rule 5(rule = 规则表,dependency = 窗口 API 或同步返回值判定,default = 未登记前缀且没用窗口 API)。 合同一侧(`hostChannelContract.ts`、`host-delegation.ts`、客户端模式预取、Host 通用路由的登记表 `hostIpcEntries/`)的通道名全部静态解析:解析不出任何一个时脚本直接失败,不会生成本清单。 @@ -95,12 +95,12 @@ | # | 领域 | 通道数 | 巡检调用到 | 调用次数 | 主要模块 | |---:|---|---:|---:|---:|---| | 1 | 伙伴与 IM | 137 | 22 | 128 | im 60、maker-ipc 40、localDb 28 | -| 2 | 任务、消息与输入队列 | 111 | 17 | 123 | maker-ipc 69、localDb 25、bootstrap-electron 12 | -| 3 | 插件、技能与 MCP | 149 | 16 | 93 | cindy-brain 53、skillhub 41、plugin-market 19 | -| 4 | 供应商与模型 | 79 | 14 | 79 | maker-ipc 52、local-model-runtime 19、bootstrap-electron 4 | +| 2 | 任务、消息与输入队列 | 112 | 17 | 123 | maker-ipc 69、localDb 26、bootstrap-electron 12 | +| 3 | 插件、技能与 MCP | 151 | 16 | 93 | cindy-brain 56、skillhub 41、plugin-market 19 | +| 4 | 供应商与模型 | 80 | 14 | 79 | maker-ipc 52、local-model-runtime 19、bootstrap-electron 4 | | 5 | git 与工作树 | 65 | 9 | 75 | git-context 21、git-review 21、worktree 13 | -| 6 | 设备互联与远程执行 | 75 | 7 | 66 | device-link 41、remote-ssh 29、bootstrap-electron 4 | -| 7 | 未登记前缀 | 125 | 17 | 29 | maker-ipc 57、bootstrap-electron 24、billing 21 | +| 6 | 设备互联与远程执行 | 74 | 7 | 66 | device-link 40、remote-ssh 29、bootstrap-electron 4 | +| 7 | 未登记前缀 | 124 | 17 | 29 | maker-ipc 55、bootstrap-electron 24、billing 21 | | 8 | 记忆、学习与钩子 | 42 | 4 | 24 | hook-control 27、learn-host 6、maker-ipc 6 | | 9 | 账号与凭据 | 40 | 4 | 17 | bootstrap-electron 30、device-link 7、subscription-accounts 2 | | 10 | 设置与偏好 | 34 | 9 | 15 | bootstrap-electron 9、appearance-settings-ipc 8、maker-ipc 6 | @@ -259,9 +259,9 @@ S·本地:界面设置与登录首帧提示,由窗口本地读同一份 prof | 通道 | 类型 | 归属 | 原因 | 调用次数 | 注册文件 | |---|---|---|---|---:|---| -| `sidebar-settings:load-snapshot-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示) | 同步通道·界面设置:窗口本地读同一份 profile 文件 | 21 | `sidebarSettingsStore.ts` | +| `sidebar-settings:load-snapshot-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示) | 同步通道·界面设置:窗口本地读同一份 profile 文件 | 21 | `sidebarSettingsStore.desktop.ts` | | `ghosts:recommendations` | event | 同步·数据归 Host(需窗口缓存镜像) | 同步通道·插件、技能与 MCP:数据归 Host,需窗口缓存镜像(Host 经事件流推送,窗口同步回答缓存)或改界面为异步,放进对应小批单独设计 | 8 | `cindy-brain/index.ts` | -| `sidebar-settings:claim-renderer-legacy-owner-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示) | 同步通道·界面设置:窗口本地读同一份 profile 文件 | 8 | `sidebarSettingsStore.ts` | +| `sidebar-settings:claim-renderer-legacy-owner-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示) | 同步通道·界面设置:窗口本地读同一份 profile 文件 | 8 | `sidebarSettingsStore.desktop.ts` | | `auth:has-persisted-session-hint-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示) | 同步通道·账号提示:只读 profile 里的首帧提示(事件流连上之前就要回答),登录状态仍以 Host 为准 | 4 | `bootstrap-electron.ts` | | `appearance-settings:get-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示) | 同步通道·界面设置:窗口本地读同一份 profile 文件 | 3 | `appearance-settings-ipc.ts` | | `layout:get` | event | 同步·本地(窗口读 profile:界面设置与首帧提示) | 同步通道·界面设置:窗口本地读同一份 profile 文件 | 3 | `layout/index.ts` | @@ -287,7 +287,7 @@ S·本地:界面设置与登录首帧提示,由窗口本地读同一份 prof | `model-favorites:host-reply` | event | R | 主进程向界面要数据的回执协议:数据在界面本地存储,Host 要用需经窗口往返,先不排期 | 0 | `maker-ipc/modelFavoritesSync.ts` | | `setup-migration:host-reply` | event | R | 主进程向界面要数据的回执协议:数据在界面本地存储,Host 要用需经窗口往返,先不排期 | 0 | `setup-migration/rendererPrefsHost.ts` | -## C 类全量(90) +## C 类全量(96) C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做的(终端优先级低)。C-两段式:窗口保留处理者做界面动作,数据那一半调 Host,每个需要一个 Host 接口,计入但低频、排在后面。C-窗口本地:路径来自用户在本窗口的选择,客户端模式下照常注册,不计入。C-专项设计:安全边界,先读 docs/product-rules/input-handoff.md,方案出来前不动。 @@ -322,7 +322,10 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `fs:resolve-path` | invoke | C-窗口本地 | 用户在本窗口选择或拖入的本机文件、本机进程监视:窗口直接处理,客户端模式下照常注册 | 0 | `bootstrap-electron.ts` | | `fs:stat-path` | invoke | C-窗口本地 | 用户在本窗口选择或拖入的本机文件、本机进程监视:窗口直接处理,客户端模式下照常注册 | 0 | `fsBrowse/ipc.ts` | | `ghosts:background-tasks:reveal` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 在访达/资源管理器或系统浏览器里打开后台持有的内容 | 0 | `maker-ipc/register.ts` | +| `ghosts:card:remote-mail-attachment` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:dialog;窗口做界面动作,数据那一半调 Host | 0 | `cindy-brain/index.ts` | | `ghosts:export` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host | 0 | `cindy-brain/index.ts` | +| `ghosts:github-release` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.getFocusedWindow;窗口做界面动作,数据那一半调 Host | 0 | `cindy-brain/index.ts` | +| `ghosts:install-github-release` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.getFocusedWindow;窗口做界面动作,数据那一半调 Host | 0 | `cindy-brain/index.ts` | | `ghosts:library-delete` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host | 0 | `cindy-brain/index.ts` | | `ghosts:library-pick-location` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host | 0 | `cindy-brain/index.ts` | | `ghosts:library-reattach-legacy` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host | 0 | `cindy-brain/index.ts` | @@ -359,17 +362,20 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `maker:file-browser:stat` | invoke | C-后台 | 任务范围内的文件操作:换窗口时不能断,网页和手机也要用,路径授权跟着运行时 | 0 | `file-browser/index.ts` | | `maker:file-browser:stop-watch` | invoke | C-后台 | 任务范围内的文件操作:换窗口时不能断,网页和手机也要用,路径授权跟着运行时 | 0 | `file-browser/index.ts` | | `maker:file-browser:write-file` | invoke | C-后台 | 任务范围内的文件操作:换窗口时不能断,网页和手机也要用,路径授权跟着运行时 | 0 | `file-browser/index.ts` | +| `maker:get-plugin-write-access-recovery` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 未登记前缀,但处理函数用到窗口 API:dialog;窗口做界面动作,数据那一半调 Host | 0 | `maker-ipc/register.ts` | | `maker:html-preview:cancel` | invoke | C-后台 | 任务范围内的文件操作:换窗口时不能断,网页和手机也要用,路径授权跟着运行时 | 0 | `file-browser/html-preview-ipc.ts` | | `maker:html-preview:open` | invoke | C-后台 | 任务范围内的文件操作:换窗口时不能断,网页和手机也要用,路径授权跟着运行时 | 0 | `file-browser/html-preview-ipc.ts` | | `maker:mcp-apps:v1` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.fromWebContents、shell;窗口做界面动作,数据那一半调 Host | 0 | `mcp-apps/ipc.ts` | | `maker:mcp:duplicates:choose` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 弹出系统选择框后写入后台数据:选择在窗口,结果归后台 | 0 | `maker-ipc/mcpHandlers.ts` | | `maker:remote-ssh:review-host-key` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 设备互联与远程执行,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host | 0 | `remote-ssh/index.ts` | +| `maker:retry-plugin-write-access` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 未登记前缀,但处理函数用到窗口 API:dialog;窗口做界面动作,数据那一半调 Host | 0 | `maker-ipc/register.ts` | | `maker:search:cancel` | invoke | C-后台 | 任务范围内的文件操作:换窗口时不能断,网页和手机也要用,路径授权跟着运行时 | 0 | `file-browser/search/index.ts` | | `maker:search:start` | invoke | C-后台 | 任务范围内的文件操作:换窗口时不能断,网页和手机也要用,路径授权跟着运行时 | 0 | `file-browser/search/index.ts` | | `peek-file-header` | invoke | C-窗口本地 | 用户在本窗口选择或拖入的本机文件、本机进程监视:窗口直接处理,客户端模式下照常注册 | 0 | `bootstrap-electron.ts` | | `plugin-market:pick-local-source` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 弹出系统选择框后写入后台数据:选择在窗口,结果归后台 | 0 | `plugin-market/registerIpc.ts` | | `profile:choose-avatar` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 弹出系统选择框后写入后台数据:选择在窗口,结果归后台 | 0 | `bootstrap-electron.ts` | | `projects-root:choose` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 弹出系统选择框后写入后台数据:选择在窗口,结果归后台 | 0 | `bootstrap-electron.ts` | +| `provider-share:export-roster` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 供应商与模型,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host | 0 | `device-link/providerShareRuntime.ts` | | `read-file-bytes` | invoke | C-窗口本地 | 用户在本窗口选择或拖入的本机文件、本机进程监视:窗口直接处理,客户端模式下照常注册 | 0 | `bootstrap-electron.ts` | | `read-file-for-attachment` | invoke | C-窗口本地 | 用户在本窗口选择或拖入的本机文件、本机进程监视:窗口直接处理,客户端模式下照常注册 | 0 | `bootstrap-electron.ts` | | `skillhub:pick-local` | invoke | C-两段式(窗口做界面动作,数据调 Host) | 弹出系统选择框后写入后台数据:选择在窗口,结果归后台 | 0 | `skillhub/registerIpc.ts` | @@ -404,12 +410,12 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | 模块 | 已代理 | A | B | W | S | R | C | 合计 | |---|---:|---:|---:|---:|---:|---:|---:|---:| -| maker-ipc | 28 | 302 | 10 | 0 | 0 | 3 | 14 | 357 | +| maker-ipc | 29 | 297 | 10 | 0 | 0 | 3 | 16 | 355 | | bootstrap-electron | 5 | 128 | 61 | 0 | 1 | 0 | 20 | 215 | | im | 0 | 60 | 0 | 0 | 0 | 0 | 1 | 61 | -| localDb | 30 | 56 | 1 | 0 | 0 | 0 | 4 | 91 | -| cindy-brain | 7 | 49 | 2 | 0 | 6 | 0 | 5 | 69 | -| device-link | 0 | 49 | 0 | 0 | 0 | 0 | 3 | 52 | +| localDb | 30 | 57 | 1 | 0 | 0 | 0 | 4 | 92 | +| cindy-brain | 7 | 49 | 2 | 0 | 6 | 0 | 8 | 72 | +| device-link | 0 | 48 | 0 | 0 | 0 | 0 | 4 | 52 | | skillhub | 0 | 40 | 0 | 0 | 0 | 0 | 2 | 42 | | remote-ssh | 0 | 28 | 0 | 0 | 0 | 0 | 1 | 29 | | hook-control | 0 | 27 | 0 | 0 | 0 | 0 | 0 | 27 | @@ -442,6 +448,7 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | local-agent | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | | model-access | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | | provider-group | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | +| quota-overview | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | | settingsNavigationIpc | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | | task-management | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | | task-migration | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | @@ -471,7 +478,7 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | right-sidebar-window | 0 | 0 | 11 | 0 | 0 | 0 | 0 | 11 | | rsb-browser-bridge | 0 | 0 | 12 | 0 | 0 | 0 | 0 | 12 | | sidebar-tab-window | 0 | 0 | 10 | 0 | 0 | 0 | 0 | 10 | -| sidebarSettingsStore | 0 | 0 | 0 | 3 | 2 | 0 | 0 | 5 | +| sidebarSettingsStore.desktop | 0 | 0 | 0 | 3 | 2 | 0 | 0 | 5 | | sidebarWindowExpansionIpc | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | | updateService | 0 | 0 | 17 | 0 | 0 | 0 | 0 | 17 | | voice-conversation | 0 | 0 | 22 | 0 | 0 | 0 | 0 | 22 | @@ -826,6 +833,7 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `ghosts:card:get` | invoke | contract | 0 | `cindy-brain/index.ts` | | `ghosts:card:get-remote` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:card:list-by-session` | invoke | contract | 13 | `cindy-brain/index.ts` | +| `ghosts:card:remote-mail-attachment` | invoke | C-两段式(窗口做界面动作,数据调 Host)(插件、技能与 MCP,但处理函数用到窗口 API:dialog;窗口做界面动作,数据那一半调 Host) | 0 | `cindy-brain/index.ts` | | `ghosts:card:report-height` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:clear-unread` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:composer-list` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | @@ -837,12 +845,14 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `ghosts:errand-prefs` | event | 同步·数据归 Host(需窗口缓存镜像)(同步通道·插件、技能与 MCP:数据归 Host,需窗口缓存镜像(Host 经事件流推送,窗口同步回答缓存)或改界面为异步,放进对应小批单独设计) | 0 | `cindy-brain/index.ts` | | `ghosts:errand-prefs:set` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:export` | invoke | C-两段式(窗口做界面动作,数据调 Host)(插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host) | 0 | `cindy-brain/index.ts` | +| `ghosts:github-release` | invoke | C-两段式(窗口做界面动作,数据调 Host)(插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.getFocusedWindow;窗口做界面动作,数据那一半调 Host) | 0 | `cindy-brain/index.ts` | | `ghosts:handoff-delete` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:handoff-folder` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:handoff-list` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:inspect` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:install` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:install-consent:resolve` | invoke | contract | 0 | `cindy-brain/index.ts` | +| `ghosts:install-github-release` | invoke | C-两段式(窗口做界面动作,数据调 Host)(插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.getFocusedWindow;窗口做界面动作,数据那一半调 Host) | 0 | `cindy-brain/index.ts` | | `ghosts:legacy-recovery-status` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:library-bind` | invoke | A(插件、技能与 MCP) | 0 | `cindy-brain/index.ts` | | `ghosts:library-delete` | invoke | C-两段式(窗口做界面动作,数据调 Host)(插件、技能与 MCP,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host) | 0 | `cindy-brain/index.ts` | @@ -970,6 +980,7 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `plugin-oauth:submit-input` | invoke | A(账号与凭据) | 0 | `device-link/ipc.ts` | | `plugin-oauth:submit-secret` | invoke | A(账号与凭据) | 0 | `device-link/ipc.ts` | | `provider-share:command` | invoke | A(供应商与模型) | 4 | `device-link/providerShareRuntime.ts` | +| `provider-share:export-roster` | invoke | C-两段式(窗口做界面动作,数据调 Host)(供应商与模型,但处理函数用到窗口 API:BrowserWindow.fromWebContents、dialog;窗口做界面动作,数据那一半调 Host) | 0 | `device-link/providerShareRuntime.ts` | | `self-hosted-relay:command` | invoke | A(设备互联与远程执行) | 3 | `device-link/selfHostedRelayRuntime.ts` | | `shared-task:account` | invoke | A(设备互联与远程执行) | 0 | `device-link/sharedTaskIpc.ts` | @@ -1307,6 +1318,7 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `local-db:session-share:unlock` | invoke | A(任务、消息与输入队列) | 0 | `localDb/ipc/session-share.ts` | | `local-db:sessions:ack-interrupted` | invoke | A(任务、消息与输入队列) | 0 | `localDb/ipc/sessions.ts` | | `local-db:sessions:create` | invoke | contract | 1 | `localDb/ipc/sessions.ts` | +| `local-db:sessions:discard-unused` | invoke | A(任务、消息与输入队列) | 0 | `localDb/ipc/sessions.ts` | | `local-db:sessions:dismiss-pending-alerts` | invoke | A(任务、消息与输入队列) | 0 | `localDb/ipc/sessions.ts` | | `local-db:sessions:error-tail-pending` | invoke | contract | 36 | `localDb/ipc/sessions.ts` | | `local-db:sessions:get` | invoke | contract | 32 | `localDb/ipc/sessions.ts` | @@ -1475,7 +1487,7 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `maker:get-new-maker-defaults` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/register.ts` | | `maker:get-new-maker-worktree-branch-pref` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/newMakerWorktreeBranchPreferenceHandler.ts` | | `maker:get-pending-interactions` | invoke | contract | 30 | `maker-ipc/register.ts` | -| `maker:get-plugin-write-access-recovery` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/register.ts` | +| `maker:get-plugin-write-access-recovery` | invoke | C-两段式(窗口做界面动作,数据调 Host)(未登记前缀,但处理函数用到窗口 API:dialog;窗口做界面动作,数据那一半调 Host) | 0 | `maker-ipc/register.ts` | | `maker:get-session-agent-switch-intent` | invoke | A(任务、消息与输入队列) | 16 | `maker-ipc/sessionAgentSwitchHandler.ts` | | `maker:get-session-tree` | invoke | A(任务、消息与输入队列) | 0 | `maker-ipc/register.ts` | | `maker:get-workflow-progress` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/register.ts` | @@ -1598,12 +1610,12 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `maker:provider:test-connection` | invoke | A(供应商与模型) | 0 | `maker-ipc/providerHandlers.ts` | | `maker:regenerate-title` | invoke | A(任务、消息与输入队列) | 0 | `maker-ipc/title.ts` | | `maker:resolve-interaction` | invoke | contract | 0 | `maker-ipc/register.ts` | -| `maker:retry-plugin-write-access` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/register.ts` | +| `maker:retry-plugin-write-access` | invoke | C-两段式(窗口做界面动作,数据调 Host)(未登记前缀,但处理函数用到窗口 API:dialog;窗口做界面动作,数据那一半调 Host) | 0 | `maker-ipc/register.ts` | | `maker:review:start` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/reviewStartHandler.ts` | | `maker:rewind:commit` | invoke | A(任务、消息与输入队列) | 0 | `maker-ipc/rewind.ts` | | `maker:rewind:preview` | invoke | A(任务、消息与输入队列) | 0 | `maker-ipc/rewind.ts` | | `maker:run` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/register.ts` | -| `maker:runtime-plugins` | invoke | A(插件、技能与 MCP) | 0 | `maker-ipc/register.ts` | +| `maker:runtime-plugins` | invoke | contract | 0 | `maker-ipc/register.ts` | | `maker:scan-at-resources` | invoke | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `maker-ipc/register.ts` | | `maker:schedule:create` | invoke | A(自动化) | 0 | `maker-ipc/schedule.ts` | | `maker:schedule:create-from-template` | invoke | A(自动化) | 0 | `maker-ipc/schedule.ts` | @@ -1846,6 +1858,12 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 |---|---|---|---:|---| | `provider-group:command` | invoke | A(供应商与模型) | 16 | `provider-group/ipc.ts` | +### quota-overview + +| 通道 | 类型 | 归属 | 调用次数 | 注册文件 | +|---|---|---|---:|---| +| `quota-tray:event` | event | A(未登记前缀,处理函数没有用到窗口 API) | 0 | `quota-overview/windowsPanel.ts` | + ### region-screenshot | 通道 | 类型 | 归属 | 调用次数 | 注册文件 | @@ -2089,15 +2107,15 @@ C-后台:换窗口时不能断、网页和手机也要用,计入要 Host 做 | `sidebar-tab-window:presentation-ready` | invoke | B(窗口外壳、窗口布局与多窗口) | 0 | `sidebar-tab-window/ipc.ts` | | `sidebar-tab-window:renderer-ready` | invoke | B(窗口外壳、窗口布局与多窗口) | 1 | `sidebar-tab-window/ipc.ts` | -### sidebarSettingsStore +### sidebarSettingsStore.desktop | 通道 | 类型 | 归属 | 调用次数 | 注册文件 | |---|---|---|---:|---| -| `sidebar-settings:claim-renderer-legacy-owner-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示)(同步通道·界面设置:窗口本地读同一份 profile 文件) | 8 | `sidebarSettingsStore.ts` | -| `sidebar-settings:load-snapshot-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示)(同步通道·界面设置:窗口本地读同一份 profile 文件) | 21 | `sidebarSettingsStore.ts` | -| `sidebar-settings:save-pinned-order` | invoke | W(窗口本地设置:窗口直接读写同一份 profile 文件,不经 Host) | 0 | `sidebarSettingsStore.ts` | -| `sidebar-settings:set-main-view-hidden` | invoke | W(窗口本地设置:窗口直接读写同一份 profile 文件,不经 Host) | 0 | `sidebarSettingsStore.ts` | -| `sidebar-settings:set-project-hidden` | invoke | W(窗口本地设置:窗口直接读写同一份 profile 文件,不经 Host) | 0 | `sidebarSettingsStore.ts` | +| `sidebar-settings:claim-renderer-legacy-owner-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示)(同步通道·界面设置:窗口本地读同一份 profile 文件) | 8 | `sidebarSettingsStore.desktop.ts` | +| `sidebar-settings:load-snapshot-sync` | event | 同步·本地(窗口读 profile:界面设置与首帧提示)(同步通道·界面设置:窗口本地读同一份 profile 文件) | 21 | `sidebarSettingsStore.desktop.ts` | +| `sidebar-settings:save-pinned-order` | invoke | W(窗口本地设置:窗口直接读写同一份 profile 文件,不经 Host) | 0 | `sidebarSettingsStore.desktop.ts` | +| `sidebar-settings:set-main-view-hidden` | invoke | W(窗口本地设置:窗口直接读写同一份 profile 文件,不经 Host) | 0 | `sidebarSettingsStore.desktop.ts` | +| `sidebar-settings:set-project-hidden` | invoke | W(窗口本地设置:窗口直接读写同一份 profile 文件,不经 Host) | 0 | `sidebarSettingsStore.desktop.ts` | ### sidebarWindowExpansionIpc diff --git a/docs/host/client-handoff-foundation.md b/docs/host/client-handoff-foundation.md index 84ed26f9cc9..539cb0778e7 100644 --- a/docs/host/client-handoff-foundation.md +++ b/docs/host/client-handoff-foundation.md @@ -40,6 +40,21 @@ Electron 内执行任务,使用原桌面装配;不自动启动 Host、不迁 首次迁移、profile 写入权切换、旧客户端恢复和个人版升级命令不属于本次地基。 真实账号、真实模型服务、正式安装包、Windows、手机及整机迁移未实测时不能宣称通过。 +## 迁移前的插件批准预检 + +正式接管已有 profile 之前,先退出使用它的桌面和 Host,运行 +`cindy-host migration-preflight `。命令只读地清点 profile 下未归属的 +`brain`、`cindy-brain` 和每个 owner 下这两种目录中的旧布局安装。 +只在命令退出码为 0 且 JSON 的 `allowed: true`、`count: 0` 时进入下一步;清点失败或非零时停止。 +如果缺批准记录,用 Cindy Desktop v0.1.48 或更新的版本以内嵌模式打开同一个 profile, +等桌面完成已有的一次性补写,退出桌面再跑预检。跨账号 profile 须让相应账号完成补写。 +仍非零时保持阻断;缺失记录本身不能作为恢复批准的授权。此命令不触发交接或写入批准, +整机迁移仍须满足发布开关和原验收条件。 + +Host 启动会在当前稳定账号的插件对账中记录缺批准的旧布局安装数量及安装标识, +可用 `cindy-host status` 或 `cindy-host status --json` 查看。`unchecked`(JSON `null`)表示 +当前运行时尚无结果。状态是当前运行账号的诊断,迁移放行以离线整份 profile 的预检为准。 + ## 尚未接通的客户端界面通道 本层的平台 RPC 是后台调用原生能力的入口,不等于已接通所有 Renderer IPC。 diff --git a/docs/host/client-mode-account-switch.md b/docs/host/client-mode-account-switch.md new file mode 100644 index 00000000000..184d7effc1d --- /dev/null +++ b/docs/host/client-mode-account-switch.md @@ -0,0 +1,547 @@ +# 客户端模式下的账号切换与添加账号:定稿方案 + +状态:方案已定稿(审核方 2026-11-17),**尚未实现**。分类为乙(迁移前必须完成)。实现排在当前甲项之后。放行表里的对应记录: + +- 第二节“已知限制(仅限测试期)”:这一行写的是测试期的后果和临时做法; +- 第四节“用户已定的产品形态”:用户的原话和安全审查结论; +- 第五节“第 25 行 25b 的修订”和“乙:客户端模式下窗口切换、添加账号”:设计决定。 + +本文把这几处,以及当时分散在几轮讨论里的决定,合成一份可以单独读懂的方案。行号按集成分支 `185fbef443` +核对;实现时以当时的代码为准。审核方第二轮审稿(2026-11-17)的补充已并入:3.1、3.3、3.5、S1、S5、第六节、第八节与第九节。 + +## 一、背景:窗口是第二个写方 + +客户端模式下,窗口进程只当界面,任务、凭据和 owner 都由 Host 管。现有设计也是这样: + +- 窗口不提交 owner:`requestStableOwnerPostCommit`,`apps/desktop/src/main/authManager.ts:325`,Host 是唯一写 owner 的一方; +- 续期交给 Host:`authManager.setAuthRefreshOverride`,`apps/desktop/src/main/bootstrap-electron.ts:1431`; +- 会话失效时不删凭据:`invalidateSession`,`authManager.ts:3924`。 + +但窗口里的切换账号、添加账号,以及登录本身,今天仍在窗口本地执行: + +- 五个账号通道在 `bootstrap-electron.ts` 里不分模式注册: + - `auth:accounts:list`,:6894; + - `auth:accounts:sync`,:6899; + - `auth:accounts:switch`,:6908; + - `auth:accounts:begin-add`,:6917; + - `auth:accounts:cancel-add`,:6926。 +- 登录动作也一样:`auth:get-login-state` :6874、`auth:dispatch-login-action` :6876、`auth:get-captcha-challenge-url` :6885。 +- Host 合同里只有三项:`auth:logout`、`auth:refresh`、`auth:get-state`,见 `packages/maker-shared/src/hostChannelContract.ts:409` 起。 + +窗口在本地切换到 B,走的是完整的 `completeLogin`(`authManager.ts:5315`),在 Host 读的同一份 profile 里: + +- 写当前会话:`writePersistedAuthSessionOrThrow`,:5356; +- 写账号保管库; +- 经 `withCloudOwnerCommit`(:2354)把技能投影的 owner 提交成 B。 + +这样窗口就成了第二个写凭据、写 owner 的一方。Host 不会跟着换,结果如下(第十节有完整写法): + +- 界面先显示 B,下一次拿到 Host 的状态时又弹回 A; +- Host 的续期读到 B 的会话会失败; +- 重启 Host 因会话与库的账号不一致而起不来。 + +凭据层面,三个写入点都在同一把跨进程锁里先重读再写,由 C 兜住。见放行表第五节“④ 窗口的三个写入点”。语义层面的问题,即界面是 B、后台还在跑 A,由本方案解决。 + +## 二、方向:交给 Host 做,窗口只当界面 + +切换账号、添加账号和登录都由 Host 执行,窗口只渲染界面、转交用户的操作。不采用“窗口做完再通知 Host”,原因有两个: + +- 那样窗口会长期是第二个写方,与客户端模式的设计、也与 C 的单写方前提相反。 +- Host 已经有全部零件: + - 读写同一份账号保管库,用同一把锁 `AUTH_ACCOUNT_VAULT_LOCK_FILE`; + - 运行时拆装:`disposeOwnerRuntime` `apps/host/src/main.ts:1925`,`ensureRuntime` :682; + - 登录提交:`commitLoginSessionAndOwner`,`apps/host/src/agent/skill-projection-owner.ts:112`; + - 账号边界停止:`runOwnerBoundary`,见第七节。 + +接口:新增 `/api/auth/accounts/*` 一组。 + +| 窗口通道 | Host 路径 | 说明 | +|---|---|---| +| `auth:accounts:list` | `/api/auth/accounts/list` | 只读保管库,返回与 `DesktopAccountSwitcherSnapshot` 同形的 `{ accounts, mutationAllowed }`。当前项按 Host 的账号标,不按窗口本地;闸门关着或切换进行中时 `mutationAllowed` 为 false | +| `auth:accounts:sync` | `/api/auth/accounts/sync` | passport 续期与成员同步:网络请求在锁外,锁内重读、比对后写(8.4)。这会写凭据,只能由单写方做;主体搬自桌面 `syncSavedAccounts`(`authManager.ts:4090`),成为共用核心 | +| `auth:accounts:switch` | `/api/auth/accounts/switch` | body `{ accountKey }`。确认在窗口那一侧做(第六节),Host 收到请求就执行第八节的顺序 | +| `auth:accounts:begin-add` | `/api/auth/accounts/add/begin` | Host 开始一个添加账号的登录事务,返回登录状态(与 `DesktopLoginActionResult` 同形,不含令牌)。闸门关着时拒绝,提示同切换(⑥);没有当前账号时的登录也一样(3.5) | +| `auth:dispatch-login-action`(客户端模式下的添加账号) | `/api/auth/accounts/add/action` | body 形如桌面的 `DesktopLoginAction`,由 Host 解释 | +| `auth:get-login-state`(客户端模式下) | `/api/auth/accounts/add/state` | 读 Host 登录事务的当前状态(`DesktopLoginState`,不含令牌,字段见 S5) | +| `auth:get-captcha-challenge-url`(客户端模式下) | `/api/auth/accounts/add/captcha-url` | 返回按构建区域拼出的公开人机验证页地址,无副作用、不含凭证(桌面 `bootstrap-electron.ts:6883–6888` 的注释);验证结果由窗口在 `request-code` 动作里带给 Host(S1) | +| `auth:accounts:cancel-add` | `/api/auth/accounts/add/cancel` | 取消 Host 的登录事务;已开始提交的不取消,同桌面 | + +- 没有当前账号时的登录也走这一组 `add/*`,见 3.5。 +- 合同项写进 `HOST_CONTRACT_CHANNELS` 的 Auth 段,形状同现有三项,标 `trustedRenderer: true`。 +- 路由写进 `apps/host/src/service.mjs`,与 `/api/auth/state`、`/api/auth/refresh` 同处(:97、:100)。 +- `/api/auth/*` 本来就不算 owner 请求(`apps/host/src/server.mjs:166`),切换进行中仍能调用。 +- 推送沿用现有的 `auth_changed` 事件,例如退出登录收尾时发的那条(`main.ts:1560`)。窗口经 `receiveHostAuthState`(`authManager.ts:501`)换显示。 +- 不走 device-link:这几个通道不在 device-link 白名单里,远程控制端本来就不能换账号。 + +## 三、设计点(审核方已定) + +### 3.1 只给 Host 的账号切换、登录完成用的 owner 提交入口(定 (ii)) + +serve 进程在加载前注入“拒绝提交 owner”:`main.ts:295` 调 `refuseSkillProjectionOwnerCommit`,定义在 `skill-projection-owner.ts:30`。只有 `cindy-host login` 放开(`allowSkillProjectionOwnerCommit`,:35)。 + +serve 要在这几处提交 owner: +- 账号切换(第八节); +- 添加账号完成; +- 没有当前账号时的登录完成(3.5); +- 启动时的补完(8.3:会话已是新账号、owner 还没提交时,按会话补提交)。 + +不全局放开,而是新增一个入口,只给 Host 的账号切换、登录完成及其启动时的补完用: + +- 放开的范围在词法上限定在这次切换或登录完成的函数内部(try/finally); +- 绑在这一次操作上,不是全局开关:进行中,别的调用方去提交仍然被拒; +- 失败后恢复为拒绝; +- 这几处之外 serve 照旧拒绝,现有根守护的语义不改。 +- 建议的实现:把“提交 owner 的能力”作为参数传进这次操作,而不是在一段时间内翻转全局开关。下面第 2 条测试正好约束这一点。 + +必做的三条测试: + +1. 这几处之外 serve 照旧拒绝(现有根守护不改语义); +2. 一次切换进行中,另一个提交尝试被拒; +3. 切换失败后,恢复为拒绝。 + +### 3.2 客户端模式下由 Host 提交 owner(25b 的修订) + +- **原决定**(25b 方案 A):窗口提交 owner,Host 只加入窗口已提交的同一 owner,serve 注入拒绝。 +- **为什么改**:窗口在本地切换、添加账号会提交新 owner,而 Host 不跟。用户已定登录结果交给 Host(第四节),切换由 Host 执行,提交也就归 Host。 +- **改后的分工**:只限客户端模式。 + - Host 在切换账号、登录完成时经 3.1 的入口提交 owner; + - 窗口在客户端模式下不再提交 owner,这是桌面改动,归第一阶段之后的桌面 PR; + - 独立安装的 Host 不变,仍由 `cindy-host login` 提交(`apps/host/src/login-cli.mjs:144`)。 + +### 3.3 `discoverHostOwner` 的缺口一并处理 + +`discoverHostOwner`(`apps/host/src/profile-path.mjs:45`)只看 profile 里 `cindy-*.db` 的个数: + +- 一个库:启动时直接认它的账号(`main.ts:2088` 起),再拿会话去对;会话是另一个账号时,`resolveAccountUser` 判为不一致而启动失败(`main.ts:452`)。 +- 零个或两个以上的库:读会话记录,会话有效就按会话的账号起(`main.ts:2096–2100`),没有有效会话才停下并报原因(:2099)。 +- 状态命令(`main.ts:204`)只数库文件,两个以上的库时读不出边界状态。 + +所以运行中切换过一次、两个库都在时,今天的启动已经会按会话认 owner。会撞上的是“只有一个库、会话却是另一个账号”,例如新账号的库还没建成就崩溃(8.3 的 (ii))。改成任何时候都按已提交的会话认 owner,状态命令同样按会话读,与切换同一单元做。 + +**会话与技能投影的 owner 不一致时谁说了算:照桌面,以会话为准。** 桌面冷启动先续期持久化的会话,再把技能投影的 owner 提交成会话的账号: + +- `runColdStartRefreshFlow` 里的 `withCloudOwnerCommit`,`authManager.ts:5134` 起,经 :2370 进 `withGhostSkillProjectionOwnerCommit`(`apps/desktop/src/main/authBoundaryQuarantine.ts:381`); +- 进程内已登录的快路径,在投影边界不是这个账号的 stable 时也补提交一次(`authManager.ts:4667–4669`)。 + +Host 照做: + +- 启动时按会话记录的账号认 owner; +- 投影边界不是这个账号的 stable 时,serve 在启动时补一次提交(经 3.1 的入口); +- 补不成就进入启动失败的 error 状态(8.2 第三层),不猜、不回退到别的账号。 + +### 3.4 `cindy-host login` 写出与桌面登录相同的存储状态 + +现在 `cindy-host login` 只写 v1 会话记录:账号库里不写这个账号,不写 passport,不写旧版令牌(放行表第五节并存行“后续九”)。要求改成写出与桌面 `completeLogin` 相同的状态,即账号库里的账号与 passport。添加账号由 Host 登录以后,Host 本来就要会写这些,两条路共用同一段写法。 + +做完后,C 的差别 a(v1 仍持有令牌时,账号库没有当前账号也写 v1)应当可以去掉。 + +### 3.5 没有当前账号时的登录,以及重新登录同一账号 + +- **退出登录后在窗口里登录**:走同一个登录事务和同一组路由(`add/begin`、`add/action`、`add/state`、`add/cancel`)。完成后的顺序是第八节去掉“拆 A”的部分:此时没有运行时,不调 `runOwnerBoundary`。 + 1. 经 3.1 的入口提交会话与 owner; + 2. `ensureRuntime(B)`; + 3. `startDeviceLink()`; + 4. 发 `auth_changed`。 +- **解除窗口本地登录的拦截**:Host 启动失败、auth state 带 `hostUnavailable` 时,客户端模式下的窗口拒绝自己的登录与跳过登录(`apps/desktop/src/main/authManager.ts` 的 `hostNotStartedInClientMode`,用在 `dispatchLoginAction` 与 `enterLocalMode` 开头,固定码 `HOST_NOT_STARTED`)。这一路改由 Host 的登录事务执行之后,去掉这两个条件;原因面板保留,面板上的操作改成走 Host 的登录(error 状态下也能开始,第九节第 7 项)。 +- **与乙 10 的关系**:乙 10 是“serve 运行中不重新采用会话,`cindy-host login` 之后要重启 serve”(放行表第五节)。窗口里的登录经 Host 自己的事务完成,由 serve 直接采用,不需要重启,所以这条路径不再受乙 10 影响。另起进程的 `cindy-host login` 仍要重启,乙 10 那一行保留,只记“窗口登录已不受影响”。 +- **登录失效后重新登录同一账号**: + - 会话失效时 `invalidateHostSession` 已经经 `runOwnerBoundary` 拆掉运行时(`main.ts:567` 起),重新登录时没有在跑的运行时; + - owner 不变:投影边界已是这个账号的 stable,提交是同 owner 的空操作; + - 运行时要重建(`ensureRuntime`),因为失效时已经拆掉。 +- **登录完成时的区域规则**: + - Host 在登录完成时按 `apps/host/src/auth/region-policy.ts` 的 `assertHostSessionRegion`(:35)判断,与桌面同一条 `canRestoreAuthSessionForMembership`;`runHostLogin` 已在 `apps/host/src/auth/login.mjs:117` 这样做。 + - 拒绝时回固定码 `REGION_MISMATCH`,窗口显示与桌面相同的提示 `login.errors.REGION_MISMATCH`(zh-CN `:9474` “登录服务区域与当前客户端不匹配”,en `:9517`)。 + - 桌面登录事务里的“区域确认”一步(`realm-confirmation`,`authManager.ts:5522` 起)属于状态机本身,随登录事务一起搬到 Host,界面不变。 + +## 四、用户的决定与安全审查结论 + +- **用户的决定**(2026-11-17,审核方转问):问题是“窗口连着 Host 时,添加账号 / 登录怎么做”,用户选“**窗口照常登录,结果交给 Host(推荐)**”。审核方在选项里向用户承诺:多出的那一次登录凭证在本机内部的传递,单独做安全审查,审查通过前不实现。 +- **安全审查结论**(2026-11-17,审核方): + - 字面做法(窗口登录后把结果交给 Host)会跨进程传长期凭据,而且令牌绑的是窗口的设备,Host 接过去连自己的远程连接身份都起不来。不采用。 + - 改为 Host 发出全部会签发令牌的认证调用,界面和操作不变;窗口只转交用户输入的一次性验证码、联系方式和账号选择。 + - 用户选的时候看重的是“窗口里的登录体验和现在完全一样、所有登录方式都能用”,这一做法满足。这属于“实现方式因审查而调整、用户看到的不变”。 + - 审核方已如实告知用户,用户可以否决,不为此再占用户一次选择。 + - 备选做法(浏览器一路窗口只交 code 和 state,其余几路不可用)不采用。 + +## 五、安全小节:添加账号时登录结果在本机内部的传递 + +### S1. 传的是什么 + +**现状**:桌面每条登录路径的终点都是 `LoginOutcome` 的 `ok`,即一对令牌,落在窗口主进程。 + +- 类型定义:`packages/auth-client/src/types.ts:174–195`,包括 `accessToken`、`refreshToken`、`membership`,以及可选的 `accountToken`、`accountRefreshToken`。 +- 各路径在桌面上的调用点(`authManager.ts`): + - 浏览器、SSO:`exchangeAuthorizationCode`,:5813,PKCE 的 verifier 在本进程里; + - 邮箱或手机验证码:`requestCode` :5740,`verifyCode` :5759; + - 选账号:`exchangeAccountMembership` :5831,`selectAccount` :5846; + - SSO 二次校验:`requestSsoVerificationCode` :5860,`verifySsoVerification` :5881; + - 绑定手机或邮箱:`requestBindingCode` :5891,`verifyBinding` :5907。 +- 落地:`finishFreshLogin`(:5508)→ `completeLogin`(:5315),把 refreshToken 写成当前会话,passport 的刷新令牌进保管库。这些都是**长期凭据**。 +- 设备绑定:桌面签发时用窗口的设备 id(`resolveRuntimeDeviceId`,`authManager.ts:369`);Host 登录时用自己的设备 id(`getOrCreateHostDeviceId`,`login-cli.mjs:110`),并写进会话记录(`apps/host/src/auth/device-identity.mjs:19`)。 + - 用窗口设备 id 签发的会话交给 Host,Host 只能沿用那个 id(`resolveSessionDevice`,:23); + - `canRegisterHostDevice`(:30)会判为不可注册,Host 的 device-link 身份就起不来。 + +**结论**:照字面“把结果交给 Host”,传的是长期凭据,还带着错的设备身份,不采用。 + +**做法**:界面不变,Host 发出所有会签发令牌的认证调用。 + +- 登录事务(相当于桌面 `runLoginAction` 的状态机)在 Host 里跑,用 Host 的设备 id。窗口照旧渲染登录状态(`DesktopLoginActionResult`,不含令牌),把用户的动作转给 Host。 +- 浏览器、SSO 一路: + - Host 生成 PKCE 的 verifier、challenge 和 state,或托管回调用的 pollSecret; + - Host 自己开系统浏览器、听本机回调,或轮询托管回调,与 `runHostLogin`(`apps/host/src/auth/login.mjs:103`)同一做法; + - 窗口只显示“请在浏览器中完成”和取消按钮,跨进程的只有“开始”“取消”两个动作。 +- 验证码、SSO 二次校验、绑定:窗口交的是用户输入的联系方式和一次性验证码,以及“发码”这个动作。ticket(`loginTicket`、`verificationTicket`、`bindTicket`)只在 Host 内存里。 +- 选账号:窗口只交 `accountId`,`accountToken` 或 `loginTicket` 留在 Host。 +- 人机验证:验证页由窗口的渲染层装载(地址是公开的,见第二节);窗口把验证结果(`captchaToken`,一次性、短期)随 `request-code` 动作交给 Host(桌面同样在这一步带上,`authManager.ts:5741`)。 +- 跨进程的物品因此只有用户输入的一次性验证码(短期、服务端一次性)、联系方式、账号 id,以及人机验证的结果(一次性、短期),**都不是长期凭据**。渲染层本来就看得到这些,它们是用户自己输入的。 + +### S2. 经哪个本机接口 + +- 渲染层 → preload → 窗口主进程: + - `apps/desktop/src/preload/preload.ts:2520–2531` 的 `auth*` 方法; + - 主进程按可信渲染层准入(`assertTrustedAppRendererEvent`)。 +- 窗口主进程 → Host:走客户端模式现有的合同代理。 + - 新通道加进 `HOST_CONTRACT_CHANNELS` 的 Auth 段,标 `trustedRenderer: true`。 + - `registerHostDelegatedIpc`(`apps/desktop/src/main/host-delegation.ts:197`)把它们装成代理;`claimProxiedChannels`(`bootstrap-electron.ts:1397`)去掉本地处理器。 + - 请求发到 Host 的本机地址 `/api/...`,带 Bearer 密钥和 `x-cindy-host-instance`。Host 地址只能是本机回环(`resolveHostDelegation`,`host-delegation.ts:38` 起)。 +- Host 侧:`server.mjs` 收 `/api/*` 的 POST,交给 `service.mjs`;`/api/auth/*` 不受 owner 请求闸门挡(`server.mjs:166`)。 +- 路由:`/api/auth/accounts/add/begin`、`/api/auth/accounts/add/action`、`/api/auth/accounts/add/cancel`,与 list、sync、switch 同组(第二节)。 +- 不走 device-link。 + +### S3. 怎么鉴权 + +- 密钥:`apps/host/src/api-token.mjs`。 + - `crypto.randomBytes(32)`(:22),写成 profile 目录里的 `host-api-token`,文件 0600(:25); + - **每个 profile 一把,在 Host 的各次运行之间复用**; + - 比对用 `timingSafeEqual`(`isAuthorized`,:31 起),没有这个头就一律不通过。 +- 交给窗口:窗口启动时从同一个 profile 目录读这个文件(`host-delegation.ts:54` 起),不经命令行、不经环境变量。 +- 实例头:带 `x-cindy-host-instance` 的请求,实例 id 必须等于正在运行的 Host(`server.mjs:143` 起),防止旧窗口打到换过的 Host 上。 +- 够不够:按 S1 的做法,跨进程的东西里没有长期凭据,拿到密钥的同用户进程也拿不到令牌。它最多能发起一次登录事务,但没有用户的验证码或浏览器授权就走不完。按现有模型,够用。 +- 另加两条限制: + 1. 这组接口只接受“Bearer + 实例头”的调用方,拒绝网页端 cookie 会话(`isWebAuthorized` 那一类)。账号增减只给桌面窗口,等同于 `trustedRenderer`。 + 2. 同一时刻只允许一个添加账号事务(S4)。 +- **威胁模型边界**(审核方补,如实写明):同一 OS 用户下的其它进程能读到这把密钥,因此能调用这组接口,例如发起切换账号。这在现有威胁模型之内,同用户进程本来就能读 profile,不另加防护。 + +### S4. 有效期和一次性 + +- Host 的登录事务照桌面的 `loginFlowEpoch` 和 `assertLoginFlowCurrent`(`authManager.ts:3694`): + - 每次 begin 开一个新事务,作废上一个; + - action 不属于当前事务,以 `AUTH_FLOW_SUPERSEDED` 拒绝; + - 事务开始提交(存会话、换 owner)后,cancel 不再生效,同桌面 `isLoginFlowCommitSealed`(:3718); + - 事务结束或超时(与浏览器授权同一上限),清掉 verifier、state、pollSecret 和各种 ticket。 +- 服务端一次性: + - 授权码换一次就失效; + - 托管回调的取回结果只能取一次; + - 验证码与 ticket 由认证服务器保证一次性、短期。 +- 重放: + - 同一条 action 再发一次:事务已推进或已结束,Host 拒绝;Host 漏判时,服务端也会拒绝。 + - 旧窗口的请求:实例头不匹配,被拒。 + +### S5. 日志里不落 + +| 点 | 现状 | 要求 | +|---|---|---| +| 渲染层到 preload | `ipcRenderer.invoke` 不记参数 | 不变 | +| 窗口主进程的代理(`registerHostDelegatedIpc`) | 不记参数、不记响应 | 不变 | +| 窗口的 Host 客户端失败时 `throw new Error(text …)`(`host-delegation.ts:87`),`text` 是 Host 的响应正文 | Host 回什么,窗口就把什么当错误消息 | 由下一行保证 | +| Host 的错误回包(`server.mjs:408–409`,`clientErrorMessage` 见 `apps/host/src/client-error.mjs:12`) | 异常消息原样回给客户端 | 这组路由自己捕获异常,只回固定错误码 `{ error: CODE }`,不带原始消息;认证客户端抛出的异常也不原样转发 | +| Host 的 stdout、stderr | 现有续期失败会记 `error.message` | 新代码只记错误码和事务阶段,不记 body,不记认证服务器的响应 | +| 桌面日志上传 | 按白名单(deny-by-default) | 不变 | + +**必做项:哨兵测试**。在 Host 测试里: + +- 向这组接口发带特征串的验证码、联系方式和人机验证结果; +- 让认证服务器的桩返回带特征串的访问令牌、刷新令牌、`accountToken`、`accountRefreshToken` 和三种 ticket(`loginTicket`、`verificationTicket`、`bindTicket`); +- 让 Host 生成的 PKCE verifier 与 pollSecret 也带特征串(测试里注入); +- 断言下列特征串不出现在任何响应正文、错误消息和 Host 写的日志里: + - 访问令牌、刷新令牌; + - `accountToken`、`accountRefreshToken`; + - PKCE verifier、pollSecret; + - 三种 ticket; + - 验证码; + - 联系方式(例外见下)。 + +Host 返回给窗口的登录状态里有哪些字段(`DesktopLoginState` = `AuthFlowState` 加 `retryAt`、`httpStatus`,`apps/desktop/src/shared/authIpc.ts:32`;`AuthFlowState` 在 `packages/auth-client/src/types.ts:319` 起): + +- **浏览器一路**:只有 `{ step: "browser-redirect"; label }`(:333)。没有授权链接,也就没有 pollSecret 或 state。桌面是在主进程里自己打开授权地址(`shell.openExternal(authUrl)`,`authManager.ts:2983`、:3107),不交给渲染层;Host 照做,由 Host 打开系统浏览器。 +- **完成**:`{ step: "completed"; membership }`(`types.ts:347`),只有成员信息,没有令牌。 +- **联系方式的例外**:验证码一步的状态带回用户刚输入的 `identifier`(`types.ts:332`);绑定一步可能带 `contact`(:342 起);SSO 二次校验只带打码后的 `targetMasked`。这是界面回显用户自己的输入,属于设计内的字段。哨兵测试对联系方式的断言因此是:只允许出现在登录状态的这几个回显字段里,不出现在错误消息、日志和其它任何响应字段里。 + +### S6. 失败时窗口不留副本 + +- 按 S1 的做法,窗口内存里从来没有令牌。用户输入的验证码只在渲染层表单状态和一次 IPC 参数里,表单关闭或重置时随状态丢弃,同桌面的 `resetLoginFlowState`(`authManager.ts:3678`)。 +- 窗口主进程在客户端模式下不能再走本地登录状态机。现在 `auth:dispatch-login-action`、`auth:accounts:begin-add` 在本地注册,本地会持有 `pendingAccountToken` 等变量(`authManager.ts:383`),`completeLogin` 会落盘。桌面 PR 要做到两点: + 1. 这些通道进合同后由代理接管,本地处理器被去掉; + 2. **必做项:第二道保险**。客户端模式下 Host 续期接管时,也就是续期 override 已设置时,本地 `completeLogin`、写会话、写保管库一律拒绝,写法同 `requestStableOwnerPostCommit`(:325)。这是桌面 PR,逐行送审。 +- Host 交付失败:窗口显示错误,让用户重试;**不在本地完成登录、不落盘、不做兜底**。 +- Host 侧失败:Host 撤销刚签发的会话,同 `runHostLogin` 的 `endRefusedSession`(`login.mjs:122` 起);并回滚会话记录,同 `commitLoginSessionAndOwner`。 + +## 六、默认行为(审核方定:与桌面今天一致;失败时不让用户落到更糟的状态) + +- **③ A 队列里没发的输入**:留在 A 的库里,回到 A 再发,与桌面换账号相同。 +- **④ 切换失败**:先验 B、不动 A;B 不行就留在 A,并说明原因。 +- **⑥ 闸门关着时**(同一 profile 上有会开库的桌面在运行,`inputQueue.isHeldForDesktop()`,`apps/host/src/agent/input-queue.mjs:629`):拒绝切换,提示先关那个桌面。添加账号(`add/begin`)和 3.5 里没有当前账号时的登录同样拒绝,给同一句提示。理由与并存规则一致:桌面占用期间,Host 不写两边共用的凭据。 +- **①② 照桌面**:只在有任务在跑时,弹桌面现有的确认框,文案不变。 + - 确认后停掉在跑的任务,并保留中断痕迹:之后有中断横幅,不自动续跑。 + - 没有确认宿主时不切;切换失败留在原账号。 + - 不在 Host 侧另加一次确认界面,因为桌面没有。Host 只加一个兜底:有任务在跑而请求没带“已确认中断”时,以固定码拒绝,窗口弹同一个确认框后重发。原因是窗口快照可能漏掉别的客户端的任务,见 8.5。 + +确认框(`apps/desktop/src/renderer/i18n/locales/*/common.json`): + +| key | 中文(zh-CN) | 英文(en) | +|---|---|---| +| `sidebar.accountSwitcher.runningTaskTitle` | 中断任务并切换账号?(:10713) | Stop running tasks and switch accounts?(:10756) | +| `sidebar.accountSwitcher.runningTaskDescription` | 当前有任务正在运行。切换账号会先中断这些任务,未完成的执行不会继续。(:10714) | Tasks are currently running. Switching accounts will stop them first, and unfinished work will not continue.(:10757) | +| `sidebar.accountSwitcher.runningTaskConfirm` | 中断任务并切换(:10715) | Stop Tasks and Switch(:10758) | +| `logic.confirm.cancel` | 取消 | Cancel | + +确认按钮为 `confirmVariant: 'destructive'`。切换中的提示是 `sidebar.accountSwitcher.switching`(“正在切换账号…” / “Switching accounts…”);失败提示是 `sidebar.accountSwitcher.switchFailed`(“切换失败,请重新登录该账号” / “Could not switch accounts. Sign in to that account again”)。客户端模式下切换失败时的提示要多说一句“刚才在跑的任务已被中断”,文案待用户定(8.2)。 + +入口(都走同一条主进程路径,确认都在渲染层用 `makerChatStore.getRunningSnapshot()` 判断): + +1. 侧边栏账号菜单 `apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx`: + - 切换:`switchSavedAccount`,:215; + - 添加:`openAddAccount`,:156。 +2. 账号切换对话框 `components/sidebar/AccountSwitcherDialog.tsx`: + - 切换:`handleSwitch`,:115; + - 添加:`handleAddAccount`,:133; + - 挂在 `features/plugin/MyPluginsPage.tsx:1179`。 + - 没有确认宿主时不切,见 :104 的注释。 +3. 按当前代码补充:设置页的账号卡片 `components/settings/UserProfileCard.tsx` 也有“添加账号”,即 `openAddAccount`,:146。它用的是同一个确认框(:131 起)。 + +添加账号的登录页 `components/login/AddAccountLoginPage.tsx:47` 调 `beginAddAccount`。切换的路径是 `AuthContext.switchAccount`(`contexts/AuthContext.tsx:612`)→ preload → `auth:accounts:switch`。 + +桌面今天的两点行为照旧,登记在此: + +1. 添加账号的确认发生在点“添加”的那一刻,账号边界要等登录完成才发生。这中间新开始的任务,会被直接停掉,不再确认。 +2. 判断只看在跑的任务,不看排队的输入;排队的留在 A,即 ③。 + +## 七、复用账号边界:`runOwnerBoundary` + +切换就是一次账号边界,经 `apps/host/src/agent/owner-boundary.ts` 的 `runOwnerBoundary(ownerBoundary, …)` 走。`ownerBoundary` 在 `main.ts:1251` 建立。`begin()` 一开始就做三件事: + +- 输入运行时进入停止态(`beginStop`,`input-queue.mjs:579`):不再接新输入,此后结束的回合记作中断; +- 持有共用的回合结束写入压制,直到拆完; +- 结束打开着的 `/chat` 流。 + +被切换停掉的任务因此保留中断痕迹,不自动续跑,与桌面账号边界(`bootstrap-electron.ts:2496`)效果相同。 + +- **`begin()` 不可撤销**:停止态只有输入运行时的 dispose 才换成新的。所以“先验 B、不动 A”(④)必须放在 begin 之前;begin 之后不存在“取消切换、原样留在 A”的路径。 +- **切换是 begin 调用点的第五处**。`owner-boundary.ts` 头注列有前四处:退出登录、会话失效、有序关闭、HTTP 退出登录。切换要加进这张清单,并照那条不变式检查:begin 之后必须到达 dispose;到不了的路径必须重建输入运行时;压制的释放写在 finally 里。 + +## 八、Host 侧的切换顺序 + +### 8.1 顺序 + +`switchAccount(accountKey, { interruptConfirmed })`: + +1. **准入**: + - 闸门关着时拒绝(⑥); + - 已在切换、登录事务提交或退出登录中时拒绝; + - B 与当前账号相同,直接返回; + - 有任务在跑、而请求没带“已确认中断”时,拒绝并回固定码(8.5)。 +2. **先验 B,不动 A**(全部在 begin 之前): + - **取 B 的资源会话**:先续期,不行再用 passport 兑换。主体搬自桌面 `switchSavedAccount`(`authManager.ts:4121` 起;续期 :4175,兑换 :4200)。 + - **写回保管库**:续期会轮换 B 的 refresh token,所以拿到后立刻在锁内把 B 轮换后的凭据写回保管库,只写保管库、不标为当前,也不写当前会话。桌面也是这样写回: + - 续期成功经 `replaceResourceSessionIfCurrent`(:1426); + - passport 兑换后经 `rememberResourceSession(…, { markActive: false })`(:4203,定义 :1400)。 + - **能只读完成的校验都放在这里**: + - 区域:按 `assertHostSessionRegion` 判 B 的 membership,同桌面在拿到令牌后、提交前判 `REGION_MISMATCH`(`authManager.ts:4209–4211`); + - 技能投影:用 `readGhostSkillProjectionBoundaryState`(`authBoundaryQuarantine.ts:571`)只读确认投影边界可读、是当前账号的 stable,不在 pending 或隔离状态。“撤销 A 的投影时写盘失败”这类问题做不到只读预检,不提前。 + - B 的库:现有代码没有不改动的可开性检查。库版本比这个 Host 新时,要到开库迁移那一步才以 `MIGRATE_FAILED` 报出(`apps/desktop/src/main/localDb/index.ts:383–385`)。不为此加新机制,不提前,交给 8.2 的第二层。 + - B 不可用、或任一预检不过,就留在 A 并说明原因(④);这时没有 begin,A 的运行时与会话都不变。 +3. **`runOwnerBoundary(ownerBoundary, { beforeDispose, dispose, afterDispose })`**: + - beforeDispose:照退出登录与会话失效的前段。关网页会话与平台客户端,`server.pauseOwnerRequests()`,`beginAppSessionBoundary()`,关确认窗与插件。 + - dispose:`disposeOwnerRuntime()`,停掉 A 在跑的回合并拆运行时。 + - afterDispose: + 1. 在 3.1 的入口里调 `commitLoginSessionAndOwner`:锁内写 B 的当前会话记录,再提交 owner;过渡里撤销 A 的技能投影。 + 2. 有阻碍就中止,会话记录回滚到 A。 + 3. 然后 `ensureRuntime(B)`。`main.ts:685` 的“运行中不许换 owner”前提是 activeOwner 已被 dispose 清空,所以拆干净后可以调;它会取租约、重做并存扫描、开 B 的库(没有就新建)。 + 4. 之后 `startDeviceLink()`,并重新排续期。 +4. **收尾**:成功与失败分开写。两种情况都必须发 `auth_changed`,否则窗口会一直停在“正在切换账号…”。 + - 成功:`commitVolatileAppSession('cloud', B)` → 释放边界 → `eventHub.clear()` → 发 `auth_changed`。窗口经 `receiveHostAuthState` 换到 B,平台客户端重连成 B。 + - 失败:按 8.2 落到 A,或第三层的 error 状态 → 释放边界 → 发 `auth_changed`,内容是 A 的状态或 error 状态。 + +### 8.2 begin 之后的失败分层 + +能提前的只读校验已在第 2 步做完。但预检和实际执行之间有时间差,所以 begin 之后这一支照样保留。 + +- **第一层:begin 之前失败**。留在 A,什么都没变(④)。 +- **第二层:begin 之后、B 没开成**。dispose 照常到达。分两种情况: + - **(a) owner 还没提交成 B 就失败**,例如撤销 A 的投影时写盘失败: + - `commitLoginSessionAndOwner` 已把会话记录回滚到 A,owner 仍是 A; + - 经 3.1 的入口把 owner 留在 A,然后 `ensureRuntime(A)`。 + - **(b) owner 已经提交成 B,开 B 的库时才失败**,例如库版本比这个 Host 新: + - 回滚顺序是**先写会话、后提交 owner**:先在锁内把会话记录写回 A,再经 3.1 的入口把 owner 提交回 A(过渡里撤销 B 的投影),然后 `ensureRuntime(A)`; + - 先写会话,是因为重启时以会话为准(3.3):回滚做到一半崩溃,重启按会话补成 A; + - 提交回 A 也失败,就落到第三层:会话已是 A,重启后按 3.3 补成 A。 + - 两种情况最后都是 `commitVolatileAppSession('cloud', A)`,发 `auth_changed`。 + - 这一支只会在用户已经确认中断之后走到,或者当时本来就没有任务在跑(8.5)。结果是没换成功;刚才在跑的任务显示为中断,可以手动继续;不丢数据。 +- **第三层:B 失败,再用 A 重开也失败**: + - 会话记录仍是 A,不能停在 B; + - 运行时进入与启动失败相同的 error 状态:同 `main.ts:2117–2125`,dispose、`commitVolatileAppSession('signed-out')`、`runtime.state = 'error'`;`runtime.detail` 只放固定错误码(S5); + - 发 `auth_changed`; + - 重启 Host 可以恢复:会话是 A,按 3.3 认 A;如果 owner 停在 B 或 pending,启动时按会话补提交成 A。 + - **窗口看到什么**:启动失败的收尾经 `disposeOwnerRuntime` 把账号清成未登录(`main.ts:1994`、:1998)。原先 `projectHostAuthState` 因此投影出普通的未登录,窗口看到的是登录页,看不到 error 和原因;原因只在 `/api/probe` 的 `runtime`(`main.ts:1454`)里。**已改(甲,2026-11-17)**:启动收尾把原因归成一个固定码(`apps/host/src/start-failure.ts`,存进 `runtime.unavailable`),auth state 带 `hostUnavailable: { reason }`;窗口在登录页显示原因与怎么办,不提供本地登录和跳过登录(`apps/desktop/src/shared/hostStartFailure.ts`,见放行表第五节“甲:Host 启动失败时窗口只看到登录页”)。本例(开 B 的库失败)显示的是 `HOST_DATABASE_UNAVAILABLE`。 + +**从 error 状态恢复**(以 8.3 的“会话还没写回 A”一行为例:重启后按会话起 B,开库仍失败,Host 停在 error)。按集成分支现在的代码逐步核实: + +1. **窗口能连上 Host**: + - Host 先开始监听、再启动运行时(`main.ts:2083` 在 :2084 之前),`/api/auth/*` 不算 owner 请求(`server.mjs:166`); + - 窗口的事件流连上时读 `/api/auth/state`(`bootstrap-electron.ts:1464`)。 + - 能连上。原先看到的是未登录、看不到错误;现在看到原因面板(见上一条)。 +2. **退出登录能执行,回到未登录**: + - `/api/auth/logout` 不受 owner 请求闸门挡(`server.mjs:257`); + - `main.ts` 的 logout 先 `await startup`(:1499),启动失败已被 catch 收住,不会卡住; + - `disposeOwnerRuntime` 对已拆掉的运行时再跑一次,末尾把运行时置回 `uninitialized`(:2001); + - `logoutHostSession` 删掉会话记录 B,并尽力吊销(`apps/host/src/auth/logout.mjs:70`)。 + - 一处不干净:启动失败时 `accountUser` 已被清空(`main.ts:1994`),logout 取到的 `outgoingUser`(:1505)为空,所以不给 B 写退出墓碑,也不把 B 从保管库移走(`logout.mjs:35` 只在有 ownerId 时做)。B 的凭据仍留在保管库里,没有被标为已退出。 + - 另外,窗口此时显示的是原因面板(原先是登录页),界面上没有“退出登录”入口。所以这一步能执行,但恢复不需要它。 +3. **登回 A,A 的数据还在**: + - `cindy-host login`(今天就能用):error 状态下 serve 的运行时 owner 为空,`serveLoginAdmission`(`login-cli.mjs` 的准入)和 :139 的检查都放行。它写会话 A,并把 owner 提交回 A(:144)。serve 不中途采用新会话(乙 10),要重启 Host;重启后两个库都在,按会话认 A(`main.ts:2088–2100`),起 A。 + - 窗口登录(3.5):今天客户端模式下窗口的登录在本地执行(第十节的测试期限制),不可用。按方案改成 Host 的登录事务以后,登录页直接登 A,Host 提交会话与 owner 到 A 并起 A,不必重启。前提是登录事务在 error 状态下也能开始,列为第九节的必做项。 + - A 的库 `cindy-.db` 在切换、回滚、退出登录、重新登录这几步里都不被删除或改写,数据在。 + +结论:今天的恢复办法是用 `cindy-host login` 登回 A,再重启 Host;窗口里还走不通。方案实现后,在窗口的登录页直接登回 A 即可,数据不丢。 +- **失败提示**: + - 要告诉用户两件事:仍在原账号;刚才在跑的任务已被中断。 + - 现有的 `sidebar.accountSwitcher.switchFailed`(“切换失败,请重新登录该账号”)不含后一句。 + - 文案**待用户定**,由审核方统一去问用户。 + +### 8.3 崩溃一致性 + +按会话与投影边界的落盘顺序,逐个崩溃点写重启后的结果。重启时按 3.3 以会话为准: + +| 崩溃点 | 盘上状态 | 重启后 | +|---|---|---| +| 第 2 步写回保管库之后、begin 之前 | 会话 A,边界 stable(A),保管库里 B 的令牌已是轮换后的 | 正常回到 A;B 的令牌仍可用 | +| begin 之后、写 B 的会话之前 | 会话 A,边界 stable(A) | 正常回到 A;被停掉的回合保留中断痕迹,进“继续上次中断的任务”列表 | +| (i) B 的会话已写、owner 还没提交(或边界停在 pending) | 会话 B,边界 stable(A) 或 pending | 照桌面冷启动:以会话为准,serve 启动时经 3.1 的入口把 owner 补提交成 B(过渡里撤销 A 的投影),再开 B 的库。补不成就进入启动失败的 error 状态(8.2 第三层的形态),会话不改回 A | +| (ii) owner 已提交、B 的库还没开 | 会话 B,边界 stable(B),B 的库可能还不存在 | 正常起 B;库不存在就新建,同首次登录 | +| 第二层 (b) 回滚途中:会话已写回 A、owner 还没提交回 A(或边界停在 pending) | 会话 A,边界 stable(B) 或 pending | 以会话为准:serve 启动时经 3.1 的入口把 owner 补提交成 A(过渡里撤销 B 的投影),再开 A 的库。补不成就进入启动失败的 error 状态,会话仍是 A | +| 第二层 (b) 回滚途中:会话还没写回 A | 会话 B,边界 stable(B) | 同 (ii):按会话起 B。如果开 B 的库仍失败,就进入启动失败的 error 状态。恢复办法见 8.2 末尾“从 error 状态恢复”:方案实现后在窗口登录页登回 A;今天用 `cindy-host login` 登回 A 并重启 Host。A 的数据不丢。回滚先写会话,就是为了让这个窗口尽量短 | + +(i) 和第二层 (b) 的“会话已写回 A、owner 还没提交回 A”要有测试。 + +### 8.4 锁与网络请求 + +- **照桌面:网络请求不在保管库锁里做**。桌面 `syncSavedAccounts`(`authManager.ts:4090` 起)的做法是: + 1. 在锁外读一次保管库; + 2. 在锁外续期、拉成员; + 3. 进锁后经 `replacePassportSessionIfCurrent`(:1589)重读、与这次请求用的令牌比对,一致才写。 +- 切换时续这个账号也一样,写回走 `replaceResourceSessionIfCurrent`(:1426),同样是锁内重读、比对。 +- 锁只在本地读写时持有,桌面每次等锁 5 秒(`waitMs: 5_000`,`authManager.ts:1235`),Host 的退出登录(`main.ts:1531`)与续期(`apps/host/src/auth/refresh.mjs:86`)也是 5 秒。 +- Host 的 `sync` 与第 2 步照这个做法:网络请求在锁外,各自用认证客户端现有的请求超时;锁内不做网络请求。退出登录等锁不会被网络请求拖过 5 秒。 + +### 8.5 运行中任务的兜底 + +- **窗口快照只看得到它收到过事件的任务**。Host 的每个回合都经 `turn-executor.mjs:67` 把事件发到 Host 的事件流,包括网页端 `/chat` 和远程控制端发起的任务;窗口把它转成 `MAKER_PUSH.EVENT`,`makerChatStore` 对任何会话都会建状态(`setState` → `getOrCreateState`,`apps/desktop/src/renderer/lib/makerChatStore.ts:4760`)。所以窗口连着时开始的任务,`getRunningSnapshot()`(:10924)能算进去。 +- **但窗口不会主动拉“已在跑的任务”**:渲染层只在账号回滚时调 `listActive`(`reconcileSessionsAfterDataOwnerRollback`,:11064 起)。窗口在别的客户端的任务开始之后才打开、或事件流断开过时,快照会漏掉它。 +- 所以在 Host 的 switch 上加一个兜底:Host 上有任务在跑(`inputQueue.hasRunningTurns()`,`input-queue.mjs:571`),而请求没带“已确认中断”时,拒绝并回固定码;窗口收到后弹现有的那个确认框,确认后带上这个标记重发。不新增界面。 + +### 8.6 窗口直接从 A 变成 B + +今天窗口只经历过 A → 未登录 →(重启后)B;切换由 Host 做以后,窗口会直接收到“另一个账号”。现状: + +- **窗口主进程**:`onAuthChanged` → `receiveHostAuthState`(`bootstrap-electron.ts:1517–1519`,`authManager.ts:501–513`)只把内存里的 owner 提交成 B(`commitVolatileAppSession('cloud', B)`),替换转发来的状态并通知渲染层,再重连平台客户端。 + - 它不跑桌面本地切换时的账号拆除(`accountSwitchTeardown`,`bootstrap-electron.ts:2690`),也不发“边界进行中”的通知。 + - 客户端模式下窗口主进程还持有哪些按账号的状态,桌面 PR 要逐项列出,并决定在这里清掉。 +- **渲染层**:`AuthContext` 的 `applyIncomingState`(`apps/desktop/src/renderer/contexts/AuthContext.tsx:260` 起)按 `dataOwnerId` 判断换了账号(`ownerBoundaryCommitted`,:336)。换了就: + - 结束旧账号的会话缓存(`publishDataOwnerGeneration(…, { finalizeSessions: true })`); + - `sessionsStore.reset()`、`clearWorkersCache()`(:350–351); + - 把按账号分区的本地存储换到 B(:363 起)。 + - 这与桌面本地切换时渲染层的处理是同一段代码。差别只在:本窗口发起的切换先经 `runDataOwnerBoundary`(:220)设一道提交前的围栏;别的客户端发起、或 Host 自己因失败落回 A 的推送没有这道围栏。 +- 因为没有那道围栏,在 A 账号下发出、B 的推送到达之后才返回的请求,结果必须丢弃,不能写进 B 的界面状态。 +- 列为桌面侧的必做测试,见第九节。 + +### 8.7 和已有机制的配合 + +- 闸门:切换只在闸门打开时做;`disposeOwnerRuntime` 会停并存监视,`ensureRuntime` 重新扫描。客户端窗口的登记 `runtime: 'client'` 被放行(`apps/host/src/agent/profile-coexistence.ts:137–142`)。 +- 凭据(C):保管库与当前会话都在同一把锁里读写,切换后的续期由 Host 单写。窗口改走 Host 接口以后,C 不用再防窗口这个写方。 + +## 九、分工、排期与改动清单 + +分类为乙。桌面部分进第一阶段之后的桌面 PR,Host 部分进下一个 Host PR。实现排在当前甲项之后。 + +**Host 侧改动** + +1. `/api/auth/accounts/*` 一组路由,以及 Host 的登录事务(S1、S4):list、sync、switch、add/begin、add/action、add/state、add/captcha-url、add/cancel。 + - 只接受“Bearer + 实例头”,拒绝网页端 cookie 会话; + - 同一时刻只有一个登录事务; + - 只回固定错误码(S5)。 + - 没有当前账号时的登录也走这组(3.5)。 +2. `switchAccount`,按第八节: + - 先验 B 并把 B 轮换后的凭据写回保管库; + - 只读预检放在 begin 之前; + - 再经 `runOwnerBoundary` 拆 A、开 B; + - 失败分三层,成功与失败分开收尾,两种都发 `auth_changed`; + - 有任务在跑而未确认时,以固定码拒绝(8.5); + - 加进 `owner-boundary.ts` 头注的 begin 调用点清单,作为第五处。 +3. 只给 Host 的账号切换、登录完成及其启动时的补完用的 owner 提交入口(3.1),实现成把提交能力作为参数传入。 +4. 启动时以会话为准认 owner:`discoverHostOwner` 不再只数库文件;投影边界不是会话账号的 stable 时,经 3.1 补提交(3.3、8.3)。 +5. `cindy-host login` 写出与桌面登录相同的存储状态(3.4);之后去掉 C 的差别 a。 +6. 账号同步 `sync` 的主体搬成共用核心,桌面与 Host 共用;网络请求在锁外,锁内重读比对后写(8.4)。 +7. error 状态下的恢复(8.2 末尾): + - Host 处在启动失败的 error 状态时,投影给窗口的状态带固定原因码,窗口在登录页说明原因(文案待用户定,不带 `runtime.detail` 原文)。**已做**(甲,2026-11-17,放行表第五节“甲:Host 启动失败时窗口只看到登录页”); + - 登录事务在 error 状态下也能开始,登回 A 后起 A,不必重启; + - error 状态下退出登录按会话记录里的账号写退出墓碑、从保管库移走,不依赖已经清空的 `accountUser`。 + - 8.3 里“第二层 (b) 回滚途中:会话还没写回 A”这个场景(会话 B,开 B 的库仍失败),今天窗口显示成“数据打不开”(`HOST_DATABASE_UNAVAILABLE`)。实现切换时给它单独的原因码和文案,恢复办法是用原账号 A 重新登录;文案到时由审核方带给用户(审核方 2026-11-18)。 + +**桌面侧改动** + +1. 五个账号通道和三个登录动作通道进 `HOST_CONTRACT_CHANNELS`,客户端模式下由代理接管、去掉本地处理器(S2、S6 第 1 点)。 +2. 第二道保险:续期 override 已设置时,本地 `completeLogin`、写会话、写保管库一律拒绝(S6 第 2 点,逐行送审)。 +3. 客户端模式下窗口不再提交 owner(3.2)。 +4. 窗口收到另一个账号时(8.6): + - 列出窗口主进程在客户端模式下持有的按账号状态,并在 `receiveHostAuthState` 换账号时清掉; + - 切换被 Host 以“有任务在跑、未确认”拒绝时,弹现有的确认框后带标记重发(8.5)。 +5. 界面不变:确认框、文案、入口、切换中的提示都照旧(第六节);失败提示的新文案待用户定(8.2)。 + +**必做测试** + +- 3.1 的三条:这几处之外 serve 照旧拒绝;一次切换进行中另一个提交被拒;切换失败后恢复为拒绝。 +- S5 的哨兵测试,范围见 S5。 +- S6 第二道保险的桌面测试:续期 override 已设置时,本地登录写入被拒。 +- 切换的 Host 测试: + - 先验 B 失败、或任一只读预检不过时,A 不受影响:没有 begin,运行时与会话不变; + - 先验 B 成功、随后切换失败时,保管库里 B 的令牌仍然可用(第 2 步写回过轮换后的凭据); + - 切换成功后,被停掉的回合保留中断痕迹、不自动续跑; + - 第二层 (a):owner 还没提交成 B 就失败时,会话回滚到 A 并重开,窗口收到 A 的 `auth_changed`; + - 第二层 (b):owner 已提交成 B、开 B 的库失败时,先写回会话 A、再提交 owner 回 A 并重开;在两步之间崩溃时,重启按会话补成 A; + - 第三层:再用 A 重开也失败时,会话记录仍是 A,运行时为 error,窗口收到 `auth_changed`,重启后回到 A; + - 崩溃点 (i):B 的会话已写、owner 未提交时重启,serve 补提交并起 B; + - 闸门关着时拒绝切换; + - 闸门关着时拒绝添加账号(`add/begin`)和没有当前账号时的登录,提示与切换相同,且不发任何会签发或轮换令牌的请求、不写保管库与会话; + - 有任务在跑而请求未确认时,以固定码拒绝; + - 两个库时重启认对 owner(3.3);只有一个库、会话是另一个账号时也认对; + - error 状态下的恢复:Host 停在启动失败的 error 时,窗口看到原因码;在窗口登录 A 后起 A,A 的库与数据不变;error 状态下退出登录给会话里的账号写退出墓碑,并回到未登录。 +- 桌面侧: + - 窗口直接收到另一个账号的 `auth_changed` 时(不经本窗口的 `runDataOwnerBoundary`),渲染层结束旧账号的会话缓存、清 `sessionsStore` 与 workers 缓存、按账号分区的存储换到 B,界面上不残留 A 的数据; + - 窗口主进程按 8.6 列出的按账号状态被清掉; + - 在 A 账号下发出、在 B 的推送到达之后才返回的请求,结果被丢弃,不写进 B 的界面状态。Host 推送的切换没有本窗口那道提交前的围栏,差别正在这里(8.6)。 +- 鉴权两条限制:网页端 cookie 会话被拒;同一时刻只有一个登录事务(新的 begin 作废上一个,属于旧事务的 action 以 `AUTH_FLOW_SUPERSEDED` 被拒,S4)。 + +## 十、测试期的已知限制与解除条件 + +做完之前,客户端模式下在窗口里切换或添加账号的后果,见放行表第二节“已知限制(仅限测试期)”那一行。概括如下: + +- 窗口在本地完成登录、写会话和保管库,并提交 owner;Host 仍在原账号下运行,新建的任务落在原账号的库里。 +- 界面先显示新账号,下一次拿到 Host 状态时又回到原账号。 +- Host 的续期读到新账号的会话会失败;原账号的访问令牌过期后,模型调用失败。 +- 重启 Host 会因会话与库的账号不一致,或 profile 里有两个账号库,而起不来。 + +测试期的做法: + +- 请勿在客户端模式下切换或添加账号; +- 要换账号,先在窗口退出登录(Host 一并退出),再用 `cindy-host login` 登录新账号,并重启 Host; +- 对用户的提醒由审核方说。 + +**解除条件**:第九节的 Host 侧与桌面侧改动都落地、必做测试都通过之后,从放行表第二节删去这一行,并在第五节“乙:客户端模式下窗口切换、添加账号”那一行记为已关闭。桌面侧必须包含: + +- 合同代理接管; +- 第二道保险; +- 窗口不再提交 owner。 + +只落 Host 侧不解除:窗口仍会在本地写。 + +同时解除的还有“Host 启动失败时窗口不在本地登录”的那两个条件(3.5):3.5 落地后去掉 `dispatchLoginAction` 与 `enterLocalMode` 开头的 `hostNotStartedInClientMode`,原因面板保留。 diff --git a/docs/host/feature-parity.md b/docs/host/feature-parity.md index a8e7f8dc4ee..a10e0c6171b 100644 --- a/docs/host/feature-parity.md +++ b/docs/host/feature-parity.md @@ -42,7 +42,7 @@ | 能力 | 状态 | 证据 / 缺口 | |---|---|---| | 本地模式(无账号) | 部分 | 登录页可进入本地模式(`authGetLoginState`/`authEnterLocal` 已实现),但随后停在 “Waking Cindy…” 启动门;Host 侧尚无本地 owner 命名空间 | -| 复用现有登录 | 已验证(单写者) | 登录态稳定:Host 后台每 30 分钟定时刷新,暴露 `/api/auth/refresh`;Desktop 客户端模式重定向所有刷新至 Host,杜绝并发 refresh token 轮转失效 | +| 复用现有登录 | 已验证(单写者) | 登录态稳定:Host 按 access token 的 exp 减 300 秒续期(与桌面同一个函数),暴露 `/api/auth/refresh`;Desktop 客户端模式重定向所有刷新至 Host,杜绝并发 refresh token 轮转失效 | | 复用现有存储 | 已验证 | 打开同一 owner 生产库(192 条存量任务与全部历史),无平行数据库,`fuser -v` 确认单写者 | | 单 Runtime 锁 | 已验证 | 第二个 Host 报 `runtime.state=blocked`、`storage=unopened` | | 设置与偏好同步 | 已验证 | 外观设置、窗口布局、全局快捷键、项目别名由 Host 统一读写,并通过带序号 SSE 事件实时广播,两端 1 秒内同步 | diff --git a/docs/host/owned-machine-verification.md b/docs/host/owned-machine-verification.md new file mode 100644 index 00000000000..c5ff07611fe --- /dev/null +++ b/docs/host/owned-machine-verification.md @@ -0,0 +1,296 @@ +# 在自有电脑验证 Host + +这份流程供维护者在自有机器上做发布前验证。下文的机器列表、别名和远端任务命令来自维护者自己的测试工具。外部贡献者只需按对应平台的说明准备 Node 和依赖,再按「Host 门禁与回执」运行命令、记录结果。 + +Ubuntu x64、Windows x64、macOS arm64 分别验证同一份待发布源码。每台机器用独立的任务目录安装 Node 和依赖。Host 回归入口和验收脚本以待测提交的 [Host CI 作业](../../.github/workflows/ci.yml) 和 [Host package.json](../../apps/host/package.json) 为准。 + +## 准备同一份源码 + +1. 在集成分支工作区记录 `git rev-parse HEAD`、`git status --short`、`git lfs ls-files`。核对需要的 LFS 文件已经展开。将改动中的文件与新文件一并计入快照,记录排除项。 +2. 在自有电脑列表里选择 Ubuntu、Windows 和一台空闲的 Mac。用各自 alias 生成 `preflight-command`,通过 Cindy SSH 执行并用 `record-preflight` 保存原始回执。检查可用磁盘、CPU、内存、活动 runner,实测 Git、Python、编译器和归档工具。Windows 用 `py -3 --version` 和 Visual Studio Installer 的 `vswhere` 核对 C++ 工具;macOS 检查 `xcode-select -p`。本流程无需系统级安装。 +3. 用 `sync` 建立独立任务,核对 manifest。仓库文件多时,可先在仓库外把**已审核的传输清单**做成 tar.gz,分成小于 50 MiB 的分片再同步。归档前逐文件检查敏感文件排除项、符号链接、LFS 指针与总容量;随包附上原提交、逐文件 SHA256、排除清单及检查脚本。远端按片名顺序二进制拼接,解压到任务的 `src`,逐文件核对。三台机器应具有相同的源码摘要。源码有变化就新建任务。 +4. 各步骤通过 `prepare-run TASK SCRIPT` 后执行回执里的 SSH 命令。长步骤按实际耗时拆分,超过原生时限的单项可用 `run-long`。下面的命令都从远端任务的 `src` 执行,环境变量要在每次运行时重新加载。 + +## 先清点二进制,再准备依赖 + +每台机器、每份快照都要在下载前向负责人报清单。每行记录工具、平台、版本、是否已经在本次任务内可用、用途、获取来源、归档字节数和校验依据。可以用 HTTP HEAD 读取归档大小;registry 返回分块响应时用带 `Range: bytes=0-0` 的 HEAD 查看 `Content-Range` 分母。已有归档记录实际大小与哈希。需要获取的项等本轮确认后再取;发现新下载就停止并补报。 + +| 项目 | 清点和准备方法 | +| --- | --- | +| Node、Corepack、pnpm | 核对 `.nvmrc` 和 `packageManager`,优先复用已按官方 SHASUMS256 校验的同平台归档。Windows 另列同版本 headers 和 node.lib。 | +| npm 依赖中的原生程序 | 从本次 lockfile 导出 registry 包名、版本、完整性摘要、tarball 来源和字节数。包含 esbuild、sharp、node-pty、各平台 Claude Agent SDK 等。注明已缓存的包与新环境可能获取的上限,better-sqlite3 使用任务内 Node 的头文件编译。 | +| Electron | 区分 npm 的 JS 包和对应平台的 Electron 运行时。源码空 profile 验收只需 JS 包。需要真实运行时的用例要单列平台、版本、来源、大小和校验值;获准后在任务内预置并核对 `dist` 中的应用和 `path.txt`。 | +| Chromium | 记录 Playwright 的浏览器 revision。需要真实浏览器时,确认归档后设置任务专用的 `PLAYWRIGHT_BROWSERS_PATH`;只运行 Host 源码健康探针时不取浏览器。 | +| Claude Code、Codex、Pi、ripgrep | 区分打包用的独立可执行文件、npm 包附带的程序和测试夹具。逐项记录已提供、需获取或本轮不用。常规无账号 Host 验证设置 `XDT_SKIP_AGENT_BIN_INSTALL=1`,涉及真实引擎、独立 rg 或真实账号的结果单列。 | + +Electron 42.11.12 的历史验收曾触发其 npm 包自带的 `install.js`。自有 macOS 任务目录出现完整的 Electron 分发包,自有 Windows 任务目录出现未完成的下载文件。两处均已清理。修复前,执行真实子 Host 的 startup-account、IPC 或 lifecycle 等路径可能在启动或刷新空会话时解析 Electron 包入口。入口发现 `path.txt` 缺失,或指向的 dist 程序缺失,就同步启动下载器。源码 Host 从 `a6cb62e1af` 起直接检查包旁的 `path.txt` 与实际文件,原生凭据操作延迟到真正加解密时解析可执行文件。 + +锁定版本的 `ELECTRON_SKIP_BINARY_DOWNLOAD=1` 会让仓库根 postinstall 跳过补装;Electron 42.11.12 的入口及其 `install.js` 本身都不读取它。`ELECTRON_OVERRIDE_DIST_PATH` 让 npm 包入口直接返回该目录下的路径,可供已有分发包的验收使用。验证“没有 Electron 也能启动”时清除此变量,并在测试前后检查 `path.txt`、dist 和子进程记录,避免路径覆盖掩盖回归。`electron_config_cache` 只控制下载缓存位置;`ELECTRON_MIRROR` / `npm_config_electron_mirror` 控制下载来源;`ELECTRON_GET_USE_PROXY` 让该版下载依赖启用环境代理。这些变量均不保证禁止下载。使用替换过的镜像时还要检查优先级更高的 npm 配置和包配置。 + +曾验收的 Chrome for Testing 153.0.8010.12 归档没有可供比对的官方 checksum。报告记录了归档、解压程序和候选包内程序的 SHA256,用于这一次临时验收和核对打包前后文件一致。 + +## Ubuntu 和 macOS + +下面的 Bash 命令使用系统已有的 curl、tar、编译器和 Python。任务目录内的 Node 发行包自带头文件,可供 better-sqlite3 本机编译。 + +```bash +set -euo pipefail +task=$(cd .. && pwd -P) +mkdir -p "$task"/{tools/bin,home,tmp} +version=$(tr -d '[:space:]' < .nvmrc) +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) platform=linux-x64; ext=tar.xz ;; + Darwin-arm64) platform=darwin-arm64; ext=tar.gz ;; + *) exit 2 ;; +esac +dist="node-v$version-$platform" +archive="$dist.$ext" +base="https://nodejs.org/dist/v$version" +( + cd "$task/tools" + curl -fsSLO "$base/SHASUMS256.txt" + curl -fsSLO "$base/$archive" + hash=$(awk -v name="$archive" '$2 == name {print $1}' SHASUMS256.txt) + test -n "$hash" + if command -v sha256sum >/dev/null; then + printf '%s %s\n' "$hash" "$archive" | sha256sum -c - + else + printf '%s %s\n' "$hash" "$archive" | shasum -a 256 -c - + fi + tar -xf "$archive" +) +export PATH="$task/tools/bin:$task/tools/$dist/bin:$PATH" +export HOME="$task/home" USERPROFILE="$task/home" +export XDG_CACHE_HOME="$HOME/.cache" XDG_CONFIG_HOME="$HOME/.config" +export XDG_DATA_HOME="$HOME/.local/share" XDG_STATE_HOME="$HOME/.local/state" +export COREPACK_HOME="$task/corepack" COREPACK_ENABLE_DOWNLOAD_PROMPT=0 +export npm_config_cache="$HOME/.npm" npm_config_nodedir="$task/tools/$dist" +export npm_config_build_from_source=better-sqlite3 SHARP_IGNORE_GLOBAL_LIBVIPS=1 +export ELECTRON_SKIP_BINARY_DOWNLOAD=1 XDT_SKIP_AGENT_BIN_INSTALL=1 +git config --global user.name 'Fixture Tester' +git config --global user.email fixture@example.invalid +corepack enable --install-directory "$task/tools/bin" pnpm +node --version +pnpm --version +pnpm install --frozen-lockfile --os="$(node -p process.platform)" --cpu="$(node -p process.arch)" --libc=current --store-dir "$task/pnpm-store" +(cd apps/host && node -e "const db=new (require('better-sqlite3'))(':memory:'); console.log(db.prepare('select sqlite_version() v').get()); db.close()") +``` + +`pnpm --version` 应与根 package.json 的 `packageManager` 一致。仓库为了制作跨平台产物配置了多个架构。上述安装参数将可选依赖限定到本机平台;保留下载明细,并核对每个实际获取的包来自获准的 registry、与冻结锁文件的 integrity 相符。测试继续使用临时 HOME 和测试 Git 身份。 + +## Windows + +在 PowerShell 中从任务的 `src` 开始,使用官方 Windows zip。每个外部命令都要采集退出码,下面用一个函数传播安装失败。 + +```powershell +$ErrorActionPreference = 'Stop' +function Invoke-Checked($program, [string[]]$argv) { + & $program @argv + if ($LASTEXITCODE -ne 0) { throw "$program exited $LASTEXITCODE" } +} +$task = Split-Path -Parent (Get-Location).Path +$v = (Get-Content -Raw .nvmrc).Trim() +$dist = "node-v$v-win-x64" +$tools = Join-Path $task 'tools' +$node = Join-Path $tools $dist +$base = "https://nodejs.org/dist/v$v" +New-Item -ItemType Directory -Force "$tools/bin","$task/home","$task/tmp" | Out-Null +foreach ($name in @("$dist.zip",'SHASUMS256.txt')) { + Invoke-Checked curl.exe @('-fsSL','-o',"$tools/$name","$base/$name") +} +$expected = Get-Content "$tools/SHASUMS256.txt" | ForEach-Object { + $parts = $_ -split '\s+' + if ($parts[1] -eq "$dist.zip") { $parts[0] } +} +if (!$expected -or (Get-FileHash "$tools/$dist.zip" -Algorithm SHA256).Hash -ne $expected) { + throw 'Node zip SHA256 mismatch' +} +Invoke-Checked tar.exe @('-xf',"$tools/$dist.zip",'-C',$tools) +$python = (& py.exe -3 -c 'import sys; print(sys.executable)') +if ($LASTEXITCODE -ne 0 -or !$python) { throw 'Python 3 is required' } +$env:PATH = "$tools/bin;$node;$env:PATH" +$env:USERPROFILE = $env:HOME = "$task/home" +$env:APPDATA = "$task/home/AppData/Roaming" +$env:LOCALAPPDATA = "$task/home/AppData/Local" +New-Item -ItemType Directory -Force $env:APPDATA,$env:LOCALAPPDATA | Out-Null +$env:COREPACK_HOME = "$task/corepack" +$env:COREPACK_ENABLE_DOWNLOAD_PROMPT = '0' +$env:npm_config_cache = "$task/home/npm-cache" +$env:npm_config_devdir = "$task/node-gyp" +$env:npm_config_python = $python +$env:npm_config_build_from_source = 'better-sqlite3' +$env:ELECTRON_SKIP_BINARY_DOWNLOAD = $env:XDT_SKIP_AGENT_BIN_INSTALL = '1' +$env:SHARP_IGNORE_GLOBAL_LIBVIPS = '1' +Invoke-Checked git @('config','--global','user.name','Fixture Tester') +Invoke-Checked git @('config','--global','user.email','fixture@example.invalid') +Invoke-Checked corepack.cmd @('enable','--install-directory',"$tools/bin",'pnpm') +Invoke-Checked node @('--version') +Invoke-Checked pnpm.cmd @('--version') +``` + +Windows 的运行时 zip 缺少编译 better-sqlite3 所需的开发文件。本次自有测试机只按官方 `SHASUMS256.txt` 校验了头文件和 `win-x64/node.lib` 的 SHA256,未验证签名。这两个文件只用于自有测试机的本次构建。先报告附加下载,再从同一官方发行目录取文件、逐个核验摘要,把头文件和链接库放到 node-gyp 指定的位置。在上述 PowerShell 环境运行: + +```powershell +$headers = "node-v$v-headers.tar.gz" +foreach ($asset in @($headers, 'win-x64/node.lib')) { + $output = Join-Path $tools (Split-Path -Leaf $asset) + $sha = @(Get-Content "$tools/SHASUMS256.txt" | ForEach-Object { + $parts = $_ -split '\s+' + if ($parts[1] -eq $asset) { $parts[0] } + }) + if ($sha.Count -ne 1) { throw "Missing official checksum for $asset" } + Invoke-Checked curl.exe @('-fsSL','-o',$output,"$base/$asset") + if ((Get-FileHash $output -Algorithm SHA256).Hash -ne $sha[0]) { + throw "SHA256 mismatch for $asset" + } +} +Invoke-Checked tar.exe @('-xf',"$tools/$headers",'-C',$tools) +$env:npm_config_nodedir = "$tools/node-v$v" +New-Item -ItemType Directory -Force "$env:npm_config_nodedir/Release" | Out-Null +Copy-Item "$tools/node.lib" "$env:npm_config_nodedir/Release/node.lib" +Invoke-Checked pnpm.cmd @('install','--frozen-lockfile','--os=win32','--cpu=x64','--libc=current','--store-dir',"$task/pnpm-store") +Push-Location apps/host +try { + Invoke-Checked node @('-e',"const db=new (require('better-sqlite3'))(':memory:'); console.log(db.prepare('select sqlite_version() v').get()); db.close()") +} finally { Pop-Location } +``` + +## Host 门禁与回执 + +每条命令的回执写明机器类型、命令、Node 版本、结果、开跑负载、日志、TMPDIR 是否显式设为真实路径及实际语言环境。新写或修改的测试至少有一轮使用默认临时目录与语言。Unix 在测试子 shell 中执行 `unset TMPDIR`,保留登录环境原有的 LANG 和 LC_*。Windows 在测试进程中清除 TMPDIR,保留原有的 TEMP、TMP 和系统区域设置。两种模式都继续隔离 HOME、应用数据与缓存。若另测显式临时目录,将 TMPDIR 指向已创建目录的 realpath,分开记录两轮结果。 + +在每条被测命令前,从同一进程环境运行以下命令,保存临时目录的原始路径、真实路径、语言变量和 Node 实际采用的区域。Windows 另记录 `Get-Culture` 和 `Get-UICulture`。环境变量未设置时照实记录。 + +```sh +node -e "const os=require('node:os'),fs=require('node:fs'),p=os.tmpdir(),e=process.env; console.log({tmpdir:e.TMPDIR,osTmp:p,realTmp:fs.realpathSync(p),lang:e.LANG,lcAll:e.LC_ALL,lcCtype:e.LC_CTYPE,lcMessages:e.LC_MESSAGES,locale:Intl.DateTimeFormat().resolvedOptions().locale})" +``` + +依赖准备结束后,在测试进程及其子进程中默认关闭对外访问,保留回环 HTTP 给 Host、桌面代理和测试服务使用。沿用 startup-account 测试里的做法,将 HTTP/HTTPS 代理指向回环上确认没有服务监听的端口,同时设置大小写两套变量。用本次测试进程的网络隔离限制连接目的地,并验证回环可用、对外连接被拒;记录沙箱是否限制了 PID 查询。无法验证隔离生效时先报告,再决定如何执行。代理只约束识别这些变量的客户端,不能当作系统防火墙;发现清单外的下载尝试就立即停下,保留请求、子进程与缓存记录,报告给负责人。保持任务专用 HOME、数据目录和工具缓存,避免命中个人安装或账号。 + +```bash +export HTTP_PROXY=http://127.0.0.1:9 HTTPS_PROXY=http://127.0.0.1:9 +export NO_PROXY=127.0.0.1,localhost,::1 +export http_proxy="$HTTP_PROXY" https_proxy="$HTTPS_PROXY" no_proxy="$NO_PROXY" +export NODE_USE_ENV_PROXY=1 ELECTRON_GET_USE_PROXY=1 +export ELECTRON_MIRROR="$HTTP_PROXY/" npm_config_electron_mirror="$HTTP_PROXY/" +``` + +```powershell +$env:HTTP_PROXY = 'http://127.0.0.1:9' +$env:HTTPS_PROXY = $env:HTTP_PROXY +$env:NO_PROXY = '127.0.0.1,localhost,::1' +$env:NODE_USE_ENV_PROXY = '1' +$env:ELECTRON_GET_USE_PROXY = '1' +$env:ELECTRON_MIRROR = "$($env:HTTP_PROXY)/" +$env:npm_config_electron_mirror = $env:ELECTRON_MIRROR +``` + +Windows 进程环境变量名不区分大小写。平台截图、浏览器或真实引擎等有外部依赖的用例,应先在准备阶段取得获准的产物,进入测试阶段后继续使用断网设置。 + +按表逐项运行并单独保存退出码。三台机器均跑类型检查。 + +| 工作目录 | 命令 | 范围 | +| --- | --- | --- | +| 根目录 | `pnpm --filter @cindy/host test` | 全部 Host 单元测试,含 startup-account.test.mjs | +| apps/host | `node scripts/check-e2e-imports.mjs` | 加载验收脚本的依赖 | +| apps/host | `node --import tsx --import ./src/loaders/register-raw.mjs scripts/provider-config.e2e.mjs` | 供应商配置验收 | +| 根目录 | `pnpm --filter @cindy/host test:ipc-route` | IPC 路由验收 | +| 根目录 | `pnpm --filter @cindy/host test:lifecycle` | Ubuntu 与 macOS;Windows 按 CI 记录跳过 | +| 根目录 | `pnpm --filter @cindy/host typecheck` | Host TypeScript | + +Windows 可调用 `pnpm.cmd`。真实账号、浏览器及真实模型服务不属于本组门禁。默认安装会尝试准备平台对应的 bundled ripgrep;本流程设置的 `XDT_SKIP_AGENT_BIN_INSTALL=1` 会跳过这一步。`outbound-path-fact.test.mjs` 创建真实的 Agent 依赖图,需要这个可执行文件。如果用例因此报 `Bundled ripgrep not found`,保留命令的实际退出码,在报告中把该项列为缺少测试依赖、未验证,不计为产品失败。准备好同版本的平台产物后再验证该项。 + +用 `fetch TASK` 取回脚本、stdout/stderr 和 result.json,逐项记录用例数、断言、跳过项和机器实测版本。SSH 中断后先取回结果并核对任务进程。确认完成并保存日志后用 `clean TASK` 清自己的 UUID 目录。 + +## 发布前的 macOS 复核 + +先用该任务的 Node,在实际运行测试的临时目录下测一次文件监听: + +```bash +node --input-type=module <<'JS' +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'host-watch-')); +let start, elapsed; +const watcher = fs.watch(dir, (_event, name) => { + if (name === 'probe' && start !== undefined && elapsed === undefined) + elapsed = performance.now() - start; +}); +try { + await delay(100); + start = performance.now(); + fs.writeFileSync(path.join(dir, 'probe'), 'x'); + await delay(1000); + console.log('fs.watch latency (ms)', elapsed); + if (!(elapsed <= 500)) process.exitCode = 1; +} finally { + watcher.close(); + fs.rmSync(dir, { recursive: true, force: true }); +} +JS +``` + +一台自有 macOS Apple Silicon 机器在本次探针中用了 12 ms 收到目标文件事件。发布前应在当轮测试目录再测一次;探针通过后,可在同一台机器复核此前因 FSEvents 异常而标为「未验证」的测试。从 `apps/desktop` 逐条运行并保留各自的通过、失败和跳过数: + +```bash +pnpm exec vitest run src/main/file-browser/__tests__/deviceOp.test.ts -t 'watch: subscribe starts local watch' +pnpm exec vitest run src/main/local-themes/__tests__/omarchy.test.ts +pnpm exec vitest run src/main/maker-host/__tests__/pi-package-store-security.test.ts +``` + +Claude 和 Codex 的 hosted e2e 会启动真实引擎并连接测试夹具。在仓库根确认这版 macOS arm64 对应的 `apps/claude-code-bin`、`apps/codex-package-bin` 和 `apps/ripgrep-bin` 产物已经准备好;缺少时测试会跳过。按前述步骤隔离 HOME,使用测试自建的网关。先在基准提交和发布候选上各独立跑三次 Codex resume,再在候选上分别跑两份完整文件。下面的命令都从 `apps/desktop` 运行,日志写到之前定义的 `$task`: + +```bash +codex_test=src/main/remote-agent/__tests__/codexHosted.e2e.test.ts +for attempt in 1 2 3; do + rc=0 + pnpm exec vitest run "$codex_test" -t 'releases an idle task under slot pressure and resumes the same Codex thread' > "$task/codex-resume-$attempt.log" 2>&1 || rc=$? + echo "Codex resume $attempt exit=$rc" +done +pnpm exec vitest run "$codex_test" +pnpm exec vitest run src/main/remote-agent/__tests__/claudeHosted.e2e.test.ts +``` + +分别保存两份快照的日志。核实真实引擎用例实际执行;若测试超时,按本轮启动的 PID 核对残留进程。之后在正常负载下运行读者测试、related 和整套门禁。读者测试用文本搜索找读取改动源文件的测试(包括读源码的断言和 mock),related 以所有改过且仍存在的桌面源文件为输入。两轮明细均须留存。 + +在**有 Git 历史的发送端**、待测的干净 checkout 根目录,基准选目标主干的 merge-base。以下命令生成路径清单,随已核对的快照传输到远端的任务目录(与 `src` 同级)。存在未提交改动时,还应纳入新建的未跟踪源文件。 + +```bash +lists=$(mktemp -d) +base=$(git merge-base HEAD origin/main) +git diff --no-renames --name-only "$base" -- apps/desktop/src > "$lists/desktop-changes.txt" +git ls-files --others --exclude-standard -- apps/desktop/src >> "$lists/desktop-changes.txt" +``` + +其中 `lists` 是发送端存放清单的临时目录。从远端 `src/apps/desktop` 运行以下 Bash 命令;`rg` 需要在预检时确认可用,也可用已准备的本平台 ripgrep。路径筛选保留删除和改名的旧模块名供文本检索。若有跨包改动,对相应 workspace 同样收集和执行,核对放行表上点名的测试是否在最终集合中。 + +```bash +set -eo pipefail +task=$(cd ../../.. && pwd -P) +sources=() +reader_status=0 +related_status=0 +: > "$task/reader-patterns.txt" +while IFS= read -r file; do + rel=${file#apps/desktop/} + case "$rel" in *.test.*|*.spec.*) continue ;; *.ts|*.tsx|*.js|*.mjs|*.cjs) ;; *) continue ;; esac + name=${rel##*/} + printf '%s\n' "${name%.*}" >> "$task/reader-patterns.txt" + if [[ -f "$rel" ]]; then sources+=("$rel"); fi +done < "$task/desktop-changes.txt" +if [[ -s "$task/reader-patterns.txt" ]]; then + rc=0 + rg -l -F -f "$task/reader-patterns.txt" -g '*.test.*' -g '*.spec.*' src > "$task/readers.txt" || rc=$? + (( rc <= 1 )) || exit "$rc" + readers=() + while IFS= read -r file; do readers+=("$file"); done < "$task/readers.txt" + if (( ${#readers[@]} )); then pnpm exec vitest run "${readers[@]}" || reader_status=$?; fi +fi +if (( ${#sources[@]} )); then pnpm exec vitest related --run "${sources[@]}" || related_status=$?; fi +printf 'readers=%s related=%s\n' "$reader_status" "$related_status" +(( reader_status == 0 && related_status == 0 )) +``` + +记录每轮输入文件、实际发现的测试、失败和 skip 数。上面两步应分别采集退出码,一轮失败后仍需独立跑另一轮。仓库根的 `pnpm test:unit:related` 还会读取 Git 基准、工作树和新文件;在无 Git 历史的源码包上会退回全量。需要验证这个入口时,使用能解析同一 merge-base 的测试 checkout 并核对日志中的 `RELATED` 模式。最终整套的执行范围与基线见[个人版迁移放行表](personal-migration-release-table.md)。 diff --git a/docs/host/personal-migration-release-table.md b/docs/host/personal-migration-release-table.md index 70e487f29bc..6867007eaa5 100644 --- a/docs/host/personal-migration-release-table.md +++ b/docs/host/personal-migration-release-table.md @@ -23,7 +23,7 @@ | 1 | 上下文窗口、输出上限、压缩阈值、核实窗口 | maker-host/index.ts、pi-host.ts 构造点 → `engineModelResolvers.ts` | 已对齐(m1-cp2a) | desktop `engineModelResolvers.test.ts`;Host `agent-graph.test.mjs` | 无 | | 1b | 任务工作上下文预算 | `model-context-settings.ts` → `sessionContextBudgetCore.ts` | 已对齐(m1-cp2b) | Host `start-options.test.mjs` | 无 | | 2 | 禁用的 Skill | `skillhub/activationPreferences.ts` | 已对齐(m1-cp3a) | Host `agent-graph.test.mjs` | 无 | -| 2b | 托管 Skill(内置与插件提供) | `maker-host/managed-skills.ts` → `managedSkillsCore.ts` | 部分(m1-cp6):三个引擎都拿到 Host 插件运行时给的同一份清单,与桌面相同;Claude、Pi 直接加载,Codex 只在任务所在电脑提供托管 Skill 时用它停用本机副本。缺口:Codex 自己看到内置与插件 Skill 要靠 Skill 投影,等第 25 行。内置 Skill 只读桌面最后一次发布的快照,Host 不发布;没发布过的 profile 清单里没有内置 Skill,不报错。插件身份读取改用桌面的 `findGhostForInstanceId`(含账号可用性收紧,`cindy-brain/ghostAvailability.ts`)。随包插件在 Host 不标内置,见第五节。**迁移前必须完成**(Codex 部分) | Host `plugins/managed-skills.test.mjs`(正式插件运行时:发布后的内置 Skill、未发布为空、四类插件身份前后一致、账号不可用时剔除)、`agent/managed-skills.test.mjs`、`agent-graph.test.mjs`;桌面 `hostPluginIdentityParity.test.ts`(桌面生产函数与 Host 逐项相同,两种账号状态) | 无 | +| 2b | 托管 Skill(内置与插件提供) | `maker-host/managed-skills.ts` → `managedSkillsCore.ts` | 部分(m1-cp6):三个引擎都拿到 Host 插件运行时给的同一份清单,与桌面相同;Claude、Pi 直接加载,Codex 只在任务所在电脑提供托管 Skill 时用它停用本机副本。缺口:Codex 自己看到内置与插件 Skill 要靠 Skill 投影,等第 25 行。内置 Skill:25b 之后,Host 在 owner 稳定且通过占用检查时,经共用准备流程发布自己的(`agent/shared-global-skills.ts:43`;2026-11-19 复查更正,原文说 Host 不发布);没发布过的 profile 清单里没有内置 Skill,不报错。插件身份读取改用桌面的 `findGhostForInstanceId`(含账号可用性收紧,`cindy-brain/ghostAvailability.ts`)。随包插件在 Host 不标内置,见第五节。**迁移前必须完成**(Codex 部分) | Host `plugins/managed-skills.test.mjs`(正式插件运行时:发布后的内置 Skill、未发布为空、四类插件身份前后一致、账号不可用时剔除)、`agent/managed-skills.test.mjs`、`agent-graph.test.mjs`;桌面 `hostPluginIdentityParity.test.ts`(桌面生产函数与 Host 逐项相同,两种账号状态) | 无 | | 3 | 插件花名册 | `mcp-integrations/ghost.ts` `getGhostRosterPrompt` | 已对齐(m1-cp3b,插件基座提交) | Host `agent-graph.test.mjs`;`plugins-installed.e2e.mjs` 花名册断言(该 e2e 未完整运行,见第五节) | 无 | | 3b | 能力路由(Claude 常量、Codex 工厂) | `capability-routing.ts`、`codexCapabilityRouting.ts` | 已对齐(m1-cp3b) | desktop `codexCapabilityRouting.test.ts`;Host `agent-graph.test.mjs` | 无 | | 3c | 引擎可用模型清单 | `catalog-to-descriptors.ts` `deriveAvailableModels` | 部分:刷新时机与桌面不同,见第二节 | Host `agent-graph.test.mjs`、`start-options.test.mjs` | 无 | @@ -32,38 +32,41 @@ | 5 | 视觉桥(已退役) | Desktop 与 Host 同轮移除全部代读路径,详见[移除方案](../plans/vision-bridge-removal.md) | 不再装配 Maker hook、代理转换、Pi 工具或额外读图请求;旧配置不读不写 | 验证结果见移除 PR | 无 | | 6 | 快速模式 | Host 原有 `session-settings.mjs` | 已对齐;Fast 轴与 Pi 价格档同步(m1-cp2b) | Host `start-options.test.mjs`(含恢复任务读到 priority) | 无 | | 6b | Claude 按模型的思考档位 | `resolveModelEfforts` | 已对齐(m1-cp2a) | desktop `engineModelResolvers.test.ts` | 无 | -| 6c | 思考开关写通道 | `register.ts` `SET_THINKING_ENABLED` | 未做(第 10 步) | — | 无 | +| 6c | 思考开关写通道 | `register.ts` `SET_THINKING_ENABLED` | 已对齐(检查点 3b-1):处理函数体搬成共用,Host 入口 `/api/sessions/set-thinking-enabled` | Host `session-update.test.mjs`“thinking:”;桌面 `makerOrcaRoleMarking.test.ts`(复核任务先被拒) | 无 | | 6d | Pi 思考开关记忆 | `newMakerDefaultsCache.ts` | 部分:读取已接(m1-cp2b);镜像由渲染层推送,客户端模式下推给窗口进程,Host 一直为空,要等 M2 的推送通道 | Host `start-options.test.mjs` | 无 | | 7 | 回合改动记录 | `turn-change-set/store.ts` | Host 现有的两类回合已对齐(m1-cp5e,m1-cp5f 补测):队列里的用户回合与直发回合。写入:引擎侧写前捕获(Claude、Pi)、派发时开记录定锚点(`beginTurnChangeSetAtDispatch`)、事件流记 Codex 原生改动(`noteTurnDiffEvent`,远程标记与桌面同一表达式)。落盘:done 与终止性错误时 `finalizeTurnChangeSet`,判定按 `sessionEventPreparation.ts` 手写(非共用代码),四种终态都有测试。清理:未派发、绑定实例关闭、同一任务换实例、删除任务。桌面另有这些发起回合的路径各自带着开记录与撤销的成对调用,Host 上都还没有:send_to_session(`register.ts:12348-12382`)、hook(`hook-control/session-runner.ts:1638`、1655、1675)、IM(`im/shared/turnRunner.ts:1948`、1961、1985)、定时任务(`scheduler-host/runner.ts:2278`、2334、2360,经 `createAutomationUserTurnGitBaselineHooks`)、goal-host(`controller.ts:2540`、2550、2591)、learn-host(`controller.ts:600`)、Orca 直发(`orcaInterAgentDispatcher.ts:878`、892,`beginDirectTurnChangeSet`)。哪条路径接到 Host,必须带上自己的这一对;查看与撤销的界面入口随 M2 | Host `input-queue.test.mjs`(锚点落盘、四种终态、先后顺序、未派发清理、实例关闭与替换);`agent-graph.test.mjs`(引擎侧) | 无 | -| 7b | Git 保存点与文件回退 | `git-snapshot-host.ts` → `gitSnapshotHostCore.ts` | 部分(m1-cp5e):保存点已接。派发前基线(队列钩子与直发钩子)、回合结束改后快照(`onTurnEnd`)、未派发撤回(`onTurnAbort`)、绑定实例关闭(`onSessionClosed`)、账号库就绪后的已删除任务引用对账,都与桌面同一份代码。未接:回退入口 `maker:rewind:preview`、`maker:rewind:commit` 随 M2 的界面通道一起接。标签:桌面用引擎自己的一次性调用(`maker.oneShot`)起标签,派发前经路由守卫做停用裁决,守卫读桌面供应商服务的视图。Host 没有等价的视图,标签一律用确定性兜底(如「改动 a.txt」),不发付费请求;路由守卫端口按「不可用」。等价的供应商视图随 M2 的模型通道做,届时再拆路由守卫并接真实调用(m1-cp12 已把之前的拆分还原,`model-route-guard-live.ts` 与 main 相同) | Host `git-snapshot.test.mjs`(真实临时仓库);`input-queue.test.mjs`(钩子顺序);desktop `hostGitSnapshotChain.test.ts`(桌面建一轮、Host 接着建一轮:同一引用按序排列,尝试记录同一 owner 目录) | 无 | +| 7b | Git 保存点与文件回退 | `git-snapshot-host.ts` → `gitSnapshotHostCore.ts` | 部分(m1-cp5e):保存点已接。派发前基线(队列钩子与直发钩子)、回合结束改后快照(`onTurnEnd`)、未派发撤回(`onTurnAbort`)、绑定实例关闭(`onSessionClosed`)、账号库就绪后的已删除任务引用对账,都与桌面同一份代码。未接:回退入口 `maker:rewind:preview`、`maker:rewind:commit` 随 M2 的界面通道一起接。标签:桌面用引擎自己的一次性调用(`maker.oneShot`)起标签,派发前经路由守卫做停用裁决,守卫读桌面供应商服务的视图。Host 没有等价的视图,标签一律用确定性兜底(如「改动 a.txt」),不发付费请求;路由守卫端口按「不可用」。等价的供应商视图随 M2 的模型通道做,届时再拆路由守卫并接真实调用(m1-cp12 已把之前的拆分还原,`model-route-guard-live.ts` 与 main 相同) | Host `git-snapshot.test.mjs`(真实临时仓库);`input-queue.test.mjs`(钩子顺序);desktop `hostGitSnapshotChain.test.ts`(桌面建一轮、Host 接着建一轮:同一引用按序排列,尝试记录同一 owner 目录) | 无。memory_review 在 Host 上报不可用(`b08fbae2fb`),报错原文沿用 maker-core `manager.ts:946` 的 “…is disabled in settings”,经 `classifyMemoryError` 归成 INTERNAL,说“设置里停用了”不准确;先不改(改 maker-core 文案会影响桌面真正停用时的提示),等辅助模型链上 Host 时一起处理(审核方 2026-11-17 定) | | 8 | 工作树租约 | `worktree/runtimeLeases.ts`(main 已去掉 Electron 依赖,Host 直接复用);`worktree/precreatedCancellation.ts` → `precreatedCancellationCore.ts` | 已对齐(main 已提供共用租约主体,撤回本线的 runtimeLeasesCore 拆分;取消预建仍复用 precreatedCancellationCore):Host 的启动钩子与桌面同一份代码,在共享 Skill 链接之前取租约、取后复查已取消的预建;启动失败且运行时确定没起来、启动清理成功、关闭时释放(Host 正常退出时 Maker 关闭会话,逐个释放)。租约写在 Host 的 profile,同一 profile 的窗口进程回收工作树前读到它并当作在用;Host 不在窗口的实例登记表里,靠写入进程的进程号与进程身份受保护。Host 只持有、只释放,回收与释放重试仍由窗口进程做:迁移后若长期没有窗口进程在跑,孤儿工作树没人回收(保守方向),M2 把回收接到 Host 时解决。Host 崩溃留下的租约与桌面自己崩溃时相同:最后一次心跳过了宽限(1 小时)或机器重启之后不再保护,文件留在原处不删;崩溃后重启的 Host 再取一份新的,宽限内两份并存 | Host `agent/worktree-leases.test.mjs`(本测试的 Node 子进程充当 Host、桌面一侧用同一份租约代码读:持有时受保护,关闭后不再保护;被杀后宽限内仍保护、过了宽限不保护;正常退出后重启只剩一份,崩溃后重启两份并存;Maker 三个钩子的释放;另一实例取消的创建在取租约之后被拦下;不在托管工作树或远程任务不取;源码形状) | 无 | | 9 | Codex 产品提示标记 | `maker-host/session-storage.ts` | 已对齐(m1-cp5a) | Host `agent-graph.test.mjs`;`codex-runtime.e2e.mjs` 数据库往返 | 无 | | 10 | 读图钩子、电脑操作防护、Bash 并发闸门 | `claudeHooks`(`maker-host/index.ts`) | 已对齐(m1-cp15b):Host 的 ClaudeCodeAgent 用同一组共用模块拼出同样的 claudeHooks;并发闸门每个运行时一个(桌面每个 Maker 一个),上限每次准入现读代理资源设置;电脑操作防护按本 owner 的 computer 插件开关给理由 | Host `agent/claude-hooks.test.mjs`(事件表与桌面拼法相同;读图钩子放过非图片;上限为 1 时第二个 Bash 排队、第一个结束后放行;键鼠模拟被拒,开、关两种理由;与 `index.ts` 逐行相同的源码形状断言) | 无 | -| 11 | Codex 任务的记忆 | `apps/host/src/agent/memory.mjs` | 已对齐(m1-cp17b 核实,产品代码不改,只更新注释):Codex 经 Host 的 MCP 桥(mcp-runtime 的 `codexDeps`)拿到 cindy_memory,与桌面同一种接法;m1-cp5c 起 `makerMemoryEnabled` 按用户设置读取。auto 模式(m1-cp18a):Codex 自己的审批复核只在 ChatGPT 订阅(oauth-bearer)路由上启用,网关与自定义供应商路由上审批交给 Host 的复核路径;cindy_memory 是可信的第一方 server,有授权上下文时在本地放行、不调用复核模型。复核不可用时(例如没有授权上下文)这类调用会被拒,与其他工具相同。ChatGPT 订阅路由上由 Codex 自己的复核决定,未覆盖 | `codex-runtime.e2e.mjs`(真实 Codex 二进制、本机模拟上游,照 `main.ts` 装配记忆:记忆开启的任务请求里列出 cindy_memory 的工具,上游回一次 memory_write,写入落在 Host profile 的 owner 记忆目录;这一步用完全访问,只核对桥,不涉及审批;同一 e2e 的 auto 一步:网关路由、Host 的授权上下文解析器,记忆同样写入,复核模型请求为 0) | 无 | +| 11 | Codex 任务的记忆 | `apps/host/src/agent/memory.mjs` | 已对齐(m1-cp17b 核实,产品代码不改,只更新注释):Codex 经 Host 的 MCP 桥(mcp-runtime 的 `codexDeps`)拿到 cindy_memory,与桌面同一种接法;m1-cp5c 起 `makerMemoryEnabled` 按用户设置读取。auto 模式(m1-cp18a):Codex 自己的审批复核只在 ChatGPT 订阅(oauth-bearer)路由上启用,网关与自定义供应商路由上审批交给 Host 的复核路径;cindy_memory 是可信的第一方 server,有授权上下文时在本地放行、不调用复核模型。复核不可用时(例如没有授权上下文)这类调用会被拒,与其他工具相同。ChatGPT 订阅路由上由 Codex 自己的复核决定,未覆盖。memory_review(让模型自审记忆,2026-11-19 核对):主干 `c9e1fcd68e` 的 Host 接线直接调用 Claude 的默认一次性模型,不读取用户的辅助模型链或停用设置。本次 Host 改用桌面同一辅助模型链。默认来源停用时拒绝,链内停用候选跳过,链无可用模型时拒绝并且不回落。占用时拒绝新发请求;已派发的用量记到发起账号。同一处接上伙伴项目的记忆目录(`projectMemoryDir`,与桌面同一函数:任务工作目录是本账号伙伴项目时记忆写进项目的 `.cindy/memory`,之前 Host 写到老位置);伙伴作用域的 `botMemoryDir` 不接(只有伙伴任务用,Host 拒绝伙伴任务)。session_search(搜任务历史)在 Host 上注册(2026-11-17):检索用桌面同一份核心(`maker-host/sessionSearchCore.ts`,从 `session-search.ts` 拆出,不依赖 Electron;结果里的任务链接带 Host 自己的设备号),调用方检查照抄桌面 `mcp-providers.ts` 的顺序(第七节第 25 项),能不能搜全部任务用 Host 的 cindy_helper 历史搜索同一个授权器(`host-tools.ts` `readsAccountHistory`);之前没绑,工具不注册。cindy_memory 的每次调用先核对调用方(2026-11-17,`withAccountDataAccess`,照抄桌面,第七节第 26 项):调用的任务必须在当前库里、不是 restricted,返回前再核一遍;之前没绑,换账号后上一个账号的任务还能读写新账号的记忆 | `agent/memory.test.mjs`(经 cindy_memory 的 MCP 调用:先写一条,memory_review 报停用、复核 agent 的一次性调用为 0;伙伴项目目录里写的记忆落在项目里;session_search 在迁移过的 owner 库里搜到另一个任务的消息、链接带设备号,不是本账号任务的调用方被拒;当前库里没有的任务与关库之后的任务调用记忆工具被拒(“a memory call from a task outside the current account is refused”);session_search 调用中途换库,结果被拒(“session_search refuses its result when the account changes during the call”);改坏能红);`codex-runtime.e2e.mjs`(真实 Codex 二进制、本机模拟上游,照 `main.ts` 装配记忆:记忆开启的任务请求里列出 cindy_memory 的工具,上游回一次 memory_write,写入落在 Host profile 的 owner 记忆目录;这一步用完全访问,只核对桥,不涉及审批;同一 e2e 的 auto 一步:网关路由、Host 的授权上下文解析器,记忆同样写入,复核模型请求为 0) | 无 | | 12 | 本机附件 | `normalizeAttachments.ts` | 部分:Codex 本机路径有自动证据;Claude、Pi 与输入框粘贴路径未验证(第 9 步) | `codex-runtime.e2e.mjs` | 无 | -| 13 | 用量与花费记录 | `maker-ipc/session*TurnUsage.ts` 与四个广播模块 | 未做(2e,M1 最后)。Host 期间不记录用量,事后补不回来,必须在迁移前完成。2e 的边界还包括:复核调用的用量(第二节);Codex 作废后“需要恢复”的账号接口确认(桌面 `verifyRecoveryWithAccountRpc`,由用量读取发起),2e 完成时对照测试补上这一步 | — | 无 | +| 13 | 用量与花费记录 | `maker-ipc/session*TurnUsage.ts` 与四个广播模块 | 记录已做(3a–3d,3d 2026-11-18,见本格末尾);推送(3f)与读取、按使用方用量归乙。原来的判断:Host 期间不记录用量,事后补不回来,必须在迁移前完成。3a 已做:定价核心搬出 Electron(`usage/modelPricingCore.ts`、`accountCurrencyStoreCore.ts`、`referenceModelPricingCore.ts`),Host 经 `agent/usage-pricing.ts` 接上,`/api/usage/model-pricing` 与 `/api/usage/reference-model-pricing` 返回真实报价;v1 定价 `maker:usage:model-pricing` 只在 Host 的 device-link 里单独注册并换成美元口径,共享协议不改。XD 报价替换的时机与桌面 `model-access/index.ts` 相同:一次 /models 成功;账号边界(目录换身份时清空);凭据状态 failed / disabled / unsupported / idle 时清空(桌面 onStatusChange),恢复到 ok 后由下一轮 /models 带回。凭据失败清空价格与桌面一致,不是差别。收到 ok 时:Key 轮换由“Key 变化 → 目录过期”覆盖(`gateway.credential` 每次实时读 Key,`agent/model-access.ts:61`;目录的连接 key 含 credential,`agent/providers.mjs:30`,变了就把上一轮标为过期、下一次读取重拉,`:49–53`);端点变化走账号边界(身份含 endpoint,`:29`)。**与桌面的差别(登记)**:Key 与端点都没变时收到 ok(手动重试,或 Key 被拒后重新同步拿回同一个 Key),桌面立刻拉一轮 /models(`model-access/index.ts:432`),Host 等 5 分钟缓存过期(`providers.mjs:3`)或下一次 force 读取。**与桌面的差别(登记)**:登出后 Host 的价格读取返回 null,桌面传空列表(`model-access/index.ts:574`)得到 `{}` 并改写快照文件。Host 登出时 closeStorage 清掉 DB 客户端、会话提交为 signed-out,价格 scope(用户加 Key 文件身份)对不上,所以不再给出上一个账号的价格(fail-closed);不改写快照文件,是为了同一账号重新登录(Key 文件不变)时价格从内存或快照立即回来,另一个账号拿不到(审核方 2026-11-17 选此做法;测试 `agent/usage-pricing.test.mjs` 登出三条)。价格变化在 Host 上暂不推送(3f 做),读方再问 `/api/usage/*`。2e 的边界还包括:Codex 作废后“需要恢复”的账号接口确认(桌面 `verifyRecoveryWithAccountRpc`,由用量读取发起),2e 完成时对照测试补上这一步;“远程与分享”页按使用方记的供应商用量(桌面 `register.ts` 在事件上写的按使用方用量存储,甲 7 事件清点第 8 条;2026-11-18 起归乙,见下),以及 Codex 的 `account_usage` 账号用量快照(`sessionEventSnapshots.ts`) | Host `agent/usage-pricing.test.mjs`(3a:/models 轮次、重启恢复、账号边界与 Key 替换、凭据 failed / disabled 清空与恢复、登出后不答、同账号恢复、换账号拿不到)、desktop `hostDesktopSourceContracts.guard.test.ts`(main.ts 把凭据状态交给目录)、`device-link.test.mjs`(v1 定价);desktop `hostDesktopSourceContracts.guard.test.ts`(桌面各只建一个定价实例) | 无。设计定稿(2026-11-17,只读 Worker inv-phase1-a 起草,审核方定):拆成 3a 定价核心 → 3b 写库与广播核心 → 3c 记录器去掉 Electron(三者是桌面搬移,按单元交审)→ 3d Host 接线加 e2e(由 Lead 做,接 listen 时和 4a 的顺序一起核“回合结束后迟到的用量事件被提前返回丢掉”)。第一阶段 Host 不发四个余量刷新请求(企业额度、Claude CLI 用量、ChatGPT 用量、grok),用显式端口绑空,第二阶段随读通道接真并照搬桌面节流与退避;`/api/usage` 的两个定价接口改为返回真实报价,算进 3a;`verifyRecoveryWithAccountRpc` 不由回合结束触发,移到第二阶段的 Codex 限额读通道;推送 3f 和甲 4 一起排在内部第三批,仍在这一个 Host PR 发布之前完成,除非它绑定在第二阶段的通道上(到时在这一行写明是哪种)。3e 逐项:按使用方的用量第一阶段 Host 不写,归乙(2026-11-18,审核方定,见下);Codex `account_usage` 账号快照没有读者,和刷新口一起放第二阶段;自动复核、工具循环复核在两端按请求记录辅助收据(2026-11-19 核对,见第二节和第五节桌面事项第 8 条)。视觉桥已在主干 `dc9afe565a` 退役,旧账目保留。标题、摘要、提示词预测、语音等类别 Cindy 后台服务不发起模型请求,因此没有漏记。**审核方 2026-11-18 定**:归甲的是 3b、3c、3d;归乙的是推送(3f)与读取、四个余量刷新、Codex 账号快照、`verifyRecoveryWithAccountRpc`,以及按使用方用量(`provider-usage-by-party.json`)连同“谁来写这个文件”的设计。**按使用方用量(审核方 2026-11-18 更正)**:第一阶段 Host 完全不写这个文件,3d 把它的端口绑成空操作;原定闸门关着时不记的 (c) 规则随之不再需要。不写的原因:这个文件由进程内存持有、1 秒后整份原子改名覆盖,跨进程不加锁、写前不重读;客户端模式下窗口进程自己也会写它(第五节并存行后续十 ②),Host 再写,两边会互相覆盖。乙要定谁来写,两种做法:(1) 客户端模式下 Host 是唯一写方,窗口收到的供应商组用量报告交给 Host 写;(2) 给存储加锁,写前重读再合并。差别登记在第二节“按使用方用量不含 Host 跑的任务”。收尾回合的用量照常写进库(库里三张日用量表、任务行、消息与定时任务运行都是库内原地累加,见第五节并存行后续十)。记录器读 `CURRENT_CINDY_REGION` 计价,照甲 20 登进 `desktop-region-readers.ts`(随 3d)。**3d 的两项裁定(审核方 2026-11-18)**:① 账号边界接受“按发起回合的账号写”:listen 建立时记下 owner,记录器每次写入前确认 owner 没变,变了就丢弃;登记为第二节差别“回合中途换账号后迟到的用量”,桌面现状记进第五节桌面事项第 9 条。② 设备互联推送选 (ii):第一阶段 Host 不推用量,广播端口绑空;用量核心经设备互联镜像(`tapWindowBroadcast`)推出的通道,Host 的镜像接收方(`device-link.ts:246`)也不转发,3d 实现时报审是在 Host 一侧过滤还是给核心加端口;登记为第二节差别“用量变化不推给远程设备”,与读取、推送那一批一起打开。3d 其余方案照准,包括按使用方用量的端口绑空。`readPriorUserRoundCost` 已先原样搬到不带 Electron 的 `localDb/ipc/localHistoryViewReader.ts`(单独提交,逐行审),`messages.ts` 转出它,桌面调用方不变。**3b、3c 已做(桌面搬移,`cindy/usage-3bc`)**:四个广播模块与三个回合记录器、回合上下文、Pi 回执原样搬成不带 Electron 的核心(`*Core.ts`),只改导入的模块路径,改到同名同签名的端口(`usageBroadcastPorts.ts`、`maker-ipc/turnUsagePorts.ts`)或已有的不带 Electron 的同一函数;原文件成了包装:保留它原来的那几条导入,把这些函数绑到端口,再转出核心,所以导入路径、导出名与导入图都不变;用量模型键与订阅估算价从 `usage/usageHistory.ts` 原样搬到 `usage/usageModelKeys.ts`。守卫 `__tests__/usageCorePortWiring.guard.test.ts`(guard 层)钉住四条:桌面生产代码只经包装用核心,包装从端口模块只取绑定函数;核心连同它导入的同组核心用到的每个端口,都由它的包装或这个包装导入的包装绑上;包装导入它的核心所导入的同组核心的包装;核心在模块加载时不调用端口。**核心顶层调用的确认(2026-11-18)**:九个核心在模块加载时执行的调用逐个列出(TS AST 列出函数体之外的 call、`new`、tagged template):3c 的五个只有 `createLogger`、`new Set`、`new WeakMap`;3b 的四个另有 `blankCodexSnapshot()`(本地纯函数)与 `createXaiRateLimitPublisher(cb)`(只在 record、clear 时才调 cb,`usage/xaiRateLimits.ts`)。都不碰端口,间接也不碰。以后遇到“顶层建对象、回调以后才调用”的写法,照同样方式确认:看被调的工厂在构造时是否调用回调。**3d 已做(2026-11-18,`cindy/usage-3d`)**:Host 在 `agent/turn-executor.mjs` 的 `listen()` 里照桌面管线(`sessionEventPipeline.ts`)的位置,在终态阶段之后依次调三个记录器核心,传原始事件;被桌面准备阶段丢弃的事件(hostProjection、turn_diff、独立通知、卡片关闭、Codex 图片)不进记录器。装配在 `agent/usage-recording.ts`:每任务的用量表照 `register.ts`,`close`、解绑时清空;回合开始时的计时、回合模型与回合上下文照 `sessionEventPreparation.ts`;终态的 persistId 照 `sessionEventTerminal.ts`(Host 现在也调 `consumeLastAssistantPersistId`,失败轮交给配对的 done,Claude 续接边界 remember/finish)。迟到的用量照记:回合结束后(`:559` 那段)与上一代的事件照样进记录器,不落消息行、不发客户端,只用失败交接的 id、不 consume。桌面占用期间(闸门关着)允许收尾的回合与它回合结束后才到的迟到 done 都照写共享库,算那一轮的收尾(审核方 2026-11-18 同意);库内原地累加,不会和桌面互相吃掉。按发起回合的账号写:写库端口在 AsyncLocalStorage 里取本任务的写队列与 owner,owner 是输入运行时在回合开始时绑定的那个(`input-queue.mjs` assertCurrent),不在事件到达时重取;不在任何任务上下文里的写端口调用一律丢弃并记日志。核心在同一次端口调用里可能在 await 之后再取库(逐个:`recordSessionTurnSpend`、`recordSessionTurnTokens` 取一次句柄后一直用;`recordModelTurnUsage` 先 await `incrementDailyModelUsage` 再取库写 `incrementDailySessionUsage`;`recordTurnSpend` 内部 `incrementDailySpend`;消息与定时任务运行的写入在任务写队列里,补丁与前一轮花费用任务 owner 的句柄,定时任务运行的花费取当前库)。Host 侧补了防护:每次写端口调用都登记,账号边界在关库之前 `await usageRecording.drain()`(先停掉新的记录与端口调用,再等登记的调用和 Pi 回执写完);Host 关掉旧库之后才装新账号的库,所以登记过的写入只会落在旧账号的库里。Pi 回执:写入用该任务第一张回执时取到的库句柄(`piUsageReceiptsCore.ts`);待定价的回执存在该账号自己的库里(`pi_usage_receipts`,priced = 0),重试只给当前库里的这些行定价,换账号后重试不会碰另一个账号;定价写入是 `UPDATE … WHERE priced = 0`,同一张回执不会记两次。桌面占用期间 Host 不触发重试,闸门放开后再做。不发请求:四个余量刷新与 `broadcastSchedulerChanged` 绑空;按使用方用量不提供(`recordProviderPartyUsage` 是可选项)。推送:广播端口绑空,设备互联不转发第一阶段名单内的通道(第二节“用量变化不推给远程设备”,第七节第 41 项)。读取的凭据只在内存:网关 key(`modelAccess.gateway.credential`)与 Codex 代理的鉴权模式,不读钥匙串。桌面搬移 D1:`register.ts` 的 `readSessionModelForUsage`、`unpricedSubscriptionValueMarker` 原样搬到 `maker-ipc/turnUsageSessionDefaults.ts`(单独提交,父提交为准备分支 `b00e47c7f9`)。测试 Host `agent/usage-recording.test.mjs`(19 条:三引擎各一轮、续跑增量、失败轮配对 done 与重放、续接边界、后台回合、中断的 Codex、停止后的 done、上一代迟到 done、换账号两种顺序、上下文外的写端口、不发请求、闸门期间收尾与迟到、close 清表、tap 名单与完整性、Pi 回执重试与闸门与换账号、drain、按使用方文件不写) | | 14 | 账号与供应商就绪、provider 冻结、model interface | 桌面启动钩子第 ③④⑤ 步 | 已对齐(m1-cp2b,就绪检查方式见第二节) | Host `start-options.test.mjs` | 无 | | 15 | 订阅 Fast 策略、价格档 | 桌面启动钩子第 ⑥⑩ 步 | 已对齐(m1-cp2b) | Host `start-options.test.mjs` | 无 | | 16 | 可选目录(账号过滤、订阅池投影) | `getDesktopSelectableCatalog` | 已对齐(m1-cp2c) | desktop `subscriptionPoolCatalog.test.ts`;Host `model-context.test.mjs` | 无 | | 17 | 共享项目 Skill 链接 | 桌面启动钩子第 ⑬ 步与 `onBeforeStart` | 已对齐(m1-cp3b);会写工作目录,见第三节 | Host `start-options.test.mjs` | 无 | -| 18 | /learn 捕获 | `learn-host/captureInvocation.ts`;`maker-ipc/register.ts` 的 `captureCindyLearnInvocation` | 部分(m1-cp10):捕获已接;/learn 在 Host 上仍不可用,依赖第 22 行与第 27 行。Host 的回合执行本来就走共用的 `createMakerSendTransaction`,补上同一个 `createCindyLearnInvocationCapture`,依赖逐项照桌面(内置 Skill 读桌面最后一次发布的快照、Cindy 的 Skill 启用设置、机器人会话检查、按引擎列 Skill)。实测:Claude(`/cindy:learn`、`/learn`)与 Pi(`/skill:learn`、`/cindy:learn`)能捕获,引擎钉住已发布的内置 learn 文件,这条用户消息记下同一份快照;Codex 要等 Skill 投影(第 25 行)才列得出内置 learn,在那之前不捕获。快照只由 Host 自己写,客户端塞进输入的同名字段既进不了消息记录,也改变不了钉住的文件。消费方 `start_skill_learning`(cindy_helper,第 22 行)与 Learn 宿主(第 27 行)都还没有,所以 /learn 只是钉住了正确的文件,实际跑不起来。依赖第 25 行:迁移后内置 learn 不再更新。**迁移前必须完成** | Host `agent/learn-capture.test.mjs`(真实发布与 Host 引擎列 Skill;各引擎、各否定条件;列出的 Skill 路径全部在夹具目录内)、`agent/learn-send.test.mjs`(经输入队列与共用事务:钉住的文件与消息记录;伪造字段两层断言);桌面 `learn-host/__tests__/hostLearnCaptureParity.test.ts`(桌面与 Host 的依赖在同一 profile 上逐场景给出同一份快照,列 Skill 的参数也相同) | 无 | -| 19 | 引擎专有项(Claude、Codex、Pi 各一组) | maker-host 构造点 | 部分(m1-cp18a):照桌面接上 Claude 的只读工具白名单(`claudeAllowedTools`)、子代理用量(进程级用量桥,Host 回环代理已在写)、Codex 凭证形态切换前对本机会话的处理(`prepareCodexLocalCredentialModeSwitch`);本机 MCP 与 Cindy 自定义 MCP 重名时的选择(`resolveLocalMcpDuplicateChoices`)拆出 core,Host 只读 owner 目录里窗口写的 `mcp-duplicate-preferences.json`,写入仍走窗口进程的 IPC(通道放 M2)。m1-cp18b:Claude 子代理显式模型的准入(`resolveClaudeSubagentModelAccess`)拆出 core,Host 传自己的网关 key 与供应商视图;先把 XD 快照的权威标记对齐桌面(第二节)。只有「拒绝」会挡,「拒绝」只来自 XD 快照(付费墓碑,或本轮成功的清单里没有);供应商视图只给出放行或未知,两者处理相同。Pi:用户自己的全局上下文目录(第三节);运行中的模型表、已下架模型的描述、网关块的描述,改用 Host 的可选目录;缓存兼容记录拆出 core,Pi 桥写 profile 里与桌面同名的文件,运行时读回(第三节共用文件);启动时的云端文件提示与 Pi 扩展对话框文案照桌面(语言见第二节)。m1-cp18b2:Pi 原生供应商(`resolvePiNativeProviders`)连同 Pi 网关块的 API 与 compat(`resolvePiGatewayModelApi`、`resolvePiGatewayModelSpec`,即 P8、P9)原样拆进 `piNativeProvidersCore.ts`(Pi 目录探测与其缓存仍是模块级,一个进程一份),桌面在 `pi-host.ts` 用原有依赖绑定,Host 用自己的端口(`pi-native-providers.ts`:回环代理的端点与就绪、Pi 二进制、Codex 账号服务的 OpenAI 订阅判断、Grok 登录、自定义供应商与 key、profile 目录);之前 Host 传的是只按自定义供应商生成的自己的实现(第 24 行)。两个端口与桌面不同:启动本机 Pi 前刷新全局 Skill 投影,Host 先不做(第 25 行);Host 没有本机模型运行时,托管 Ollama 与 llama.cpp 的任务得到桌面在未就绪时的同样报错(`[LOCAL_OLLAMA_NOT_READY] … (absent)`、`[LOCAL_LLAMACPP_NOT_READY]`)。Pi 判断 OpenAI 订阅只算用户添加的来源,与桌面相同(m1-cp18b2)。m1-cp18c:Pi 持久子代理(`spawnPiSubagentRunner`,P4)接上:桌面用 Electron 的 utilityProcess,Host 用 Node 的 `child_process.fork`(进程类型不同,审核方同意;见第二节)。启动前的路径检查与按 pid 结束原样拆进 `piSubagentRunnerLaunchCore.ts`,两边共用;Host 的中间入口 `pi-subagent-runner-process.cts` 与桌面 `piSubagentRunnerProcess.ts` 除发 ready 帧的方式与“发完断开 IPC”(对应桌面抹掉 parentPort)外逐行相同;子进程只拿 maker-core 给的环境(源自 boot-env 清过的 `process.env`)。结束只按 maker-core 持有的句柄(账号边界与结束动作走 `terminateSubagentRunner`,引擎释放与 Host 退出经 `Maker.shutdown` 走 `PiAgent.dispose`),与桌面同一份代码;普通的任务关闭按设计不结束持久子代理,与桌面相同。m1-cp18c2:Host 崩溃时 runner 随之结束(入口盯父进程,见第二节)。Pi 包(P10–P13):`pi-package-store.ts`(约 4200 行)与 `pi-managed-package-mutation.ts` 原样拆进 `piPackageStoreCore.ts`、`piManagedPackageMutationCore.ts`,所有模块状态(变更监听与变更标记的文件监听、变更队列、检查缓存、版本探测)进实例,桌面加载时建一个实例,文件监听仍在第一个订阅者出现时才开始;Host 用自己的端口(`pi-packages.ts`:profile 目录、Pi 二进制)接上启动时的包清单、包路径与资源、任务里的包管理命令,以及桌面在变更前后与观察到别的进程改动后让本机 Pi 任务重新加载的收尾(`maker-host/index.ts`、`maker-ipc/register.ts`,渲染层广播属 M2)。Pi 本体更新在 Host 上拒绝(第 34 行),归类为 maker-core 新增的 `unsupported`,Pi 的回执写“Updating the Pi core is not available here yet; package install, update and remove still work.”、不提示重试;回执里结构化的 `recovery` 字段仍是 store 给的 `check-host-update-and-retry-core`,未改。m1-cp18d:Codex 线程位置索引、只读发现、恢复准备与登记复用桌面同一份 Node 主体,历史目录与 SQLite 目录跟线程走,不跟新启动账号迁移;归档、分叉与路线交接使用同一组依赖。订阅池按历史反查账号仍归 M2,见下表。`prepareCodexHostToolCatalog` 只服务第 29 行,随它定。m1-cp18e(C3 盘点的丙类):Codex 线程登记产品提示时给智能子代理路由盖上父任务当前推理档位(桌面 d142106052,Host 的重写没跟上);Codex 的 OAuth 令牌读取照桌面先取 oauth-bearer 状态、已登录才读凭据,每次读取核对会话边界、owner、区域与 Codex 运行时;Claude 适配器补上 `getOneShotAuth`。Codex 与 Pi 鉴权适配器的整体对照已加,差别见第二节(Pi 那一类 m1-cp18b2 已对齐) | 桌面 `hostCodexThreadStorageParity.test.ts`(m1-cp18d:同夹具对照、只读零写入、历史与 SQLite 原目录、异常/并发与 owner 边界),Host `scripts/codex-runtime.e2e.mjs`(原生跨账号恢复、归档/取消归档、分叉/尾裁与路线换宿主;远端/受邀者不查本机历史);Host `agent/engine-deps.test.mjs`(m1-cp18b 起含子代理模型准入接线、Pi 全局上下文只读夹具、模型解析、缓存兼容记录的路径与读回、提示与对话框文案按系统语言,各有源码形状断言)、`agent/codex-thread-routes.test.mjs`、`hostPiPackagesParity.test.ts`(m1-cp18c2,真实 Pi 与本地包:两边轮流改同一个 pi-package-home、一边在改时另一边等它、各自看到对方的改动后读取逐项相同;Host 在自己改动前后与观察到桌面改动后让本机 Pi 任务重新加载;例外只有 Pi 本体更新)、maker-core `pi-auto-review-dispatch.test.ts`(`unsupported` 的回执文字不含重试,取值校验接受它、丢弃未知值)、`agent/pi-subagent-runner.test.mjs`(m1-cp18c:真实 fork Host 的入口与 maker-core 的真实 runner,runner 再起一个假 Pi;ready 一次、加载 runner 前通道已断、只带请求给的环境、越界路径不 fork;经 `terminateSubagentRunner` 与 `Maker.shutdown` 两条路径后 runner 与它的 Pi 子进程都退出;不理 SIGTERM 的 runner 在 1.5 秒后被 SIGKILL;入口与桌面入口的源码形状;m1-cp18c2 起另有:作为 Host 的父进程被 SIGKILL 后 runner 与它的 Pi 子进程都在几秒内退出,清理卡住时 5 秒强制退出,盯父进程的判断用注入的进程信息测五种情形)、`agent/codex-token-reader.test.mjs`、`scripts/claude-proxy.e2e.mjs` 第 5 步(m1-cp18e);桌面 `hostCodexAuthTokenReaderParity.test.ts`(桌面回调与 Host 读取器十种情形逐项相同)、`hostClaudeAuthAdapterParity.test.ts`(m1-cp18e 起比较 `getOneShotAuth`)、`hostCodexAuthAdapterParity.test.ts`、`hostPiAuthAdapterParity.test.ts`;桌面 `hostMcpDuplicateChoicesParity.test.ts`(窗口保存的每种选择与读不懂的文件,两边结论相同,文件逐字节不变;本机配置读取限制在夹具内)、`hostXdSnapshotAuthorityParity.test.ts`(六种状态下两边的 XD 快照相同;m1-cp18b2 起另有冷启动首轮失败与同账号换 key 两串事件,含嵌入模型兜底)、`hostPiNativeProvidersParity.test.ts`(m1-cp18b2:同一组输入两边的 Pi 原生供应商与 env 逐项相同,例外只有本机模型两处;探测失败返回 null 且不缓存;SuperGrok 选了而代理未就绪时先于探测报错;只有桌面刷新 Skill 投影;网关块 API 与 compat 是同一对函数)、`hostSubagentModelAccessParity.test.ts`(六种快照状态 × 请求上下文 × 模型 × 有无 key,两边结论逐格相同);拆分后桌面原有的 `pi-native-compat-overrides-store.test.ts`、`contextOverflowRollover.test.ts` 照过 | 无 | -| 20 | 诊断:进程登记、cc-debug、出口路径事实 | maker-host 构造点;`codex-tool-tree-reaper.ts`;`logger.ts` | 部分(m1-cp17b):三个引擎的进程登记照桌面接到同一份 `process-monitor/codex-process-registry.ts`;Host 真正退出时(`main.ts` 的 `stop`,Maker 关闭之前)照桌面退出时调一次 Codex 工具进程回收,只回收登记过、且在新取的进程快照里仍是 Host 直接子进程的 app-server 下面的进程树,app-server 本身留给正常关闭;账号切换、登出(`disposeOwnerRuntime`)和窗口交接不经过这里。进程监视器的界面通道放 M2。Claude 的 cc-debug 用桌面同一对函数,落在 profile 日志根的 `sessions//cc-debug.raw.log`,Host 启动时按 `XDT_CC_DEBUG_NET` 打开汇入;设置里的开关(`cc:set-debug-net`,B 类)留在窗口进程,Host 上只有带这个环境变量启动才开;桌面启动时对 raw 文件的修剪和全局 raw 文件不照搬:两个进程共用日志目录,Host 修剪可能截掉窗口进程正在写的文件,留到 M2 把这个开关的通道接到 Host 时一起定。桌面退出时的 `reapClaudeOrphansSync` 不照搬:它还按命令行标记回收父进程已退出的历史 Claude 进程,属于按名字匹配。后果:Host 崩溃后留下的 Claude 进程由窗口进程下次启动时的回收处理,长期没有窗口进程时没人回收。`claude-orphan-reaper.ts` 在 Host 的加载图里(Codex 回收用它的 `killProcessTree`),`reapClaudeOrphansSync` 在 Host 没有调用;它加载时只建一个具名 logger、算几组常量,没有 I/O、定时器或信号处理。出口路径事实随出口代理对齐一起做(第 28 行) | Host `agent/diagnostics.test.mjs`(三个引擎的登记与桌面同一拼法;本测试自己起的假进程树:只回收登记过的 Host 子进程下面的树,同名未登记的进程、登记了但已不是 Host 子进程的不受影响;调用点只在 Host 退出、在 Maker 关闭之前;cc-debug 与桌面同一函数) | 无 | +| 18 | /learn 捕获 | `learn-host/captureInvocation.ts`;`maker-ipc/register.ts` 的 `captureCindyLearnInvocation` | 部分(m1-cp10):捕获已接;/learn 在 Host 上仍不可用,依赖第 22 行与第 27 行。Host 的回合执行本来就走共用的 `createMakerSendTransaction`,补上同一个 `createCindyLearnInvocationCapture`,依赖逐项照桌面(内置 Skill 读当前已发布的快照(owner 稳定且通过占用检查时 Host 也经共用准备流程发布自己的内置 Skill,`agent/shared-global-skills.ts:41–51`;2026-11-19 复查更正)、Cindy 的 Skill 启用设置、机器人会话检查、按引擎列 Skill)。实测:Claude(`/cindy:learn`、`/learn`)与 Pi(`/skill:learn`、`/cindy:learn`)能捕获,引擎钉住已发布的内置 learn 文件,这条用户消息记下同一份快照;Codex 要等 Skill 投影(第 25 行)才列得出内置 learn,在那之前不捕获。快照只由 Host 自己写,客户端塞进输入的同名字段既进不了消息记录,也改变不了钉住的文件。消费方 `start_skill_learning`(cindy_helper,第 22 行)与 Learn 宿主(第 27 行)都还没有,所以 /learn 只是钉住了正确的文件,实际跑不起来。依赖第 25 行:迁移后内置 learn 不再更新。**迁移前必须完成** | Host `agent/learn-capture.test.mjs`(真实发布与 Host 引擎列 Skill;各引擎、各否定条件;列出的 Skill 路径全部在夹具目录内)、`agent/learn-send.test.mjs`(经输入队列与共用事务:钉住的文件与消息记录;伪造字段两层断言);桌面 `learn-host/__tests__/hostLearnCaptureParity.test.ts`(桌面与 Host 的依赖在同一 profile 上逐场景给出同一份快照,列 Skill 的参数也相同) | 无 | +| 19 | 引擎专有项(Claude、Codex、Pi 各一组) | maker-host 构造点 | 部分(m1-cp18a):照桌面接上 Claude 的只读工具白名单(`claudeAllowedTools`)、子代理用量(进程级用量桥,Host 回环代理已在写)、Codex 凭证形态切换前对本机会话的处理(`prepareCodexLocalCredentialModeSwitch`);本机 MCP 与 Cindy 自定义 MCP 重名时的选择(`resolveLocalMcpDuplicateChoices`)拆出 core,Host 只读 owner 目录里窗口写的 `mcp-duplicate-preferences.json`,写入仍走窗口进程的 IPC(通道放 M2)。m1-cp18b:Claude 子代理显式模型的准入(`resolveClaudeSubagentModelAccess`)拆出 core,Host 传自己的网关 key 与供应商视图;先把 XD 快照的权威标记对齐桌面(第二节)。只有「拒绝」会挡,「拒绝」只来自 XD 快照(付费墓碑,或本轮成功的清单里没有);供应商视图只给出放行或未知,两者处理相同。Pi:用户自己的全局上下文目录(第三节);运行中的模型表、已下架模型的描述、网关块的描述,改用 Host 的可选目录;缓存兼容记录拆出 core,Pi 桥写 profile 里与桌面同名的文件,运行时读回(第三节共用文件);启动时的云端文件提示与 Pi 扩展对话框文案照桌面(语言见第二节)。m1-cp18b2:Pi 原生供应商(`resolvePiNativeProviders`)连同 Pi 网关块的 API 与 compat(`resolvePiGatewayModelApi`、`resolvePiGatewayModelSpec`,即 P8、P9)原样拆进 `piNativeProvidersCore.ts`(Pi 目录探测与其缓存仍是模块级,一个进程一份),桌面在 `pi-host.ts` 用原有依赖绑定,Host 用自己的端口(`pi-native-providers.ts`:回环代理的端点与就绪、Pi 二进制、Codex 账号服务的 OpenAI 订阅判断、Grok 登录、自定义供应商与 key、profile 目录);之前 Host 传的是只按自定义供应商生成的自己的实现(第 24 行)。启动本机 Pi 前刷新全局 Skill 投影:Host 已接(`agent/pi-native-providers.ts:55`、`agent/runtime.ts:835`;2026-11-19 复查更正,原文说 Host 先不做);Host 没有本机模型运行时,托管 Ollama 与 llama.cpp 的任务得到桌面在未就绪时的同样报错(`[LOCAL_OLLAMA_NOT_READY] … (absent)`、`[LOCAL_LLAMACPP_NOT_READY]`)。Pi 判断 OpenAI 订阅只算用户添加的来源,与桌面相同(m1-cp18b2)。m1-cp18c:Pi 持久子代理(`spawnPiSubagentRunner`,P4)接上:桌面用 Electron 的 utilityProcess,Host 用 Node 的 `child_process.fork`(进程类型不同,审核方同意;见第二节)。启动前的路径检查与按 pid 结束原样拆进 `piSubagentRunnerLaunchCore.ts`,两边共用;Host 的中间入口 `pi-subagent-runner-process.cts` 与桌面 `piSubagentRunnerProcess.ts` 除发 ready 帧的方式与“发完断开 IPC”(对应桌面抹掉 parentPort)外逐行相同;子进程只拿 maker-core 给的环境(源自 boot-env 清过的 `process.env`)。结束只按 maker-core 持有的句柄(账号边界与结束动作走 `terminateSubagentRunner`,引擎释放与 Host 退出经 `Maker.shutdown` 走 `PiAgent.dispose`),与桌面同一份代码;普通的任务关闭按设计不结束持久子代理,与桌面相同。m1-cp18c2:Host 崩溃时 runner 随之结束(入口盯父进程,见第二节)。Pi 包(P10–P13):`pi-package-store.ts`(约 4200 行)与 `pi-managed-package-mutation.ts` 原样拆进 `piPackageStoreCore.ts`、`piManagedPackageMutationCore.ts`,所有模块状态(变更监听与变更标记的文件监听、变更队列、检查缓存、版本探测)进实例,桌面加载时建一个实例,文件监听仍在第一个订阅者出现时才开始;Host 用自己的端口(`pi-packages.ts`:profile 目录、Pi 二进制)接上启动时的包清单、包路径与资源、任务里的包管理命令,以及桌面在变更前后与观察到别的进程改动后让本机 Pi 任务重新加载的收尾(`maker-host/index.ts`、`maker-ipc/register.ts`,渲染层广播属 M2)。Pi 本体更新在 Host 上拒绝(第 34 行),归类为 maker-core 新增的 `unsupported`,Pi 的回执写“Updating the Pi core is not available here yet; package install, update and remove still work.”、不提示重试;回执里结构化的 `recovery` 字段仍是 store 给的 `check-host-update-and-retry-core`,未改。m1-cp18d:Codex 线程位置索引、只读发现、恢复准备与登记复用桌面同一份 Node 主体,历史目录与 SQLite 目录跟线程走,不跟新启动账号迁移;归档、分叉与路线交接使用同一组依赖。订阅池按历史反查账号仍归 M2,见下表。`prepareCodexHostToolCatalog` 只服务第 29 行,随它定。m1-cp18e(C3 盘点的丙类):Codex 线程登记产品提示时给智能子代理路由盖上父任务当前推理档位(桌面 d142106052,Host 的重写没跟上);Codex 的 OAuth 令牌读取照桌面先取 oauth-bearer 状态、已登录才读凭据,每次读取核对会话边界、owner、区域与 Codex 运行时;Claude 适配器补上 `getOneShotAuth`。Codex 与 Pi 鉴权适配器的整体对照已加,差别见第二节(Pi 那一类 m1-cp18b2 已对齐) | 桌面 `hostCodexThreadStorageParity.test.ts`(m1-cp18d:同夹具对照、只读零写入、历史与 SQLite 原目录、异常/并发与 owner 边界),Host `scripts/codex-runtime.e2e.mjs`(原生跨账号恢复、归档/取消归档、分叉/尾裁与路线换宿主;远端/受邀者不查本机历史);Host `agent/engine-deps.test.mjs`(m1-cp18b 起含子代理模型准入接线、Pi 全局上下文只读夹具、模型解析、缓存兼容记录的路径与读回、提示与对话框文案按系统语言,各有源码形状断言)、`agent/codex-thread-routes.test.mjs`、`hostPiPackagesParity.test.ts`(m1-cp18c2,真实 Pi 与本地包:两边轮流改同一个 pi-package-home、一边在改时另一边等它、各自看到对方的改动后读取逐项相同;Host 在自己改动前后与观察到桌面改动后让本机 Pi 任务重新加载;例外只有 Pi 本体更新)、maker-core `pi-auto-review-dispatch.test.ts`(`unsupported` 的回执文字不含重试,取值校验接受它、丢弃未知值)、`agent/pi-subagent-runner.test.mjs`(m1-cp18c:真实 fork Host 的入口与 maker-core 的真实 runner,runner 再起一个假 Pi;ready 一次、加载 runner 前通道已断、只带请求给的环境、越界路径不 fork;经 `terminateSubagentRunner` 与 `Maker.shutdown` 两条路径后 runner 与它的 Pi 子进程都退出;不理 SIGTERM 的 runner 在 1.5 秒后被 SIGKILL;入口与桌面入口的源码形状;m1-cp18c2 起另有:作为 Host 的父进程被 SIGKILL 后 runner 与它的 Pi 子进程都在几秒内退出,清理卡住时 5 秒强制退出,盯父进程的判断用注入的进程信息测五种情形)、`agent/codex-token-reader.test.mjs`、`scripts/claude-proxy.e2e.mjs` 第 5 步(m1-cp18e);桌面 `hostCodexAuthTokenReaderParity.test.ts`(桌面回调与 Host 读取器十种情形逐项相同)、`hostClaudeAuthAdapterParity.test.ts`(m1-cp18e 起比较 `getOneShotAuth`)、`hostCodexAuthAdapterParity.test.ts`、`hostPiAuthAdapterParity.test.ts`;桌面 `hostMcpDuplicateChoicesParity.test.ts`(窗口保存的每种选择与读不懂的文件,两边结论相同,文件逐字节不变;本机配置读取限制在夹具内)、`hostXdSnapshotAuthorityParity.test.ts`(六种状态下两边的 XD 快照相同;m1-cp18b2 起另有冷启动首轮失败与同账号换 key 两串事件,含嵌入模型兜底)、`hostPiNativeProvidersParity.test.ts`(m1-cp18b2:同一组输入两边的 Pi 原生供应商与 env 逐项相同,例外只有本机模型两处;探测失败返回 null 且不缓存;SuperGrok 选了而代理未就绪时先于探测报错;只有桌面刷新 Skill 投影;网关块 API 与 compat 是同一对函数)、`hostSubagentModelAccessParity.test.ts`(六种快照状态 × 请求上下文 × 模型 × 有无 key,两边结论逐格相同);拆分后桌面原有的 `pi-native-compat-overrides-store.test.ts`、`contextOverflowRollover.test.ts` 照过 | 无。显式端口批次(`70ae7d471c`,2026-11-17)查出并接上:Codex 的服务端压缩选择(`getCodexServerCompactionPreference`)。桌面每次启动 Codex 读用户在窗口里的选择(owner 目录的 `codex-compaction-settings.json`,`compaction-settings-store.ts`);Host 原来不传,用户的选择在 Host 任务上被忽略,现在读同一个文件(`agent/runtime.ts`,测试 `engine-deps.test.mjs`“server-compaction”) | +| 20 | 诊断:进程登记、cc-debug、出口路径事实 | maker-host 构造点;`codex-tool-tree-reaper.ts`;`logger.ts` | 部分(m1-cp17b):三个引擎的进程登记照桌面接到同一份 `process-monitor/codex-process-registry.ts`;Host 真正退出时(`main.ts` 的 `stop`,Maker 关闭之前)照桌面退出时调一次 Codex 工具进程回收,只回收登记过、且在新取的进程快照里仍是 Host 直接子进程的 app-server 下面的进程树,app-server 本身留给正常关闭;账号切换、登出(`disposeOwnerRuntime`)和窗口交接不经过这里。进程监视器的界面通道放 M2。Claude 的 cc-debug 用桌面同一对函数,落在 profile 日志根的 `sessions//cc-debug.raw.log`,Host 启动时按 `XDT_CC_DEBUG_NET` 打开汇入;设置里的开关(`cc:set-debug-net`,B 类)留在窗口进程,Host 上只有带这个环境变量启动才开;桌面启动时对 raw 文件的修剪和全局 raw 文件不照搬:两个进程共用日志目录,Host 修剪可能截掉窗口进程正在写的文件,留到 M2 把这个开关的通道接到 Host 时一起定。桌面退出时的 `reapClaudeOrphansSync` 不照搬:它还按命令行标记回收父进程已退出的历史 Claude 进程,属于按名字匹配。后果:Host 崩溃后留下的 Claude 进程由窗口进程下次启动时的回收处理,长期没有窗口进程时没人回收。`claude-orphan-reaper.ts` 在 Host 的加载图里(Codex 回收用它的 `killProcessTree`),`reapClaudeOrphansSync` 在 Host 没有调用;它加载时只建一个具名 logger、算几组常量,没有 I/O、定时器或信号处理。出口路径事实:Codex 的 `getOutboundPathFact` 已随出口代理的 28a 接上(第 28 行)。主干同步 6(2026-11-19):桌面真退出先经 `prepareForAppQuit` 封口,异步拆除时为未结算的 Claude 合成 `cancelled` done。Host 先停输入队列、关会话,再无参数调用 Maker shutdown,仍只回收既有登记覆盖的 Codex 工具树。退出帧差异本轮只登记,见第五节“重启后被打断的回合”。 | Host `agent/diagnostics.test.mjs`(三个引擎的登记与桌面同一拼法;本测试自己起的假进程树:只回收登记过的 Host 子进程下面的树,同名未登记的进程、登记了但已不是 Host 子进程的不受影响;调用点只在 Host 退出、在 Maker 关闭之前;cc-debug 与桌面同一函数) | 无 | | 21 | 启动时清掉从终端继承的 Anthropic 凭据与端点变量 | `main/index.ts` `stripSensitiveAnthropicEnv` | 已对齐(m1-cp5b):`main.ts` 第一个导入执行同一步,保留导入用的 Claude 配置目录 | Host `boot-env.test.mjs` | 无 | -| 22 | Cindy 内置工具服务 | `mcp-integrations/mcp-providers.ts` `createLiziMcpProviders` | 部分(main #9825 已带入):`agent/host-tools.ts` 用共用 `createLiziMcpProviders` 建 cindy_helper,已接宿主服务发现与调用、任务历史(目录、任务列表、消息、搜索)、文件、存储和终端;任务写调用经共用的输入授权与确认服务,`main.ts` 提供 `inputQueue.taskActionInput`。browser、computer 由 platformTools 并入同一个 provider 列表,另有 cindy_memory 与插件网关。未提供的 helper 端口(创建/删除任务、读附件、分叉与回退、session_control 的权限模式等)仍归 M1 任务组;cindy_lsp、cindy_ssh 也未接。M2 做设置、cindy_scheduler、cindy_docs、inputHandoff;M3 做伙伴、Orca、IM、群聊记录、android、sessionImport、远程状态。Agent 的 helper `hostCaller` 经宿主服务入口已接;插件可用范围的差别见第二节。任务历史的远程 `invokeRemote` 没有提供,返回 NOT_CONNECTED,不等于已接远程历史。系统提示与桌面相同,工具缺口仍须在开放迁移前逐项清零 | main 自带 `host-tools.test.mjs`、`platform/tools.test.mjs`;本轮在合并结果上运行(不是本分支新增的逐项桌面对照) | 无 | +| 22 | Cindy 内置工具服务 | `mcp-integrations/mcp-providers.ts` `createLiziMcpProviders` | 部分(main #9825 已带入):`agent/host-tools.ts` 用共用 `createLiziMcpProviders` 建 cindy_helper,已接宿主服务发现与调用、任务历史(目录、任务列表、消息、搜索)、文件、存储和终端;任务写调用经共用的输入授权与确认服务,`main.ts` 提供 `inputQueue.taskActionInput`。browser、computer 由 platformTools 并入同一个 provider 列表,另有 cindy_memory 与插件网关。未提供的 helper 端口(创建/删除任务、读附件、分叉与回退、session_control 的权限模式等)仍归 M1 任务组;cindy_lsp、cindy_ssh 也未接。M2 做设置、cindy_scheduler、cindy_docs、inputHandoff;M3 做伙伴、Orca、IM、群聊记录、android、sessionImport、远程状态。Agent 的 helper `hostCaller` 经宿主服务入口已接;插件可用范围的差别见第二节。任务历史的远程 `invokeRemote` 没有提供,返回 NOT_CONNECTED,不等于已接远程历史。主干同步 6(2026-11-19)后,粘贴共享任务链接时跳过账号历史快照,已有会话引用的投影可以附带设备任务链接;链接本身不授予读取源任务的权限,Host 仍未绑定 `history.readSharedTaskProgress`。系统提示与桌面相同,工具缺口仍须在开放迁移前逐项清零 | main 自带 `host-tools.test.mjs`、`platform/tools.test.mjs`;本轮在合并结果上运行(不是本分支新增的逐项桌面对照) | 无。xdtHelper 未点名端口的阶段(审核方 2026-11-17 定,归属表见只读 Worker inv-scripts-ports 的 xdt-helper-stages.md):`productHelpDocs` M1,已接(`e801ceedd4`:`agent/host-tools.ts` 的 xdtHelper 照桌面 `mcp-providers.ts:774` 传 `HELP_KNOWLEDGE`;测试 `host-tools.test.mjs`“the Host cindy_helper serves the desktop product help to agents”,去掉这一行即报 `HELP_UNAVAILABLE`);`runtimeCapabilities` M1,分两步——先在桌面准备分支把 `maker-host/index.ts:1077–1109` 的闭包搬成共用(先交可行性),再 Host 改绑;`askUserQuestionAsync`、`manageUserQuestions` M1,和协调器的 `onOwnerMessage` 一起由 Lead 在 4b 之后接;github 本机部分 M1;`piRuntime` 随第 34 行;`subscriptionUsage`、`listAvailableModels`、`sessionShare`、`grokLogin`、`mcpSetup`、`skillhub`、`githubIssue` M2;`skillLearning`、`authorizeSkillLearning` M2,但第 27 行要求**迁移前必须有结论**;`machines`、`sharedTask` M3;`appUpdate` 不在 M1–M3 | +| 22b | cindy_helper 的任务运行时工具(`get_session_runtime`、`set_session_runtime`) | `maker-ipc/sessionControlService.ts`(`createSessionControlService`,register.ts 交给 `createLiziMcpProviders` 的 `sessionControl`) | 未做(4b 清点,2026-11-17 登记;定类:乙,随第 22 行 M1 任务组的 helper 端口,迁移前关闭)。Host 的 cindy_helper 没有接会话控制(`agent/host-tools.ts` 不传 `sessionControl`),这两个工具在 Host 上不注册:用户能在窗口里看、改任务的模型与路线,Agent 不能。接的时候:`set_session_runtime` 改完要把 `effectiveProfile`(运行时调整优先,`control.effectiveOverride ?? profiles.effective`)与待生效的调整回给 Agent,`get_session_runtime` 经 `readSessionRuntimeProfiles`(Host 已用同一个共用工厂)读,不能直接读任务行 | 无 | 无 | | 23 | 引擎运行时配置(`runtimeConfig`) | `maker-host/runtime-configs.ts`;`pi-host.ts` `buildDesktopPiRuntimeConfig` → `runtimeConfigsCore.ts` | 已对齐(m1-cp5c):产品系统提示、回答呈现提示、`behaviorFlags`、`taskShellEnv`、压缩阈值、换模型时的上下文评估、子代理模型、记忆设置(每次读取)、`userDataPath`、内置 ripgrep。Host 的 endpoint 仍是账号网关,见第 24 行;代输入的环境变量在 Host 上恒为空,见第二节 | desktop `hostRuntimeConfigParity.test.ts`:同一组输入分别走桌面装配与 Host 装配,逐字比较 systemPrompt、answerDeliveryPrompt,函数项按输入矩阵比较输出,允许不同的只有写死的 endpoint;Host `agent-graph.test.mjs`(含缺 ripgrep 时与桌面同样报错);`codex-runtime.e2e.mjs` 断言真实 Codex 请求带产品提示 | 无 | | 24 | Claude 与 Pi 的本机兼容代理与订阅桥 | `maker-host/anthropic-compat-proxy-host.ts` → `anthropicCompatProxyHostCore.ts`(`getClaudeEndpoint`);`anthropic-responses-bridge-host.ts` → `anthropicResponsesBridgeHostCore.ts`;`pi-subscription-websocket.ts` → `piSubscriptionWebSocketCore.ts` | 已对齐(24a 代理,24b 订阅桥;Pi 的订阅 m1-cp18b2)。Pi 的订阅:m1-cp18b 更正为“部分”:Host 给 Pi 的原生供应商只按自定义供应商配置生成(`provider-config.ts` 的 `piNativeProviders`),没有 ChatGPT、SuperGrok 这类订阅供应商,原先写“已对齐”的依据只有代理运行时的单测。m1-cp18b2 改用桌面同一份 `resolvePiNativeProviders`(第 19 行),真实 Pi 二进制经 Host 的回环代理与订阅桥走通 ChatGPT 订阅与 SuperGrok(`pi-native.e2e.mjs`)。以下是已对齐的部分:Host 的 Claude 与 Pi 经同一模块的回环代理(只监听 127.0.0.1),按模型路由、字段适配与恢复规则与桌面相同;自定义供应商由直连改为经代理;Pi 登记会话 token;任务的供应商与思考档位登记与桌面相同。24b:ChatGPT 与 SuperGrok 订阅(Claude 走 HTTP,Pi 走 HTTP 与 WebSocket)经与桌面同一份订阅桥,凭据来自 profile 自己的登录:ChatGPT 读 profile 的 codex-home 与独立账号目录,SuperGrok 读 Host 的 grok 登录;桥的凭据缓存在 Codex 登录、登出、作废时清空,与桌面相同;上游判定 ChatGPT 登录被撤销时按第 26 行作废,独立账号经账号服务作废,SuperGrok 经 grok 恢复流程。Codex 子代理读 OAuth 改为经同一个桥(桌面 `readSubagentOAuth`)。Claude 认证与桌面适配器逐个分支相同,订阅账号按桌面 `subscriptionAccountState`(SuperGrok 读自己的登录,独立 Claude 账号报已停用)。订阅桥属于 Codex 运行时,没有 Codex 运行时时见第二节。`maker:session-background-activity` 一族与 `maker:claude-session-route:get` 的状态已在 Host 上具备,见第六节。与 2e 的分工:代理按桌面的时机写路由登记、挂子代理用量与余量观察器;读登记写用量表、注入余量 listener 归 2e | Host `agent/claude-proxy-runtime.test.mjs`(入站门、占位常量、网关口令按当前 key 转发与换 key、换 owner 与关闭后拒绝、订阅交给桥、无 Codex 运行时时拒绝、关闭清理、字段剥离、分类器失败)、`agent/native-auth.test.mjs`、`agent/agent-graph.test.mjs`、`scripts/claude-proxy.e2e.mjs`(真实 Claude Code:网关、同一个进程运行中换网关 key 后下一轮带新 key 成功、自定义供应商、ChatGPT 订阅经桥到本机模拟的 ChatGPT 后端并带 profile 的登录、上游撤销后作废且下一次请求不再外发)、`scripts/pi-native.e2e.mjs`(m1-cp18b2,真实 Pi:ChatGPT 订阅与 SuperGrok 各一轮到本机模拟后端,带 profile 自己的假登录,别处没有请求;Pi 先试 ChatGPT 的 WebSocket,隧道被模拟服务拒绝后退回 HTTP;用 Host 改动前的原生供应商时没有任何上游请求、脚本失败);桌面 `hostClaudeAuthAdapterParity.test.ts`(桌面与 Host 的 Claude 适配器在 来源 × 凭据模式 × 模型 × 登录事实 的 4096 格里状态与环境变量都相同,差别写死为两类:占位常量对运行时密钥,网关 key 对网关口令(14 格))、`anthropicCompatProxyStartup.test.ts`、`anthropicCompatProxyInboundPort.test.ts`、`hostRuntimeConfigParity.test.ts`(例外清单为空);包 `server-inbound-admission.test.ts` | 无 | -| 25 | 全局 Skill 投影、内置 Skill 发布、Codex 账号 CODEX_HOME 准备 | `authBoundaryQuarantine.ts` 的 owner 提交协议;`auth-adapters.ts:555-572`(`ensureSharedGlobalSkills`、`prepareBuiltInSkills`)、`:1373`(`prepareCodexGlobalSkillsLinks`)、`:2494`(`prepareCodexAccountHome`) | 未做(M1,紧挨第 11 步,与 Host 的 owner 提交一起;动手前先交切断清单)。Host 的 owner 提交不写投影边界状态;Host 里没有 `ensureSharedGlobalSkills`、`prepareCodexGlobalSkillsLinks` 的引用;Codex 独立账号直接用 `nativeSubscriptionAccount.configDir`,没有托管 Skill 投影与规则拷贝。Codex 上的内置与插件 Skill、home 级 Skill 链接都等这一行。内置 Skill 发布:Host 只读桌面最后一次发布的快照(m1-cp6),自己不调 `prepareBuiltInSkills`;迁移后桌面不再运行,内置 Skill 必然不再更新,因此这一行要让 Host 按同一 owner 提交协议发布内置 Skill。Pi:桌面在启动本机 Pi 前刷新全局 Skill 投影(`resolvePiNativeProviders` 的第一步),Host 的这个端口现在什么都不做(m1-cp18b2),随这一行接上。**迁移前必须完成** | — | 无 | +| 25 | 全局 Skill 投影、内置 Skill 发布、Codex 账号 CODEX_HOME 准备 | `authBoundaryQuarantine.ts` 的 owner 提交协议;`auth-adapters.ts:555-572`(`ensureSharedGlobalSkills`、`prepareBuiltInSkills`)、`:1373`(`prepareCodexGlobalSkillsLinks`)、`:2494`(`prepareCodexAccountHome`) | 部分(M1,紧挨第 11 步)。审核方 2026-11-17 定方案 A:窗口提交 owner,Host 只加入窗口已提交的同一 owner,自己不写边界状态。25a 已做(2026-11-17):桌面 `authBoundaryQuarantine.ts` 不再引用 Electron,profile 改读 `getUserDataDir()`;被动实例的判定改为注入,默认“不被动”。桌面在 `index.ts` 固定 userData 之后、动态加载 `bootstrap-electron` 之前注入原来的判定,guard 测试守着顺序,桌面行为不变。Host 加载同一模块,加只读诊断 `agent/skill-projection-boundary.ts`:启动时在 `configureHostOwner` 之后读一次,每次已授权的 `/health` 现读,结果放在 `runtime.skillProjectionBoundary`(`stable`、`other-owner`、`pending`、`quarantined`、`missing-or-invalid`、`unreadable`,只有类别,不带 owner id);不是 `stable` 时记一条 warn(`host-skill-projection`,只带类别),类别变化时再记,没有界面。25a 不改任务行为:Host 仍没有任何投影修改,下面的现状不变。25b 已做(2026-11-17,审核方定 (a)):**谁提交 owner**:窗口(客户端模式),或独立 Host 上的 `cindy-host login` 命令行进程;常驻的 `serve` 在加载前注入拒绝(桌面边界模块新增 `configureProjectionBoundaryOwnerCommit`,默认允许、桌面不注入;守护 `scripts/__tests__/host-skill-projection-owner.test.mjs` 钉住 serve 的注入)。login 先过并存检查(`createDesktopScanner`,读不出就拒绝并写明原因);serve 在跑但没有账号运行时可以登录,在跑账号 A 时只许 A 重新登录、换 B 拒绝并提示先停 serve(判断用 serve 的 status 里的 runtime.owner);按桌面顺序在账号 vault 锁内先存会话、再经边界过渡提交,过渡里照桌面 `suspendAllGhosts` 撤销所有 owner 投影根的 Ghost Skill 链接(根目录列表从 `ownerNamespaceMigration.ts` 原样搬到 `ownerProjectionRoots.ts`),有 blocker 就中止、边界留 pending、会话回滚到原记录,再跑一次 login 可恢复。serve 在跑时登录成功后提示重启 serve 才采用(serve 运行中不重新采用会话,现状)。**共享投影**:桌面 `ensureSharedGlobalSkills`/`runEnsureSharedGlobalSkills` 原样搬成共用 `sharedGlobalSkillsPreparationCore.ts`(`preparationScope` 一起搬),Host 四个触发点:账号库就绪后、每次 Claude 启动(照桌面先标记 Claude 已使用)、本机 Pi 启动前、`/api/agent-skills`;发布包带上 `resources/system-skills`(用户定 Host 自带内置 Skill)。并存闸门关着(同一 profile 上有会开库的桌面在运行,输入队列的 hold)时全部跳过刷新,`/api/agent-skills` 只列不刷新。锁目录不可用时这一轮不发布、不建链接(照桌面,`withSkillMutation` 返回 undefined);唯一例外是桌面 `prepareSharedGlobalSkillLinks` 在取变更锁之前就建好的空 `~/.agents/skills` 根目录,Host 跑同一份代码,同样会建(测试如实钉住,桌面未改)。**退出登录**(审核方定 (ii)):serve 退出登录成功后,在 `withStableOwnerBoundaryMutation(A)` 里跑同一套撤销,不新增提交能力,边界保持 stable(A) 到下一次 login 过渡;闸门关着时跳过(共用投影归正在运行的桌面),退出登录本身照常成功;客户端模式下窗口先退出、已把边界过渡为 null 时 serve 识别为 not-stable 不再清(两边都只在 stable(A) 时动、同一把 owner 锁,第二次清扫找不到可删的,不互相当成 blocker)。`cindy-host status` 在已登录但边界为 missing 或 other-owner 时提示重新运行 `cindy-host login`(老安装需要一次)。**L1**:`/api/agent-skills` 改走 `maker.listAgentSkills` 并传请求期的停用列表(照桌面 `readActivation`),用户停用的 Skill 不再出现(原来直接调引擎扫描,绕过了这道过滤,甲)。**appData 同源**:实测(仓库自带 Electron、隔离 user-data-dir、mock 钥匙串、只打印路径、按 PID 确认退出)macOS 上 Electron 的 appData 不跟 `$HOME` 走而 Host 的跟,改过 HOME 时两边的 Skill 变更锁目录会分开;Host 现在优先用启动方传入的 `CINDY_HOST_APP_DATA_DIR`,独立安装才自己算;桌面拉起 Host 时传值归迁移器(第五节乙 8)。未做:25c(Codex 的 Skill 投影与账号目录准备,拒绝启动的提示照用桌面原文;Codex 登录前的预热放在 Host Codex 适配器的 `triggerLogin`,与 `cindy-host login` 无关,更正 25a 时“Host 登录命令行路径要不要预热”的说法)。以下现状写的是 25b 之前:Host 的 owner 提交不写投影边界状态;Host 里没有 `ensureSharedGlobalSkills`、`prepareCodexGlobalSkillsLinks` 的引用;Codex 独立账号直接用 `nativeSubscriptionAccount.configDir`,没有托管 Skill 投影与规则拷贝。Codex 上的内置与插件 Skill、home 级 Skill 链接都等这一行。内置 Skill 发布:Host 只读桌面最后一次发布的快照(m1-cp6),自己不调 `prepareBuiltInSkills`;迁移后桌面不再运行,内置 Skill 必然不再更新,因此这一行要让 Host 按同一 owner 提交协议发布内置 Skill。Pi:桌面在启动本机 Pi 前刷新全局 Skill 投影(`resolvePiNativeProviders` 的第一步),Host 的这个端口现在什么都不做(m1-cp18b2),随这一行接上。窗口连着 Host 时在窗口里退出登录,Host 一并退出(用户已定,见第四节“用户已定的产品形态”)。**迁移前必须完成** | 25a:Host `boundary.test.mjs` 三条(同一模块在 Host 的 Node 里加载、用 Host 配置的 profile、默认不被动,窗口提交的 owner 稳定时可加入并修改;五种不稳定状态逐一归类,warn 只带类别,修改被拒;另一个进程持锁时修改失败、对方放锁后成功;全部在临时 HOME 下,先断言锁路径在临时目录里;改坏能红)、`startup-account.test.mjs`(`ensureRuntime` 先配置 owner、再读边界、再开账号库);桌面 `authBoundaryQuarantine.test.ts` 断言未改,只改准备部分;guard `authPassiveSharedInstance.test.ts`(注入在固定 userData 之后、加载 `bootstrap-electron` 之前) | 无 | | 26 | Codex 原生登录被服务端作废 | `auth-adapters.ts` `DesktopCodexAuthAdapter.invalidate`(实例隔离分支)与 `maker-host/index.ts` 的 `setOnLogoutSuccess`、`setOnInvalidatedBroadcast` | 已对齐(24b;登录、登出收口 m1-cp9),迁移来的共享登录也已对齐(m1-cp13;用户 2026-11-13 决定,原话「和桌面完全一样」):安装版 Host 像已打包桌面一样与系统 Codex 登录对账,链接、认领、作废后在系统重新登录时自动恢复(`codex-system-login.ts`);与桌面的差别见第二节。原为既有缺口,24b 补上:之前 Host 的 Codex 适配器没有 `invalidate`,服务端判定登录失效后不落标记、不清凭证。安装版 Host 读系统 `~/.codex/auth.json` 并把 profile 的 codex-home/auth.json 链接过去(与已打包桌面相同),源码运行不读系统登录;标记按检测到的凭据范围写,共享系统登录时记恢复 owner;迁移来的 profile 里 codex-home/auth.json 若是指向系统登录的链接,Host 平常经这个链接读写系统那份登录(订阅桥刷新令牌、Codex 自己刷新都是),与桌面相同,作废只删 profile 里的链接,外面那份文件不变。能指明被拒凭证的失效:凭证代次与当前 auth.json 一致才按被拒的那份记标记;文件换了(inode 不同)或登录进行中不动;同一文件就地改写时记不带指纹的标记、压住当前这份(m1-cp15a 起,与桌面相同;代次用桌面同一个解析函数读)。顺序与桌面相同,标记 → 解除授权 → 删 auth.json → 退役本机 Codex 进程与代理注入 → 删模型缓存 → 通知界面并让 Pi 的 MCP 桥失效。子进程没说明是哪一份凭证的失效(maker-core 目前都报这一种):与桌面相同,凭证原样保留,写抑制标记,登录进行中或显式断开后不动;为此账号登录服务加了只读的 `isCodexAccountLoginActive`(共用模块,桌面不调用)。两种都与桌面同一份标记位置与格式,写不进时同桌面改写撤销标记兜底;m1-cp15b 按桌面 invalidate 的分支对应表补齐五处:只有独立账号的 providerId 不作废(网关、自定义供应商的任务报失效时照样作废原生登录);去掉 Host 独有、无调用方的被拒令牌入参;收口中途 owner 变了就在桌面同样的位置停下;codex-home 本身是或链接到 `~/.codex` 时不删 auth.json;收口结束时重读标记,仍是这次的原因和范围才播报。m1-cp16 按桌面显式登出的分支对应表对齐 Host 的原生登出:取消进行中的登录,写桌面同一个持久断开标记(写不进就登出失败),保留 auth.json(共享登录的链接留在原地,对账由标记停住),退役本机进程,删模型缓存,结束前再写一次标记,最后撤销授权;每一步之前查 owner,第二次登出并入第一次,登出期间开始的登录等它结束,登出期间完成的登录不绑定。Host 不再经账号服务的 `logoutCodexAccount`,不再写账号服务自己的 `disconnected` 文件(原生连接只有登录成功后才读它,那时已被删除)。随后与桌面相同:profile 里的 auth.json 已经不在时,迟到的失效照样重新记作废并播报,登录占着这段空窗时不动;凭据范围读不出时用标记记下的上一次范围(桌面重启后同样从标记恢复);作废时登录正在进行、两次写盘都失败、日志先后三处不改,见第二节;读登录态时与桌面一样报出作废原因,直到重新登录。登录成功、登出、作废三处收口逐步对应桌面 `setOnLoginSuccess`、`setOnLogoutSuccess`、`setOnInvalidatedBroadcast`(m1-cp9 补上登录与登出:退役所有持本机登录的 Codex 进程、清代理注入、发路由变化、让 Pi 的 MCP 桥失效) | desktop `hostCodexSystemLoginParity.test.ts`(每个场景两边各建一份、各用一个假 HOME:8 种继承登录的作废与系统重新登录组合、全新 profile 链接认领、无系统登录、硬链接换符号链接、Cindy 里登录的保留、账号不同的旧版显式归属、同账号本地文件重链、显式断开、登录进行中与登录中途开始、owner 中途变更、同进程与重启、getAuthEnv 三种模式、启动时单次对账、恢复只给原 owner、遗留硬链接的作废、共享登录就地改写后的作废、两种 relink 失败;比较登录态、链接形态、绑定与标记,假系统登录的字节、inode、修改时间不变);Host `agent/codex-system-login.test.mjs`(三种运行方式的系统登录路径)、`agent/codex-invalidation.test.mjs`;桌面 `hostCodexInvalidationParity.test.ts`(代次与当前文件不一致的三种情形两边结果相同;双向:两种失效下 Host 作废后桌面读到的与桌面自己作废后相同;桌面作废并重新登录后 Host 先读到作废原因、再读到已登录;HOME 为空目录且跑完仍为空);Host `agent/codex-auth-boundary.test.mjs`(三处收口逐步对照桌面;登出与并行的登录、收口中途改写标记的作废);m1-cp16 登出的对照(cp13 的“显式断开”一例改跑 Host 自己的登出;先作废再登出、保留 auth.json 删模型缓存、作废收口中登出两边都不播报、登出后在 Cindy 里重新登录,Host 经自己的账号服务和假的 Codex CLI 登录;auth.json 已不在时的迟到失效);m1-cp15b 五处补齐的对照(`hostCodexInvalidationParity.test.ts`:网关、自定义供应商、独立账号三种 providerId,收口中途换 owner,收口中途被登录取代不播报;`hostCodexSystemLoginParity.test.ts`:codex-home 链接到假系统 `~/.codex` 时系统文件字节、inode、修改时间不变;Host `codex-invalidation.test.mjs`:入参与 maker-core 上下文一致、没有系统登录路径时同样不删 `~/.codex/auth.json`、标记被改写成别的原因或范围时不播报)、`codex-invalidation.test.mjs` 的链接用例(指向 profile 外的硬链接、符号链接,两种作废,外面的文件内容、inode、修改时间不变) | 无 | | 27 | Learn 宿主 | `learn-host/`(`controller.ts`、`staging.ts`、`apply.ts`、`runStore.ts` 等,约 4200 行) | 未做,归属待定:到第 22 行交 cindy_helper 分组清单时与 `start_skill_learning` 一起定,届时说明哪些部分依赖 Electron 或窗口、apply 与 Skill 投影(第 25 行)的先后、它写到 profile 之外的位置。**迁移前必须有结论** | — | 无 | -| 28 | 出口代理(系统代理与 PAC) | `maker-host/outbound-proxy-resolver.ts`(`resolveDesktopOutboundProxy`);`authManager.ts` 的 `net.fetch` | 未做,**迁移前必须有结论**。现状:Host 的出站请求只读代理环境变量(`HTTPS_PROXY`、`HTTP_PROXY`、`ALL_PROXY`、`NO_PROXY`,`apps/host/src/outbound.mjs`),不读系统代理与 PAC,涵盖模型网关与供应商(回环代理的上游)、订阅桥、复核、插件网络、平台工具、服务端接口;登录与会话刷新原先用 Node 自带的 fetch,连代理环境变量也不读,m1-cp18a 起改走同一出口(`auth-fetch.mjs`)。桌面先读代理环境变量,没有时按系统代理与 PAC 逐个地址解析,登录走 Chromium 网络栈。引擎子进程的代理环境变量都来自 Host 进程自己的环境;Claude 订阅任务的命令行在桌面上会按系统代理指向本机 CONNECT 桥,在 Host 上只有代理环境变量给的是 SOCKS5 时才这样。没有任何途径从窗口进程拿到系统代理。影响:只靠系统代理或 PAC 才能连出去的用户(代理软件开“系统代理”而非 TUN 模式、公司 PAC),迁移后上面这些请求都直连,在直连不通的网络里失败;TUN 或透明代理、直连可用的用户不受影响;带代理环境变量启动 Host 的,与桌面相同。计划:静态系统代理计划对齐(环境变量优先,加 macOS 静态系统代理),排在 M1 第 9、10 步之后、第 11 步之前;PAC:用户 2026-11-13 决定要支持,列为第 28 行那一步的必做项;切断清单里给出方案比较(Host 自己下载并在隔离环境里执行 PAC 脚本、由窗口进程代为判定并下发、两者结合)、各自的测试办法,并单独写一节 PAC 脚本的安全处理;位置不变(第 9、10 步之后、第 11 步之前)。Windows 与 Linux 的系统代理随这两个平台发布一起做 | Host `auth-fetch.test.mjs`(登录与会话刷新经代理环境变量指向的本机监听) | 无 | -| 29 | 本机 Agent 服务(local-agent) | `local-agent/`(本机应用接入 Cindy 的 Agent 会话协议,见 `docs/local-agent-api.md`);`maker-host/index.ts` 在 Maker 建好后调 `installLocalAgentHost`;Codex 的 `prepareCodexHostToolCatalog` 只为它的 hostToolsOnly 会话准备隔离的工具目录 | 未做,归属待定:到第 22 行交 cindy_helper 分组清单时一起定。Host 没有这项服务 | — | 无 | -| 30 | Cindy 保底压缩与原生会话恢复 | `maker-ipc/contextOverflowRollover.ts`(约 1370 行,register.ts 的 `createContextOverflowRollover`);决定见 `cindyContextCompression.ts`;发送前经 `prepareUnhealthySessionForSend` | 未做,归 M1:第 8 步之后单列一步(8f),先交切断清单,**迁移前必须完成**(审核方 m1-cp18b 复核时定;m1-cp18b 发现)。桌面在上下文溢出、Codex 历史过大、请求参数不受支持(含 Pi 缓存字段被明确拒收时经 `recordPiNativeCompatOverride` 记下、再重放一次)、远端压缩的加密内容错误、Pi 请求体恢复用尽时,关掉原生会话,用交接重建上下文,再安全续接或无副作用地重放一次;换到窗口更小的模型前、发送前遇到不健康的原生会话时也经它重建;订阅账号发送前换号与故障切换(`prepareSubscriptionAccountForSend`、`prepareSubscriptionAccountFailover`)也用它重建会话。Host 没有这一层,也没有这两处换号:这些错误不经自动恢复(未实测具体表现)。Pi 桥自己的缓存兼容学习不依赖它,Host 上照常(第 19 行) | — | 无 | -| 31 | 自动续跑(8g) | `maker-ipc/interruptedTurnAutoResume.ts`、`usageLimitAutoResume.ts`、静默停止的续跑;协调器钩子 `isResumableTurnErrorCandidate`、`onResumableTurnError`、`onResumableTurnErrorDiscarded`、`onUnconfirmedAutoResumeTurn`、`onUsageLimitedTurnError`;事件准备阶段的续跑守卫与 `autoResumeBookkeeping` | 未做,归 M1:第 8 步之后单列一步,先交切断清单,**迁移前必须完成**(C3 盘点发现,审核方 m1-cp18e 定)。Host 上中断后不自动继续、限额后不等重置再继续、静默停止不续跑:错误照常显示,要用户手动继续。接入时同时对齐 main 的 `createUserMessageDurably`(ec4b515bd7):真实用户与直投输入的静默停止续跑额度记账、自动输入不重置中断续跑额度,以及用户消息进入同一持久化先进先出队列。Host 当前的用户消息路径是协调器调用 `insertSessionMessage`,没有该额度守卫与用户消息 FIFO 包装;已有 `historyFor(...).enqueueDurableWrite` 是事件历史及元数据写入队列,不等于这条用户消息路径。并入这一步的事件管线项:网关代理令牌失效类错误交给界面自愈、不落库(`isGatewayProxyTokenRecoveryErrorEvent`;上报与重新同步已在 m1-cp18e 接上);灵动岛预览里的重试替换记账。与 8f 都在回合终态上做决定,能否合成一步在切断清单里给判断 与上下文恢复(检查点 4)的关系:桌面是协调器在准备阶段先收到终态、再认领;Host 是在投递处先认领、`finish` 结束时协调器才收到。`autoResumeSuppressesPersist` 由桌面协调器在准备阶段算出再交给认领,Host 现在恒为 false;**接入自动续跑时要重排**,让协调器先于认领收到终态。被 Host 关闭打断、或进程被强制结束时正在进行的恢复,理想结局是重启后自动接着做(现状见“上下文恢复:关闭时的处理”一行)。 | — | 无 | -| 32 | 发送前处理与换引擎交接(8h) | `makerSendTransaction` 的 `resolveRecoveredWorkingDir`、`isPersistedWorktreeFallback`、工作目录恢复说明、`restoreArchivedSessionForSend`、`applyPendingAgentSwitch` 与交接文本、计划对账与目标状态说明、`onModelDispatched`;协调器的 `resolveSessionReferences`、`refreshAgentReferencesBeforeDispatch`、`persistTerminalSendError`、`onPersistedSendRejected`、`supersedeRetriedUserTurn`、`onRejectedUserTurn` | 未做,归 M1:第 8 步之后单列一步,先交切断清单,**迁移前必须完成**(C3 盘点发现,审核方 m1-cp18e 定)。Host 上:工作目录没了时发送失败;往已归档任务发消息不恢复任务状态;输入框选中的会话引用不读;计划对账与目标说明不注入;不记“这一轮换了模型”;换引擎只改任务行,不关旧引擎、不写交接(桌面留下的待发交接摘要,Host 已随下一次发送带上,见“待发交接摘要”行);回合中改模型:桌面延期到下一次发送,Host 当场改(见“改模型时的窗口保护”行)。线索:Host 的发送本来就按任务行对账并应用设置(`applyQueuedSessionSettings`),回合中只写任务行、不动运行中的会话,下一次发送时自然生效,可能就是 Host 上最省事的延期,到这一步再评估;已落库但派发失败时是否补可重试的错误行未核(清单里先回答)。并入这一步的事件管线项:Codex 生图结果的实时投递(`deliverCodexGeneratedImage`)、目标空闲通知、活跃时间(`onUserAction`)、事件快照(`recordSessionEventSnapshots`)。派发不可逆后与清空边界上的 4 个协调器回调、Codex 重启与凭证形态切换的收尾,等价性在清单里核清 | — | 无 | -| 33 | 插件按任务的提示、上下文、回合选项与意识拦截(8i) | `makerSendTransaction` 的 `prepareRuntimePrompt`、`composeRuntimeContext`、`prepareRuntimeTurn`(`createTaskRuntimePlugins`、`composeGhostRuntimeContext`);协调器的 `screenUserMessage`、`onUserMessageBlocked`、`onUserMessageRewritten` | 未做,归 M1:第 8 步之后单列一步,先交切断清单,**迁移前必须完成**;属插件基座,单独提交,发布时要白名单审批(C3 盘点发现,审核方 m1-cp18e 定)。main #9825 已接宿主工具服务、逐次确认、任务输入授权与历史读取(见第 22 行),这不等于接上本行的回合钩子。Host 上插件按任务给的系统提示、运行时上下文与回合选项都不生效,意识对用户消息的拦截与改写也不生效。清单里写清桌面的规则和拦截逻辑出错时的方向。并入这一步的事件管线项:插件任务终态(`onPluginTaskTerminal`)、会话运行时控制收尾(`settlePendingSessionRuntimeControl`)。定时任务的安静输出投影(`projectQuietScheduledOutput`)随 M3 | — | 无 | -| 34 | 引擎二进制管理(8k) | `agent-binaries/index.ts`(就绪路径 `getReadyBinaryPath`、安装与更新 `updateReadyPiBinary` 等)及其下载器一族(manifestService、downloader/http、clientEndpointsService、pi-kernel-manager 等) | 未做,归 M1:排在 8f 到 8i 之后、第 9 步之前,先交评估、不动手(审核方 m1-cp18c 前定),**迁移前必须完成**。方向:Host 复用桌面现有的 agent-binaries 管理逻辑,不另造一套;“窗口安装、Host 读就绪路径”只作备选。交接任务的答复:现在的个人版仍是内嵌桌面,运行期间由谁安装、更新引擎没定也没联调,不能靠重启 Host 弥补启动时把路径定死。它建议的五条边界:进行中的任务固定用实际启动时的引擎版本;新任务重新解析经过验证的就绪路径;新版本先装到独立目录再发布就绪状态;旧 Host、子进程或在途启动仍在引用的版本必须保留,清理不能只看窗口版本或当前就绪指针;“首次没有某个引擎、运行中装好后能否直接启动”“Pi 自更新后新旧任务各用哪个版本”进 M1 或 M4 的放行表。评估要回答:那一族各自的 Electron 依赖与拆 core 的规模;管理器状态(就绪路径、下载中的任务、清单缓存)放在哪里,客户端模式下窗口进程是否仍初始化它、两个进程都初始化时谁是唯一安装者;五条边界逐条对照桌面现状;三个引擎“总是创建、启动任务时才取路径”(第二节“引擎二进制的路径”)与这一步的关系;下载出口走 hostOutbound 与第 28 行系统代理的关系;窗口安装与更新界面通道(M2)怎么对上(窗口只发起、Host 执行)。在这一步之前:Host 启动时定路径;Pi 本体更新在 Host 上报错并写明原因(m1-cp18c2,hostStage `unsupported`)。8k 完成后 Host 不再产生 `unsupported`,届时决定这个取值是保留还是删掉。同一中间状态下,Pi 回执里结构化的 `recovery` 字段仍是 store 给出的 `check-host-update-and-retry-core`(模型能读到),用户看到的文字不含重试;8k 完成后这一中间状态不再存在,现在不改(审核方 m1-cp18c2 复核时定) | — | 无 | -| 35 | 空闲运行时的释放 | `maker-ipc/claudeIdleReleaseWatcher.ts`(`register.ts` 装配):普通本机任务(不含机器人、Orca、目标、远程与隐藏任务)空闲 30 分钟后释放运行时,下一次发送再懒加载续上原生会话。Claude 与 Pi 原来就有(Claude 的分钟数可设置;Codex 沿用 Pi 与 Claude 的 30 分钟默认,见该文件注释);Codex 由 main 的 `868de6dc38` 纳入,释放前经 maker-core 的 `hasLiveBackgroundWork` 确认没有后台工作 | 未做,归 M1,**迁移前要评估**:Host 没有任何对应的空闲释放,运行时会一直占着。个人版迁移后任务长期挂在后台,这一条直接影响内存占用。上下文恢复这一批不做(审核方定,2026-11-15) | 无 | 无 | +| 28 | 出口代理(系统代理与 PAC) | `maker-host/outbound-proxy-resolver.ts`(`resolveDesktopOutboundProxy`);`authManager.ts` 的 `net.fetch` | 28c 已落地,未关闭(2026-11-18)。~~启动预热~~(serve 与默认命令先监听,登录请求等预热)。待验证两项:① CI 首次运行(钥匙串前后对比、Windows 对比);② Windows 三项实测:冷启动耗时、自动检测开启且没有 WPAD 时的耗时、内存,Linux 归乙(第五节“乙:Linux 上 Host 只读代理环境变量”),CI 比对待 Host PR(第五节,甲类)。**迁移前必须有结论**。28a 已做(2026-11-17):桌面 `outbound-proxy-resolver.ts` 除 Electron 两处以外原样搬成共用核心 `maker-host/outboundProxyResolverCore.ts`(`createOutboundProxyResolver`),端口 `isAppReady`、`getProxySession` 与原文一样在 try 之外调用;系统代理缓存、日志去重、环境变量解析器、路径快照进实例。桌面原处只绑 Electron(`app.isReady()`、`session.defaultSession`),桌面行为不变。Host 改走同一核心(`apps/host/src/outbound-proxy.ts`,经 `explicitPorts`:`isAppReady` 恒为 true,`getProxySession` 恒为空)。转发结果不变:设了代理环境变量时与原来的环境变量解析器逐字相同,一个都没设或只设了 `NO_PROXY` 时直连。有差别但不影响转发的四处:同步返回改为 Promise;每个 origin 的判定变化时多记一条 info 日志(`outbound-proxy`);多一份最多 256 条的诊断快照;系统代理缓存在 Host 上始终为空。Codex 的 `getOutboundPathFact` 随之接上(第二节“Codex 后端不可达时的出站路径”、第七节第 24 项)。28b 已做(2026-11-17):macOS 上没有代理环境变量时,Host 读静态系统代理设置(`apps/host/src/macos-system-proxy.ts`)。读法:`/usr/sbin/scutil --proxy`(写死绝对路径,不经 PATH 查找),与 Chromium 读的是同一份字典(`SCDynamicStoreCopyProxies`);照 Chromium 148 的规则换成同样的 PAC 结果串交给共用核心,核心与桌面都不动,只换 Host 的 `getProxySession`,由 `main.ts` 启动时接上(`startHostSystemProxySettings`,登录命令也走这里),其他平台仍为空。读设置这一层缓存 5 秒、并发请求合并为一次读取,加上核心的 30 秒,改设置或切换网络后最长 35 秒生效(桌面 30 秒);不做常驻监听。开了 PAC 地址:拒绝,判定记 unknown(resolve_failed),按直连,带 warn;只开自动发现(WPAD)、没有 PAC 地址:用手动设置,并记一条 warn 说明未做自动发现(只进日志,诊断快照没有放这句话的字段,要放得改共用核心);手动设置里带用户名的代理(macOS 15 起的 `HTTPUser`、`HTTPSUser`、`SOCKSUser`,密码在钥匙串里):Host 不读钥匙串,这次请求要用的那个代理带用户名就按 unknown 处理并带 warn,不拿没有密码的用户名去连;读不懂的输出:unknown,不猜。scutil 的原始输出与其中的值不进日志与诊断快照(报错只写行号)。与 Chromium 的逐项对照、按源码定而待 CI 实测的几条见第七节第 29 项;与桌面的差别见第二节“macOS 系统代理”。行为变化:28b 之前,macOS 上配了系统代理的用户,Host 是直连;之后跟随系统代理,与桌面一致。这是预期的对齐,但属于已合并的 Host 行为发生了变化。28c 已做(2026-11-18,审核方定做法 B):PAC 与自动发现(WPAD)交给 Chromium 本身。Host 在 macOS、Windows 发布包里本就带着 Electron(`scripts/build.mjs`,凭据编解码用的同一份),新加一个独立的辅助进程 `apps/host/src/chromium-proxy-worker.cjs`,由 `chromium-proxy.ts` 按需启动:只走标准输入输出、逐行 JSON,不开端口、没有窗口;userData 是 Host 数据目录下自己的 `proxy-helper`,不申请单实例锁、不碰桌面 profile;问的是不落盘的内存分区(`session.fromPartition`,不带 `persist:`),不调 safeStorage;只收到地址(去掉用户名、查询串与片段),只回 Chromium 的 PAC 结果串,交给与桌面同一个解析核心。按需:设了代理环境变量时核心先用环境变量,不问它;macOS 上静态设置仍走 28b,只有配了 PAC 地址或开了自动发现才问它;Windows 在 serve 或 login 启动时预热,之后保持运行。就绪:先 `setProxy`、再 `forceReloadProxyConfig`(实测只 `setProxy` 时 3 次里有 2 次在 PAC 加载前就回了 DIRECT)、再解析一次,才报 ready;ready 之前一律回 not_ready,Host 也不在 ready 之前发问。等待上限:serve 与 login 首次联网前,Windows 或 macOS 已配置 PAC/WPAD 时等辅助进程就绪,最多 8 秒;环境变量或静态设置不等辅助进程。超时沿用降级。普通判定最多 1.8 秒(低于核心的 2 秒),起不来 15 秒、不回 ping 3 秒就停掉,按 1 秒起、翻倍到 60 秒的退避重启;这期间 macOS 退回 28b 的静态结果,Windows 按直连、路径记 unknown(resolve_failed),并记一条 warn。生命周期:随 Host 停止时按句柄停(先关 stdin,0.5 秒后 SIGTERM,1.5 秒后 SIGKILL);Host 崩溃时它的 stdin 关闭,自己退出;进程与管道不占事件循环,`cindy-host login` 这类短命令不会被它拖住。内存:最小化配置(无窗口、关硬件加速)下 4 个进程物理占用合计约 58 MB(本机 macOS 实测;Windows 待在自有机器上测)。需要认证的代理(407):辅助进程拿不到凭据,PAC、自动发现与 Windows 系统代理给出的认证代理与桌面那条 Node 转发路径一样收到 407、记同一条 warn;macOS 静态设置里带用户名的代理仍按 28b(unknown、直连)。`cindy-host status` 多一行出站代理来源(是否设了代理环境变量、系统设置怎么读、辅助进程状态),不显示地址或设置。以下现状写的是 28a 之前(28b 起 macOS 上没有代理环境变量时读静态系统代理,见上):Host 的出站请求只读代理环境变量(`HTTPS_PROXY`、`HTTP_PROXY`、`ALL_PROXY`、`NO_PROXY`,`apps/host/src/outbound.mjs`),不读系统代理与 PAC,涵盖模型网关与供应商(回环代理的上游)、订阅桥、复核、插件网络、平台工具、服务端接口;登录与会话刷新原先用 Node 自带的 fetch,连代理环境变量也不读,m1-cp18a 起改走同一出口(`auth-fetch.mjs`)。桌面先读代理环境变量,没有时按系统代理与 PAC 逐个地址解析,登录走 Chromium 网络栈。引擎子进程的代理环境变量都来自 Host 进程自己的环境;Claude 订阅任务的命令行在桌面上会按系统代理指向本机 CONNECT 桥,在 Host 上只有代理环境变量给的是 SOCKS5 时才这样。没有任何途径从窗口进程拿到系统代理。影响:只靠系统代理或 PAC 才能连出去的用户(代理软件开“系统代理”而非 TUN 模式、公司 PAC),迁移后上面这些请求都直连,在直连不通的网络里失败;TUN 或透明代理、直连可用的用户不受影响;带代理环境变量启动 Host 的,与桌面相同。计划:静态系统代理计划对齐(环境变量优先,加 macOS 静态系统代理),排在 M1 第 9、10 步之后、第 11 步之前;PAC:用户 2026-11-13 决定要支持,列为第 28 行那一步的必做项;切断清单里给出方案比较(Host 自己下载并在隔离环境里执行 PAC 脚本、由窗口进程代为判定并下发、两者结合)、各自的测试办法,并单独写一节 PAC 脚本的安全处理;位置不变(第 9、10 步之后、第 11 步之前)。Windows 的系统代理随 28c 由辅助进程问 Chromium(静态、PAC、自动发现都含);Linux 仍只读代理环境变量,gsettings/KDE 与 PAC 都不读,归乙(第五节) | Host `auth-fetch.test.mjs`(登录与会话刷新经代理环境变量指向的本机监听);28a:桌面 `outboundProxyResolver.test.ts` 一条未改,经桌面接线走到共用核心;Host `outbound-proxy.test.mjs`(九种代理环境变量设置下的转发地址与原来的环境变量解析器相同,含一个都没设、只设 `NO_PROXY`;没有代理环境变量时判定记 unknown(session_unavailable),不记 direct)、`agent/outbound-path-fact.test.mjs`(经真实 Codex 回环代理,网关连不上之后按线程取到实际出口的判定;代理环境变量带用户名和密码时,判定与解析器快照里都没有它们,脱敏在共用核心 `recordOutboundPath`:地址只取 `parseOutboundProxyUrl` 规范化后不含 userinfo 的 `url` 再经 `redactProxyUrlForLog`,上游只取 `originForLog` 的 scheme://host;没走过的线程、没有线程号时为 null);28b:Host `macos-system-proxy.test.mjs`(注入固定的 scutil 输出,经 `resolveHostOutboundProxy`:手动代理的各种组合、端口与主机的缺省和无效、例外规则与隐式例外、PAC 与自动发现、带用户名的代理、读不懂的输出、5 秒缓存与并发合并、最长 35 秒生效、代理环境变量优先时不读系统设置;带 `*User` 键的样本,用户名不进日志文件与快照);macOS CI 比对(`.github/workflows/macos-system-proxy-compare.yml`,在 GitHub 托管的 runner 上改系统代理,与 Electron 的 `resolveProxy` 逐条比对),尚未运行(第五节,甲类);guard 层 `hostDesktopSourceContracts.guard.test.ts`(main.ts 启动时接上、scutil 写死绝对路径;`CHROMIUM_RULES_ELECTRON_VERSION` 等于桌面的 Electron 版本);28c:Host `chromium-proxy.test.mjs`(替身辅助进程:ready 之前不回答、只在限时内等;按需启动;起不来时按退避重启;无答时 macOS 退回静态结果、Windows 记 unknown;按句柄停止;环境与地址不带 Host 的配置)、验收 `scripts/chromium-proxy-worker.e2e.mjs`(真实 Electron,回环 PAC:连起 20 次、ready 之前只回 not_ready、从不回 DIRECT;Host 一侧经 Chromium 与 PAC 按主机判定;内存分区不落 cookie;崩溃后退避重启;Host 被杀后辅助进程退出;Host 包的 Electron cookie 加密为关),守护“Host Chromium proxy helper”三条(生产启动不带测试开关、只用内存分区且不碰钥匙串、只用 npm 原版 cookie 加密关闭的 Electron)与“network modules the Host loads”(Host 加载的每个自开网络连接的模块都登记在 `apps/host/src/host-network-modules.ts`,新增网络模块、已登记模块新增 fetch、WebSocket 构造或通过静态导入的网络 API 新增调用时,守护要求重新核对路由);macOS 与 Windows 的 CI 比对(第五节) | 无 | +| 29 | 本机 Agent 服务(local-agent) | `local-agent/`(本机应用接入 Cindy 的 Agent 会话协议,见 `docs/local-agent-api.md`);`maker-host/index.ts` 在 Maker 建好后调 `installLocalAgentHost`;Codex 的 `prepareCodexHostToolCatalog` 只为它的 hostToolsOnly 会话准备隔离的工具目录 | 未做,归属待定:到第 22 行交 cindy_helper 分组清单时一起定。Host 没有这项服务。接这项服务时,要在 Host 的四个入口调用 `takeOverLocalAgentVisibleSession`(甲 6 并入这里,入口与桌面调用点见甲 6);`local-agent/visibleSessions.ts` 不带 Electron,可以直接导入 | — | 无 | +| 30 | Cindy 保底压缩与原生会话恢复 | `maker-ipc/contextOverflowRollover.ts`(约 1370 行,register.ts 的 `createContextOverflowRollover`);决定见 `cindyContextCompression.ts`;发送前经 `prepareUnhealthySessionForSend` | 部分(#10613,2026-11-15 合并)。已对齐:上下文超长的终态认领、自动重建与重放一次(同一个恢复工厂,`apps/host/src/agent/context-recovery*.ts`),待发交接摘要随下一次发送带上并写回已发送,改模型到更小窗口且占用到危险线时,在发送落定那一刻先重建再换(检查点 3,与桌面同一份 `handleSetModel`、`prepareModelWindowSwitch`,见第二节“改模型时的窗口保护”),有序关闭时的收尾;详见第二节“上下文恢复”各行、“待发交接摘要”“改模型时的窗口保护”。线 A ③ 接上共用发送事务里的 `prepareUnhealthySession`:满窗、压缩失败或历史里留下可重建的错误时,发送前先处理;准备失败则本次不派发。旧库里的 Codex 历史过大错误由原生历史分类器核实,健康就保留原会话,过大或无法核实就重建;任务已换引擎时照桌面直接重建。终态认领仍只开放上下文超长;Codex 历史过大(当前引擎不产生)和 Pi 不支持的请求字段(Pi 同轮自愈,这层后备未经真实引擎验证)仍关闭,见第二节“上下文恢复:开放的类型”。尚未接入:订阅账号发送前换号与故障切换(`prepareSubscriptionAccountForSend`、`prepareSubscriptionAccountFailover`)没有接;接的时候读任务必须带上运行时调整,不能直接读任务行:桌面 `register.ts` 的 `readSubscriptionRuntimeSession` 用调整盖过任务行的模型与来源,`moveRoute` 核对任务行或调整的来源仍是换号前的来源,再经 `remapSessionRuntimeProvider` 把调整里的来源一起改掉(4b 清点,2026-11-17)。桌面的范围:桌面在上下文溢出、Codex 历史过大、请求参数不受支持(含 Pi 缓存字段被明确拒收时经 `recordPiNativeCompatOverride` 记下、再重放一次)、远端压缩的加密内容错误、Pi 请求体恢复用尽时,关掉原生会话,用交接重建上下文,再安全续接或无副作用地重放一次;换到窗口更小的模型前、发送前遇到不健康的原生会话时也经它重建;订阅账号发送前换号与故障切换(`prepareSubscriptionAccountForSend`、`prepareSubscriptionAccountFailover`)也用它重建会话。Pi 桥自己的缓存兼容学习不依赖它,Host 上照常(第 19 行) | Host `input-queue.test.mjs`(认领与结算、重放、待发交接摘要、关闭时的收尾、经 `/api/chat` 的恢复)、`session-update.test.mjs`(改模型是意图)、`input-queue.test.mjs`“model change at send”(发送时落定、危险线重建、冷启动 Pi 核实、恢复重放落定);三个真实引擎 e2e 的溢出恢复一段(Codex、Claude 含经 `/api/chat` 的变体,Pi 同轮修复) | 无 | +| 31 | 自动续跑(8g) | `maker-ipc/interruptedTurnAutoResume.ts`、`usageLimitAutoResume.ts`、静默停止的续跑;协调器钩子 `isResumableTurnErrorCandidate`、`onResumableTurnError`、`onResumableTurnErrorDiscarded`、`onUnconfirmedAutoResumeTurn`、`onUsageLimitedTurnError`;事件准备阶段的续跑守卫与 `autoResumeBookkeeping` | 按事实更正(审核方 2026-11-18 定范围)。**A 中断后自动续跑:已接**(检查点 4b):`agent/auto-resume.ts` 绑桌面的续跑运行时、钩子与用户行记账(`createUserMessageDurably` 的共用写法),`agent/coordinator-deps.ts` 绑六个协调器钩子;检查点 4a 已重排,协调器先于认领收到终态(`881f371fe6`)。**B 静默停止后续跑:已接**(2026-11-18):桌面搬移 refactor(desktop): move the silent-stop settle into a shared module(`maker-ipc/silentStopSettle.ts`,见下方“桌面准备 PR 里的非搬移提交”)。Host 的 `agent/silent-stop.ts` 照桌面的回合观察(`sessionTurnObserver.ts`)与事件准备(`sessionEventPreparation.ts`)做:每个静默停止的终态排一次决策,运行时留住这一代次(`claimHostTurnContinuation`)。1.5 秒后经共用的 `silentStopTurnEnd.ts` 决定:续一句隐藏的“继续”(同一轮换新代次,`turn-executor.mjs` 接过代次,否则续跑的事件会被代次过滤丢掉);或者结算(有排队工作、profile 里的设置关着、profile 被桌面占用);或者用完额度弹“继续”横幅(`silentStopFailure.ts`)。设置与额度和桌面是同一份(`silent-stop-auto-resume-settings.json`、守卫的常量)。`sessionEventTerminal.ts:496` 的 hold 已接上:静默停止的 done 结束列表活动项时 hold,续跑派发后丢弃原结束时间,结算时按原时间写一次。盖章(消费最后一条回复的 persistId 的方式不变)、列表预览、取归属都留在静默停止的 done 上,与桌面终态阶段相同。桌面结算里的 idle、唤醒协调器、凭据切换与运行时控制落定、Codex 重启服务,在 Host 上由回合的 `finish` 一步做:交给协调器 done 之后跑已落定回合的钩子。`/api/chat` 跟到续跑结束(第七节第 21 项)。评审补的三处(2026-11-18):决策在结算之前失败(共用代码某一步抛错,例如耗尽横幅的广播)时,还在等决策的这一轮照共用结算对续跑失败的做法逐步收尾,不会一直挂到重启(Host 加的保护,桌面没有,见第五节“后续阶段的桌面事项”第 10 条);账号边界或关闭开始之后到点的决策不续跑,按中断收尾;静默停止的 done 不写回合结束,续跑进行中仍算进行中的回合,被打断时进“继续上次中断的任务”(与桌面不同,见第二节“静默停止续跑期间的回合标记”)。**C 撞用量上限后等重置自动继续:改列乙**(审核方 2026-11-18),见第五节乙 16,第二节登记测试期差别。**D 网关代理令牌失效类错误交给窗口自愈、不落库:归乙,Host 保持立即写**,第二节登记差别。**E 灵动岛预览里的重试替换记账:关闭**:记账已接(`markReplacementDispatching`、`rollbackReplacementPreview`),灵动岛是桌面窗口。被 Host 关闭打断、或进程被强制结束时正在进行的恢复,理想结局是重启后自动接着做(现状见“上下文恢复:关闭时的处理”一行)。 | Host `agent/input-queue.test.mjs`:auto-resume exit 1–6、额度与换路线各条(A);“silent stop: …”六条与“profile hold: a silent stop decided while held settles without a continuation”(B);评审补的:“silent stop: a decision that fails before its settle still ends the turn, and the next input runs”、“owner boundary: a silent stop decided after the boundary began sends no continuation, and the turn ends”、“owner boundary: a silent-stop continuation that is running counts as a running turn until it ends” | 无。检查点 4a(`881f371fe6`,2026-11-17)已重排:Host 在事件到达时把终态交给协调器(桌面准备阶段的条件),放行下一条仍等这一轮落盘结束;用户消息写入(`createUserMessageDurably`)随续跑的运行时挪到 4b(审核方同意) | +| 32 | 发送前处理与换引擎交接(8h) | `makerSendTransaction` 的 `resolveRecoveredWorkingDir`、`isPersistedWorktreeFallback`、工作目录恢复说明、`restoreArchivedSessionForSend`、`applyPendingAgentSwitch` 与交接文本、计划对账与目标状态说明、`onModelDispatched`;协调器的 `resolveSessionReferences`、`refreshAgentReferencesBeforeDispatch`、`persistTerminalSendError`、`onPersistedSendRejected`、`supersedeRetriedUserTurn`、`onRejectedUserTurn` | 部分(第一批检查点 2)。已对齐:往已归档任务发消息先恢复任务(共用 `restoreArchivedTaskForSend`,写入见第二节“恢复已归档任务”);工作目录检查与恢复改用共用的 `createWorkingDirectoryPreflight` 与 `createWorkingDirectoryRecovery`(`agent/working-directory.ts`),发送事务接上 `resolveRecoveredWorkingDir`、`isPersistedWorktreeFallback`、恢复说明的 peek 与 consume;计划对账、已封计划的清除与目标说明(排在任务的持久写入之后读);`onModelDispatched`(共用 `createTurnModelAttribution`);协调器的 `resolveSessionReferences`(读别的设备的任务按未连接处理,见第二节)、`refreshAgentReferencesBeforeDispatch`、`supersedeRetriedUserTurn`、`persistTerminalSendError`(用户消息已落库但派发失败时补可重试的错误行,与桌面相同)、`onPersistedSendRejected`(Pi 提示超时时关掉卡住的运行时)。没做:换引擎关旧引擎、写交接与边界消息(检查点 3);`onRejectedUserTurn` 里的续跑部分(检查点 4),其余部分 Host 没有对应功能;托管工作树丢失时的 Git 恢复(第二节);并入这一步的事件管线项都后移:活跃时间 `onUserAction`(桌面只给限额后自动继续用,随第三批)、事件快照 `recordSessionEventSnapshots`(上下文占用写回见第 36 行;Codex 账号用量随第三批)、Codex 生图实时投递(随媒体与附件,第 12 行)、目标空闲通知(Host 没有目标模式,平台差别)。用户看得见的变化:往已归档任务发消息会把它恢复为进行中;被删掉的普通工作目录(所在的盘还在)会在原位置重建为空目录,下一条消息带一次恢复说明,盘不可用时改用 profile 里的对话恢复目录;派发失败时聊天里多一条可重试的错误行;引用的任务内容会带给 Agent;换了模型的回合会出现模型变更卡 | Host `session-update.test.mjs`(恢复:两条路走同一事务;已删除的不恢复;伙伴任务拒绝;群聊专线恢复并标 archived_at;持锁时可重入、锁外等待);`input-queue.test.mjs`(发送前恢复一次;普通目录被删后重建并带一次说明;托管工作树丢失立即失败且不建恢复目录;中断的 Codex 计划带开放步骤;目标裁决后带目标说明;记录本轮模型与一张模型变更卡;派发失败补错误行;Pi 提示超时关运行时;重试替换旧回合;引用带入、远程引用不带) | 无 | +| 33 | 插件按任务的提示、上下文、回合选项、意识拦截与工具钩子(8i) | 发送前的提示、上下文、回合控制,用户消息拦截,Claude 和 Pi 的工具调用及结果控制,插件工具逐次确认 | 已接,共用桌面的拦截和失败判定。Host 经逻辑沙箱把答复交给同一订阅网关。设置通道 `maker:runtime-plugins` 只由可信桌面窗口转发,profile 占用期间拒绝读写;写入在锁内再次核对准入 | 见第二节及第五节发布门槛 | 基座通过 A(共用主体)与 B(Host 沙箱)分开送审,迁移前需白名单审批。C 搬出桌面的发送和设置绑定。held-replay 探针(基点 `c09d1b7594`)记录溢出重放在占用期间仍经过普通发送事务。插件持久改线被闸门拒绝时沿用 onFailure;取快照前在任务锁内复核,避免旧操作认领新账号同任务 ID 的实例。Pi 已接受但未落库时只退役对应实例,并在账号与代次仍有效时恢复内存。只读钩子和本机 Pi 逐次请求改线照常运行。原生工具钩子明确无页时按 onFailure 收口;已受理后失去回复则等原有截止时间,超时放行。插件记忆来源已接。任务终态回执、消息与任务状态订阅仍按乙跟踪,定时任务的安静输出随 M3。文件确认、设置协调器与设置交互桥已有 Host 端口;打包暂存、会话语义索引、向量服务懒启动与交互生命周期通知归乙。无浏览器用例用同协议的沙箱替身,本机缺 Chromium 时实浏览器夹具明确跳过,迁移放行前在自有机器实跑。未补齐批准 receipt 的旧布局安装在 Host 保持停用。启动报告、正式接管前的零值预检和桌面补写顺序见第五节甲项。 | +| 34 | 引擎二进制管理(8k) | `agent-binaries/index.ts`(就绪路径 `getReadyBinaryPath`、安装与更新 `updateReadyPiBinary` 等)及其下载器一族(manifestService、downloader/http、clientEndpointsService、pi-kernel-manager 等) | 未做,归 M1:用户已定 Host 不自带引擎、由 Host 下载(见第四节“用户已定的产品形态”);排在 8f 到 8i 之后、第 9 步之前,先交评估、不动手(审核方 m1-cp18c 前定),**迁移前必须完成**。方向:Host 复用桌面现有的 agent-binaries 管理逻辑,不另造一套;“窗口安装、Host 读就绪路径”只作备选。交接任务的答复:现在的个人版仍是内嵌桌面,运行期间由谁安装、更新引擎没定也没联调,不能靠重启 Host 弥补启动时把路径定死。它建议的五条边界:进行中的任务固定用实际启动时的引擎版本;新任务重新解析经过验证的就绪路径;新版本先装到独立目录再发布就绪状态;旧 Host、子进程或在途启动仍在引用的版本必须保留,清理不能只看窗口版本或当前就绪指针;“首次没有某个引擎、运行中装好后能否直接启动”“Pi 自更新后新旧任务各用哪个版本”进 M1 或 M4 的放行表。评估要回答:那一族各自的 Electron 依赖与拆 core 的规模;管理器状态(就绪路径、下载中的任务、清单缓存)放在哪里,客户端模式下窗口进程是否仍初始化它、两个进程都初始化时谁是唯一安装者;五条边界逐条对照桌面现状;三个引擎“总是创建、启动任务时才取路径”(第二节“引擎二进制的路径”)与这一步的关系;下载出口走 hostOutbound 与第 28 行系统代理的关系;窗口安装与更新界面通道(M2)怎么对上(窗口只发起、Host 执行)。在这一步之前:Host 启动时定路径;Pi 本体更新在 Host 上报错并写明原因(m1-cp18c2,hostStage `unsupported`)。8k 完成后 Host 不再产生 `unsupported`,届时决定这个取值是保留还是删掉。同一中间状态下,Pi 回执里结构化的 `recovery` 字段仍是 store 给出的 `check-host-update-and-retry-core`(模型能读到),用户看到的文字不含重试;8k 完成后这一中间状态不再存在,现在不改(审核方 m1-cp18c2 复核时定) | — | 无。两件先记(审核方 2026-11-17 定):① 桌面安装新版本后删掉所有其它版本目录(`agent-binaries/factory.ts:540` `cleanupOldVersions`);桌面单独运行时没问题,Host 与桌面窗口在同一个 profile 上并存时,窗口一装新版本就会删掉 Host 正在用的目录——不算桌面今天的缺陷,但是两者并存的硬前提,迁移前必须解决。② Host 不读桌面的 Pi 内核选择(`pi/selected.json`,只有 `agent-binaries/pi-kernel-manager.ts:88` 读),多个版本并存时用哪个取决于目录扫描的返回顺序(`binaryStatus.ts:72–82`),甲类;能否先做只读修正,在第 34 行的设计里答。②已修正(34-fix,2026-11-17):Host 在每个 owner 运行时启动时按桌面规则给三个引擎各选一次二进制(`agent/harness-binary.ts`)——Pi 的显式选择优先(选择无效时 Pi 不可用、记 `pi_selection_invalid`、不退回别的版本),其次 Host 自带或开发版的二进制,再次 profile 安装里二进制报告的实际版本最高的那个,与目录名和目录顺序无关;判定代码从桌面搬出(`agent-binaries/pi-kernel-selection.ts`、`local-version-selection.ts`),逻辑不变、桌面行为不变,但不是逐行原样:`listVerifiedBinaries` 把 `getFinalBinPath`、`getVerifiedMarker` 展开成在已取到的根目录上拼路径(路径相同;原来每拼一次都经 `getInstallRoot` 再 mkdir 一次,现在只在取根目录时一次,mkdir 是幂等的),读 Pi 选择从类的私有方法改成带根目录参数的函数(审核方 2026-11-17 对照 `factory.ts:48–64` 核过等价)。模型设置里取 Claude、Codex 二进制的两个函数也改用这一次的结果:owner 运行时启动之后才装好的引擎,要重启 Host 才看得到,属于 34c。只读:不安装、不更新、不删除;启动时定值的限制留给 34c。引擎状态 `harnessStatus`(probe 与启动快照里的 `harness`)在选定之后报告这一次的选择:选中的二进制仍可执行才算就绪,Pi 选择无效时不再显示就绪;owner 运行时启动之前仍用 `binaryStatus.ts` 的同步扫描,`binaryStatus.ts` 本身不改(34-fix 补充提交)。所以同一个 profile 上,某个引擎的状态可能在 owner 运行时启动前后从“就绪”变成“不就绪”(例如 Pi 选择无效而留着高版本安装:启动前按扫描报就绪,选定后报不就绪),这是已知行为,不是状态抖动。选定的结果是进程级的:每次 `ensureRuntime` 都重新选一次并覆盖,两次之间沿用上一次的选择;这没有问题,因为引擎安装目录在 profile 级(`/pi`、`claude-code`、`codex-package`),不随 owner 变,换 owner 时也会重新选。启动会变慢(审核方接受):每个 owner 运行时启动时,没有自带二进制的引擎要给 profile 里每个已验证的安装各跑一次 `--version`(Pi 有显式选择时只探测选中的那一个),单次探测上限 5 秒(`binary-version-probe.ts` 的 `VERSION_PROBE_TIMEOUT_MS`)。代码是并发探测:同一引擎的各个安装经 `Promise.all` 同时探测(`local-version-selection.ts`),三个引擎也同时解析(`harness-binary.ts`),所以最坏多等约 5 秒,不是“安装数 × 5 秒”;同时起的探测进程数等于这些安装的总数。③ 桌面打包版在 Linux 上回落到系统或私有运行时(`findCachedLinuxRuntimeFallbackBinary`),Host 没有,随 Linux 发布做(审核方 2026-11-17 定)。测试 Host `engine-deps.test.mjs` 五条(选择较低版本时用较低的;选择格式不对或指向没有 `.verified` 的目录时 Pi 不可用;目录名与实际版本不一致、两种创建顺序下都取实际版本最高的;Claude Code、Codex 同一规则,自带二进制在前;选定之后 Pi 选择无效时引擎状态不显示就绪);桌面 `pi-kernel-manager.test.ts`、`factory-local-version.test.ts`、`factory.test.ts` 原样通过 | +| 35 | 空闲运行时的释放 | `maker-ipc/claudeIdleReleaseWatcher.ts`(Claude 与 Codex)、`piIdleReleaseWatcher.ts`(Pi),`register.ts` 装配;装配里两边都要的部分已移到共用文件(`idleReleaseInputGates.ts` 的待处理输入与排队、续跑判据,Pi 的候选查询,Claude 与 Codex 的普通任务判断与只关空闲运行时;Claude 分钟数覆盖文件经 `claudeIdleReleaseSettingsCore.ts` 按给定的 profile 根目录读)。普通本机任务(不含伙伴、Orca、目标、远程与隐藏任务)空闲 30 分钟后释放运行时,下一次发送再懒加载续上原生会话。Claude 的分钟数可由 profile 根目录的 `claude-idle-release.json` 覆盖;Codex 释放前经 `hasLiveBackgroundWork` 确认没有后台工作 | 已对齐(第一批检查点 1):`apps/host/src/agent/idle-release.ts` 用桌面的三个回收器、同样的忙闲判据和同一把任务锁,每个 owner 的输入运行时一套;Agent 运行时就绪后(`main.ts`)开始,有序关闭、登出、换账号时先于停止任务停掉。桌面的“回合还在收尾”在 Host 上是执行器里仍在进行的回合,“有待回答的交互”是 Host 的交互代理(与桌面相同,Pi 回收器不看这一条)。Claude 的“回合结束后子进程仍在调模型”检测,Host 之前没有喂回合起止,检测恒为否;现在按桌面的位置从事件流喂入(`turn-executor.mjs` 的 `noteBackgroundActivity`:前台 running 状态开始,done、终态错误与前台 running=false 状态结束,任务更新刷新后台命令),回收器据此不释放。待切换的凭据:Host 已登记,空闲释放前查询对应账号与任务的待切状态(`agent/runtime-selection.ts:1047–1051`、`agent/idle-release.ts:45,64`;2026-11-19 复查更正,原文说恒为否) | Host `idle-release.test.mjs`(真实迁移后的账号库:到点释放、只关空闲且是瞬态关闭;Claude 覆盖只影响 Claude;排队输入、回合收尾、待回答交互、后台任务、Claude 后台活动时不释放;等任务锁,锁内发送开始了新一轮则不释放);`input-queue.test.mjs`(启动前不扫、处置后不再扫;回合起止喂给后台活动检测);三个真实引擎 e2e 各一段(释放后下一条消息续上同一个原生会话并带着历史);桌面 `claudeIdleReleaseWatcher.test.ts`、`piIdleReleaseWatcher.test.ts`、`claudeIdleReleaseSettings.test.ts` | 无 | +| 36 | 上下文占用写回任务行 | 事件快照 `recordSessionEventSnapshots`(`sessionEventSnapshots.ts`)经 `recordSessionContextSnapshot`(`sessionSpendBroadcaster.ts`)把每轮的 `contextTokens`、`contextWindow` 写进任务行并推送 | 部分(检查点 3)。写库已对齐:快照判断与写库都搬成了共用代码(#10730 第 8、9 个提交:`maker-ipc/sessionContextSnapshot.ts`、`localDb/sessionContextSnapshotPersistence.ts`),Host 在同样的事件上调用(`agent/context-usage.ts`,`turn-executor.mjs` 监听里先算快照、回合终止分支与事件投递之后写)。与桌面的三处过滤差别(只会让任务行保留上一次写入的值,不会写成 0):无回合记录 / 非当前会话 / 非当前实例的事件不写(桌面流水线挂在每个会话上);`hostProjection` 不写(与桌面 `prepareSessionEvent` 相同);回合代次不符的状态不写(桌面普通 Done 照写,只压缩快照查代次)。没做:写入之后的推送(`broadcastContext` 端口为空),客户端看到的占用要等下一次读任务行,归第五节甲 4 | Host `input-queue.test.mjs`“context usage”(回合结束写、迟到的 Done 照写;红:注释掉两处写入后,发送时落定不重建);桌面 `sessionSpendBroadcaster.test.ts` 等 | 无 | +| 37 | 停用的模型或供应商、欠费路线的拦截 | 选择与落定时的路线裁决:`modelRouteAdmission.ts` `assertModelRouteUsable` → `verdictForModelRoute`(停用覆盖、目录墓碑、欠费路线 `isXdGatewayPaymentRequiredRoute`);待切凭据生效前经 `resolveLenientSessionRoute` 重新裁决 | 已对齐(检查点 3 接了改模型与发送落定两处,2026-11-17 接上新建与启动运行时,见第五节甲 17)。Host 用同一组函数(`assertModelRouteUsableWith`、`verdictForModelRouteWithProviders`、`resolveLenientSessionRouteWithProviders`,后两个在 `model-route-guard-catalog.ts`),只把供应商列表换成 Host 自己的。① 改模型(选择时):已对齐,换引擎当场裁决,不可用就拒(`[INVALID_PARAMS]`)。② 发送时落定:已对齐,同引擎不可用则这次发送不受理、意图保留,跨引擎不可用则照常用当前引擎发、意图保留,与桌面 `applyPendingAgentSwitchIfIdle` 相同;待切凭据生效前经 `resolveLenientSessionRoute` 重裁决也已接。③ 新建与启动运行时(启动准入):已对齐,Host 的三条启动路径(发送时启动、插件页的任务恢复、device-link 新建)跑桌面同一个工厂 `createLocalRouteAdmission`,经核实的续接只钉独占来源,改路由的来源与桌面一样写回任务行,见第五节甲 17。列表读取失败时的降级(只看停用覆盖)是桌面自己的逻辑,两边一致 | Host `input-queue.test.mjs`“same-engine landing failure”“engine pick that cannot land”、“route admission: …”五条;`session-update.test.mjs` | 无 | ### 第 26 行:Codex 原生登录的对齐记录与索引 @@ -98,7 +101,21 @@ | 项 | 桌面 | Host | 后果 | |---|---|---|---| +| 桌面占用期间的插件静默(2026-11-19) | 桌面上的插件照常运行 | Host 暂停逻辑页和插件 Node 进程,保留分区与安装批准。手机和远程端连着 Host 时插件暂不可用,插件工具与宿主请求返回服务层相同的 `PRECONDITION_FAILED`。有意关页时,待决钩子按静默失败收口且不计熔断。这是 8i「受理后失页等截止」的例外,意外失页仍等原截止。用户和助手消息钩子没有 `onFailure`,暂停时跳过询问并沿用既有放行 | 正在执行的插件工具调用会中断,调用方收到「结果不确定」,重试前需要核对。在途回合的输出不会经过消息钩子改写或拦截。已有插件终端保持运行,占用期间不新开。占用期间的旁听事件直接丢弃。占用前已缓冲的事件等下一条事件再送。Host 未使用桌面的 `preparePublish` 会话切换去重调用点。 | +| 桌面占用期间的发现延迟(2026-11-19) | 桌面没有占用闸门 | 占用靠每 10 秒重扫加目录监听(去抖 250 毫秒)发现,从桌面开库到后台服务察觉最长约十秒,这期间后台服务照常读写 | 这是整个并存方案的真实边界。入口检查之后才开始的占用,可能留下一个空任务行或空对话目录,与发现延迟同类,不单独处理 | +| 桌面占用期间不经 service 的入口(2026-11-19) | 桌面没有占用闸门 | `server.mjs` 自己应答的入口逐个分类,根目录源码契约 `scripts/__tests__/host-server-hold-classification.test.mjs`(`pnpm test:runner` 执行)守护,新增入口没登记就失败。**拒绝**:开启远程控制、开关 Agent-Net(入口与设置锁内各查一次);`/chat` 为不存在的任务建任务(读完任务、建任务前同步查一次;新任务在开流前被拒,返回 500 与 `chat_failed` 事件,与任务不存在时相同;已存在任务在开流后被队列拒,返回 200 与同一事件,这是原有行为)。**登记例外**:关闭远程控制、撤销控制设备,写 profile 根的 `device-link-settings.json`,与桌面同一份文件、同一把跨进程锁,正在运行的桌面每 5 秒轮询跟随:关闭会断开桌面当前所有控制链路,撤销会断开对应设备;写之前先走两端共用的分享可用性策略,有登记时向账号区域的服务停用对应分享的可用性,并从共用的 `provider-share-availability.json` 移除登记。占用期间后台服务的远程控制仍在线,已授权的控制端仍能读,撤销在这时有实际用处;只有本机持后台服务令牌的客户端能触发。登出:持账号库跨进程锁更新共用账号库与登出标记,删除登录令牌记录。`/control/stop`:关停收尾,排空队列、在途用量入库、有条件写错误行。**不写共用数据**:`/control/attachment`、`/control/platform`、`/web/pair`、`/web/session`、`/events` 与读接口、IPC 现有只读绑定。Agent-Net 设备身份是后台服务自己的记录 | 占用期间在后台服务登出:桌面不会立即登出,最迟在下次续期时(通常在令牌到期前五分钟,鉴权失败可提前)回到登录页并提示“本机的登录凭证已失效(可能是同一台设备上的其他实例退出了登录),请重新登录。”,同时停止该账号仍在跑的任务;在此之前桌面仍用内存里的令牌工作。用户 2026-11-19 定:保持允许。结构性的改法(服务器层对占用期间的写请求统一默认拒绝)登记为待办,不在第一阶段 | +| 任务里遇到缺失插件(主干同步 4,2026-11-19) | 主干 `089105c276`、`d9fc65bd15` 之后,桌面任务遇到缺失插件,可以在任务内搜索、选择发行版、确认安装(`ghost_market_search`、`ghost_market_install`) | 后台服务的插件网关没有注入市场服务(`apps/host/src/plugins/gateway.ts:86–115`),任务里只得到“去这台任务电脑的插件设置里看”的提示(共用 `ghost.ts:1863,1906–1922,1939–1940`)。主干同时删掉了共用代码里原来的兜底引导(回查已安装清单或改道),所以后台服务上的引导比同步前少。客户端模式的窗口里,插件设置目前也装不上:`plugin-market:install`、`ghosts:install` 留在窗口进程,而安装确认的答复 `ghosts:install-consent:resolve` 被委托给后台服务,只认后台服务事件流登记的请求,窗口本地的确认在代理里被拒,安装不落盘(`hostChannelContract.ts:433–482`、`bootstrap-electron.ts:1360–1382,1499–1519`、`host-delegation.ts:227–231`;这条委托是主干 `a7f5289e84` 加的);网页端也没有安装入口。**所以目前连着后台服务时没有可用的安装途径。** | 要装缺失插件,先退出后台服务,在普通桌面里装好、退出普通桌面后再启动后台服务。同一 profile、同一账号的安装,后台服务下次发现或调用时重新扫描磁盘即可使用,不必重新批准;静默期间则在解除占用后的 reconcile 里重扫(`plugins/runtime.ts:126–148,466–492`、`profile-coexistence.ts:342–377`)。客户端窗口的官方市场取不到账号访问令牌,依赖账号鉴权的条目可能更早就看不到。已批准插件的正常运行不受影响。迁移前要解决,见第五节 | +| 已登录后的凭据续期(乙) | 桌面与 Host 按 access token 的到期时间安排续期 | 在 macOS 上,Host 监听后,`commitRenewal` 持账号库锁重读会话,同步解密两轮实测 648 / 780 ms。正常定时续期在 `exp` 前 5 分钟;若 token 有效一小时,约每 55 分钟一次,实际以 token 为准。启动恢复会话、被服务端拒绝后刷新也可触发,临时失败按退避重试 | 两次测量中,正在运行的任务需由 Host 事件循环处理的回调、输出和 IPC 分别停顿约 0.65 / 0.78 秒。独立引擎子进程仍可运行;测量值是这次同步重读的时长。 2026-11-19 补记:Host 远控中转每次建立连接或重连取令牌一次;稳态心跳(Host 的中转客户端配置 15 秒,`device-link.ts:393`)不取;2026-11-19 复查更正,原文写 20 秒。普通重连起步约 0.7–1 秒,最高退避档约 21–30 秒。已有 Agent-Net 身份在成功读取后按节点实例、账号与服务缓存,通常每个实例每个账号只解密一次;读取失败会在下次连接再查。同步解密可能影响连线恢复与同一事件循环里的在途操作,纳入本乙项。0.65–0.78 秒是续期路径的实测,Agent-Net 走同一通道,未另测时延。 | +| Windows 启动时的 PowerShell 调用(乙) | 跨进程锁读取本进程创建时间,数据库 schema 租约读取本次系统启动代次,进程身份查询读取登记的 PID | 启动路径上有几次 PowerShell 调用,机器忙时会变慢 | 后续与 Windows 的 IPC 慢启动一起处理。 | +| 启动时始终查不清进程身份(甲,并存) | 桌面推迟迁移或清理 | Host 持有租约重读登记和进程身份,连首次最多四轮。只有身份不明时才按十秒预算决定是否再等一轮,已经查清就采用本轮结论。用尽仍不明就释放租约,以原原因码拒绝开库 | 需要手动重启后台服务。此时“桌面版正在使用”的提示可能并不属实。 | +| 桌面占用期间的回合结算(线 A ②) | 桌面没有 profile 互斥闸门。终态依次通知凭据切换、运行时控制和其他等待的任务 | 评审定 A:保留两种待办。两次干净扫描、运行时重建后,按登记时的账号、任务路线与待办代次复核;任务又在运行则等它结束 | 关闸期间只允许既有回合收尾。实测 Pi 已回执但尚未写库时进入占用,旧实例与来源内存会暂留新值;成功解闸会先关闭该任务的实例并清空来源内存,之后才复核并废弃失效选择。下一次懒创建读取库里的当前路线。同值路线 UPDATE 也计为写入。凭据失败提示沿用桌面:Pi 通过 `maker:session-credential-switch-failed` 报告;非 Pi 的凭据切换作废时用户看不到提示(与桌面相同);复核或写库出错只记日志并重试 | +| 桌面占用期间的溢出重放(甲) | 桌面在普通发送事务中恢复存档、落定待切引擎并修正改名模型 | 已认领的回合可以重放。Host 只重放 active 任务,保留待切引擎,改名模型留给解闸后的下一次发送。窗口预算在没有存活实例时不写库。重建实例时的来源确认和 Git 基线属于原回合收尾 | 占用时归档的任务保持归档,重放按恢复失败收口。未占用时沿用普通发送的恢复和落定行为 | +| 运行时改线成功后的定时模型偏好清理(8i) | 用户选定路线和调度器的路线处理都可更新 `sessions.scheduled_model_baseline` | `keepAsTaskChoice` 在改线成功后只清空 `scheduled_model_baseline`。Host 的伙伴路线回调为空;这一步是已提交改线的收尾,遇占用也执行 | 桌面可写同列。UPDATE 比较刚读到的基线,因此不会清除读取后才换入的不同值;若桌面在 Host 读取前保存基线,Host 仍可清空这次读到的值 | +| `local-db:sessions:update` 上的运行时设置(甲 8) | `updateSessionInDb` 对 `effort`、`fastMode`、`permissionMode`、`planModeEnabled` 只写库、不碰运行时(`sessionPatchToRow`) | `/sessions/update` 拒绝这四项(UNSUPPORTED_CAPABILITY,指明专用入口),白名单外字段 INVALID_PARAMS | 没有客户端经这条路发这四项,所以对用户没有可见差别。理由:桌面那条是没人用的第二条实现,Host 不复制它。桌面要不要也改成拒绝:审核方 2026-11-18 定不改,见第四节 | +| 任务窗口预算的两条写入路径(3b-2) | 本机界面经 `updateSessionInDb`:先广播 `{ contextWindowBudget }`,再写偏好文件;偏好文件写不进时已广播了没保存的值(桌面原有缺陷,见第五节);任务不存在报 NOT_FOUND | `/sessions/update` 经 `persistSessionFieldsWith`:先写偏好文件、成功才广播;不存在的任务由 Host 先查行补上 NOT_FOUND(`persistSessionFieldsWith` 本身不查行,会照写偏好) | 写失败时 Host 不广播未保存的值,比桌面对。两处差别由桌面 `sessionsUpdate.test.ts` 的对照测试钉住现状 | +| 任务窗口预算:应用时的锁 | `updateSessionInDb` 只带预算时不拿路由锁(`sessions.ts` `if (p.workingDir === undefined && !moveGuard) return update();`);写完后应用钩子(`bootstrap-electron.ts` 注册的 `applySessionContextWindowBudgetChange`)自己拿发送锁做对账 | `/sessions/update` 整段在路由锁(即发送锁)里,应用钩子再拿发送锁时走同一异步链的重入放行(`sendToSessionLock.ts` `withSendToSessionLock`) | 只有一把锁,不会自等、不会反序;Host 上写和对账之间插不进发送,更严。重启在等时:桌面钩子排锁前、Host 重入时都过重启栅栏,都抛错并被 `persistSessionFieldsWith` 接住只记警告,预算已存、下次启动生效(Host 测试钉住) | | 启动前的就绪检查 | 等账号供应商发现屏障(`ensureCurrentAccountProviderReadiness`),等完再核对账号 | 等 Host 自己的 `listProviders`(把账号网关模型装进目录),等完再核对账号 | 等价;失败与换账号都用桌面的 `ACCOUNT_PROVIDER_NOT_READY` 拒绝 | +| Pi 选择无效时的引擎就绪状态(第 34 行 ②) | 准备引擎遇到 `pi_selection_invalid` 时删掉 `lastReadyPath`,同步快查 `getCachedBinaryStatus('pi')`(`agent-binaries/index.ts:315`)就退回 `binaryStatus.ts` 的目录扫描:只要还留着已验证的高版本安装,照样报 `binaryReady: true`,而这时 Pi 并不会启动(桌面既有缺陷) | 从 34-fix 补充提交(fix(host): report the engine binaries it chose as the harness status)起,引擎状态 `harnessStatus`(probe 与启动快照里的 `harness`)报告这次实际选中的二进制,选择无效时 Pi 显示不就绪(`agent/harness-binary.ts`,`engine-deps.test.mjs` 钉住),不再出现这种不一致;owner 运行时启动之前仍是同一份扫描 | 桌面那边的缺陷不改,只记录(审核方 2026-11-17 定);同一情形下桌面会显示 Pi 就绪、Host 显示不就绪 | | 引擎模型清单刷新 | 9 处目录变更点即时刷新 | `listProviders` 应用模型之后、每次启动任务之前刷新 | 运行中的任务在其它目录变更后可能用旧清单,直到下一次启动 | | 插件花名册在账号变更后 | 无此情形 | 返回空串 | 不会把上一个账号的插件写进新任务 | | Fast 轴的初值 | bootstrap 时取任务行 | `prepareStartOptions` 取本次启动参数(来自任务行) | 效果相同 | @@ -111,7 +128,14 @@ | 自动复核的授权上下文 | 插件委托任务按其登记的范围复核 | 同一个解析器;插件委托在 Host 上还没有投递,正在运行的输入一旦标成插件委托(包括客户端自选的 client id),就失败时关闭,复核变成询问 | 插件委托的授权上下文随 M2 或 M3 的投递一起接 | | Auto 分类器失败的降级 | 代理观察到分类器失败后,由协调器把该任务的复核切到 Cindy(register.ts) | 同一个协调器(m1-cp11b) | 无差。未实测:原生分类器只在 Claude 订阅登录(oauth-bearer)的任务里出现,真实触发需要真实订阅登录;接线由 `auto-review.test.mjs` 覆盖 | | 安装型 BYOK 供应商的凭据 | `readCustomProviderKey` 先读安装型 BYOK 供应商的凭据,再读自定义供应商 key | Host 的 `providerConfig.readKey` 只读自定义供应商 key,不含安装型 BYOK 凭据 | 用这类供应商跑任务时 Host 缺 key;辅助模型链里放了这类模型时,该候选不可用(落到下一个,全部不可用就询问)。**迁移前必须对齐**;随等价的供应商视图一起放在 M2 的模型通道 | -| 复核调用的用量(2e 之前) | 记录 | 不记录 | Host 上复核调用的用量在 2e 之前不记录;2e 的边界表要把它算进去 | +| 复核调用的用量(2026-11-19 核对) | 自动复核、工具循环复核收到可解析的用量时写 `auxiliary_usage_receipts`,来源为 `auto-review`、`tool-loop-review`;记忆自审用 `memory-review`。普通 `/review` 任务按回合记 | 自动复核、工具循环复核写相同来源的辅助收据。视觉桥移除后两端都停止发起描述请求。记忆自审用相同记录器,来源为 `memory-review`(第一节第 11 行) | 读取及推送按第一节第 13 行推进。 | +| 占用期间的辅助收据(2026-11-19,审核方定) | 内嵌桌面没有占用闸门 | 在途回合的自动复核、工具循环复核收据照写。用量随发起时的账号,关库等已保留的写入。占用期间新发起、不属于在途回合的辅助请求在入口拒绝,目前涉及记忆自审,Host 在路线选择和模型请求前复核占用。 | 保留已发出请求的账目。视觉桥移除后 Pi 子运行不再写 `vision-usage.jsonl`。 | +| 占用期间的记忆(2026-11-19) | 内嵌桌面没有占用闸门 | 在途回合经 `cindy_memory` 读、列举、搜索、写、删、合并或自审都会收到与服务层一致的 `PRECONDITION_FAILED`。工具列表和任务历史搜索照常。Host 也在引擎打开记忆 store 前检查占用,挡住提示词初始化与 Pi 压缩摘要写入。 | 占用期间任务不能经记忆工具读取共享记忆。放开后同一入口恢复,等锁中的旧请求与只读热 store 的后续方案见乙 20、乙 21。占用期间的上下文恢复重放会新建实例并载入提示词,这时提示词里的记忆那一段被跳过;这是“在途任务读不了记忆”的一种具体表现,不是缺陷(审核方 2026-11-19)。 | +| 按使用方用量不含 Host 跑的任务(测试期,审核方 2026-11-18 定) | 桌面在任务事件上按使用方记供应商用量(`register.ts` 写 `provider-usage-by-party.json`,本机的 local 一类) | 第一阶段不写这个文件,端口绑空(3d);谁来写归乙,见第一节第 13 行的两种做法 | 测试期间 Host 跑的任务不计入按使用方用量,“远程与分享”的供应商分摊页 local 一类少算。花费与 token 照常记进库(三张日用量表、任务行、消息与定时任务运行) | +| 回合中途换账号后迟到的用量(审核方 2026-11-18 定) | 记录器写库时取写那一刻的 `getDbClient()`,只在广播前查 owner 范围(按使用方用量另有 `ownerDb` 检查,`register.ts:6359`);回合中途换账号时,旧回合迟到的用量写进新账号的库 | 按发起回合的账号写:owner 取输入运行时在回合开始时绑定的那个(`input-queue.mjs` assertCurrent),迟到事件没有回合记录时也用它;每次写库端口调用前确认它仍是当前库,变了就丢弃;账号边界关库前等已开始的写入写完(3d,第七节第 40 项) | 换账号之后才到的旧回合用量,Host 上不记,桌面记进新账号。桌面现状记进第五节桌面事项第 9 条 | +| 换账号时正在记的那一轮(3d 评审 2026-11-18,登记,不加机制) | 记录写库时取当时的库,换账号之后照写,可能写进新账号 | 账号边界关库前先停掉新的记录与写端口调用(`agent/usage-recording.ts` `drain`),再等已开始的写入写完。已经开始、但还在等价格或回合模型的记录,之后再调写端口会被拒绝(被拒时记一条带端口名的 info) | 换账号时正在记的那一轮,用量可能只记了一部分:比如 Pi 的回执与 token 已写入,后面的 `recordTurnSpend`、`recordSessionTurnSpend` 被拒,记了 token 没记金额(`sessionPiTurnUsageCore.ts` 的定价段)。不会写进新账号 | +| 用量变化不推给远程设备(第一阶段,审核方 2026-11-18 选 (ii)) | 记录用量时把任务花费、任务 token、消息回合花费、模型不符与今日用量推给窗口,并经设备互联镜像(`tapWindowBroadcast`)推给手机等远程设备 | 第一阶段不推:广播端口绑空;设备互联的镜像接收方不转发 `agent/usage-push-channels.ts` 名单里的 12 条通道(任务花费、任务 token、消息回合花费、模型不符、两条 xAI 限额、两条 Codex 账号、Claude 订阅、订阅供应商账号、Claude 账号、xAI 订阅),名单外的通道照常转发(3d,第七节第 41 项) | 手机和远程端看不到用量的实时更新:花费与用量要等下一次读取才更新。与读取、推送那一批(乙,3f)一起打开,届时删掉名单。设备互联可转发的 `usage:` 通道(`PUSH_FORWARD_ALLOWLIST`)每一条都要么在名单里,要么在“有意转发”清单里写明理由(现在为空),测试钉住;`usage:session-context-changed` 不在可转发清单里,桌面与 Host 都不转发;`usage:today-spend-changed`、`usage:today-tokens-changed` 只发窗口、不经镜像 | +| 失败回合的配对 done(2026-11-18,`noteFailedTurnCompletionTail` 一单的结论) | 终止性 error 时记下失败轮的完成尾巴(`autoResumeBookkeeping.noteFailedTurnCompletionTail`),同一代随后那条 done 据此不算成功完成 | 不记尾巴:回合在终止性 error 时就结束(`finish`),同一代随后的 done 走已结束回合那一段,上一代的 done 被代次过滤挡下,都进不了成功判定 | 无用户可见差别;见第五节同名一行的依据与测试 | | 订阅余量(2e 之前) | 代理读订阅余量响应头,交给注入的 listener 落库并广播 | 观察器照挂,不设 listener | 不记录订阅余量;2e 接上 | | XD 快照的权威标记(m1-cp18b 对齐,m1-cp18b2 补齐) | 每轮 `/models` 刷新开始时撤销权威,本轮成功才恢复,失败保持撤销并保留付费墓碑;换账号清空 | 权威标记、清单、付费墓碑与桌面相同(`providers.mjs`,m1-cp18b):首轮进行中、成功、再次进行中、失败(之前成功)、换账号、失败(从未成功)六种状态。之前有过一次成功就保持权威,m1-cp2c 之前就是这样,影响过 Codex 回环代理对 grok 线路模型的归属判断(`xdProviderClaimsWireModel`)。m1-cp18b2 补齐两处(审核方选甲):1. 冷启动第一轮还没成功时(进行中或失败),保留目录里 XD 的静态嵌入模型兜底,与桌面相同(之前 Host 第一次读取就清掉);2. 同一账号只换网关 key 时,保留上一份清单与付费墓碑、只撤销权威并立即重拉,刷新失败也保留,与桌面相同(之前 Host 清空)。换 owner、代次或端点仍清空;刷新失败时用当前快照(`main.ts` 的 `readModels` 端口,读本进程 active-catalog 模块里的同一份快照,也就是子代理模型准入、Codex 代理与辅助模型候选读的那一份)。同时修正一处:强制刷新失败后,5 分钟缓存窗口内的下一次读取会把上一次成功重新当作权威,现在失败后缓存作废,只有下一轮成功能恢复权威 | 读这个标记与快照的三处,对齐之后:子代理模型准入(第 19 行)在进行中与失败后给出未知、照常放行,付费墓碑仍拒绝,只有本轮成功的清单能把缺席判成拒绝;Codex 代理的 grok 判断在非权威时把 grok 线路模型当作网关的,与桌面相同;媒体模型投影里的嵌入模型兜底在第一次成功之后两边都关掉,换账号时两边都关掉。刷新时机仍不同:桌面在凭据就绪、登录、冷启动、换账号时立即刷新,窗口获得焦点时最多 5 分钟一次,不轮询;Host 最多 5 分钟一次,由启动任务与界面读取触发,不轮询,失败后不退避(`hostXdSnapshotAuthorityParity.test.ts`:三串事件,含冷启动首轮失败与同账号换 key,快照含嵌入模型兜底,期望值写死;Host `provider-credentials.test.mjs`:换 owner、代次或端点后刷新失败不露出旧清单,只换 key 后刷新失败保留清单与墓碑且不权威,失败后读取不恢复权威,失败时用端口读到的当前快照) | | Pi 提示与对话框的语言 | 系统首选语言列表(`app.getPreferredSystemLanguages`),用户在窗口里选过语言后跟随窗口(`setMainLocale`) | 进程的系统语言(`Intl` 的 locale,与 `plugins/authorization.ts` 相同);窗口的语言选择到不了 Host | Pi 的云端文件启动提示与扩展对话框文案:用户在窗口里改过语言、或系统首选语言不受支持而第二语言受支持时,Host 上这几处可能与窗口语言不同。M2 由窗口把语言推给 Host 时对齐(审核方定,方案甲) | @@ -141,21 +165,46 @@ | Codex 具名来源的连接态、xd/cindy 来源优先、控制入口与账号视图(M2) | 适配器主要按模式判定,不看具名来源的连接态 | Host 对具名自定义来源先查供应商视图的连接态与 Codex 路由,对 xd、cindy 来源直接给网关状态,对 `openai` 在原生登录无效时不退到网关 | 这些输入不在 maker-core 真实路径上(入口枚举)。随 M2 的供应商视图与来源合同一起对齐 | | Codex 适配器的 identity 文案与连接诊断(M2) | “API Key · Cindy AI”“Provider OAuth · Proxy”或真实登录身份,附设置页的凭据诊断 | “Cindy AI”、来源 id 或不带身份,没有诊断 | 凭据与放行结论相同,但同一个窗口里显示的身份可能不同;scope 与恢复原因不算显示差异(已在上面对齐)。随 M2 的供应商视图做 | | Pi 鉴权适配器的整体对照(m1-cp18e) | `desktopPiAuthAdapter` | 同一个 `createPiAuthAdapter`,端口是 Host 的;64 格里 4 格不同,写死在 `hostPiAuthAdapterParity.test.ts`:Host 判断 OpenAI 订阅时把目录里任何带原生 Codex 登录的供应商都算上,桌面只算用户添加的;内置目录里除 openai 外没有这种供应商,目前只是理论差别。m1-cp18b2 对齐:Host 改用 Codex 账号服务(与桌面同一个 `createCodexAccountAuth`)的判断,只算 openai 与用户添加的来源,例外清单清零。经 Codex 适配器的那一支继承上一行的差别 | 已对齐(m1-cp18b2),无差 | -| 上下文恢复:终态认领(m1,检查点 4) | 事件管线的准备阶段协调器先收到终态(`sessionEventPreparation.ts:576`),投递时压住溢出类错误的广播(`sessionEventDelivery.ts:112`),终态阶段同步认领(`sessionEventTerminal.ts:324`),随后结算(`contextRecoveryTerminal.ts`) | 同一组共用函数(`apps/host/src/agent/context-recovery.ts`):在投递处压住同一类错误、同步认领,认领后不发布、`finish` 不写错误行;`finish` 开始后结算,交给工厂的 `tryRecover` 先等被认领那一轮落盘结束(`onTerminal` 已把错误交给协调器)再开始。没有恢复工厂时与之前完全相同 | 顺序不同:Host 先认领,协调器在 `finish` 结束时才收到终态;不影响现在的结果(自动续跑未接,见第 31 行“接入时要重排”)。Host 没有自动续跑、远程鉴权重试、产品回合的失败收尾,这几个输入恒为空 | -| 上下文恢复:关闭时的处理(m1,检查点 4) | 退出时进程结束,不等恢复;恢复中的那一轮错误行不落(共同改进项,主干清单) | 有序关闭先等所有在飞的恢复合起来最多 `RECOVERY_SHUTDOWN_WAIT_MS`(5 秒)结束;恢复的检查在关闭中会失败,按失败收场落错误行。到上限还没结束的,由 Host 用同一失败路径的内容写下这一行(不广播),落盘后再按原顺序停止。重放已被接受(工厂的 `onRebuilt`)的不等也不写;恢复在停止后才醒来不会写第二行 | 相对桌面多一步(桌面没有先例)。队列快照只存排队中的输入,不存协调器的错误,所以必须落错误行,重启后由 error-tail 列为未处理错误、可以继续。**已知限制**:Host 进程被强制结束(不是有序关闭)时,正在恢复的那一轮重启后只剩用户消息,没有错误行,也不被认作中断(被认领那一轮已标结束);与桌面相同 | -| 上下文恢复:工厂装配与重放(m1,检查点 5) | `register.ts` 在进程里建一个 `createContextOverflowRollover`;重放走 `sendToAgentAcceptedUnlocked`(同一发送事务,不取锁);`onRebuilt`(`contextRecoveryRebuilt`)同步调协调器的 `clearError` 并重置环境说明 | 同一工厂(`apps/host/src/agent/context-recovery-assembly.ts`),每个输入运行时一个。重放用 `turn-executor.mjs` 的 `replay` 走同一发送事务:不入队、不写用户行、不取锁;任务还有运行时就拒绝;Git 基线只开一次,没被接受就取消。`onRebuilt` 同样同步清错,关闭中、任务已关闭、账号已换时不动。真实引擎验证前各类都关闭(`isContextRecoveryOpen`),关闭的类型走普通错误路径 | 1)重放的启动参数与普通发送逐字段相同,只多任务标题 `title`:这是共用重放函数的输入,桌面重放同样带;Maker 只用它打日志、给新建的任务行做默认标题。2)“这条输入已续过一次”的记忆(`continuedInputs` 等)桌面活到进程结束,Host 活到输入运行时结束。重启后两边都清空;换账号时桌面不清空、Host 清空,换回来后 Codex 历史过大与 Pi 请求选项两类,同一条输入最多再续一次(溢出一类靠数据库里的重建标记,不受影响)。3)Host 没有外部恢复所有者、原生会话交接、伙伴回忆、冷启动 Pi 校验,这几个输入恒为空;Cindy Make 的项目围栏不执行(Host 拒收 Cindy Make 输入)。更正记录:审核方原要求清错时暂停执行、写盘后放开;实测清错不写快照,暂停还会中止进行中的引导,已撤回,改为与桌面一致(`input-queue.test.mjs` 两条测试) | -| 上下文恢复:开放的类型(m1,检查点 7) | 三类终态错误都由同一个恢复工厂处理:上下文超长、Codex 历史过大(终态认领与发送前处理不健康会话 `prepareUnhealthySession` 两条路径)、Pi 不支持的请求字段(Pi 自己的缓存自愈没处理时的后备) | `main.ts` 的 `OPEN_CONTEXT_RECOVERY_KINDS` 只开上下文超长。真实引擎验证(`apps/host/scripts/`,本机模拟上游、个人目录隔离、经 `context-recovery-wiring.ts` 与生产相同的装配):`codex-runtime.e2e.mjs` 第三方供应商超长后重建、重放一次带上一轮摘要与该供应商的凭据;`claude-proxy.e2e.mjs` 经网关,CLI 自己的压缩也失败后才交给 Cindy,重建期间换 key,重放用新 key。两条都断言客户端没看到错误、只有一条用户消息、摘要只带一次、下一条不再带 | Codex 历史过大:关闭。现在没有引擎发出这个错误(maker-core 的 Codex 不再产生 `codex_history_oversized`,测试断言不产生),桌面同样走不到;Host 也没有接发送前处理不健康会话。Pi 不支持的请求字段:关闭。打包的 Pi 由 Cindy 装入的缓存自愈在同一轮里去掉字段重试并记住路线(`pi-native.e2e.mjs` 验证),错误到不了 Host,这一类的后备没有真实引擎的验证;没开时与之前相同,错误照常显示 | +| 上下文恢复:终态认领(m1,检查点 4) | 事件管线的准备阶段协调器先收到终态(`sessionEventPreparation.ts:576`),投递时压住溢出类错误的广播(`sessionEventDelivery.ts:112`),终态阶段同步认领(`sessionEventTerminal.ts:324`),随后结算(`contextRecoveryTerminal.ts`) | 同一组共用函数(`apps/host/src/agent/context-recovery.ts`):在投递处压住同一类错误、同步认领,认领后不发布、`finish` 不写错误行;`finish` 开始后结算,交给工厂的 `tryRecover` 先等被认领那一轮落盘结束再开始。没有恢复工厂时与之前完全相同 | 顺序已对齐(检查点 4a,`881f371fe6`):协调器在事件到达时先收到终态,再同步认领,与桌面相同;协调器从收到到重建清掉之前持有这条错误,不写错误行(测试“the coordinator holds an overflow error from its arrival”)。是否被自动续跑接管改为从协调器读(`isSessionErrorSuppressed`,与桌面投递同一判据)。产品回合的失败收尾 Host 已接(`agent/turn-executor.mjs:479–497`),远程鉴权重试端口仍留空(2026-11-19 复查更正) | +| 上下文恢复:关闭时的处理(m1,检查点 4) | 退出时进程结束,不等恢复;恢复中的那一轮错误行不落(共同改进项,主干清单) | 有序关闭先等所有在飞的恢复合起来最多 `RECOVERY_SHUTDOWN_WAIT_MS`(5 秒)结束;恢复的检查在关闭中会失败,按失败收场落错误行。到上限还没结束的,由 Host 用同一失败路径的内容写下这一行(不广播),落盘后再按原顺序停止。重放已被接受(工厂的 `onRebuilt`)的不等也不写;恢复在停止后才醒来不会写第二行 | 相对桌面多一步(桌面没有先例)。队列快照只存排队中的输入,不存协调器的错误,所以必须落错误行,重启后由 error-tail 列为未处理错误、可以继续。**已知限制**:Host 进程被强制结束(不是有序关闭)时,正在恢复的那一轮重启后只剩用户消息,没有错误行,也不被认作中断(被认领那一轮已标结束);与桌面相同。普通回合(不在恢复中)在有序关闭和账号边界(退出登录、会话失效)时留成中断:不写结束时间,下次启动列入“继续上次中断的任务”,由用户决定是否继续,不自动续跑;与桌面相同(第五节“甲:账号边界停止提前置位”)。主干同步 6 后,桌面真退出多一条给未结算 Claude 的合成 `cancelled` done,Host 的有序停止没有这条帧。本轮只登记,中断任务的恢复规则照旧。 | +| 上下文恢复:工厂装配与重放(m1,检查点 5) | `register.ts` 在进程里建一个 `createContextOverflowRollover`;重放走 `sendToAgentAcceptedUnlocked`(同一发送事务,不取锁);`onRebuilt`(`contextRecoveryRebuilt`)同步调协调器的 `clearError` 并重置环境说明 | 同一工厂(`apps/host/src/agent/context-recovery-assembly.ts`),每个输入运行时一个。重放用 `turn-executor.mjs` 的 `replay` 走同一发送事务:不入队、不写用户行、不取锁;任务还有运行时就拒绝;Git 基线只开一次,没被接受就取消。`onRebuilt` 同样同步清错,关闭中、任务已关闭、账号已换时不动。真实引擎验证前各类都关闭(`isContextRecoveryOpen`),关闭的类型走普通错误路径 | 1)重放的启动参数与普通发送逐字段相同,只多任务标题 `title`:这是共用重放函数的输入,桌面重放同样带;Maker 只用它打日志、给新建的任务行做默认标题。2)“这条输入已续过一次”的记忆(`continuedInputs` 等)桌面活到进程结束,Host 活到输入运行时结束。重启后两边都清空;换账号时桌面不清空、Host 清空,换回来后 Codex 历史过大与 Pi 请求选项两类,同一条输入最多再续一次(溢出一类靠数据库里的重建标记,不受影响)。3)冷启动 Pi 的窗口核实端口 Host 已接(`agent/context-recovery-wiring.ts:24,66`),外部恢复所有者、原生会话交接、伙伴回忆这几个输入仍为空(2026-11-19 复查更正);Cindy Make 的项目围栏不执行(Host 拒收 Cindy Make 输入)。更正记录:审核方原要求清错时暂停执行、写盘后放开;实测清错不写快照,暂停还会中止进行中的引导,已撤回,改为与桌面一致(`input-queue.test.mjs` 两条测试) | +| 上下文恢复:开放的类型(m1,检查点 7) | 三类终态错误都由同一个恢复工厂处理:上下文超长、Codex 历史过大(终态认领与发送前处理不健康会话 `prepareUnhealthySession` 两条路径)、Pi 不支持的请求字段(Pi 自己的缓存自愈没处理时的后备) | `main.ts` 的 `OPEN_CONTEXT_RECOVERY_KINDS` 只开上下文超长。真实引擎验证(`apps/host/scripts/`,本机模拟上游、个人目录隔离、经 `context-recovery-wiring.ts` 与生产相同的装配):`codex-runtime.e2e.mjs` 第三方供应商超长后重建、重放一次带上一轮摘要与该供应商的凭据;`claude-proxy.e2e.mjs` 经网关,CLI 自己的压缩也失败后才交给 Cindy,重建期间换 key,重放用新 key。两条都断言客户端没看到错误、只有一条用户消息、摘要只带一次、下一条不再带 | Codex 历史过大的终态认领关闭,当前引擎不再产生 `codex_history_oversized`。线 A ③ 起,发送前会读到旧库留下的错误;对仍用 Codex 且有原生线程号的任务,Host 和桌面用同一个定位器与分类器:健康时继续原线程,历史过大或查不清时重建并随新输入带一次摘要。已换引擎的任务不再查 Codex 历史,照桌面重建。关闭旧实例与写重建记录时核对发起这次发送的运行时所绑定的数据库;换账号后不写新账号的同名任务。Pi 不支持的请求字段:关闭。打包的 Pi 由 Cindy 装入的缓存自愈在同一轮里去掉字段重试并记住路线(`pi-native.e2e.mjs` 验证),错误到不了 Host,这一类的后备没有真实引擎的验证;没开时与之前相同,错误照常显示 | | 待发交接摘要(m1,检查点 5) | 进程单例 `agentHandoffPendingSingleton.ts`:发送事务 `peekPendingHandoff` / `consumePendingHandoff`,接受后把消费位写回(`markLatestAgentHandoffConsumed`,引擎切换边界改写后重新广播);`/clear` 时 `invalidate` / `sealClearBoundary`,回退时 `clear` | Host 进程一个注册表(`apps/host/src/agent/handoff-pending.ts`,同一个 `createAgentHandoffPending`),发送事务接同样两个端口。消费引擎切换边界时,改写当前数据库里的那一行,只发布给调用时的账号 | Host 发送现在会带上桌面留下、还没发出的摘要:引擎切换、删除消息后的重建、溢出重建。重启后从数据库重建,与桌面一致。Host 没有 `/clear` 清上下文、回退与删除消息的入口,所以没有作废调用,随这些入口接入时一起接。Host 换引擎仍不写交接(第 32 行) | -| 改模型时的窗口保护(m1,上下文恢复检查点 6) | 本机窗口里改模型(`register.ts` 的 `applySessionRuntimeSelection`)用共用的 `assessRuntimeModelSwitchGate` 判断:核实过是缩小、且占用到 danger 或 overflow 时,调 `prepareModelWindowSwitch`,可以在确认后把对话交接成摘要并重建;回合中的选择延期到下一次发送时兑现,兑现时再做本机的窗口保护。Device Link 发来的改模型按“远程”判断:同样的情况直接拒绝(`PRECONDITION_FAILED`,`remote model-window rebuild is unsupported; runtime selection was not changed`),回合中则延期 | `/api/sessions/update`(`apps/host/src/agent/session-update.ts`、`model-window-gate.ts`)走桌面 Device Link 那条路:同一个 `assessRuntimeModelSwitchGate`,目标窗口与当前窗口按同样的方式核实(含任务的窗口预算,运行中 Pi 的路线预览与运行时窗口)。核实过是缩小、且占用到 danger 或 overflow 时,在改任何东西之前返回同样的错误码与原文;其余情况(未核实、占用不高、窗口变大、Codex)照常热切换。不调 `prepareModelWindowSwitch`,不重建,不涉及确认 | 1)桌面本机窗口可以确认后重建,Host 只能拒绝;界面上的确认往返属于第二阶段。2)回合中:桌面延期,下一次发送时兑现;Host 当场改(与之前相同),但按空闲同样过这道闸。3)冷的 Pi 任务:桌面先冷启动核实,核实失败时放行;Host 没有冷启动核实,当前窗口算未核实,放行。后果是换到更小的窗口后,下一次发送可能报上下文过长,溢出一类打开后由恢复接住。4)运行中 Pi 的路线预览不可用时桌面拒绝,Host 按目标窗口未核实处理(`session-update.test.mjs`) | -| 任务的发送互斥(m1,上下文恢复检查点 3) | `withSendToSessionLock`(`sendToSessionLock.ts`)把同一任务的发送(`register.ts` 的 `sendToAgentAccepted`)、改模型与改努力、切换运行时、丢弃未发送的任务、关闭任务、插件页面会话恢复等串行;停止不取这把锁 | 同一把锁(同一模块):发送(`turn-executor.mjs` 的 `send`,持锁到接受或拒绝)、`updateSession`(含入队时兑现引擎切换)、删除、丢弃、插件页面会话恢复(`agent/session-route-lock.mjs`)。`switch-agent` 只记意图、`agent-switch-intent` 只读,不取锁;停止不取锁;输入队列的命令不取锁 | 无差别。Host 没有的入口(预热、上下文预算对账、回退、手动压缩、伙伴、插件委托、Orca、IM 等)随各自功能接入时一起进锁。相对改前的 Host 变慢的一处(与桌面一致):发送卡在被接受之前(例如引擎进程起不来)时,删除、丢弃要等这个发送放锁,最多等到锁的超时放行 `SEND_LOCK_BAIL_MS`(5 分钟,`sendToSessionLock.ts:104`);之前 Host 的删除直接停止。先停止再删除不受影响:停止不取锁,被取消的启动随即放锁(`input-queue.test.mjs` 两条测试)。这三个入口与插件页面会话恢复原来就没有经过真实装配的自动测试,见“待办与未完整运行的验证” | +| 改模型时的窗口保护(m1,上下文恢复检查点 6;检查点 3 改为与桌面同一份代码) | 本机窗口里改模型是意图,下一次发送时落定(`sessionRuntimeSelectionApply.ts` 的 `handleSetModel`,发送事务 `makerSendTransaction.ts` 1108–1119 调 `applyPendingAgentSwitch`)。落定时核实过是缩小、且占用到 danger 或 overflow,就调 `prepareModelWindowSwitch` 先重建再换,不再询问(`confirmedTargetPressure`);冷的 Pi 任务先冷启动核实窗口 | 检查点 3 起与桌面同一份代码:`/api/sessions/update` 与 `/api/sessions/set-model` 走 `agent/runtime-selection.ts` 的 `setModel`(共用 `handleSetModel`,选择是意图),发送事务的落定钩子同桌面;冷启动 Pi 核实用共用的 `createColdPiRehydrationForWindowVerification`。Host 自写的 `model-window-gate.ts` 已删 | 无(闸门本身)。**自 #10613(2026-11-15)起存在、检查点 3 补上的洞**:#10613 的 Host 闸门按任务行的占用判断已释放的任务,而 Host 从不写这两列(第 36 行),行里是桌面最后写的旧值或默认的 0,0 被当成“已知、没用”;冷的 Pi 任务没有冷启动核实,当前窗口算未核实,放行。两种情况下,占用到危险线的任务都能换到更小的窗口而不重建。检查点 3:第 36 行写回占用;改模型改成桌面的“意图 + 发送时落定 + 危险线重建”;冷启动 Pi 核实接上真的(之前的占位抛错会被共用代码当成核实失败而放行,不重建,见 `input-queue.test.mjs`“released Pi task”的红)。剩下的差别:占用写入后的推送没做(第 36 行)| +| 任务的发送互斥(m1,上下文恢复检查点 3) | `withSendToSessionLock`(`sendToSessionLock.ts`)把同一任务的发送(`register.ts` 的 `sendToAgentAccepted`)、改模型与改努力、切换运行时、丢弃未发送的任务、关闭任务、插件页面会话恢复等串行;停止不取这把锁 | 同一把锁(同一模块):发送(`turn-executor.mjs` 的 `send`,持锁到接受或拒绝)、`updateSession`(含入队时兑现引擎切换)、删除、丢弃、插件页面会话恢复(`agent/session-route-lock.mjs`)。`switch-agent` 只记意图、`agent-switch-intent` 只读,不取锁;停止不取锁;输入队列的命令不取锁 | 无差别。Host 已提供 Device Link 的 Pi Skill 预热入口(`device-link.ts:275`);其余 Host 还没有的入口(上下文预算对账、回退、手动压缩、伙伴、插件委托、Orca、IM 等)随各自功能接入时一起进锁(2026-11-19 复查更正)。相对改前的 Host 变慢的一处(与桌面一致):发送卡在被接受之前(例如引擎进程起不来)时,删除、丢弃要等这个发送放锁,最多等到锁的超时放行 `SEND_LOCK_BAIL_MS`(5 分钟,`sendToSessionLock.ts:104`);之前 Host 的删除直接停止。先停止再删除不受影响:停止不取锁,被取消的启动随即放锁(`input-queue.test.mjs` 两条测试)。这三个入口与插件页面会话恢复原来就没有经过真实装配的自动测试,见“待办与未完整运行的验证” | | Codex 共享运行时的延迟重启(m1,上下文恢复检查点 1) | 会话启动前钩子(`maker-host/index.ts` 的 `onBeforeStart`,`register.ts` 的 `setBeforeLocalCodexSessionStartHook`)在本机 Codex 会话加入共享运行时之前兑现两种待执行的重启:网关 key 变更(`gatewayCodexRestartService`)与记忆设置变更撞上 Codex 忙时登记的软重启(`deferredCodexRestartService`) | 同一位置(`apps/host/src/agent/start-options.ts` 的 `onBeforeStart`)兑现网关 key 变更的重启,每次本机 Codex 启动一次;之前在每次发送前兑现,已移到这里。Host 没有改记忆设置的入口,所以没有记忆设置的延迟重启 | 记忆设置一支:无可观察差别;Host 加上改记忆设置的入口时,要同时接上它的延迟重启。Host 自身的行为变化(与桌面一致):网关 key 变更时(`gatewayCodexRestart.ts` 的 `schedule` 随即在 `onSessionSettled` 里尝试重启),没有忙的 Codex 会话就当场重启;忙则等回合结束(`onSessionSettled`)或每 10 秒重试(`deferredCodexRestart.ts:33`)。之前 Host 还会在每次发送前再试一次,现在不试;在“还有待执行的重启、但会话都空闲”的窗口里(上一次重启失败等重试,或换 key 与发送挤在同一时刻),下一条发送先在原来的 Codex 运行时上执行,重启在这一轮结束后兑现。上游拿到的仍是新 key:Host 的 Codex 回环代理把已被替换的网关 key 换成当前 key(`codex-proxy-host.ts:2612–2616`)。`codex-runtime.e2e.mjs`“a gateway key change while a live Codex session is idle”断言下一条发给同一活会话的请求带新 key | | 引擎二进制的路径 | 每次启动任务时取本进程已准备好的路径(`getReadyBinaryPath`,`b1c5d88705` 起);没装时也建引擎,启动任务时报“去设置里安装”,后台装好后不用重启 | Host 启动时用同一个 `readCachedBinaryStatus` 定下路径,之后不变;启动时没有的引擎不注册,Codex 运行时也不建 | 运行期间二进制被更新或替换、旧路径不在时,Host 上该引擎的任务起不来,直到重启;启动后才装好的引擎要重启 Host 才能用。对齐要改成三个引擎总是创建、Codex 运行时按需建、能力上报跟着变,不是小改动。交接任务已答复(运行期间的安装与更新没定、没联调),并入第 34 行“引擎二进制管理(8k)”,**迁移前必须完成**。同一行的中间状态:Pi 本体的更新(`pi update --self` 与 `--all` 的核心部分,桌面经 `updateReadyPiBinary` 装到新目录)在 Host 上拒绝(m1-cp18c2),归类为 `unsupported`,Pi 的回执写明暂不支持、包的安装更新删除照常、不提示重试(审核方定甲);不允许原地自更新 | | Pi 持久子代理的进程类型(m1-cp18c) | Electron 的 utilityProcess(`piSubagentRunnerHost.ts`),中间入口经 `process.parentPort` 发 ready 帧后抹掉 parentPort | Node 的 `child_process.fork`(`pi-subagent-runner.ts`),中间入口经 `process.send` 发同一帧后断开 IPC;路径检查与按 pid 结束是同一份代码 | 两边都不把持久子代理登记进进程登记表(审核方定甲,与桌面相同)。崩溃时(m1-cp18c 实测,父进程被 SIGKILL 模拟崩溃):桌面主进程崩溃时 utilityProcess 里的 runner 随之消失,runner 起的 Pi 子进程(独立进程组)留下;Host 上 m1-cp18c2 起 runner 随 Host 结束(Host 的入口盯父进程:pid 加启动时间,每秒检查是否被过继或 pid 已不在、每 30 秒核对启动时间以识别 pid 复用;父进程没了给自己发 SIGTERM,走 runner 自己的清理,5 秒内没退出就强制退出),Pi 子进程也一并结束。这是 Host 比桌面更干净的一处(审核方选乙)。另:Host 的 exit 事件带 Node 给的 signal,桌面只有 code,只影响失败说明里的文字 | | 保存点标签的停用裁决 | 读桌面供应商服务(订阅池、`getDesktopSelectableBaseCatalog`、连接认领、Fast 投影) | Host 的 `publicViews` 用 `getActiveCatalog`、无订阅池与认领,两边视图不等价;Host 端口按「不可用」 | 标签走兜底,不发付费请求。同一个不等价的视图还作为端口交给了 Codex 启动配置(`createCodexSpawnConfig` 的 `listProviders`)与子代理路由签名(`createCodexRoutingSignature`);刷新自定义供应商进目录时 Host 用 `config.list`,rc10 已补同一读取实例的代次与 owner 栅栏,仍没有桌面的升级迁移与完整供应商视图(C3 盘点丙 6–8)。等价的供应商视图随 M2 的模型通道做,届时再拆路由守卫、接真实调用;m1-cp12 已还原之前的拆分。安装型 BYOK 供应商的凭据挂在同一个 M2 事项下 | +| Codex 后端不可达时的出站路径(显式端口,2026-11-17;28a 改写) | “后端不可达”终局升级时,读本次请求实际出口的出站路径判定(`getOutboundPathFact`:Codex 代理记的线程出口 origin,加出站代理解析器按 origin 的判定),把通用猜测换成实测事实 | 28a 起 Host 也报实测事实:同一份解析核心,取法与桌面那三行逐行对应(第七节第 24 项)。没设代理环境变量时:macOS 上 28b 起按静态系统代理给出判定(来源 system,与桌面相同;要用的代理带用户名时报 unknown(resolve_failed);28c 起 PAC 与自动发现由 Chromium 辅助进程给出,见第 28 行);Windows 上 28c 起由辅助进程给出(无答时 unknown,resolve_failed);Linux 报 unknown(session_unavailable),因为 Host 在 Linux 上不读系统代理 | 设了代理环境变量时与桌面相同。没设时:macOS 上静态系统代理与桌面相同,PAC 与带认证的代理是“判定没问出来、按直连兜底”的说明;Linux 上一直是这样的说明,而不是确认直连 | +| macOS 系统代理(28b,2026-11-17;28c,2026-11-18;审核方定) | 问 Chromium(`session.resolveProxy`)。开了 PAC 或自动发现时先跑脚本:自动发现依次试 DHCP(macOS 上不做)与 `http://wpad/wpad.dat`,再试 PAC 地址,都失败才用手动设置;脚本运行出错时直连。带认证的代理照样给出,转发层不带凭据,代理回 407(`outbound-fetch.ts` 已写明不支持)。系统设置一变 Chromium 就重读,加上核心的 30 秒缓存,最长 30 秒生效 | 28c 起:配了 PAC 地址或开了自动发现时,问 Chromium 辅助进程(第 28 行),与桌面相同(同一个 Chromium,脚本运行、自动发现、例外规则都由它做);辅助进程起不来、正在重启或超时(每次最多 1.8 秒)时退回下面的静态读法。静态读法(28b):开了 PAC 地址时按直连并报 unknown;只开自动发现时直接用手动设置,记一条一次性的 warn 说明未做自动发现——这句只进日志,诊断快照没有放它的字段,不为它改共用核心、不动桌面(审核方定);只开自动发现、又没有手动设置时判定为 system/direct(与 Chromium 自动发现失败后退回空的手动设置相同,审核方定保持);这次请求要用的代理带用户名时按直连并报 unknown;最长 35 秒生效。普通源码 Host 由 `main.ts` 启动系统代理解析;直接导入 `outbound.mjs` 的验收脚本与测试不读,系统代理对比脚本另启真实 helper 并读取系统设置(`scripts/macos-system-proxy-compare.mjs`、`windows-system-proxy-compare.mjs`;2026-11-19 复查补全) | 28c 之后:PAC 与自动发现与桌面相同;剩下的差别是辅助进程刚启动(约 0.2–0.8 秒加 PAC 下载)或重启期间,请求按静态读法处理(配了 PAC 地址时直连、报 unknown),以及设置改动后 Host 最多晚 5 秒(静态读法的缓存)。28c 之前:配了 PAC 地址:常见于用代理工具“自动代理模式”(PAC 模式)的用户,迁到 Host 后请求直连,在直连不通的网络里可能连不上模型服务。只开自动发现、网里真有 WPAD 服务器:桌面走 WPAD 脚本给的代理,Host 走手动设置;没有手动设置时 Host 直连,诊断也显示直连,唯一的提示是那条一次性的 warn;归 28c 一起解决。网里没有 WPAD 服务器时两边相同。带认证的系统代理:两边都连不通,桌面是代理回 407,Host 是直连。改设置后 Host 最多晚 5 秒生效 | +| Windows 系统代理(28c,2026-11-18) | 问 Chromium(`session.resolveProxy`),读当前用户的 Internet 设置(手动代理、例外、PAC 地址、自动检测) | 28c 起:没有代理环境变量时问 Chromium 辅助进程(第 28 行),与桌面相同;首次联网前预热并等待就绪(最多 8 秒),之后保持运行;起不来、正在重启或超时时按直连并报 unknown(resolve_failed),记一条 warn。28c 之前 Host 在 Windows 上完全不读系统代理 | 启动预热超时或重启期间解析失败时直连;其余与桌面相同。多一个常驻的 Electron 辅助进程;Windows 冷启动耗时、无 WPAD 的自动检测耗时与内存均待自有机器实测(第五节) | +| Linux 系统代理与 PAC(乙,2026-11-18 审核方定) | 问 Chromium,读 GNOME(gsettings)或 KDE 的代理设置与 PAC | 只读代理环境变量;系统设置与 PAC 都不读,没有代理环境变量时直连,路径记 unknown(session_unavailable);`cindy-host status` 写明“system proxy settings and PAC are not read on this platform” | 只靠系统代理或 PAC 才能连出去的 Linux 用户,要给 Host 设代理环境变量;第五节乙类,迁移前处理 | +| 落盘窗口里的活回合探针(检查点 4a,Host 独有) | 回合跟踪在终态时就转空闲,没有“已收到终态、回复行还在落盘”这段窗口 | 协调器在终态到达时就排空,而 Host 在落盘结束前仍算回合在跑(`isTurnRunning`),Session 已空闲。Host 绑给协调器的 `isLiveTurnRunning` 在这段窗口答“不可用”(`undefined`,按失败关闭),不把 Host 自己的回合记录当成运行中的 Session(共用代码对这个探针的约定)。没有这一处时,协调器把这段当成“边界过期”,每 250 毫秒查一次;之后遇到“不忙但队首不能派发”(失败的停止)就一直查下去。真正挡住“回复行落完之前派出下一条”的是 `isTurnRunning`(协调器派发前都会重查),不是这一处。测试:“the next input is not dispatched before the reply rows settle”(让 `isRunning` 在终态时提前变假就红);“once the rows settle no stale-boundary retry is left running”(去掉这一处就红);`reconcileIdle` 改成返回 true 两条都不红 | 无(用户看不到);去掉会多一个空转的定时器 | +| 附件归一化失败(第 12 行,审核方 2026-11-17 定保留 Host 做法) | 附件落盘或解析失败时只记日志、丢掉这个附件,消息照发(`maker-ipc/normalizeAttachments.ts` `normalizeUserMessage`) | 整条拒绝,不发(`apps/host/src/attachments.ts`,共用的 `createAttachmentNormalizer` 之外 Host 的处理) | 静默丢附件会让用户以为模型看到了;桌面那边记进桌面事项,以后一并问用户要不要改 | | 代输入(sudo、ssh、git 密码提示) | 任务的 shell 带代输入的 askpass 环境变量,提示转给用户 | 同一个 `taskShellEnv`,但 Host 不启动 askpass,返回空 | 这些提示在 Host 任务里照命令行默认行为失败,不会转给用户;随代输入一起补 | | 内置 ripgrep 的位置 | 打包版 `resources/tools/ripgrep`;开发时 `apps/ripgrep-bin/<平台>`(`pnpm install:ripgrep` 安装) | `hostRuntimeLayout().harnessRoot/ripgrep-bin/<平台>`:开发时就是同一个 `apps/ripgrep-bin/<平台>`;发布版是 `apps/host/scripts/build.mjs` 从 `apps/ripgrep-bin` 拷进 `resources/harnesses` 的同一个文件 | 同一个 rg 二进制;找不到时与桌面抛同一条错误(Pi 在构造时,Codex 在启动读 PATH 前缀时) | | 插件工作进程调用宿主工具(main #9801、#9825) | 插件的 Node 工作进程经 broker 的 `hostToolRequest` 调用宿主工具,按 `approvedHostToolGroups` 与逐次确认放行 | main #9825 已接 `hostToolRequest: hostTools.request`;Node broker 与管子运行时共用这条入口。与 Agent 共用 provider 和 handler,批准记录与回执仍用共用代码,确认经 `host-confirmations.ts` 发往当前认证控制器 | 不再是一律拒绝。没有控制器、控制器断开、owner 变化时不批准。插件调用 cindy_computer 在创建运行时与弹确认之前返回 UNSUPPORTED_CAPABILITY,Agent 路径保留(main 自带限制,`host-tools.test.mjs`);插件使用侧栏浏览器无任务标签页时被拒,专用浏览器/用户浏览器可用(共用 providers.ts)。这些差别只记录,不在本轮扩展能力 | -| 插件订阅消息与任务状态事件(main #9801) | 花名册广播时注册任务变更监听(`setTaskChangeListener` → 任务事件索引 → 订阅网关),按批准记录里的 `approvedEventTopics` 把消息与任务状态推给插件 | 合并 main #9825 后仍没有订阅网关,也不注册这条监听;新增的宿主工具/确认/历史服务没有接事件主题推送;Host 上运行的任务的消息与状态变化不推给插件。客户端模式下窗口进程里的监听是进程内的,看不到 Host 进程写入的变化 | 已批准事件主题的插件收不到 Host 任务的事件。未做,随第 33 行(8i,插件基座)一起接 | +| 插件订阅消息与任务状态事件(main #9801) | 通过 `setTaskChangeListener` 和任务事件索引,按批准记录投递消息与状态主题 | 8i 已接裁决网关及回合钩子。Host 还没有注册任务变更监听,客户端模式的窗口也收不到 Host 进程的库变更 | 已批准消息与状态主题的插件在 Host 还收不到这些通知,归乙 | +| 恢复已归档任务(第一批检查点 2) | 发送前与任务列表的恢复都走 `patchSessionMetaInDb` 的 active 分支:取 worktree 变更锁;`noteSessionsRestoring`;数据库事务 `sessions.setStatus`;通知灵动岛;请求 Codex 原生线程的归档同步;广播 `sessions:patched` | 两条路都走 `agent/task-restore.ts`,只保留决定结果的三步:`noteSessionsRestoring`(共用;Host 装与桌面任务管理同一个观察者,记下恢复时间,甲 22)、同一个数据库事务 `sessions.setStatus`(已删除不恢复、伙伴任务拒绝、群聊专线同一事务标 `archived_at`,与桌面同样输入同样结果)、发布 `session_changed`。任务列表的恢复先写其他字段、再走这个事务,与桌面先后相同。发送时恢复取任务的发送锁(Host 把发送锁装成共用的路由锁,与桌面 `registerAll` 相同):发送路径已持锁时可重入,上下文恢复的重放不持锁时等锁 | 灵动岛 Host 没有。原生归档同步 Host 没有:Host 归档时也不同步,随将来 Host 的归档同步一起接(乙 11)。worktree 变更锁:Host 的任务可以有托管 worktree,但 Host 进程不回收 worktree,进程内没有与恢复并发的回收。桌面窗口的回收在另一个进程:它在自己的路由锁里删除前再读一次库,确认任务仍可删除(`isSessionStillRemovable`),Host 的恢复先落库则回收放弃。两个进程的锁互不相干,若恢复恰好落在回收复查之后、删除之前,工作树会被删掉,下一次发送按托管工作树缺失直接失败(不转恢复目录)。桌面自己在恢复时取变更锁,没有这个窗口 | +| 手动归档(任务列表,第一批检查点 2 核对) | `patchSessionMetaInDb` 的归档分支:已删除与伙伴专线的检查、群聊专线标 `archived_at`(事务 `sessions.setTerminalStatus`)、回收 worktree、发插件事件、同步原生线程、关闭共享任务 | `/sessions/update` 只改 status 这一列 | Host 归档时不做已删除与专线的检查,不标群聊专线的 `archived_at`,不回收工作树,不发插件事件,不同步原生线程(乙 11),不关闭共享任务。建议随工作树那一块(工作树的恢复与回收)一起改走同一套事务 | +| 工作目录检查(第一批检查点 2) | `createWorkingDirectoryPreflight` 加 `createWorkingDirectoryRecovery`;托管工作树先看就绪,缺失时用 Git 恢复,恢复不了(`gone`)才转“未恢复的工作树”恢复目录;工作目录缺失时广播一条错误横幅 | 同一个工厂与恢复、同一套目录探测(`workdir-probe-host`,有并发上限与超时)、同一个 profile 里的对话恢复目录(`agent/working-directory.ts`)。托管工作树:Host 不做 Git 恢复,目录存在算就绪,其余一律 `retry`(桌面读绑定的函数在会带进 Electron 的 `worktree/restore.ts` 里,所以只看目录);Cindy Make 工作区按 Host 拒收 Cindy Make 输入的原话拒绝;工作目录缺失只记日志 | 托管工作树丢失时 Host 直接失败(`WORKDIR_MISSING`,原文与之前相同),不转恢复目录。**接入工作树的 Git 恢复之前不要返回 `gone`**:那会把任务悄悄挪到恢复目录,而桌面在那里会先恢复工作树。缺失的横幅:Host 客户端从发送失败本身拿到原因 | +| 移动任务:运行中的判断(甲 5) | 关闭空闲运行时之前只看活实例在不在回合中(`bootstrap-electron.ts` `closeIdleSessionForMove`) | 活实例在回合中,或执行器那一轮还在收尾(终态已到、回复还在落盘,即 4a 那段窗口)都算运行中,拒绝移动(`agent/session-move.ts`) | Host 更严:收尾窗口里关闭运行时可能和落库冲突(审核方甲 5 定)。用户在那段时间里移动会看到“运行中的任务不能移动”,稍后重试即可 | +| 移动任务:最近项目的推送(甲 5) | 写入最近项目后经 IPC 发给本机窗口 `local-db:recent-workdirs:changed`,payload `{ path }`,带 owner 戳(不经 device-link) | 同一频道、同一 payload 经事件流的 `plugin_push` 发出,不带 owner 戳(与 ghosts 频道一致,渲染层没有戳时放行);网页端 shim 转给 `localDb.recentWorkdirs.onChanged`,桌面客户端模式的窗口转发白名单(`bootstrap-electron.ts` onPluginPush)加了这个频道(桌面提交 `4cbeb69ff2`) | 两种客户端都与桌面相同。客户端模式白名单里凭据切换那几个频道当初就没加,是先例缺口,这次不补 | +| 区域(甲 20) | 版本区域在构建时写死(`shared/brandRegion.ts`)。中国大陆版:1. `/models` 第一次成功之前隐藏未核实的 XD 图像、嵌入与非 Seedance 视频模型(`active-catalog.ts`,各引擎模型列表同源);2. 没有花费的任务与定时运行,零金额是 CNY(`regionalMoney.ts`,经 `localDb/mapper.ts`);3. 没存过语音设置时默认语言 zh-CN(`voiceInputData.ts`);4. 续接 Codex 旧线程时还找旧品牌 `xdt-maker` 的 codex-home(`codexLocalSessionsCore.ts`) | 原来四处都按 global。现在发布包按 `--region`、源码按 `CINDY_HOST_REGION`,与同区域桌面相同 | 已关闭(甲 20)。国际版没有差别。dev 桌面配 cn 包(审核方定,§1.1:dev 行为归 cn 系),dev 与 cn 在第 3、4 处不同:经 cn Host 时这两处按 cn 走 | +| 读别的设备的任务引用(第一批检查点 2) | 经 Device Link 读来源设备的历史 | Host 已运行 Device Link,但来源设备的引用历史与生成图读取所用的出站解析端口仍返回未连接(`NOT_CONNECTED`,与桌面没连接时相同;2026-11-19 复查更正) | 引用不可用时协调器不带引用历史,消息照发(`agent-input-coordinator.ts` `resolveReferenceContexts`),与桌面相同 | +| 发送前读取的排队方式(第一批检查点 2) | 计划对账、目标说明的读取,已封计划的清除,本轮模型的记录,都排在全局持久写入队列之后;这个队列遇到失败不暂停 | 排在任务的持久写入队列之后(`turn-executor.mjs` `behindDurableWrites`)。Host 的这个队列在写入失败后会暂停这个任务后面的回复写入、等重试,所以这几项自己失败时只把错误交还调用方,不进暂停(读取失败不带说明,记录失败记日志),与桌面结果相同 | 无 | +| /api/chat 在“已落库但派发失败”时结束(第一批检查点 2) | 桌面没有这个入口 | 错误行落库后发这条输入的 `interrupted` 回执,`/api/chat` 收到后结束;同一 clientId 重连直接得到 interrupted。只在协调器写错误行的这条路上发:被上下文恢复认领、之后被自动续跑压住的错误不写这一行,流不提前结束 | 之前这个场景的流不结束,调用方一直等。结束条件见第七节第 21 项 | +| 任务的 PR 关联(主干 9013dae440 带进 Host 导入图,2026-11-17;写入已对齐,甲 24) | 每条 user/assistant 消息落库后提取 PR 与 MR 链接写进 `session_pr_refs`(`localDb/ipc/messages.ts` `createMessage` 经 `localDb/messagePrRefs.ts` `trackMessagePrRefs`);改正与撤回助手回复、无原行的 user/assistant 更新之后,先等这一行的提取写完再重算(`reconcileCorrectedMessagePrRefs`、`reconcileUpdatedMessagePrRefs`);删除、回退、清除后的恢复也重算(`recomputePrRefsForSession`);有变化时经 `setPrRefsChangedListener` 推 `git-context:pr-refs-changed` 给窗口(`git-context/ipc.ts`),窗口经 `git-context:pr-refs:list`、`list-all`、`manage` 读写 | 写入与桌面相同(甲 24):Host 写消息(`message-store.ts` `createHostMessageStore`,这一行发布时)调同一个 `trackMessagePrRefs`;改正与撤回助手回复(`agent/event-persistence.ts` `updateDbMessageContent` 有原行时、`discardPersistedAssistantMessage`)调 `reconcileCorrectedMessagePrRefs`;无原行的 user/assistant 更新调 `reconcileUpdatedMessagePrRefs`(照桌面同一分支;共用的事件写入今天只在工具、计划、提问行上走无原行的更新,这一支在 Host 上暂时走不到);清除后的恢复(`createHostMessageRecovery`)与 MCP App 卡片更新(共用的 `mcp-apps/service.ts`)重算。仍不同(乙 13):不装 `setPrRefsChangedListener`;Host 的窗口读不到 PR 关联:网页端 `gitContext.listPrRefs`、`listAllPrRefs` 固定返回空(`apps/web/shim.js`),客户端模式不转发 `git-context:pr-refs:*`(不在 Host 通道合同里) | Host 上的窗口不显示任务的 PR 关联(乙 13,随 M2 的推送一批)。库里的记录与桌面相同:之后用桌面打开同一份 profile,Host 跑的任务里提到的 PR 照常显示。甲 24 之前 Host 写下的消息不会补:历史回填(`ensurePrRefsBackfill`)在标记 `git_context_pr_refs_backfill_v4` 写过后不再补,要等这些任务的下一次重算 | +| 置顶卡片摘要(测试期,乙 14) | 置顶段是卡片模式时,置顶任务的卡片显示一句话摘要(`sessionTaskSummary.ts`,回合结束、置顶时、切到卡片时生成) | 客户端模式下,置顶卡片显示列表预览而不是摘要:Host 不生成摘要 | 只是显示退回成预览,不丢数据、不花钱。解除条件:乙 14 落地 | +| Cindy Make 上游合并回合(甲 10 登记,2026-11-18) | 产品回合失败收口(`createProductTurnFailureFinalizer`)的 interrupt 结束 Cindy Make 的上游合并回合(`cindy-make/upstreamMergeRuntime.ts` 的 `interruptUpstreamMergeTurn`),成功回合经 `finishUpstreamMergeTurn` 收尾 | 空操作:这个模块引 Electron,Host 不加载,Host 上没有上游合并回合 | 无(Host 上没有这类回合)。要在 Host 上跑 Cindy Make 时接到 `agent/product-turn.ts` 的 interrupt 与 finish | +| 后台回合终态的产品回合收口(甲 10 登记,2026-11-18;已定,审核方 2026-11-18) | 终态阶段的成功与失败分支不看回合范围(`sessionEventTerminal.ts` 的 `terminalOwner`);当前引擎发出的后台事件不带 done 或终止性 error,生产上走不到(2026-11-19 复查)。若将来有与当前前台回合同实例、同代次的后台终态错误进入桌面失败收口,并且前台活动项尚无结束时间,失败收口会提前将该活动项标为已结算,导致前台的结束时间漏写 | 只对前台回合(非续接)的终态走产品回合(`turn-executor.mjs` 的 `settleProductTurn`),后台回合的终态不登记、不收口 | 已定(审核方 2026-11-18):Host 只对前台、非续接的终态走产品回合。理由:照桌面做,前台回合进行中会丢一次活动时间写入(桌面这一处登记在第五节“后续阶段的桌面事项”第 7 条) | +| 撞用量上限后的自动继续(测试期,乙 16) | 普通任务撞上订阅账号的 5 小时或周用量上限:照常报错,同时等额度重置,横幅显示“将于 X 自动继续 · 取消”,到点没人处理就自动继续(`usageLimitAutoResume.ts`,`register.ts`);等待存进 `usage-limit-waits.json`,重启后恢复 | 只报错,不显示“将于 X 自动继续”,到点不继续;桌面存下的等待在 Host 上不恢复(协调器的 `onUsageLimitedTurnError` 未绑,`agent/coordinator-deps.ts`) | 用户要在额度重置后自己发一句或点重试。解除条件:乙 16 落地 | +| 网关代理令牌失效(8g D,审核方 2026-11-18 定乙类) | Cindy AI Key 被拒的终态错误不写错误行,交给窗口自愈:窗口重新取凭据后重试(`retryLastError`),失败才经 `maker:persist-turn-error-deferred` 补写(`sessionEventTerminal.ts`、`renderer/lib/makerChatStore.ts`) | 立即写错误行(`turn-executor.mjs` 的 `finish`);上报与重新同步照桌面(`reportAgentCindyGatewayKeyRejected`) | 窗口自愈成功后,历史里多一条旧的“Key 被拒”错误行。Host 可能没有窗口,立即写能保证错误不丢 | +| 静默停止续跑期间的回合标记(8g B 评审第 2 项,2026-11-18) | 静默停止的 done 就写回合结束(`sessionEventTerminal.ts` 的 `markTurnEndedAfterPersistDrain`);续跑开始不再记回合开始(`sessionEventPreparation.ts` 只在“回合外”的运行状态记,静默停止的 done 把回合状态拨回了回合中)。决策期间或续跑进行中崩溃、退出登录或关闭,任务看起来已经结束,不进“继续上次中断的任务” | 静默停止的 done 不写回合结束(`turn-executor.mjs` 的 `settleSilentStopSegment`):没有续跑就结算时按 done 的时刻写,续跑结束时写,被账号边界打断时不写 | Host 上决策期间或续跑进行中被打断的任务会进“继续上次中断的任务”。桌面那边记进第五节“后续阶段的桌面事项”第 10 条 | +| 托管推理的模型目录(账号过滤)(主干 2656e83a31,2026-11-17) | 托管会话(远程 Agent 托管、供应商分享的受邀者)推理时核对模型用的目录,由 `createDesktopProviderService.ts` 经 `setGuestProviderModelCatalogReader` 装成 `projectSubscriptionPoolCatalog(getActiveCatalog(), true)`:只做订阅账号池投影,**不按账号过滤** | `agent/model-context.ts` 装成同一个投影,但先经 `filterProviderCatalogForAccount`(与可选目录同一条账号过滤):没有 Cindy 账号时去掉 Cindy AI(`xd`)。这是主干有意为之:主干的 `agent/model-context.test.mjs` 断言“仍有效的托管授权也绕不过当前账号的过滤” | 现在用户碰不到:Host 拒绝托管会话(`bindHostedSessionProvider`、`registerGuestProviderRoute` 都不在 Host 上装,见 `desktop-module-setters.ts`),也不会在未登录时运行。放开托管会话(远程执行,第七节第 18 项;供应商分享,乙 6)时要重看:没有 Cindy 账号的本机托管 Cindy AI 模型,桌面放行而 Host 拒绝 | +| 项目自动图标的出站请求(2026-11-17 设置函数守护发现,审核方定甲类;已对齐) | `projectAutomaticIcon.desktop.ts` 经 `configureProjectIconRuntime` 装上桌面的 `guardedOutboundFetch`(`maker-host/outbound-fetch.desktop.ts`,走桌面的出口代理判定),另装 `readRemote`(经远程文件浏览器读远程工作目录里的图标文件) | 已对齐:`project-icon.ts` 的 `bindHostProjectIconRuntime`(`main.ts` 启动时调用)装上 Host 出口的 `hostOutbound.guardedOutboundFetch`(`outbound.mjs`,与插件用的是同一个 `createOutboundTransport`,DNS 固定、跳转与私有地址防护相同,代理判定走 `outbound-proxy.ts`)。`readRemote` 不装:桌面经远程文件浏览器读远程工作目录,Host 拒绝远程工作目录(远程执行,第七节第 18 项),远程项目的图标在 Host 上本就没有 | 无(远程项目没有自动图标,与 Host 拒绝远程工作目录一致)。测试:Host `project-icon.test.mjs`“the Host fetches project icon websites through its own outbound transport”(经 `/api/project-info/auto-icon` 的处理函数,网站请求出现在 Host 出口的代理判定里) | +| OpenAI 图片 API key 是否已配置(2026-11-17 设置函数守护登记;审核方定乙 12,接受现状) | OpenAI 媒体模型发现(`maker-host/model-discovery/openai-media.ts`)经 `setOpenAiImagesApiKeyConfigured` 写入;为 true 时 OpenAI 订阅供应商不再加托管的 `openai/gpt-image-2`,图片模型以平台清单为准(`active-catalog.ts`)。这一项由图片通道注册表(`cindy-brain/index.ts` 的 `ImageChannelRegistry`)接到 Codex 订阅的图片通道(`cindy-brain/codexImageClient.ts`,用所选 ChatGPT 账号请求 `chatgpt.com/backend-api/codex/images`)出图 | Host 不加载这段发现,标记恒为 false | **只是清单里多一项,Host 在 M1 上不能用它出图**:图片通道注册表、Codex 图片通道、读供应商图片模型的媒体目录(`cindy-brain/cindyMediaCatalog.ts`、`cindy-media/providerMediaRuntime.ts`)与供应商界面处理(`maker-ipc/providerHandlers.ts`)都不在 Host 的导入图里(按设置函数守护同一份 esbuild 导入图核对,2026-11-17)。Host 加载的代码里读 `imageModels` 的只有 `maker-host/provider-connection-state.ts`,只用来判断企业 BYOK 图片供应商有没有凭据,与 OpenAI 订阅无关,也不出图。配了 Images API key 的用户在 Host 上,OpenAI 订阅供应商的目录里多出托管的 `gpt-image-2` 一项,Host 上没有用它出图的路径(既不走订阅通道,也不用用户的 key)。`desktop-module-setters.ts` 记为 pending(乙 12)。未改代码 | ### 订阅账号放置与供应商视图(rc10) @@ -176,7 +225,19 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | 项 | 桌面与 Host | 后果 | |---|---|---| +| 组织账号跨区登录时的 5 处版本区域发送(D1–D5,用户 2026-11-17 定为符合预期) | B 区组织账号登进 A 区版本时,以下请求按版本区域发往 A 区服务:D1 公开插件分享(选署名时带 token 与 authRealm,`plugin-market/sharing.ts:41-60`);D2 本地插件分享(`localSharing.ts:35-56`);D3 群聊邀请分享(`chatInviteShares.ts:9-40`);D4 日志上报含崩溃与性能追踪(userId,`log-upload/index.ts:119,151-166`);D5 TapDB 使用统计(`tapdbClient.ts:75-92,551-557`) | Host 上没有这 5 个模块(导入图核过)。Host 网页端的使用统计是新出现的入口,与 D5 不同:账号 realm 与渲染层区域不一致时不上报(甲-1),不新增跨区上报;已做,见第五节甲 21 | | 网关 key 更换时运行中的 Pi 任务(m1-rc4 核对) | Pi 进程的 `CINDY_PI_API_KEY` 是启动时的网关 key;本机代理按会话 token 准入,转发 Pi 持有的 key(同一个路由核心) | 换 key 之后,运行中的 Pi 的下一次网关请求仍带旧 key,网关还认旧 key 时成功,不认时失败;桌面相同。m1-rc4 的修复只覆盖 Claude(代理换成当前 key);Codex 的本机代理按当前 key 改写网关请求的 authorization(`codex-proxy-host.ts` 的网关路由);Pi 两边都不换(`claude-proxy-runtime.test.mjs` 按桌面现状断言) | +| 远程(URL)MCP app 的出站(28c 守护发现,2026-11-18) | `mcp-apps/connection.ts` 连远程 MCP app 用 Node 的全局 fetch,不经出口代理解析;桌面主进程的全局 fetch 同样是 Node 的,同样不走系统代理与 PAC;插件自带的 MCP app 走插件的传输 | 只靠系统代理或 PAC 才能连出去的用户,远程 MCP app 连不上;两边相同。登记在 `apps/host/src/host-network-modules.ts`(same-as-desktop),守护核对该模块的 fetch 使用次数,新增直接调用时会报错 | +| Agent-Net 的出站(本次主干同步,28c 守护) | 启用 Agent-Net 后,Host 与桌面共用会话 UDP、STUN、UDP 中继和局域网发现,均直接走 UDP。Host 的 HTTP 和 WebSocket 走已有出口代理解析 | 依赖 HTTP 代理的环境要分别验证 UDP 可达性。Host 只运行客户端,Agent-Net 开关默认关闭。分类见 `apps/host/src/host-network-modules.ts` | + +### 已知限制(仅限测试期) + +迁移前必须解决(乙,见第五节“乙:客户端模式下窗口切换、添加账号”);在那之前只登记,对用户的提醒由审核方说。 + +| 项 | 后果与测试期的做法 | +|---|---| +| 窗口连着 Host 时在窗口里切换或添加账号(乙,第一阶段之后的桌面行为变更 PR) | 窗口在本地完成登录:把新账号写成当前会话和保管库,并把技能投影的 owner 提交成新账号;Host 不跟着换,仍在原账号下运行,新建的任务落在原账号的库里。窗口的账号列表显示新账号为当前,头像与资料仍是原账号,下一次拿到 Host 状态时界面会回到原账号。Host 的下一次续期读到新账号的会话会失败(只记告警),原账号的访问令牌过期后模型调用失败;重启 Host 时,如果 profile 里只有原账号的库、会话却是新账号,会因账号不一致而起不来(有两个以上的库时启动按会话认账号),要重新 `cindy-host login` 原账号。测试期请勿在客户端模式下切换或添加账号;要换账号,先在窗口退出登录(Host 一并退出),再用 `cindy-host login` 登录新账号并重启 Host | +| 后台服务重启后,已经开着的 Cindy 窗口(审核方 2026-11-18 登记) | 窗口不会自动重连,要重新打开 Cindy;这期间窗口不提示原因。窗口启动时钉住后台服务的实例号,后台服务重启后实例号变了,窗口通过鉴权、带旧实例号的请求都被拒(409 `host_instance_changed`;公开探针和鉴权失败各走自己的分支),实测见第五节“甲,发布前必须回答”那一行。启动失败面板上每条“怎么办”都先让用户重新打开 Cindy(数据库不可用和通用启动失败两类,之后另给 `cindy-host status` 的排查说明;2026-11-19 复查补全)。**解除条件**:窗口交接落地(第四节“电脑上已有 Host 在运行时打开桌面版”) | ## 三、Host 会写到 profile 之外的位置 @@ -191,7 +252,15 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | Git 保存点对账删除 | 当前账号库里标记为已删除的任务在其仓库中的 `refs/cindy/savepoints/<任务 id>` | 账号库就绪后一次 | m1-cp5e | | Claude 托管 Skill 暂存目录 | 系统临时目录下的 `cindy-claude-skills-*`(maker-core `managed-skill-plugins.ts`):每个插件一个目录,含 `plugin.json` 和指向批准来源的链接,不复制 Skill 内容 | 每次启动 Claude 任务且托管 Skill 清单非空时建;该次查询中止或启动失败时删除 | m1-cp6 | | Pi 模型目录探测的临时目录 | 系统临时目录下的 `cindy-pi-catalog-*`:写一份只含占位 key 的 `models.json`,以离线模式启动 Pi 列出它自带的模型目录(`piNativeProvidersCore.ts` 的 `readPiBundledModels`,从 `pi-host.ts` 原样搬来) | 每个 Pi 二进制在本进程第一次启动本机 Pi 任务时一次,失败时下次再试;用完即删 | m1-cp18b2 | +| Agent-Net 已有的签名身份(2026-11-19) | Host 凭据库的 `safe-storage/agent-net-.enc`,走与账号凭据相同的解密通道。macOS 使用 Electron safeStorage 和系统钥匙串;Windows 辅助进程退出时可能把包装密钥写入 `Local State`。 | 远控经中转取令牌时由 `prepareTransportStatement` 读取,开关关闭时也检查。有文件才解密,已读结果按节点实例缓存。 | 主干 `8c4fc825b4`。 | | 系统 Codex 登录(经链接) | 迁移来的 profile 里 codex-home/auth.json 若是指向 `~/.codex/auth.json` 的链接:订阅桥刷新令牌时原地写回(`anthropicResponsesBridgeHostCore.ts`),Host 拉起的 Codex 自己刷新时也写;作废只删 profile 里的链接,不改外面那份 | 令牌快过期时 | 24b | +| 重建被删掉的工作目录 | 任务工作目录的原位置(目录被删、所在的盘还在时)建空目录,不恢复内容 | 发送时的工作目录检查发现目录不存在 | 第一批检查点 2 | +| Claude 转录复制 | 任务绑定的 Claude 配置目录(没有绑定时 `CLAUDE_CONFIG_DIR`,未设时 `~/.claude`)下 `projects/<新工作目录的键>/<会话 id>.jsonl`:只复制、不删旧的(共用 `relocateClaudeTranscriptsForSessionMove`) | 本机 Claude 任务移到另一个工作目录时 | 甲 5 | +| W1 跨 Agent 共享 Skill 根 | `~/.agents/skills/`:建目录;用户开了跨 Agent 同步时把 `~/.claude/skills`、`~/.codex/skills` 的 Skill 链进来,已有的非链接路径不覆盖;删 Cindy 自己以前建、未被改过的内置 Skill 旧链接 | `ensureSharedGlobalSkills` 没命中 30 秒缓存时(启动、Claude 与本机 Pi 启动、Codex 启动、列 Skill);失败只记告警,任务照常启动 | 第 25 行 25b | +| W2 Claude 的 Skill 根 | `~/.claude/skills/`:同 W1,另在用户开了同步、`~/.claude` 已存在或本进程启动过 Claude 任务时才建目录 | 同 W1 | 第 25 行 25b | +| W3 内置 Skill 包 | `/Cindy/shared-system-skills/`:版本目录、`.active` 指针、清单;只在本构建的包更新或需要修复时写,全机取最新版本 | 同 W1(发布是第一步);失败保留已装的包、记告警,这一轮不投影 | 第 25 行 25b | +| W4 内置 Skill 变更锁 | `/Cindy/shared-skill-mutation-locks/`:每个 Skill 名一个锁文件与 `pending/` 回执 | 每次发布;目录不可用时这一轮跳过、不写(照桌面) | 第 25 行 25b | +| W5 共享 Skill 根的跨进程锁 | `~/.cindy/ghost-skill-projection-boundary.json.lock`,第一次用时建 `~/.cindy` | 每次修改 W1、W2;拿不到锁就失败(fail-closed),Codex 的 Skill 投影随之失败 | 第 25 行 25b | ### Host 会读到的 profile 之外的位置 @@ -200,11 +269,16 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | 读取 | 位置 | 何时 | 引入 | |---|---|---|---| | 本机 Claude 的 MCP 配置(判断与 Cindy 自定义 MCP 重名的连接) | `CLAUDE_CONFIG_DIR/.claude.json`,未设时 `~/.claude.json`;`CLAUDE_CONFIG_DIR/settings.json` 或 `~/.claude/settings.json`;任务工作目录及其各级上级目录的 `.mcp.json`、`.claude/settings.json`、`.claude/settings.local.json`;只读 | 每次本机 Claude 任务启动时 | m1-cp18a | +| Codex 原生线程的历史 | 线程索引未命中时,定位器也会只读查找 `CODEX_HOME` 和 `~/.codex` 下的会话历史及其文件位置;分类器只读所定位的 rollout | 续接 Codex 任务、定位原生历史;线 A ③ 起,向留有“历史过大”错误的旧任务发送时也会定位并分类 | m1-cp18d 跨账号原生历史存储(#10469)起;发送前分类自线 A ③ 起 | | 官方 Codex Browser 插件的描述 | 系统 `~/.codex/config.toml` 的 `[plugins]`(共用启动配置里的 `prepareCodexBrowserCompanion`);只读 config,不碰凭证 | 每次准备本机 Codex 进程的启动参数时 | M1 之前(Host 接入共用 Codex 启动配置时,m1-cp0 已有) | | 系统 Codex 登录(经链接) | 同上,迁移来的 profile 里经链接读系统那份登录 | 每次读 Codex 登录态与派发请求时 | 24b | | 系统 Codex 登录(对账) | `~/.codex/auth.json`:stat、读取账号,建指向它的符号链接;只在安装版 Host | 启动时、读登录态、取启动环境、订阅桥取令牌、在 Cindy 里登录后 | m1-cp13 | | Claude Code 的配置与 Skill | `CLAUDE_CONFIG_DIR`,没设时 `~/.claude`(Claude 任务用 CLI 默认配置目录;/learn 捕获列 Skill 时也读这里) | 启动 Claude 任务、列 Skill 时 | m1-cp10 起用于 /learn 捕获 | | 用户自己的 Pi 全局说明 | `PI_CODING_AGENT_DIR`(`~` 展开),没设时 `~/.pi/agent`:其中的 `AGENTS.override.md`、`AGENTS.md`、`CLAUDE.md` 等上下文文件(maker-core `global-context.ts`);只读。伙伴与受邀者任务不读 | 每次启动本机 Pi 任务时 | m1-cp18b | +| Codex 与通用 Skill 源 | `~/.codex/skills`、`~/.agents/skills`:只作 codex-home 里链接的目标,不改 | Codex 启动、列 Skill | 第 25 行 25c(未做) | +| 用户的 Codex 规则 | `~/.codex/AGENTS.md`:复制进 codex-home,带标记的才更新,用户自己放的不动 | 同上 | 第 25 行 25c(未做) | +| 用户的 Codex 插件 | `~/.codex/plugins/cache`(只链接,或在 codex-home 里做收紧后的副本);`~/.codex/config.toml` 的 `[plugins]`(只读,条目只增不改地合进 codex-home 的 config) | 同上 | 第 25 行 25c(未做) | +| Skill 根的指纹 | 三个全局 Skill 根目录的修改时间 | 每次检查共享投影的缓存 | 第 25 行 25b | ### Host 在 profile 内与窗口进程共用的文件 @@ -212,16 +286,22 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | 文件 | Host 是否写 | 原因 | 引入 | 旧桌面可读的依据 | |---|---|---|---|---| +| owner 目录的 `task-management.json`(空闲归档设置与 `restoredAt`) | 写:只在恢复已归档任务时记 `restoredAt`(甲 22) | 与桌面同一份代码(`task-management/store.ts` 的 `restored`,经 `createOverrideSettingsFile` 原子更新)、同一个文件 | 甲 22 | 同一份 normalize:旧桌面读得懂 `restoredAt`,Host 不改设置字段 | | owner 目录的 `auxiliary-model-settings.json`、`auxiliary-model-settings-migration.json` | 不写、不删 | 见第二节「辅助模型设置文件」 | m1-cp11b | Host 不写 | | profile 根目录的 `pi-package-home/`(Pi 包、`settings.json`、变更标记)与 `pi-package-home.mutation.lock` | 写:任务里的包管理命令(安装、更新、删除)经 Host 的包存储执行(m1-cp18c2) | 与桌面同一份代码(`piPackageStoreCore.ts`)、同一个目录、同一把跨进程变更锁(`withSecurityBoundaryLock`),窗口的设置页与 Host 互斥;任一边改动后写变更标记,另一边观察到后刷新并让本机 Pi 任务重新加载 | m1-cp18c2 | 同一份代码写、同一份代码读;包命令由同一个 Pi 二进制执行(`hostPiPackagesParity.test.ts`:两边轮流改、读取逐项相同) | +| profile 根目录的 `pi/selected.json`(Pi 内核的显式选择) | 不写内容;但读时若主文件缺失而 `selected.json.bak` 在,会把 `.bak` 改名回主文件 | 每个 owner 运行时启动时选 Pi 二进制要读它(第 34 行 ②),用的是桌面同一个 `readAtomicFileSync`(`pi-kernel-selection.ts`),它先恢复备份再读。窗口写选择时持 `pi/install.lock`、经 `atomicWriteFileSync` 写;Host 读时不持这把锁,与桌面自己的读取(`hasSelection`)相同 | 34-fix | 恢复的是窗口自己写下的上一份完整选择,格式不变。但这个改名是 Host 在共用 profile 里的一个写动作(内容不变):只有在内嵌桌面与 Host 不同开的前提下才安全,依赖并存方案 A。只有 Windows 上原子替换走备份交换兜底时主文件才会暂缺:Host 恰在这时读,会把旧选择改名回去,窗口这次写入可能失败并报错、旧选择保留。这种交错未验证,归 34a–c 时在自有 Windows 机器上验 | | profile 根目录的 `pi-native-compat-overrides.json` | 写:Host 拉起的 Pi 里的 Pi 桥(`cache-recovery-source.ts`)学到缓存兼容时写;Host 进程本身只读 | 与桌面同一个文件、同一套普通 `.lock` 与 reclaim gate 协议(持锁后重读、合并、原子替换,`docs/dev-rules/pi-harness.md`),与窗口进程(显式拒收恢复时经 `recordPiNativeCompatOverride` 写)和两边的 Pi 桥互斥。记录有效期 7 天或 24 小时,只是性能提示 | m1-cp18b | 同一份代码写(maker-core 的 Pi 桥)、同一份代码读(`piNativeCompatOverridesStoreCore.ts`);读不懂的文件按未学习处理并保留 | | `safe-storage/.enc`(账号会话、网关 key、自定义供应商 key 与头、OAuth 等) | 写 | Host 的凭据库读写桌面已有的 safeStorage 记录,不另开一份 | m1-cp0 前 | 同一目录、同一格式:macOS 与 Windows 经 Electron 辅助进程调 safeStorage,钥匙串身份用桌面 keychain-identity 的同一份判定代码;Linux 是兼容 OSCrypt v11 的同一格式;原子替换。以上只是共享路径和格式,是必要条件,不是兼容证明:现有只有注入进程的单测(`store.test.mjs`),没有真实钥匙串互通测试。实际签名的辅助进程能否解密旧凭据、系统授权怎样表现、Host 写入后桌面能否反向解密,都未验证,归第五节「登录凭据的联合验收」 | -| 账号会话记录(`AUTH_SESSION_KEY`) | 写:刷新令牌轮换后原子写回 | 桌面同样轮换写回 | m1-cp0 前 | 共用 schema 解析(代码层面的依据,未经真实验收)。轮换后失败回退、刷新在途时落盘失败或崩溃的恢复都未验证,归第五节「登录凭据的联合验收」,两边现在的刷新做法记在那里。由 `cindy-host login` 建立的登录带 `hostDeviceId`:旧桌面读时忽略它,自己轮换写回时不带它,之后 Host 的设备身份回落到覆盖值或物理设备号(m1-cp18e 实测);采用桌面已有登录时记录本来没有这个字段,不受影响 | +| 账号会话记录(`AUTH_SESSION_KEY`) | 写:刷新令牌轮换后原子写回 | 桌面同样轮换写回 | m1-cp0 前 | 共用 schema 解析(代码层面的依据,未经真实验收)。轮换后失败回退、刷新在途时落盘失败或崩溃的恢复都未验证,归第五节「登录凭据的联合验收」,两边现在的刷新做法记在那里。2026-11-17 起 Host 续期还在账号库的跨进程锁里写账号库里这个账号的资源令牌(`cindy_auth_accounts_v1`,只改这一项,版本写 1,同桌面)与已存在的旧版独立令牌(`cindy_auth_refresh_token`),规则与桌面同一份(并存行后续九)。由 `cindy-host login` 建立的登录带 `hostDeviceId`:旧桌面读时忽略它,自己轮换写回时不带它,之后 Host 的设备身份回落到覆盖值或物理设备号(m1-cp18e 实测);采用桌面已有登录时记录本来没有这个字段,不受影响 | | 账号库 `cindy-.db` | 写 | 任务、消息等 | m1-cp0 前 | 桌面同一个 localDb 客户端与迁移;迁移契约由迁移器强制(交接任务) | | owner 目录(记忆、各设置 store、MCP 重名偏好等)与窗口设置文件(appearance、analytics、layout、shortcuts、sidebar、voice-input-data) | 写(MCP 重名偏好与辅助模型设置不写) | 同一份 store 与规范化代码;窗口设置由 `profile-settings.mjs` 写同一路径 | 各行 | 同一份代码;Host 不删读不懂的文件(第二节) | | codex-home、codex-accounts | 写 | Codex 登录、作废标记、账号目录 | 24b、m1-cp9、m1-cp13 | Codex 自己的格式;账号服务同一 core;作废双向对照(`hostCodexInvalidationParity.test.ts`) | | pi-agent-home、工作树租约、回合改动记录 | 写 | Pi 运行目录与会话;租约;改动记录 | 各行 | 同一份代码 | | browser-runtime、windows-atomic-rename | 写 | 托管浏览器运行目录;Windows 原子改名辅助程序缓存 | M1 前 | 与桌面同名,同一份代码、同一布局 | +| profile 根目录的 `ghost-skill-projection-boundary.json`、`.quarantine.json`(Skill 投影的 owner 边界) | serve 不写状态,只在修改时持同一把锁(`.json.lock`);独立 Host 的 `cindy-host login` 命令行进程照桌面协议写(隔离标记、pending、stable) | 方案 A:窗口提交 owner;独立 profile 上由 login 提交,serve 注入拒绝(第 25 行 25b) | 25a、25b | 同一份桌面代码写、同一份读 | +| profile 根目录的 `claude-idle-release.json`(Claude 空闲释放的分钟数覆盖) | 不写,只读 | 空闲释放每次扫描时读(第一批检查点 1,第 35 行) | 第一批检查点 1 | Host 不写 | +| profile 根目录的 `worktrees.json`(桌面的 worktree 登记表,electron-store) | 不写、不建,只读 | 移动任务时判断 worktree 归属(甲 5):每次读,文件不存在等于没有绑定,读不懂(不是 JSON、结构不对、条目没有路径)就拒绝移动,与桌面的 store 抛错一致 | 甲 5 | Host 不写 | +| owner 目录 `dialogues/` 下的对话恢复目录;对话工作区设置 | 写恢复目录(盘不可用或工作树未恢复时建,里面是 Agent 写的文件);设置只读 | 工作目录恢复(第 32 行),与桌面同一份代码 | 第一批检查点 2 | 同一份代码、同一路径;桌面按同一规则沿用已选的恢复目录 | | Host 专用:两个锁库、`host-endpoint.json`、`host-api-token`、`host-device.json`、`host-background.log`、`platform-power` | 写 | Host 自己的运行状态 | M1 前 | 内嵌的旧桌面不读;`host-api-token` 只有客户端模式的窗口进程读(`host-delegation.ts`) | ## 四、移出 M1 @@ -229,25 +309,122 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | 项 | 移到 | 原因 | |---|---|---| | 供应商分组执行 | M3 | 任务会派到组内其它电脑执行,依赖 Device Link 的准入与转发(`docs/product-rules/provider-groups.md`) | -| 伙伴的会话环境(`resolveSessionEnvironment`)与伙伴工具集 | M3 | 伙伴任务在 M1 继续拒绝。随它一起接:桌面启动钩子在取工作树租约之前补 `createOpts.id ??= sessionId`,只给伙伴工作区运行时(`prepareBotWorkspaceRuntime`)用 | +| 伙伴的会话环境(`resolveSessionEnvironment`)与伙伴工具集 | M3 | 伙伴任务在 M1 继续拒绝。随它一起接:桌面启动钩子在取工作树租约之前补 `createOpts.id ??= sessionId`,只给伙伴工作区运行时(`prepareBotWorkspaceRuntime`)用。放开伙伴任务时要重看 `apps/host/src/desktop-module-setters.ts` 里以此为由的 not-applicable 项(现在是 `initBotAuthorizationService`) | | SkillHub 发现隔离(`scanLocalCustomizations`) | M2 | 只影响 Skill 列表界面,不影响任务运行 | | Pi 包的安装与卸载 | M2 | 界面发起的写操作;运行只需读已安装的包 | | 本地模式下运行任务 | M2 | 要先定本机登录或 API key 的认领方式与模型隔离规则 | | 自动化/定时任务的宿主直发接入 | M3 | main 的宿主直发适配器 `wireHostSession` / `beginHostTurn`(6b04f79d5f)目前没有生产调用方,只有定义、转发和测试。接入时调用方必须在输入被接受的边界补齐 Git 基线开始、改动记录开始(真实 clientId)、复核上下文与输入来源;/learn 只捕获真实、持久的用户输入。本轮不接这些开始侧钩子:只允许本执行器启动过基线/记录的回合结算,直发终态不能取走普通回合的基线或记录 | | 远程附件(OSS、点对点) | M3 | 手机远控的一部分 | +### 用户已定的产品形态(2026-11-17,审核方转问用户) + +以下是用户本人的决定,后续设计直接引用,不再重复问。 + +| 问题 | 用户的决定 | 落到哪里 | +|---|---|---| +| 个人版 Host 是否自带引擎 | **不自带,由 Host 下载**。安装和更新只有一套机制:Host 负责下载和更新,窗口只发起 | 第 34 行:选版本的顺序里没有“自带”这一档(开发版二进制那一档仍保留给开发态);首次没有引擎时由 Host 下载,依赖第 28 行,顺序不变 | +| 窗口连着 Host 时在窗口里退出登录 | **Host 一并退出**:正在跑的回合先停下,之后不再接新任务;不允许出现“界面已退出、后台还在用原账号跑” | 并存设计与第 25 行决定 3:窗口退出登录是要传给 Host 的动作,Host 照现有的作废收口处理(停回合、断凭据)。实现排在哪一阶段另定,预期以此为准 | +| 电脑上已有 Host 在运行时打开桌面版 | **自动连接这个 Host**:桌面变成它的窗口,界面上标明当前连接的是后台 Host | 并存方案 B 的方向。会改桌面的启动行为,属于桌面行为变化,归第一阶段之后的单独桌面 PR 或迁移设计,不进现在的桌面准备分支。方案要答:窗口与 Host 版本不兼容时怎么办(审核方默认:拒绝并提示,不硬连);标识放在哪里。区域不一致时同样拒绝(甲 20 登记,未实现):Host 的 `status --json`(`/health`)报构建区域,桌面比对自己的区域,不一致就拒绝连接并提示,与版本不兼容放在同一处处理;dev 桌面连 cn Host 算同区(甲 20 第 6 项)。B 落地之前:Host 启动时拒绝(方案 A),运行期间定期重扫。**窗口交接要解决的清单**(2026-11-18 实测,第二节“后台服务重启后,已经开着的 Cindy 窗口”):后台服务重启后,已开着的窗口仍钉在旧实例号上——事件流每秒重试、一律 409 `host_instance_changed`(`hostEventStream.ts` 只在 401 时停止);`auth:get-state` 与 `/api/auth/refresh` 也都是 409;IPC 代理有意不换绑实例(`host-ipc-proxy.ts`:“Rebinding is the window's handover”)。不为每秒一次的重试单独改重试策略 | +| Host 安装包怎么发(区域) | 原话:“国内版、国际版各发一个包”(2026-11-17) | Host 发布包的区域与桌面一样在构建期定死(`region-and-editions.md` §2.4):构建必须给区域、只收 cn / global;包的区域与启动时 `CINDY_HOST_REGION` 不同就拒绝启动;国内版桌面配国内版 Host 包、国际版配国际版。实现单元排在 2e 之前(区域常量那一行) | +| 账号区域与版本不一致 | 原话:“我们理论上,不能再国际版查询国内用户的数据,反之亦然”(“再”应为“在”,2026-11-17)。这是数据边界原则,不是对提示方式的选择 | 先只读清点桌面跨区域组织登录与 Host 各类对外请求用的是版本区域还是 `account.realm`,带着事实再问用户具体规则;在那之前不新增拒绝登录的逻辑,个人版 Host 跟随桌面现有登录 | +| Host 的跨区域登录规则 | 原话:“和桌面版一致”(2026-11-17,审核方带着区域数据边界清点去问) | 个人账号只能在本区域版本登录,企业组织账号可以跨区域;Host 直接用桌面的 `canRestoreAuthSessionForMembership`,按包的区域对会话 realm 与账号类型判定(登录时与采用桌面 profile 时都判)。已做(第五节甲 21);包的区域取区域单元的版本区域(`auth/region-policy.ts` 的 `hostPackageRegion`) | +| 桌面现有 5 处跨区发送(D1–D5,见第二节) | 原话:“符合预期,不用处理”(2026-11-17) | 只登记,不改桌面,也不进后面的桌面行为变更 PR;不再重复问 | +| 窗口连着 Host 时,添加账号 / 登录怎么做 | 原话(选项):“窗口照常登录,结果交给 Host(推荐)”(2026-11-17,审核方转问) | 窗口照常走登录界面,登录结果交给 Host,由 Host 写会话、提交 owner、切到新账号;窗口只当界面。审核方在选项里向用户承诺:多出的那一次登录凭证在本机内部的传递单独做安全审查(传什么、经哪个本机接口、怎么鉴权、有效期与一次性、日志不落、失败时窗口不留副本),审查通过前不实现。**安全审查结论(2026-11-17,审核方)**:字面做法(窗口登录后把结果交给 Host)会跨进程传长期凭据,且令牌绑的是窗口的设备,Host 接过去连自己的远程连接身份都起不来,不采用;改为 Host 发出全部会签发令牌的认证调用,界面和操作不变,窗口只转交用户输入的一次性验证码、联系方式和账号选择;已告知用户(用户可否决)。备选做法(浏览器一路窗口只交 code 和 state,其余几路不可用)不采用。方案见第五节“乙:客户端模式下窗口切换、添加账号” | +| 界面文字里能不能出现 “Host” | 原话:“Host 这个词,建议不要展现给用户,不容易理解”(2026-11-18,看了启动失败面板的文案候选后) | 给用户看的界面文字(各语言 i18n 文案、面板、横幅、toast、对话框)不出现 “Host” 一词;代码标识、i18n key 名、日志、文档、放行表、命令名不在此列。命令字面量 `cindy-host login`、`cindy-host status` 作为要照着敲的命令保留,句子里不再用 “Host” 指代它。桌面准备分支随启动失败面板加一条守护:各语言 locale 的值里不出现独立的 “Host” 一词。Host 直接抛给界面的英文报错原文里的 “Host” 并进乙“toast 显示原始报错文本”那条,届时换成有翻译的文案 | +| 指代 Host 的用词 | 用户在选项中选“Cindy 后台服务(推荐)”(2026-11-18,审核方转问) | 中文「Cindy 后台服务」(zh-TW「Cindy 後台服務」),一律写全称、不简写成“后台服务”:主干 zh-CN 的“后台服务”已另有所指(`daemonRunning` / `daemonStopped`、`bashServiceStatus` 指任务里的后台命令),审核方 2026-11-18 撤回了先前允许的简写;英文一律 "the Cindy background service";其它语言照此意思译。主干 zh-CN / zh-TW 的 `hostConnection.*` 原来叫“Cindy 后台”,随启动失败面板那一单统一成“Cindy 后台服务”(改主干已有文案,记入非搬移清单;用户可以改主意)。“重新启动后台服务”在个人版里对应什么操作,仍挂在“含 Host 字样的文案以后要按迁移器定下的用户操作重写”那条乙上 | +| 附件处理失败时怎么发(第五节“后续阶段的桌面事项”第 3 条) | 原话:“好的”(2026-11-18,审核方转问:桌面改成和后台服务一样,整条拒绝不发) | 后台服务已是这样(第二节),不改代码。桌面 `normalizeAttachments.ts` 的静默丢弃改为整条拒绝,进后面的桌面行为变更 PR,不进这次的桌面准备 PR | +| 移动任务时任务正在跑(第 5 条) | 原话:“拒绝移动。”(2026-11-18) | Claude 任务也改成在回合中拒绝移动,和 Pi、Codex 一致。后台服务现在照搬了桌面的行为,两边在后面的桌面行为变更 PR 里一起改 | +| 自动复核、工具循环复核、图片描述这几类模型调用的用量(第 8 条) | 原话:“补寄”(语音识别,应为“补记”,2026-11-18) | 桌面和后台服务都补记这几类调用的用量,进后面的桌面行为变更 PR,两边一起改 | +| 回合中途换账号后迟到的用量(第 9 条) | 原话:“好的”(2026-11-18,审核方转问:桌面改成和后台服务一样) | 按发起这一轮的账号记,账号换了就不记。后台服务已是这样(第二节“回合中途换账号后迟到的用量”),不改代码;桌面进后面的桌面行为变更 PR | +| 静默停止后自动续跑期间崩溃或退出(第 10 条第二处) | 原话:“好的”(2026-11-18,审核方转问:桌面改成和后台服务一样) | 这类任务要进“继续上次中断的任务”。后台服务已是这样(第二节“静默停止续跑期间的回合标记”),不改代码;桌面进后面的桌面行为变更 PR | +| 非 Pi 任务的模型或来源切换失败(第五节“桌面事项:非 Pi 凭据切换失败的提示”) | 原话:“好的”(2026-11-18) | 补上给用户的失败提示,桌面和后台服务都补;提示文案到时给用户选。进后面的桌面行为变更 PR | +| 一条消息把上下文撑爆、后面已排着另一条(第五节“溢出错误时后面已排着输入”) | 用户点选“留一句提示”(2026-11-18 晚,审核方换成例子重新问) | 在撑爆的那条消息下面显示一句话,说明这条因为内容太长没有处理、已继续处理后面的消息;后面那条照常处理。不重发旧消息,#4170 的规则不变。改共用代码的桌面产品行为,桌面和后台服务两边一起改,进后面的桌面行为变更 PR;提示文案到时给用户选 | +| 经旧入口改推理档位、快速模式等四项设置,桌面要不要也改成拒绝(第五节“第一阶段剩余桌面事项”第 2 条) | 用户表示不太理解;审核方 2026-11-18 定:不改(已告知用户对使用没有影响,用户可以否决) | 现在没有任何客户端走这条旧入口,改不改用户都看不到差别。保持现状:桌面不改,后台服务继续拒绝并指明正确入口;以后如果有客户端要走这条入口再议 | + +同一轮由审核方定(非用户问题):个人版 Host 自带一份内置 Skill(问题单第 2 条)。 + ## 五、待办与未完整运行的验证 | 项 | 状态 | |---|---| +| 缺口清单(检查点 3 定,以后以本表为准) | 甲类:Host PR 发布前关闭。乙类:绑定后续阶段,迁移前关闭。来源:检查点 3 正式交付与审核方复核(2026-11-16) | +| 甲:迁移前清点缺批准 receipt 的存量插件(8i) | **已关闭。** 这是安装时间的边界:#1080 的 receipt 模型重新落地于 `5cdef3b886`,桌面一次性补写为 `cd3b170ec1`。仓库发布标签中 v0.1.46 仍在重落地前,首个同时含两者的是 v0.1.48;要识别的是采用旧布局安装且未补写的实例,和插件自己的版本号无关。旧批准依据是安装目录里的 `ghost.json`、可能有的 `.cindy-trust.json` 与 `.disabled`,缺 Host 独立状态根 `ghost-install-state` 中对应的 `<安装相对键>.json` 批准 receipt。`GhostInstallReceiptStore.read/readAsync` 将缺失投影为 `legacy-unapproved`,损坏另标 `invalid`。这个状态也可能是新安装批准被移除,单靠缺文件不能断定可迁;桌面共用迁移仍受全局一次性台账及已钉住的待迁清单约束。Host 复用当前 owner 启动时的 `GhostManager.listAsync()` 投影,记录缺 receipt 的旧布局安装数量和标识;本机 bearer 的 `cindy-host status [--json]` 同样可见。报告不补写 receipt,也不改旧安装文件。可列出、不可运行:`enabled:false`,不唤醒实例或投递 hook;旧任务的运行时控制沿原 onFailure 处理,插件工具命中实例时回 `GHOST_ASLEEP`。正式接管前按 S8 运行 `cindy-host migration-preflight `,读取未归属及所有 owner 的旧布局,退出码为 0 且数量为 0 才继续。非零先由 v0.1.48 或更新的桌面内嵌模式走原一次性补写,退出后再复查。清点失败或仍非零时停止交接。临时 profile 测试覆盖阻断、用桌面原路径补写后放行、报告和 CLI 状态的权限。这道门槛对任何一次接管已有 profile 都适用,不只是 Debian A1:个人版迁移的步骤清单写出来时,这一步必须列在启动后台服务接管之前(审核方 2026-11-18)。 | +| 乙:Host 自行补齐旧布局插件批准 | 接入桌面同一份一次性补写和既有台账约束,由 Host 只在持有对应 profile 与 owner 写入权时执行。验证原已装已启用插件无需重装或重新批准。具备同等恢复后去掉迁移前的零值门槛。 | +| 甲 1:只改推理档位、快速模式 | 已关闭(检查点 3b-1 专用入口,甲 8 收掉旧路径):两个处理函数体搬成共用(`sessionRuntimeAxisSettings.ts`),Host 的 `/api/sessions/set-effort`、`set-fast-mode` 跑同一份;有用户待定意图时并入意图,与桌面相同。经 `/sessions/update` 写 `effort`、`fastMode` 的旧路径已改为拒绝(甲 8) | +| 甲 2:思考开关 | 已关闭(检查点 3b-1):共用的处理函数体,Host 入口 `/api/sessions/set-thinking-enabled`,复核任务先被拒 | +| 甲 3:任务窗口预算 | 已关闭(检查点 3b-2)。事实:桌面界面改预算不走预算 IPC,而是 `sessionService.update({ contextWindowBudget })`(`ContextWindowBudgetChip.tsx`),即 `local-db:sessions:update` → `updateSessionInDb`;`maker:set-context-window-budget` 只有 device-link 远程任务经隧道调。网页端在 Host 上改预算一直失败:`/sessions/update` 白名单从来没有这个字段(甲 8 之前普通错误 500,之后 INVALID_PARAMS),界面弹“保存失败”。这次接上:Host 的 `/sessions/update` 接收 `contextWindowBudget`,先跑桌面同一份范围校验(`assertSessionContextWindowBudgetPatch`,从 `updateSessionInDb` 原样抽出,INVALID_PARAMS 与原文相同),带预算时先查任务行、不存在报 NOT_FOUND,再经 `persistSessionFieldsWith`(带应用钩子)写偏好文件、广播、交给运行时;只带预算不写任务行(不动 updatedAt),与桌面相同;混合补丁里预算写不进时只降级不抛,纯预算请求要抛。应用钩子与发送前重放是桌面原样搬出的 `createSessionContextWindowBudgetReconcile`,两张表在 `sessionContextWindowBudgetState.ts`;Host 的发送钩子在落定与改名恢复之后重放欠下的预算重建(第 4 步),运行时关闭时清两张表里这个任务的条目(照桌面 `cleanupClosedSessionRuntime`)。测试:桌面 `sessionsUpdate.test.ts`(两条写入路径的对照)、`sessionContextWindowBudgetReconcile.test.ts`;Host `session-update.test.mjs`(写偏好不写行;空闲活实例为新预算重建;四种越界值;任务不存在;偏好文件不可读时纯预算失败、混合只保留标题;重启在等时预算存下不报错、下次启动读到新预算)、`input-queue.test.mjs`(发送前重放;关闭清表) | +| 甲 4:上下文占用的推送 | 写库已做(第 36 行),推送端口为空 | +| 甲 5:工作目录修改 | 已关闭(甲 5,审核方定方案 A)。事实:桌面界面有入口——侧栏任务菜单与标题栏“移到项目”发 `{ workingDir, workspaceKind:'project' }`,“移到对话”只发 `{ workspaceKind:'dialogue' }`,输入框选文件夹发 `{ workingDir }`,都经 `local-db:sessions:update` → `updateSessionInDb`;网页端在 Host 上一直是 INVALID_PARAMS(“移动失败”,选文件夹不生效)。这次:`updateSessionInDb` 里移动相关的 7 段不连续代码逐行原样搬到不加载 Electron 的 `localDb/ipc/sessionWorkingDirMove.ts`(每段一个函数、各在原位置调用,局部状态经参数与返回值传:`p` 就地改写后原对象广播,`beforeMove` 跨 await;`readSessionWorktreeResources` 一起搬),放回原处与原文逐行一致(缩进除外,比对脚本 PASS)。Host 的 `/sessions/update` 放行 `workingDir`、`workspaceKind`,按桌面顺序调这几段(`agent/session-update.ts`):整段在路由锁与 worktree 变更锁里(Host 入口本就持发送锁,段内取锁是同链重入),workspaceKind 校验、目录规范化、复核任务检查(对整个补丁)、worktree 归属守卫与关闭空闲 Pi/Codex 运行时、Claude 转录迁移、最近项目;移动字段经共用 mapper 写行(移到项目或对话时清掉显式项目),发出的补丁是段内就地改写过的那个,带 `projectDir`。端口(`agent/session-move.ts`):worktree 归属只读 profile 根目录里桌面的 `worktrees.json`(见第三节),文件不存在等于没有绑定,读不懂一律拒绝移动;空闲运行时经执行器自己的 `closeRuntime` 关闭(压住重建,照桌面);Claude 的活实例桥(`setLiveCcSessionBridge`,桌面在 `register.ts` 注入,清点时漏列)由 Host 在 `main.ts` 注入,关闭交给 Maker 本身——Maker 关闭时先给未完的回合发终态再清监听,执行器那一轮因此能结束(测试钉住;若经执行器的 `closeRuntime` 先解绑,那一轮会一直“运行中”);最近项目的推送经 `plugin_push` 频道 `local-db:recent-workdirs:changed`,网页端 shim 与桌面客户端模式的转发白名单都加了这个频道。Host 没有 MCP 移动工具,`moveGuard` 写 undefined。顺带关闭:复核任务改窗口预算,桌面拒绝、Host 原来照写,现在同样 UNSUPPORTED_CAPABILITY。有意的行为变化:`/sessions/update` 带 `workingDir` 不再报 INVALID_PARAMS(`session-update.test.mjs` 原“未知字段”那条断言改为只点名 `colour`)。测试:Host `session-update.test.mjs`(空闲 Codex 移动;Claude 转录迁移与就地改写的 resume id;锁重入与另一持锁者等待;worktree 登记表六种状态;回合中与收尾中拒绝;复核任务拒绝移动与预算)、`input-queue.test.mjs`(关闭后下一次发送在新目录新建运行时;回合中移动 Claude 任务,执行器那一轮结束)。与桌面不同见第二节两条“移动任务:…” | +| 甲 7:权限、计划模式 | 已关闭(检查点 3b,甲 7):桌面 `commitSessionPermissionMode`、`SET_PERMISSION_MODE` 与 `SET_PLAN_MODE` 发送方检查之后的部分、Agent 自己切计划模式后的写库(`emitWiredSessionEvent` 的 `plan_mode_changed`)原样搬进 `sessionPermissionSettings.ts`,伙伴分道同步搬成 `botPermissionSyncCore.ts`(两个端口:Maker、广播)。Host 新增 `/api/sessions/set-permission-mode`、`set-plan-mode`,跑同一份:按任务串行(伙伴权限、任务权限两道队列)、每步核对账号、拦复核任务、读不到任务报 NOT_FOUND、无效档位报 INVALID_PARAMS(不碰运行时)、写库失败回滚运行时、档位真变化时撤销分享供应商的“本任务总是允许”(`forgetCredentialGrants` 是同一个进程内存储;Host 上任务回退的授权登记在这里,所以必须是真函数),伙伴分道的任务行、授权和广播跟着变。两个入口不套任务的发送锁(与桌面相同:先权限队列、后发送锁)。Host 的新输入入口(`/api/input/enqueue`、`/api/chat`,`agent/user-input.ts`)先等权限队列、等完核对账号,与桌面 `maker:send`、`INPUT_ENQUEUE` 相同;队列自己的下一条、上下文恢复的重放不等。执行器在事件分流处接住 `plan_mode_changed`(`turn-executor.mjs`),只写库并广播任务的 patch,不再当回合事件转发,与桌面相同。网页端 `setPermissionMode`、`setPlanMode` 改调新入口,原样传参(空任务号现在和桌面一样报 INVALID_PARAMS,原来是静默返回)。`/sessions/update` 里 `permissionMode`、`planModeEnabled` 的旧路径已由甲 8 改为拒绝。测试:Host `input-queue.test.mjs`(生效到运行时、任务行与客户端;无效档位不碰运行时;写库失败回滚、无任务 NOT_FOUND、复核任务拒绝;真变化才撤销授权,计划模式同样;同任务两次改档按序;新输入等改档、换账号拒收;队列下一条与恢复重放不等;计划模式生效,Agent 自切写库,旧值、换了运行时、换了账号三种不写;伙伴分道跟着变)、`server.test.mjs`(两个路由的参数);桌面 `pluginWriteAccess.test.ts`(放回原位后截取执行,重建文本与搬移前逐字相同)、`sessionPermissionPersistence.test.ts` | +| 甲 8:`/sessions/update` 的旧路径 | 已关闭(甲 8,审核方定“拒绝”):`agent/session-update.ts` 先校验、整体拒绝,校验在读库、`setModel`、动运行时之前。`effort`、`fastMode`、`permissionMode`、`planModeEnabled` 报 UNSUPPORTED_CAPABILITY,信息写明专用入口(`/api/sessions/set-effort (maker:set-effort)` 等,照桌面 `updateSessionInDb` 拒目录授权的写法);白名单外的字段(含原来白名单里的 `agentKind`)报 INVALID_PARAMS 并列出字段名(原来是普通错误,HTTP 500);混合补丁什么都不写、不登记选模型意图。网页端移动任务带的 `workingDir`、`workspaceKind` 原来就不在白名单里,回答从 500 变成 INVALID_PARAMS(400),功能本身仍归甲 5。这几项原来对运行中的 Agent 的直接应用(`applyLiveSessionSettings`)随之从这条入口去掉,`getLiveSession` 依赖删除。不选转发:没有调用方(网页端、e2e、Host 内部都不经这条入口发这些字段),转发要在路由锁外先提交,前面生效、后面失败无法回滚。与桌面的差别见第二节“`local-db:sessions:update` 上的运行时设置”。`model` / `providerId` 照旧走 set-model:渲染层“切到 Claude 订阅”(`CCAgentSessionView` `handleSwitchToClaudeSubscription`)只在 set-model 答 applied 时才调 `sessionService.update({ model, providerId })`;Host 的 set-model 固定 `source: 'user'`,本机任务只答 pendingUntilSend、superseded 或报错(远程执行报 UNSUPPORTED_CAPABILITY),渲染层的 `setModelWithWindowConfirmation` 得到 `'pending'`,这次写入在 Host 上走不到。测试:`session-update.test.mjs`(四个字段各被拒、指明入口、运行时任务行广播都不变;待定选模型时用 effort 被拒、意图不变;`agentKind` 与未知字段 INVALID_PARAMS 带字段名;混合补丁整体拒绝、不登记意图、不先读库;订阅切换在回合内外都答 `'pending'`)。主干新增的任务延后(`snoozedUntil`):Host 的更新入口已接(2026-11-19),照桌面校验日期,经桌面同一个映射函数写 `snoozed_until`、`snoozed_at`,归档和恢复时清空,推送带实际值;到点没有后台唤醒,由桌面和手机列表的定时器重新分组(第七节第 43 项) | +| 甲 6:本机 Agent 接管 | **已关闭(并入第 29 行,2026-11-18 定)**。桌面的接管:本机别的应用经本机 Agent 服务(`local-agent/`)打开对用户可见的 Cindy 任务时,`local-agent/runtime.ts:423` 的 `registerLocalAgentVisibleRuntime` 在 `local-agent/visibleSessions.ts` 登记一个外部运行时;用户在 Cindy 里对这个任务发输入、改设置或换引擎之前,桌面调 `takeOverLocalAgentVisibleSession` 关掉它,由 Cindy 自己的管线接着跑(只打开、查看任务不算)。桌面的四个调用点:`register.ts:8380`(输入准入 `assertReviewExternalInputAllowed`)、`:8387`(设置 `assertReviewSettingsUnlocked`)、`:11584`(换引擎 `pendingAgentSwitchApplyHolder`)、`:17774`(发送事务的 `prepareExternalInput`)。Host 上对应的四个入口:`agent/runtime-selection.ts` 的 `assertReviewSettingsUnlocked`、输入准入(`agent/turn-executor.mjs` 的 `readExecutionSession`)、换引擎(`agent/runtime-selection.ts` 的 `applyPendingAgentSwitch`)、发送事务的 `prepareExternalInput` 端口(`agent/turn-executor.mjs` 的 `transactionDeps`,现在没传)。关闭理由:Host 没有本机 Agent 服务(第 29 行),没有任何代码会登记外部运行时,现在接上只是空操作,测试也只能测接线本身,测不出用户能看到的结果;对用户没有可见后果(Host 上不会出现外部应用与 Cindy 同时驱动一个任务)。接管随本机 Agent 服务一起接 | +| 重启后被打断的回合(检查点 4 设计时核对,2026-11-17) | **桌面**:应用退出或崩溃打断回合后,重新启动**不自动续跑**。回合开始时记 startedAt、结束时记 endedAt(`localDb/sessionActiveTurn.ts`);启动后把“startedAt > endedAt 且早于本进程启动”的任务认作疑似中断(`listInterruptedPendingRows`,bootAt 在模块加载时定格),给红点(`local-db:sessions:interrupted-pending`,`localDb/ipc/sessions.ts:1327`)和启动弹窗“继续上次中断的任务”(`InterruptedTasksResumeDialog.tsx`,默认全选,用户点继续才对每个任务发 `CONTINUE_AFTER_APP_EXIT_PROMPT`;不点就什么都不写,任务里的“继续任务”横幅照常保留)。定时任务被打断时,继续走 `resumeInterruptedScheduleRun`(`register.ts` `INPUT_ENQUEUE` 约 20569)。**Host**:两个查询入口已有(`/api/sessions/interrupted-pending`、`/api/sessions/interrupted-candidates`,经 hostChannelContract 映射给窗口),Host 发送时记开始、排空后记结束,`main.ts` 启动时就加载这个模块,所以“早于本进程启动”指早于 Host 进程启动。Host 重启后,原来在跑的回合同样显示为疑似中断,窗口弹窗经 Host 拿到它们,点继续经 `/api/input/enqueue` 发到 Host。与桌面的差别:候选不含伙伴任务(Host 不跑伙伴);“正在做什么”给的是工具名原文,桌面是本地化文案;Host 的入队没有定时任务那条特殊处理(`resumeInterruptedScheduleRun`),待核对是否影响 Host 上的定时任务。**范围**:检查点 4 的中断续跑处理的是运行中进程里上游出错的回合,不处理重启,重启这一块不在检查点 4。**和“升级不中断任务”的关系**:现在 Host 升级就是 Host 重启,升级那一刻正在跑的回合会中断,要用户在弹窗里一键继续,与桌面今天退出时相同;真正不中断需要升级流程本身(先排空或交接再重启),不在第一阶段。主干同步 6(2026-11-19)复查:桌面真退出先冻结回合标记并调 `prepareForAppQuit`,异步拆除时为未结算的 Claude 合成 `cancelled` done,并带上已有的可用量(`bootstrap-electron.ts`、`maker.ts`、`session.ts`);Pi、Codex 沿用自身的终态。Host 经有序停止保留中断标记,队列关会话后才无参数调用 Maker shutdown,不合成这条 Claude 退出帧。此差异本轮只登记,重启后仍由用户决定是否继续。 | +| 甲 17:新建与启动运行时的停用路线准入 | 已关闭(2026-11-17)。桌面在共用的 `bootstrapSession`(`register.ts:8785`,同文件 12 处直接调用,按准备分支 `43a545067c`:新建、发送时懒启动、恢复、换引擎等所有启动路径)里裁决,不只在 `maker:create-session` 处理器里:闭包 `admitLocalRoute`(`register.ts` 8956–9000,主干 9183–9227)在 Agent 在本机时调一次(9001,主干 9228),供应商组换回本机时再调一次(9114,主干 9341)。不是“经核实的原样续接”就过 `assertModelRouteUsable`,隐式来源的原生默认落点被停用而有启用的替代拷贝时显式改路由过去(`shouldApplyExclusiveProviderRerouteLive`);经核实的续接走 `pinExclusiveSessionProvider`(`model-route-guard-live.ts:135`)。桌面准备:闭包原样搬成共用工厂 `createLocalRouteAdmission`(`maker-ipc/localRouteAdmission.ts`,四个端口:本机模型服务就绪、profile 目录、路线裁决、独占来源钉死),`pinExclusiveSessionProvider` 拆出 `pinExclusiveSessionProviderWithProviders`(`model-route-guard-catalog.ts`,带列供应商参数,同 `verdictForModelRoute` 的做法);桌面两处调用不变,行为不变。Host:准入在 `runtime-selection.ts` 组装(路线裁决与供应商列表用 Host 已绑的那一份),三条启动路径都在 `maker.createSession` 之前调用——发送时启动(执行器的 bootstrap 端口:先把续接用的 `resumeSessionId` 算出来再准入,改路由在 `prepareStartOptions` 冻结来源之前定下)、插件页的任务恢复(执行器的 `restoreSession`,对应桌面 `register.ts:18359`)、device-link 新建(`agent/create-runtime-session.ts`,函数体从 `main.ts` 原样挪出;准入在写任务行之前,被拒不留任务行,改路由的来源写进同一次插入)。发送时启动与恢复两条在启动成功后与桌面一样经共用的 `persistAndHydrateSessionProvider`(对应 `register.ts:9125`)把启动时的来源写回任务行,写失败就关掉刚起的运行时并拒绝这次启动;不写回时,改路由只留在内存,下次续接会回到被停用的默认拷贝,正在运行的任务下一条消息也会被设回旧来源。第二次调用不接:Host 的启动端口没有启动失败后换电脑的循环(没有 `applyProviderGroupAssignment`、`nextAfterStartFailure`),供应商组在读任务行、发送与恢复时都被拒(`assertProviderExecutionSupported`)。Host 没有托管本机模型服务:Claude、Codex 任务走托管 Ollama 或 llama.cpp 时,启动时按桌面“未就绪”的文案被拒(`hostManagedLocalModelNotReady`),与桌面服务未就绪时相同。测试:Host `input-queue.test.mjs`“route admission: …”五条(被停用的拷贝在发送、恢复、device-link 新建时被拒且不起运行时、不留任务行;经核实的续接照常启动;改路由先于冻结、写回任务行、运行中与续接都保持),改坏都会红。“先算 `resumeSessionId`”这一步本身改坏不会红:现有调用方都已从任务行带上 `resumeSessionId`(共用的选项对账、冷启动 Pi 核实、换引擎、`storedSessionOptions`),执行器的兜底取不到不同的值。device-link 新建原来不拒供应商组任务(`main.ts:1743` 只查 `remoteHostId`、`agentDeviceId`、`orcaRole`,不调 `assertProviderExecutionSupported`),审核方定为甲类,已关闭(2026-11-17):这一检查从 `main.ts` 原样挪到 `send-preflight.ts` 的 `createHostProviderExecutionCheck`,发送路径(`readExecutionSession`)与 device-link 新建(`agent/create-runtime-session.ts`,在准入与写任务行之前)用同一个;测试 `input-queue.test.mjs`“Device Link create: a provider group task is refused with no task row and no runtime”(带类型地拒绝 `[UNSUPPORTED_CAPABILITY]`、不起运行时、不留任务行;去掉这一行会红) | +| 甲 18:`/sessions/update` 的 updatedAt | 已关闭(甲 18,审核方定甲类)。事实:桌面只改设置的补丁(标题、置顶、静音、移动、模型等,`SETTINGS_ONLY_FIELDS`)不写 updatedAt,带状态等活动字段才写(侧栏按它排序);Host 原来每次都写,在 Host 上改名、置顶、静音、移动会把任务排到前面。这次:判定从 `updateSessionInDb` 逐行原样搬到不加载 Electron 的 `localDb/sessionSettingsOnlyPatch.ts`(`isSessionSettingsOnlyPatch`,原位置调用,比对脚本 PASS);Host 的 `/sessions/update` 在同一位置调它,只改设置时不写 updatedAt,没有要写的列就不写(照 `writeSessionPatch`;只改模型时行不动,模型是待切意图)。测试:Host `session-update.test.mjs`“updatedAt: settings-only patches leave it, a status change moves it”(标题、置顶、静音、移动不动,归档会动)。桌面原有测试没有覆盖这张表里的某一项(去掉 `title` 桌面测试仍全绿),Host 这条会红 | +| 甲 19:Host 发送不记最近项目 | 已关闭(甲 19,审核方定甲类,与甲 18 同一单元)。事实:桌面 `touchUserSendInDb` 发送时把任务所在的项目写进最近项目(保留真实使用时间)并广播;Host 的 `touchUserSend` 只改行、发 `session_changed`。这次:那一段从 `touchUserSendInDb` 逐行原样搬到 `localDb/ipc/touchUserSendRecentWorkdir.ts`(`recordRecentWorkdirForSend`,原位置调用,比对脚本 PASS);Host 的 `touchUserSend` 改为 `agent/touch-user-send.ts`,同一次改行、owner 没变时发 `session_changed`,再调这一段,写入入口的数据库,owner 没变时经最近项目推送(与甲 5 同一个 `plugin_push` 频道)发出。改行没生效(同一时间戳或更早)时什么都不做,与桌面相同。测试:Host `session-update.test.mjs`“send: …”(写入并推送;同一时间戳不再推送;发送途中换了 owner 不推送、行照写) | +| 甲 20:区域常量与按区域发包 | 已关闭(审核方 2026-11-17 定甲类,排在 2e 之前;用户定“国内版、国际版各发一个包”,见第四节)。事实:桌面的区域常量 `CURRENT_CINDY_REGION`(`shared/brandRegion.ts`,读 `import.meta.env?.VITE_CINDY_AUTH_REGION`)在桌面构建时写死;Host 源码方式与发布包都不替换 `import.meta.env`,它在 Host 上永远是 global。主进程与 shared 里引用它的一共 46 个文件,Host 导入图里 6 个(2026-11-17 只读清点,导入图用 `build.mjs` 原样的依赖插件跑 esbuild metafile),用户看得见的差别 4 处,见第二节“区域(甲 20)”。合并 host-m1(`bc8feaf471`)之后又进来一个:报价工厂 `usage/modelPricingCore.ts`(`agent/usage-pricing.ts` 引入)用区域拼报价缓存的作用域(3a,作用域里还带 Model Access 地址与账号),现在 7 个;它跟着包的区域走,与同区域桌面写的作用域一致,用户看不出差别。这次(不改桌面代码):1. 发布构建:`scripts/build.mjs` 必须给 `--region cn|global`(`release-region.mjs` `selectReleaseRegion`),不给或给别的值时在写任何输出之前失败,照桌面带版本打包必须给区域(`region-and-editions.md` §2.2 的 fail-closed 例外);`define` 把桌面模块的 `import.meta.env.VITE_CINDY_AUTH_REGION` 写成字面量;`__CINDY_HOST_RELEASE__` 与 `release.json` 带 `region`;`cindy-host status --json` 报 `region`(`control.mjs`,取自已授权的 `/health`)。2. 网页界面:渲染层构建没有专门的区域标记,但 `brandRegion.ts` 的可选访问让 Vite 内联整个 env 对象,每份构建都带一个 `VITE_CINDY_AUTH_REGION:"<区域>"`;打包时读它(`assertWebRegion`),读不到、不止一个或不是本区域都拒绝。协议域名当不了标记:两个区域的构建里 cindy.cn 与 cindy.app 两套链接都在,运行时二选一。3. 源码方式:`loaders/raw-hook.mjs` 给桌面模块加同一个 define,读 `process.env.CINDY_HOST_REGION`,不设为 global,只用于开发。Host 测试命令(`apps/host/package.json` 的 `test`,CI 跑的就是它)先加载 `loaders/test-region.mjs`,清掉 `CINDY_HOST_REGION` 与 `VITE_CINDY_AUTH_REGION`;测 cn 的用例给自己的子进程显式传。4. 两个来源合一:`resolveHostRegion()`(`profile-path.mjs`)在发布包里返回构建区域;启动时设了 `CINDY_HOST_REGION` 而且不同,所有命令在读 profile 之前拒绝(`HOST_REGION_MISMATCH`,`main.ts`),不静默忽略。`account.realm` 不变,只管登录与端点。systemd 单元里的 `CINDY_HOST_REGION=global` 改成注释,`docs/host/systemd.md` 写明。5. 桌面 profile 里没有可靠的版本区域标记:只有默认目录名(`Cindy`、`CindyGlobal`、`CindyDev`,`regionUserData.ts`),`--user-data-dir`、`XDT_USER_DATA_DIR` 与隔离 profile 都会改它;端点清单缓存(`endpoint-manifest-cache*.json`)是可选缓存,跨区登录时两区都写,也不能当标记。所以 Host 启动时不核对 profile。迁移器与客户端模式的两层防错见乙 7 与第四节“自动连接 Host”那一行。6. dev:Host 导入图里的读取方,dev 与 cn 有两处不同:语音默认语言(dev 为自动,cn 为 zh-CN,`voiceInputData.ts`)、续接时找旧品牌 `xdt-maker` 的 Codex 目录(dev 不找,`codexLocalSessionsCore.ts`);目录投影与零金额币种相同。审核方定(2026-11-17):dev 桌面配 cn 的 Host 包,Host(发布包与源码方式)只收 cn / global,不为 dev 开第三个值。依据:`region-and-editions.md` §1.1,dev 是内部开发构建身份,不是发行版本,行为归 cn 系。因此 dev 桌面连 cn Host 时这两处按 cn 走(语音默认 zh-CN、会找 xdt-maker 目录),与 dev 桌面自己不同,接受。将来客户端连接比对区域时,dev 桌面连 cn Host 算同区。7. 守护:Host 导入图里读区域的文件(含读 `CURRENT_APP_ID` 与直接读 env 的写法,现在 7 个)与 Host 自己的区域兜底三元式(`main.ts` 的 `startDeviceLink`、`disableShareAvailability`:`account.realm === 'cn' ? 'cn' : 'global'`,按现在的启动顺序走不到,审核方 2026-11-17 定单独登记)登记在 `apps/host/src/desktop-region-readers.ts`,由 `hostDesktopSourceContracts.guard.test.ts` 用模块级设置函数守护的同一张导入图(`hostImportGraph`,构建一次两处共用)收集:新读取方不登记就红,登记了却不再读也红;清点里那些暂不在导入图里的文件,进图时由它拦下逐个判断;兜底写法移到别的函数也会被拦下重判。登记理由同设置函数表,不写“文件:行号”。测试:Host `release-region.test.mjs`(源码方式子进程:cn 下 XD 嵌入模型为 0、零金额 CNY、语音默认 zh-CN,未设时 7 个、USD、自动;不给或给 dev 区域时构建在写输出前失败;渲染层区域核对四种情况)、`profile-path.test.mjs`(发布包返回构建区域、环境变量冲突时拒绝);打包后验收 `scripts/release-region.e2e.mjs`(两个区域各一个发布包:`release.json`、`status --json` 与打进包的渲染层都是本区域,网页端启动值里的语音默认语言,`CINDY_HOST_REGION` 冲突时 `serve` 拒绝且不发布端点)。发布前在 Ubuntu 与 Windows 上跑构建与这条验收(第五节“发布前条件”) | +| 甲 21:跨区域登录与网页端统计(H-1、H-2、甲-1) | 已关闭(2026-11-17,用户定“和桌面版一致”,见第四节)。判定一律用桌面的 `canRestoreAuthSessionForMembership`(`authRealmPolicy.ts`,组织账号放行,个人账号只在会话 realm 等于包的区域时放行),Host 侧只有 `auth/region-policy.ts`:`hostPackageRegion()` 是包的区域的唯一取值点,取区域单元的版本区域(甲 20 的 `resolveHostRegion()`:发布包是构建时定的区域,`CINDY_HOST_REGION` 写了另一个区域就拒绝启动;源码方式取 `CINDY_HOST_REGION`,没设按 global),`assertHostSessionRegion` 不放行时抛 `HOST_CROSS_REGION_PERSONAL_ACCOUNT`,信息写明会话与包各是哪个区域、个人账号只能登录本区域的 Host、组织账号可以跨区,不带账号 id。**H-1**:`runHostLogin` 在授权码换得会话之后、写凭据之前判定(账号类型要等这一步才知道),不放行就不保存会话;`login-cli.mjs` 传 `hostPackageRegion()`。换会话的那次请求已发往账号自己区域的认证服务;签发的会话不保存,并用刚拿到的 access token 经同一个认证客户端调一次登出,只发往账号所属区域、不发往包的区域,最多等 5 秒,失败只记一句不带 token 与账号标识的提示,不影响拒绝与退出码(审核方 2026-11-17 同意。桌面没有这条路径,Host 新增,仅为不留无人持有的会话)。**H-2**:`main.ts` 的 `resolveAccountUser`(启动采用、`ensureRuntime`、定期与按需刷新都走它)在刷新与 `me` 之后、发布身份之前判定,与桌面冷启动和运行中刷新相同:刷新后的新 token 照常写回它所属区域的那份记录,但这个身份不采用,按未登录处理(启动时不开账号库,状态写明原因);运行中刷新遇到时与会话失效同样收口(`invalidateHostSession`,不删记录;未单测,与启动采用走同一判定 `resolveAccountUser`);被拒时把 `account.realm` 清空,之后取端点回到包的区域(照桌面 `resetActiveAuthRealmToBuild`)。**甲-1**:网页端渲染层是预先构建的桌面渲染层,TapDB 采集端在那次构建时定死,Host 不知道它是哪个区域;所以拦在出口:`apps/web/analytics-region-guard.js`(网页端 shim 加载时安装,Host 的网页端,不是桌面代码)对 XMLHttpRequest、`navigator.sendBeacon`、图片像素和 fetch,凡是发往 TapDB 采集端(取自桌面 `shared/endpoints.ts` 的 `TAPDB_EVENT_URL_BY_REGION`)的请求,只有采集端属于已登录账号的区域时才放出;没登录或区域未知时全部拦下,其他请求不动。账号区域经 `bootValues.auth.realm`、事件流开头那次 `/api/auth/state` 读取与 `auth_changed` 事件带给 shim,只在已登录时取(退出登录后的状态仍带着记录里的 realm,不能沿用)。shim 构建(`web-client-build.mjs` 与 `build.mjs`)给 `shared/endpoints.ts` 里另两个 Vite 构建值定义为空(`WEB_SHIM_DEFINE`),否则浏览器里加载即抛错。与第二节 D5 的区别:D5 是桌面现有行为,用户定了不动;甲-1 是 Host 网页端新出现的上报入口,不新增跨区上报。测试:`auth/login.loopback.test.mjs`“login follows the Desktop rule…”(真实认证客户端对两个本机假认证服务:个人跨区被拒且不保存、组织跨区放行、同区照常,请求只到账号自己的区域);`startup-account.test.mjs`“an adopted cross-region personal session stays signed out…”(桌面写法的会话记录,跑 `main.ts` 的 `ensureRuntime` 与 `resolveAccountUser`:跨区个人会话不开库、不采用、记录按原区域写回、`account.realm` 清空;跨区组织会话照常);`auth/login.loopback.test.mjs` 另两条:被拒时账号区域那台假认证服务收到一次登出、另一台什么都没收到,登出失败或不回应时照样拒绝;cn 发布包(子进程,带构建期的发布常量)在 `CINDY_HOST_REGION` 没设时按 cn 判定;`web-shim.test.mjs`“Host web usage statistics leave only for the signed-in account region”(真实 shim 加真实 TapDB SDK,页面自己的 XHR、beacon、像素当假采集端:一致时发出,不一致、没登录或开页后退出登录时一条都不发,其他地址不受影响);改坏都会红 | +| 甲 22:Host 恢复的任务记下恢复时间(审核方 2026-11-17 定甲类) | 已关闭(本提交)。桌面的任务管理在恢复前经 `setSessionRestoreObserver` 记下恢复时间(owner 目录的 `task-management.json` 里的 `restoredAt`),空闲自动归档在保留天数内不选它(`eligibility.ts` 的 `restored`)。Host 原来不装这个观察者。**Host 模式下谁在跑自动归档**:没有人。Host 不加载桌面的任务管理,自己不跑空闲归档;客户端模式下窗口进程不开库(`localDb/index.ts` 的 `ensureReady` 在客户端模式直接返回),它的归档引擎拿不到库,也不跑。所以缺这一项的实际后果是:之后桌面自己打开同一份数据(非客户端模式)时,会立刻把在 Host 上恢复过的、很久没动的任务再归档掉。改法:观察者的函数体原样搬成共用 `task-management/restoreObserver.ts` 的 `recordTaskArchiveRestores`,桌面 `service.ts` 原处只装它;Host 的 `agent/task-restore.ts` 的 `bindTaskRestoreRetention` 装同一个函数,`main.ts` 在建恢复入口之前调用。测试 `session-update.test.mjs`“restore: both routes record the restore, so later idle archiving keeps the task”:任务列表与发送两条恢复路径都记下时间,桌面自己的保留期判定对这条久未使用的行给出 `restored`,同一行没有记录时会被归档。不等 Host 上并不存在的自动归档 | +| 甲 23:Host 的后台文案跟随语言(审核方 2026-11-17 定甲类) | 已关闭(本提交)。桌面 `bootstrap-electron.ts` 经 `configureUiText` 装主进程的语言表,后台服务直接给用户看的文案(数据库启动失败的提示、插件 MCP app 的历史标题)跟随语言;Host 原来不装,一律是英文兜底,而数据库启动失败正是用户最需要看懂的一句。Host 的 `ui-text.ts` 的 `bindHostUiText` 照桌面绑法装 `createMainI18n`(语言取进程的系统语言,与 Host 其它主进程文案相同,见第二节“Pi 提示与对话框的语言”),`main.ts` 在开 owner 数据库之前调用。测试 `apps/host/src/ui-text.test.mjs`:没绑时是英文兜底,系统语言为 zh-CN 时数据库占用的标题是中文 | +| 甲 24:任务的 PR 关联写入(审核方 2026-11-17 定甲类) | 已关闭(本提交)。桌面在写消息、改正与撤回助手回复、无原行的 user/assistant 更新之后记录或重算 `session_pr_refs`;Host 只在清除后的恢复里重算,Host 跑的任务里提到的 PR 不进库。对齐:桌面这几段原样搬进共用的 `localDb/messagePrRefs.ts`(桌面提交 refactor(desktop): move the message PR reference hooks into a shared module,见下方“桌面准备 PR 里的非搬移提交”),Host 的写消息、改正、撤回三处调同一份代码。测试:Host `sessions.test.mjs`“Host message writes record task PR references as the desktop does, only into the writing owner”(与桌面 `createMessage` 的两步 `writeMessageRow`、`trackMessagePrRefs` 结果相同;写完立即切换 owner,新 owner 里没有记录)、“Host reply corrections and retractions recompute task PR references as the desktop does”。窗口的读写通道与推送另列乙 13 | +| 甲 25:改正回复后释放不再显示的图片(审核方 2026-11-17 发现、定甲类,与甲 24 同一族) | 已关闭(本提交)。桌面 `updateMessageContent` 改正最终回复时对原行调 `reconcileAssistantDerivedState`:除了重算 PR 关联,还对原内容里的每张图调 `removeSessionAttachmentRefIfUnreferencedByLiveMessage`(`reconcileAssistantMediaRefs`),已没有在用消息引用的图从任务名下摘掉。Host 的 `agent/event-persistence.ts` `updateDbMessageContent` 有原行时原来只查原行的 id、只提交新内容的挂账,被改正去掉的图一直挂在任务名下,占空间直到任务删除,不丢数据;撤回那一支原本就清。对齐:取原行整行,改正写入之后(回读不到行时也一样)先逐张释放、再重算 PR 关联,单张失败记 warn 不影响其余(与桌面同一句日志)。与桌面的差别:桌面这一步不等待(先等这一行未完成的挂账写入),Host 在写入队列里等它做完,因为 Host 的挂账在写消息时已经同步提交、没有未完成的写入可等。测试:Host `sessions.test.mjs`“a Host reply correction releases the images it no longer shows, as the desktop does” | +| 事件清点(甲 7 交付,2026-11-16) | 桌面在事件上写任务行、偏好或进程内状态的地方,与 Host 执行器逐个对照(只读核对,native subagent 做、审核方确认归类)。下面甲 9–甲 16 是 Host 没做、本表原来也没记的;第 8 条“按使用方记的供应商用量”并进第一节第 13 行。归类依据不变:乙类只收绑定在后续阶段子系统上的,显示质量差一点不是进乙类的理由 | +| 甲 9:回合结束给最后一条回复盖章 | 已关闭(2026-11-18;主干同步 6 后由 PR 首轮修复提交 `59ea890ff5` 恢复对齐,2026-11-19)。桌面 `sessionEventTerminal.ts` 的 `markAssistantTurnCompleted` / `markAssistantTurnFailed`:最后一条助手消息写 `turnCompleted`、原生分叉锚点、任务结果 id。Host 原来不写:之后读历史的最终回复与标题判断会读错,原生分叉锚点丢失,停下的 Codex 计划可能显示为已完成。对齐:Host 回合收尾(`agent/turn-executor.mjs` 的 `finish`)照桌面的顺序,先落库助手块、补落孤立工具结果,再在同一写入队列里盖章,最后写错误行。盖章用共用持久化核心的同一组函数(`consumeLastTopLevelAssistantPersistId`、`markAssistantTurnCompleted`、`markAssistantTurnFailed`、`isSuccessfulCodexDoneEventData`)。回合章的持久化顺序和 Codex 原始状态判断仍与桌面一致。主干 `7ace44b2b7` 新增对所有引擎非成功 done 的统一判据,Host 的产品回合收口先已使用,历史盖章原来未用,Pi 直接发出的 `cancelled` done 可让半截回复误盖成功章。首轮修复也让 `sealLastReply` 使用共用的 `isSuccessfulAssistantReplyDoneData`:成功 done(Codex 仍另要求 `raw.status` 为 completed)盖 completed 并带原生分叉锚点;终止性 error 与取消、失败、中断或 `is_error` 的 done 盖 failed。仅收到取消 done 时不额外写错误行。任务结果 id 只有伙伴任务有,Host 拒绝伙伴任务,不传。没有终态事件的停止不盖章;id 一律取走,不留给下一轮。写入队列暂停时这条章与其他写入一起等重试(队列自己报错,章的 promise 只吞掉拒绝,Node 下不留未处理的拒绝)。续接边界与后台回合也一样:桌面的终态阶段在每一个 done 与终止性 error 上都跑,Host 在前台续接边界的 done、后台回合的 done 与终止性 error 上调同一段收尾(`settleTurnBoundary`:带事件的 agent meta 落库助手块、补落孤立工具结果、盖章、保留后台还要用的状态并重置这一轮的持久化状态),续接前后两段各成一条回复、各盖一章,后台回合走的是同一个 history 与持久化核心。测试:Host `agent/input-queue.test.mjs`“turn seal: the Host seals the last reply of a turn as the desktop does”(成功 done、成功与中断的 Codex done、终止性 error)、“turn seal: continuation boundaries and background turns are sealed as the desktop seals them”。首轮修复补 Pi 取消、Claude 取消与正常完成对照,两个取消用例修前均误写 `turnCompleted: true`。原盖章提交里两条经 `/api/chat` 的上下文恢复测试在结束前等这一轮收尾:章是这一轮最后的写入,在流结束之后才落,而这两条测试的夹具先关库再停队列 | +| 甲 10:回合结束更新最近活动时间 | 已关闭(2026-11-18)。桌面经列表活动跟踪(`SessionListActivityTracker`)写 `last_activity_at`:派发与插话时(协调器钩子),回合结束时(`sessionEventTerminal.ts`),被自动续跑或上下文恢复接住的那一轮在结束时 hold,等接住它的一方最终放弃时由产品回合失败收口补写。Host 原来都不写:侧栏“最近活动”排序停在发送那一刻。**写入**:搬成共用(桌面提交 refactor(desktop): move the task list activity write into a shared module,`localDb/sessionActivityWrite.ts`,见下方“桌面准备 PR 里的非搬移提交”),Host 的 `agent/session-activity.ts` 照 `touchSessionActivityInDb` 包一层,`main.ts` 交给协调器的 `touchSessionActivity` 端口(原注释里的“A5 单元”这一处由此关闭)。**回合结束与 hold**:`agent/product-turn.ts` 在 Host 上绑桌面现成的 `createDeferredProductTurnFailureGate`、`createProductTurnFailureFinalizer`(`maker-ipc/productTurnFailureOwner.ts`)与 `SessionListActivityTracker`,每个账号运行时一套;归属核对照 `register.ts` 的 `isCurrentProductTurnFailureOwner`(Host 绑定的运行时、实例、代次),用执行器的绑定(`turn-executor.mjs` 的 `boundSession`)。执行器的接点照桌面:前台“运行中”状态 start(实例:代次);前台 isRunning=false 状态 statusOnly end(自动续跑待定或推迟时 hold);回合的 done 与终止性 error 先取归属(`settleProductTurn`),被自动续跑压住错误行的那一轮把归属登记进闸门,再 end(被续跑压住、被上下文恢复认领、续跑待定或推迟时 hold),成功回复的 done 清掉归属,没人接住的失败立即过收口;目标回合不记;运行时关闭时清掉这个实例的归属并删掉这一项,新运行时绑定时接过归属(`register.ts` 的 onBind)。三个出口都经闸门或收口结算:自动续跑最终放弃时,`agent/auto-resume.ts` 的 `surfaceSuppressedError`(簿记先写出被压住的错误行,恰好一次,再调它)结算闸门;上下文恢复认领时在 `agent/context-recovery.ts` 的 defer 里登记归属,最终失败时在 notify 里过收口。显式停止清掉这个任务的归属(`resetForExplicitStop`)。**与桌面的差别**:共用的 defer 规则对网关密钥恢复与计划内关闭也 hold(桌面之后经延迟落库结算),Host 立即写它们的错误行、没有之后的出口,所以只在认领(claimed、in-flight)与自动续跑压住时 hold;后台回合的终态不走产品回合(见第二节“后台回合终态的产品回合收口”)。收口里的插件任务回执与 Cindy Make 上游合并回合在 Host 上是空操作(第 33 行、第二节“Cindy Make 上游合并回合”)。测试:Host `agent/input-queue.test.mjs`“list activity: a dispatched or steered input moves the task's activity time forward, as the desktop does”、“list activity: a turn's done writes the task's activity time at its end, once”、“list activity: a turn an automatic resume holds writes its end time only when the resume gives up, with one error row”、“list activity: a context recovery that finally fails commits the held end time”、“list activity: a context recovery that finally fails after a newer turn started leaves that turn its own write” | +| 甲 11:Codex 生成的图片 | 已关闭(桌面搬移 `4ec2c71fd3`,Host `f4c41019d2`、`75d487e317`,补充测试 `61f20d73ee`)。原来:桌面 `sessionEventPreparation.ts` 接住 Codex 的 `image` 事件,保存图片、写进历史、发出的是存好的引用;Host 什么都不存,原始事件(含 base64)直接发给客户端。对齐:桌面的存图与交付搬成共用(原样搬移,桌面行为不变):`cindy-media/generatedImageStorageCore.ts` 的 `createGeneratedImageStorage` 收原 `generatedImageStorage.ts` 的全部实现,媒体库函数作端口,桌面在 `generatedImageStorage.desktop.ts` 绑现有实例,原路径改成重新导出;`generatedImageDelivery.ts` 原地加端口(存图、写消息、行广播、挂账、文案),桌面在 `generatedImageDelivery.desktop.ts` 绑;解码与读文件移到 `generatedImageBytes.ts`(`generatedMedia.ts` 重新导出)。Host 的 `agent/generated-images.ts` 用 Host 的媒体库(`media-store.ts`)建同一套存图与交付:行经 Host 的消息写入(`message-store.ts` 现在认 `deferMediaRefs`,与桌面一样由交付在条件更新之后自己挂账),挂账走 `hostChatAttachments`(同甲 25),文案走甲 23 的 ui-text(两句文案里没有 Host 字样)。执行器 `turn-executor.mjs` 遇到 Codex 的 `image` 事件,与桌面一样交给交付并暂停事件流(`holdEventStream`),原始事件不存不发;回合内外都处理(在执行器自己的回合检查之前,次序同桌面:先记本次尝试,再交付);安静的定时输出不交付;交付后补发的已提交行只在捕获时的账号仍当前时发出(同桌面 `broadcastMessageRow` 的 owner 范围)。恢复与清理:`setGeneratedImageRecovery` 由 `createHostGeneratedImages` 绑上(模块级设置函数表由待绑改为已绑);共用历史读取器读历史时恢复,删除任务时释放(`main.ts` `deleteSession`,同桌面 `localDb/ipc/sessions.ts` 删除时),owner 数据库就绪时续做清理回执(`main.ts`,同桌面 `localDb/ipc/registerAll.ts`)。Host 没有清空任务,所以没有清空那一处;以后做清除任务的入口时照桌面,在清除之后触发一次生成图恢复(`localDb/ipc/sessions.ts` `clearSessionContextInDb` 清除之后的那一行,审核方 2026-11-18)。与桌面的差别:Host 没有 Device Link,来源在别的电脑上的图片按“那台电脑未连接”处理(`invoke` 回答未连接,结果是 `REMOTE_SOURCE_REQUIRED`),共享任务的三个端口不给(Host 准入时拒绝共享任务);读取来源只认 `cindy-media://` 与本机路径,不接 SSH 文件服务与旧的 `xdt-image` 缓存,远程主机任务的图片同样按未连接处理。测试:Host `agent/input-queue.test.mjs`“a Codex generated image is stored, saved as its imagegen rows with a media reference, and published by address, never as base64”“a Codex generated image that cannot be stored, arriving after its turn ended, is saved and published as a failed delivery, never as base64”。补充测试(审核方 2026-11-18 要求,Host 同一文件):“deleting a task releases only its own generated-image references; another task's use of the same image stays”“the startup reconcile keeps an image the history still references and clears one no task references”“reading the history recovers a generated image whose delivery failed, once its source is there”。补测时查到:读历史时恢复原来在 Host 上没有触发点。历史视图读的是 outline,不触发恢复;桌面由消息列表首页触发,而 Host 的消息列表(`/api/messages/list`)是 Host 自己的 `agent/history.ts` `readMessagesList`,不调。`61f20d73ee` 照桌面,在它的首页(没有游标时)不等待地开始恢复 | +| 甲 12:运行时自己收掉的确认卡片 | 已关闭(桌面搬移 `2d1ecbe2bb`,Host `cd502f7d2a`、`75d487e317`,补充测试 `61f20d73ee`)。原来:桌面 `sessionEventPreparation.ts` 处理 `interaction_dismissed`:清掉待处理的卡片,保存提问 / 计划的决定(含撤回原因);Host 只有中止会到确认中转(`interactions.mjs`),运行时自动收掉的卡片一直挂着、决定不存,回合外到达的撤回被丢掉(执行器没有回合就返回)。对齐:桌面 `sessionEventPreparation.ts` 里的这一段与另两段(甲 12、14、15)原样搬进 `maker-ipc/sessionEventPreparationSteps.ts`,桌面在原处调用(桌面行为不变);Host 执行器 `turn-executor.mjs` 在自己的回合检查之前调用同一函数,回合内外都处理。`handleInteractionDismissedEvent` 经确认中转新加的 `clearPending` 摘下卡片(同桌面 `clearPendingInteraction`:只摘下,不另发结算),按 `defaultDecisionForPending`(从 `register.ts` 一并搬来)给出决定,提问与计划的决定经 `onInteractionResolved` 保存(同桌面 `persistInteractionDecision`,撤回原因随提问保存),客户端收到 `interaction_dismissed`。与桌面的差别:浮窗(agent island)是桌面窗口,Host 不做。测试:Host `agent/input-queue.test.mjs`“a question the runtime withdraws after its turn ended leaves the pending cards, and its withdrawal is saved”。补充测试(审核方 2026-11-18 要求):“a dismissal from another task's runtime leaves this task's card pending and unsaved”(`clearPending` 只摘本任务的卡) | +| 甲 13(次要):回合结束刷新列表预览和置顶卡片摘要 | 列表预览已对齐,关闭(2026-11-18);置顶卡片摘要见乙 14。桌面 done 后 `refreshSessionListPreview`(读最近一条可见消息,推 `local-db:sessions:patched` 的 `preview`)。Host 回合收尾在 done 之后、写入队列排空之后,用桌面同一个读取 `localDb/latestMessageText.ts` 的 `latestVisiblePreview` 与 `sessionTaskSummary.logic.ts` 的 `sessionListPreviewPatch`,经事件流推 `session_changed` 的预览补丁(`agent/turn-executor.mjs` 的 `refreshListPreview`);不等它,回合照常结束;终止性 error 不刷新;读失败记 warn 并吞掉,都与桌面相同。桌面的条件只排除续接边界,后台回合的 done 也刷新,Host 在 `settleTurnBoundary` 里同样在这一回合的写入排空后刷新。测试:Host `agent/input-queue.test.mjs`“list preview: after a done the Host publishes the latest visible message as the task's preview” | +| 甲 14(次要):Pi 扩展的独立通知 | 已关闭(桌面搬移 `2d1ecbe2bb`,Host `cd502f7d2a`)。原来:桌面 `sessionEventPreparation.ts` 把带 `standaloneText` 的 `text` 事件存成单独的通知行(`onStandaloneTextEvent`);Host 当作普通的后台助手文本,可能和下一条回复并在一起或时间记错。对齐:桌面 `sessionEventPreparation.ts` 里的这一段与另两段(甲 12、14、15)原样搬进 `maker-ipc/sessionEventPreparationSteps.ts`,桌面在原处调用(桌面行为不变);Host 执行器 `turn-executor.mjs` 在自己的回合检查之前调用同一函数,回合内外都处理。`routeStandaloneTextEvent` 经 Host 持久化(共用的 `createMessagePersistence`)的 `onStandaloneTextEvent` 存成单独的行,不作为文本事件发给客户端。所属输入取本回合的输入;输入来源只用来判断伙伴私信,Host 准入时拒绝伙伴输入,所以给空。测试:Host `agent/input-queue.test.mjs`“a standalone notice is its own row in and out of a turn, never reply text or a client text event” | +| 甲 15(次要):Opus 计划模式的错误原因 | 已关闭(桌面搬移 `2d1ecbe2bb`,Host `cd502f7d2a`)。原来:桌面 `sessionEventPreparation.ts` 对 Claude Opus 计划模式的终态错误改写成规范化的原因再存,并消费观察登记;Host 存原始消息,登记不消费。对齐:桌面 `sessionEventPreparation.ts` 里的这一段与另两段(甲 12、14、15)原样搬进 `maker-ipc/sessionEventPreparationSteps.ts`,桌面在原处调用(桌面行为不变);Host 执行器 `turn-executor.mjs` 在自己的回合检查之前调用同一函数,回合内外都处理。`claudeOpusPlanTerminalErrorData` 在交给协调器和记录之前改写,终态错误带规范化原因存、发,观察登记被消费;登记来自 Host 的 Claude 代理装的同一个观察器(`anthropicCompatProxyHostCore.ts`)。测试:Host `agent/input-queue.test.mjs`“a Claude Opus plan-mode terminal error carries its normalized reason and consumes the observation” | +| 甲 16:运行时退役失败的恢复通知 | 已关闭(桌面搬移 `c87bbac21b`,Host `e68e5ab8ba`)。原来:桌面 `register.ts` 订阅 `session.onRuntimeRecovery`,把恢复回执存成本地化的通知行并广播;触发点是 maker-core `Session.performClose`,带退役回执的关闭失败时发出(在清掉监听与改状态之前)。Host 已经在用这种退役(`agent/pi-packages.ts`),但不订阅,失败时没有通知、不存行。对齐:桌面 `sessionEventPreparation.ts` 换成本地化文字的那一段原样搬成 `localizeRuntimeRecoveryEvent`(同甲 12、14、15 的 `sessionEventPreparationSteps.ts`,桌面在原处调用)。Host 执行器 `listen()` 订阅 `session.onRuntimeRecovery`:当前 owner 不是这个运行时接上时的 owner、或绑定已换时不处理;文字经甲 23 的 `uiText(key, 英文)` 换(跟随语言,文案里没有 Host 字样),再走已有的 `history.event` 存成助手行、`publishAgentEvent` 发出,与回合无关。测试:Host `agent/input-queue.test.mjs`“a runtime retirement that failed after its turn is saved and published as a notice in the user's language”“a runtime retirement receipt after the owner changed saves and publishes nothing””。文案(审核方 2026-11-18):句子是“请重启 Cindy 后再使用 Pi”,窗口连着 Host 时真正要重启的是 Host(Pi 运行时在它里面),只重开窗口不够;归“个人版里‘重启’对应什么操作”的文案事项,届时一起改,现在照桌面不动 | +| 较小差别:只有 running=false 的状态不写回合结束时间 | 桌面 `sessionEventDelivery.ts` 在前台 `status` running=false 时也写 `last_turn_ended_at`;Host 只在 done、终态错误、中止时写 | +| 较小差别:回合结束后才到的 turn_diff 不记 | 桌面在 `emitWiredSessionEvent` 里记,不看回合;Host 的执行器在回合已结束或不是当前回合时先返回,迟到的 diff 不进改动记录 | +| 已对齐:turn_diff 不发给客户端 | 原来 Host 把 `turn_diff`(可达数 MB)发给每个客户端,也交给历史记录;桌面只交给改动记录(`sessionEventPreparation.ts`)。核查过没有读它的客户端:web shim、`apps/web`、`apps/host/scripts` 的 e2e、手机端、渲染层都不读。Host 执行器在记进改动记录之后返回(`turn-executor.mjs`),测试 `input-queue.test.mjs`“a turn diff stays with the change record …” | +| 乙 6:`maker:set-context-window-budget` 的 Host 入口 | 这条 IPC 在桌面上只有 device-link 控制端经隧道调(本机界面走 `local-db:sessions:update`,见甲 3)。Host 不开这一条通道(`maker:set-context-window-budget`),处理函数体也不搬,随这类控制端入口上 Host 时一起接(审核方 3b-2 定)。更正(2026-11-17,只读清点 C 发现):原来写的“Host 现在不接 device-link 的调用”比代码宽——Host 登录后会启动 device-link(`apps/host/src/main.ts:1820`),注册全部 `HOST_CONTRACT_CHANNELS`、`maker:create-session` 与 MCP Apps(`apps/host/src/device-link.ts:92–99`),远端控制端能调到这些入口。共用分发器(`device-link/dispatch.ts` `createInboundDispatch`)里 Host 没传的平台端口:13 个有缺省值,调到时抛带类型的 `[NOT_SUPPORTED] … is not available on this Host`(:494–496),Host 也不对外宣告这些能力(`device-link.ts` 的 `capabilities: []`);7 个没有缺省值的逐个核过,都只经 `?.` 调用,没有抛普通错误、也没有静默放行:`stopFilePeers`、`remoteDesktop`、`remoteCredentialHost` 只在断开与撤权时收尾(:2823–3052),Host 起不了文件对端与远程桌面(`requestFilePeer`、`requestRemoteDesktop` 缺省即拒);`configureStandbyGuestCleanup` 不传就不登记那段清理回调(:5655),`delegatedProviderShareLeases`、`invalidateProviderShareDelegation` 只在那个回调里用(:5658–5659);`delegatedProviderShareGuestAccess`(:4849、:4859)位于 `runProviderShareInvoke` 的第一道门 `providerShareGuestAccess` 之后,Host 从不调 `setProviderShareAccess`(只有桌面 `providerShareRuntime.ts:1360` 调),这道门在 Host 上恒为空,分享受邀者一律得到带类型的 `PROVIDER_SHARE_ACCESS_FAILURE`。13 个报 NOT_SUPPORTED 的端口归属(审核方 2026-11-17 定):`readUsageWidgetSnapshot`、`readKimiCodingAccountUsage`、`readOpenCodeGoAccountUsage` 随第 13 行的设计定,倾向 M2;`transcribeRemoteVoiceInput`、`adviseAndRecordVoiceInputDictionaryLearning`、`buildMobileDictionarySnapshot`(手机语音输入)M2;`readTelegramRemoteStatus`、`setTelegramRemoteOnline` M3;`prepareShareAvailability`(供应商分享)、`requestTaskMigration`(任务换电脑)、`fetchLocalMediaToOss`(远程附件)、`requestFilePeer`(文件对端)M3;`requestRemoteDesktop` 不上 Host(远程桌面是窗口进程的能力,平台差别)。测试:`apps/host/src/device-link.test.mjs`“Host device-link refuses provider-share guests and the platform features it does not wire”(经 Host 真实装配 `createHostDeviceLink`、真实 `DeviceLinkClient` 与本机替身中继)——分享受邀者对端调远程 Agent、同账号读与未知通道,都得到带类型的 `PROVIDER_SHARE_ACCESS_FAILURE`(`ACCESS_REVOKED`),不进 Host 服务;控制端调 `requestRemoteDesktop` 得到带类型的 `[NOT_SUPPORTED]`;调 `requestFilePeer` 得到 `FILE_PEER_UNAVAILABLE`,不是 NOT_SUPPORTED:文件对端的调用处(`dispatch.ts:5070–5073`)把任何异常都换成这句,缺省实现的 `[NOT_SUPPORTED]` 到不了控制端 | +| 预算:取消待切意图时的清理 | 桌面取消待切意图(`cancelPendingAgentSwitchHolder`)时删 `appliedContextWindowBudgets` 里这个任务,不删重放意图。Host 没有取消意图的入口(`clearIntent` 只用在删除、丢弃任务,那时运行时关闭,已由关闭清理覆盖),这一处绑定在“Host 有取消意图的入口时”再对齐 | +| 乙 1:定时任务的模型范围 | 发送钩子第 1 步 `scheduledModelScope.restore`,随定时任务上 Host。Host 今天在定时任务上有什么(2026-11-17 核对):只有队列这一侧——`agent/input-queue.mjs` 用共用的 `createSchedulerQueueBridge` 与 `runSchedulerQueuedPreparation` 组出 `schedulerQueue` 接口(排队、准备、撤回与通知执行器的那一套,有测试);没有定时任务的执行器(桌面 `scheduler-host` 的 runner),生产代码里没有谁调 `schedulerQueue`,Host 自己不会产生定时任务来源的输入。但 Host 启动时会从共用库恢复排队快照(`loadAgentInputQueueSnapshot`),桌面写下的快照里可能有定时任务来源的排队项;迁移来的任务行也可能带 `scheduledModelBaseline`。所以必须在迁移前接上,不能因为 Host 不跑定时任务就算不适用。Host 的定时任务验收脚本 `apps/host/scripts/scheduler-runtime.e2e.mjs`(`pnpm --filter @cindy/host test:scheduler`)自 main `41ed3b9f40`(2026-11-12,IM 文案随界面语言)起加载即失败:“electron does not provide an export named app”。导入链:桌面 `scheduler-host/runner.ts` → `im/shared/turnRetryNotice.ts` → `im/shared/imText.ts` → `i18n.desktop.ts`(顶层 import electron)。Host 生产代码不加载 runner,只影响这个脚本;审核方定不现在修(2026-11-17),见下面“后续阶段的桌面事项” | +| 乙 2:待切凭据的登记入口 | 服务已接(检查点 3);Host 现有入口登记不到:判断“忙”只看回合是否在跑(`codex-credential-switch.ts` `isLocalSessionBusy`,不看后台任务),用户的选择只在空闲时落定(`applyPendingAgentSwitchIfIdle` 开头 `if (live?.isTurnRunning()) return;`),桌面上用户这条路同样登记不到。登记入口是 Agent / 系统 / IM 卡片 / 定时任务的换模型,随它们上 Host;届时用测试钉住登记、回合结束生效、关闭时清除三条路径。原先要的“后台任务在跑时换供应商”测试作废(理由同上) | +| 乙 3:Orca 与供应商组的发送前检查 | 发送钩子第 5 步:Orca 有意图未落定时拒发、`providerGroupService.beforeSend`,随 Orca、供应商组上 Host。放开 Orca 时要重看 `apps/host/src/desktop-module-setters.ts` 里以此为由的 not-applicable 项(现在是 `setWorkerCreationPrefsCache`) | +| 乙 4:伙伴路由对账 | `reconcileBotModelRoute.acceptTaskChoice`(Host 空操作,调用处本就吞错),只对伙伴任务有效;Host 不执行伙伴任务(`send-preflight.ts`)。随伙伴上 Host | +| 乙 5:换电脑、组内换机 | 换引擎的五个端口(`confirmNativeHistoryFallback`、`relocateNativeHistory`、`resolveProviderGroupTarget`、`assertAgentDeviceRouteUsable`、`describeAgentDevice`)。Host 入口拒绝非空 `agentDeviceId`,走不到。随远程执行上 Host | +| 乙 7:迁移器只拉同区域的 Host 包 | 迁移前提(甲 20 登记,2026-11-17):国内版桌面只拉国内版 Host 包,国际版只拉国际版;包的区域读 `release.json` 的 `region` 或运行中 Host 的 `status --json`。交接分支实现,本分支不做 | +| 乙:Linux 上 Host 只读代理环境变量(28c 登记,2026-11-18 审核方定) | 迁移前处理。现状:Linux 的 Host 包不带 Electron,28c 的 Chromium 辅助进程不覆盖 Linux;Host 不读 GNOME(gsettings)与 KDE 的代理设置,也不执行 PAC,没有代理环境变量时直连,路径记 unknown(session_unavailable),`cindy-host status` 如实写明系统设置与 PAC 在这个平台上不读。不做“检测到 PAC 就提示”的界面。要处理时:静态设置照 Chromium 的 `proxy_config_service_linux` 读,PAC 另定做法(审核方已排除在 Host 里自跑 PAC 脚本的 A 方案,Linux 若要 PAC 须重新决定) | +| 乙 8:桌面拉起 Host 时传自己的 appData | 迁移前提(第 25 行 25b 登记,2026-11-17):macOS 上 Electron 的 appData 不跟 `$HOME` 走,Host 自己算的跟;两边要共用 `/Cindy` 下的 Skill 变更锁与内置 Skill 包,否则改过 HOME 时互斥静默失效。Host 已支持优先用传入的 `CINDY_HOST_APP_DATA_DIR`(`profile-path.mjs`,有测试);迁移器拉起 Host 时把 `app.getPath('appData')` 传进去。同一条前提:Host 用自己的 profile、桌面用默认 profile 同时运行时,两边共用 home 下的 Skill 根,靠整机的共享根锁与 `/Cindy` 下的 Skill 变更锁串行,这要求两边锁目录相同;macOS 上改过 HOME 时两者不同(实测),所以这种并存也以本行为前提 | +| 乙 9:列 Skill 的其余三处差别(L2–L4) | 第 25 行 25b 登记:L2 不标官方 Skill(`markCindyOfficialSkills`,只影响面板上的“官方”标记);L3 不准备项目里的 Skill 链接(`preparePaletteProjectSkillLinks`,任务开始前的列表可能缺共享项目 Skill,任务启动时 Host 已建);L4 Pi 的托管 Pi 包与任务运行时 Skill 已随 L1 改走 `maker.listAgentSkills` 一并接上,留待核对。L1(停用 Skill 仍列出)是甲,已在 25b 关闭 | +| 25b 并存检查的残余窗口(第 25 行 25b 登记) | `cindy-host login` 先扫一次桌面(`.dev-instances` 与 SingletonLock),扫描与提交之间若有桌面启动、开库,提交照样进行:桌面开库不拿边界锁,提交时也没有第二次扫描能挡住。窗口只在“扫描后、提交前”这一小段里;发生时桌面与命令行各自在同一 profile 上动边界,桌面下一次登录或修复会重新过渡 | +| 乙 10:服务先起、再登录要多一步重启 | 第 25 行 25b 登记(审核方 2026-11-17 接受现状):serve 运行中不重新采用会话,常见路径“systemd 开机自启 serve,再跑 `cindy-host login`”登录成功后要重启 serve 才生效;login 会写明这一点并给出重启办法(systemd 用户服务:`systemctl --user restart cindy-host`,见 `docs/host/systemd.md`;否则 `cindy-host stop` 后再启动),有测试。和迁移器一起设计:迁移器拉起 Host 的顺序与登录后的重启 | +| 乙 11:原生归档同步(2026-11-17 审核方定乙类) | 第二节“恢复已归档任务”“手动归档”两行登记的差异:桌面恢复或归档任务时经 `setSessionArchiveSyncRequester` 装的请求把 Codex 原生线程的归档状态同步过去(`maker-host/index.ts` 的 `createSessionArchiveSync`),Host 没装,共用的归档/删除清理调 `requestSessionArchiveSync` 时什么都不做,Host 上归档或恢复的任务,Codex 原生线程的归档状态不跟着变。迁移前要有结论:随 Host 的归档同步一起接,或带着事实回来问是否接受。设置函数守护表里这一项是 pending,挂本编号 | +| 乙 12:模型发现与供应商视图(M2,2026-11-17 设置函数守护登记) | 第二节“订阅账号放置与供应商视图(rc10)”与“订阅池按账号发现的 Codex 模型清单”记的差异,按设置函数列一遍:活动目录的 `setAnthropicDiscoveredModels`、`setCodexApiModelCapabilities`、`setDiscoveredProviderMediaModels`、`setDiscoveredProviderModels`、`setManagedProviders`、`setXaiDiscoveredModels`,Codex API 能力回填的 `setCodexApiModelProbe`,maker-core 的 `setClaudeSupportedModelsListener`。Host 都不绑,可选目录里没有这些发现结果。随 M2 的模型发现与供应商视图一起接,迁移前要有结论;设置函数守护表里这 8 项是 pending,挂本编号 | +| 乙 13:任务 PR 关联的窗口通道与推送(审核方 2026-11-17 定乙类,随 M2 的推送一批) | 第二节“任务的 PR 关联”的“仍不同”与第六节 `git-context:pr-refs-changed` 那一行:Host 绑 `setPrRefsChangedListener`,经事件流 `plugin_push` 发 `git-context:pr-refs-changed`(带 owner 检查);桌面客户端模式的 `onPluginPush` 名单与 Host device-link 的名单加这个频道(桌面改动);把 `git-context:pr-refs:list`、`list-all` 登记进 Host 通道合同,网页端 shim 接 `listPrRefs`、`listAllPrRefs`、`onPrRefsChanged`;`manage` 要经 GitHub 核实,随第 22 行的 `setGithubReadRuntime`。`desktop-module-setters.ts` 的 `setPrRefsChangedListener` 记为 pending,引用此项 | +| 乙 14:置顶卡片摘要(审核方 2026-11-18 定乙类) | **要做,理由是与桌面对等,不算新功能**:迁移以后,个人用户的窗口就是连着后台服务的那个窗口;后台服务不生成摘要,置顶卡片就从摘要退回成预览,这是桌面现有功能的退化。费用不增加:同一份代码、同一套频率、同一个用户、同一台电脑,只是发请求的进程换了。**范围(审核方定)**:只有客户端模式的本机窗口能触发生成,它走 Bearer 加实例头的可信渲染层通道,也只有它能告诉后台服务“置顶段是卡片模式”;远程控制端(device-link)不触发,卡片回退成预览,与桌面今天对控制端的做法一样(`localDb/ipc/sessions.ts` 那条处理函数写明“oneShot 只服务本机卡片展示,控制端卡片回退 preview,不把付费生成推到被控端”);网页端(cookie 会话)先不触发,回退成预览,以后要开单独定;被桌面占用、闸门关着的期间不发,这个通道不进 `HOST_PATHS_ALLOWED_WHILE_HELD`。**频率照搬桌面**:只在 active、已置顶、卡片模式时生成,在飞的请求去重,20 秒节流,回合结束时 force。**做的时候**:`sessionTaskSummary.ts`(引 Electron 与 `getMaker`,Host 加载不了)改成 `createSessionTaskSummary(ports)`,作为桌面搬移提交逐行送审;通道 `local-db:sessions:set-pinned-card-summaries` 进合同的方案先交审核方;Host 侧测试证明网页端与远程控制端触发不了、闸门关着时不发、频率与桌面一致(同一组节流用例)。**为什么归乙、不归甲**:测试期里缺了它,只是置顶卡片显示预览而不是摘要,不丢数据、不花钱、不误导人;做它要一次 481 行的大搬移外加一次通道名单的改动,不值得压在第一个 Host PR 前面 | +| 乙 15:Host 的清除任务上下文入口(审核方 2026-11-18 登记) | 桌面经 `localDb/ipc/sessions.ts` 的 `clearSessionContextInDb` 清除任务上下文(`/clear`),Host 现在没有这个入口(另见 `docs/host/headless-runtime-plan.md` “Host 当前没有历史清空入口”)。做的时候照桌面:清除之后触发一次生成图恢复(`clearSessionContextInDb` 清除后的那一行,见第五节甲 11);待发交接摘要的 `invalidate` / `sealClearBoundary`(第二节“待发交接摘要”);PR 关联的重算(甲 24 已接的 `recomputePrRefsForSession` 端口)。归属:随客户端模式窗口的 `/clear` 通道一起上 Host。审核方 2026-11-18 补三点:一、清除、回退(rewind)、删除消息这三个入口一起做,不分三次——它们动的是同一组派生状态(图片挂账、PR 关联、交接摘要);二、客户端模式下 Host 清除失败时,窗口不能先把界面清了:以 Host 的结果为准,失败就保留界面并提示;三、做这条所需的桌面小搬移如果是纯原样搬移,可以提前随当前的准备 PR 走,不必等后面的桌面 PR(审核方当时定过两处,记录里找不到具体是哪两处,接手的 worker 做方案时重新列出,交审核方定) | +| 乙 16:用量上限后的自动继续(审核方 2026-11-18 定乙类,随 `maker:usage:*` 那一批) | 整块随订阅用量读取器上 Host 时一次对齐,不做“没有账号窗口时不等”这类临时差别(第二节“撞用量上限后的自动继续”)。范围:等待(协调器现成的 `armUsageLimitWait` 等)、存档与重启恢复(`usage-limit-waits.json`,`usageLimitRecoveryStore.ts`)、取消(`maker:input:cancel-usage-limit-wait`,要进 Host 通道合同)、发消息或换模型即接手(`noteUserAction`,`auto-resume.ts` 现在是空函数)、关闭与切账号时冻结,以及账号用量窗口、Codex 重置卡提前恢复(`hasRestoredCodexQuota`)、同供应商换号(`canSwitchAccount`)。做的时候:`register.ts` 的等待运行时(`resolveSessionUsageResetAt` 到 `UsageLimitAutoResume` 的构造)搬成共用,替换点清单先交审核方;求重置时刻必须经 `resolveSessionRuntimeRoute`(或它的共用版本)取任务此刻实际在跑的来源与模型,不能直接读任务行(4b 清点);`subscriptionFamilyOf` 所在的 `usage/accountUsageLimit.ts` 经 `usageBroadcaster` 引 Electron,Host 加载不了,要先拆出来。现在能在 Host 上加载的:`usageLimitAutoResume.ts`、`usageLimitRecoveryStore.ts`、`goal-host/usageLimit.ts`、`automaticContinueEligibility.ts`;加载不了的:`maker-ipc/usage.ts`、`subscription-accounts/*`(引 `original-fs`)(8g 清点,2026-11-18) | +| 乙 17:插件的引擎原生恢复事件(2026-11-19) | 桌面经 `ghostNativeRecoveryObserver` 发布 `native-recovery`。Host 的引擎尚未绑定该发布端口,共用网关因此不向插件投递该主题,其他订阅和拦截照常。随 Host 插件事件补齐。 | +| 乙 18:Codex 登录链接替换中的文件操作(2026-11-19) | Host 建目录、写标记和调用替换前复核占用;发生账号切换时照桌面完成文件链接,账号是否仍可绑定由最终的绑定步骤复核。共用的 `relinkSharedCodexAuth` 内仍有 stat、sidecar、rename 的短窗口,Windows 还有删除旧目标与 ACL 修复,保留其现有替换和失败恢复流程。占用依靠周期扫描发现。发现后停止发起新的共享写入,原生确认、等锁和等模型这类可能长时间等待的步骤在写入前复核。毫秒级的本地文件操作窗口小于扫描间隔,同类窗口不单独关闭。 | +| 乙 19:旧版窗口的项目元数据写入(2026-11-19) | `legacyDesktop` 只服务旧版窗口,只能改已有项目的元数据,不能借 Host 授权新增项目或目录。服务入口检查占用,进入后仍有等项目写锁的窗口,锁内未复核。新版窗口的确认路径、非旧窗口的直接请求和 MCP 项目设置写入均使用写前复核。 | +| 乙 20:已进入的记忆写操作(2026-11-19) | Host 在最外层打开 store 之前拦截。已进入 store、正在等锁的一次写入仍可完成,属于乙 18、乙 19 同类的在途窗口。 | +| 乙 21:占用期间读取已初始化的记忆(2026-11-19) | 目前一起拒绝所有打开 store 的操作。将来需要占用期间热读时,再考虑共用层的独立写许可与只读打开端口。 | +| 客户端模式的 profile 上、桌面没在运行时用命令行登录(第 25 行 25b 登记) | `CINDY_HOST_DATA_DIR` 指向桌面的 profile、桌面没在运行时,`cindy-host login` 同样提交 owner,过渡时清掉窗口留下的 Ghost Skill 投影;桌面下次启动时按它自己的边界重新投影(审核方 2026-11-17 接受) | +| 第 25 行 25b 的修订:客户端模式下由 Host 提交 owner(审核方 2026-11-17 定) | **原决定**(25b 方案 A):窗口提交 owner,Host 只加入窗口已提交的同一 owner,serve 注入拒绝。**为什么改**:客户端模式下窗口在本地切换、添加账号会提交新 owner 而 Host 不跟(见第二节“已知限制(仅限测试期)”);用户已定窗口的登录结果交给 Host(第四节),切换由 Host 执行,提交也就归 Host。**改后的分工**:只限客户端模式。Host 在切换账号、登录完成(含启动时的补完)时提交 owner,经一个只给 Host 的账号切换/登录完成用的提交入口:放开的范围在词法上限定在这些函数内部(try/finally),绑在这一次操作上,不是全局开关(建议把提交能力作为参数传入);切换进行中别的调用方提交仍被拒,切换失败后恢复为拒绝;切换之外 serve 照旧拒绝(现有根守护语义不改)。窗口在客户端模式下不再提交 owner(桌面改动,归第一阶段之后的桌面 PR)。独立安装的 Host 不变,仍由 `cindy-host login` 提交。`discoverHostOwner` 只数库文件个数的缺口并进同一单元 | +| 乙:客户端模式下窗口切换、添加账号(审核方 2026-11-17 定为乙) | 方案方向已定:交给 Host 做,窗口只当界面,新增 `/api/auth/accounts/*` 一类接口。审核方定的默认(照桌面;失败时不让用户落到更糟的状态):A 队列里没发的输入留在 A 的库里,回到 A 再发;切换先验 B、不动 A,B 不行就留在 A 并说明原因;闸门关着时拒绝切换,提示先关那个桌面;切换时有回合在跑、切换前要不要确认,照桌面今天的做法(待只读核实)。方案已定稿(审核方 2026-11-17),排在当前甲项之后实现。**登录凭证在本机内部的传递**:Host 发出全部会签发令牌的认证调用(登录状态机在 Host、用 Host 的设备 id),窗口只转交用户输入的一次性验证码、联系方式和账号选择,不传长期凭据。鉴权用 Host 现有的 API 密钥(每个 profile 一把、多次运行复用,0600 文件)加实例头,另加两条限制:这组接口只接受“Bearer + 实例头”的调用方、拒绝网页端 cookie 会话;同一时刻只允许一个添加账号事务。威胁模型边界如实写明:同一 OS 用户下的其它进程能读到这把密钥,因而能调用这组接口(例如发起切换账号),在现有威胁模型之内,不另加防护。**必做项**:这组路由只回固定错误码,加哨兵测试(构造的验证码、联系方式、ticket 与桩令牌的特征串不出现在任何响应、错误消息与 Host 日志里);桌面第二道保险(客户端模式下 Host 续期接管时,本地 `completeLogin`、写会话、写保管库一律拒绝,桌面 PR,逐行送审);Host 补桌面账号边界的 turn-ended 压制(`beginSessionTurnEndedSuppression`),让被切换停掉的任务保留中断痕迹、不自动续跑。**①② 照桌面**:只在有任务在跑时弹桌面现有的确认框(`sidebar.accountSwitcher.runningTask*`,文案不变),确认后停掉在跑的任务并保留中断痕迹,没有确认宿主时不切,切换失败留在原账号;桌面今天的两点行为照旧:添加账号的确认发生在点“添加”那一刻、之后到登录完成之间新开始的任务会被直接停掉,判断只看在跑的、不看排队的。桌面部分进第一阶段之后的桌面 PR,Host 部分进下一个 Host PR**并入的一项:`cindy-host login` 写出与桌面登录相同的存储状态**(审核方 2026-11-17 登记,C 落地时):现在 `cindy-host login` 只写 v1(并存行后续九):账号库里不写这个账号、不写 passport、不写旧版令牌。要写出和桌面 `completeLogin` 相同的状态(账号库里的账号与 passport)。用户已定添加账号由窗口登录、结果交给 Host,到那时 Host 本来就要会写这些。做完后,C 的差别 a(v1 仍持有令牌时,账号库没有当前账号也写 v1)应当可以去掉。**切换复用第五节“甲:账号边界停止提前置位”的 `runOwnerBoundary`**:`begin()` 不可撤销(输入运行时只有 dispose 才换成新的),所以“先验 B、不动 A”必须放在 begin 之前;切换是 `agent/owner-boundary.ts` 头注 begin 调用点清单的第五处,照那条不变式(begin 之后必须到达 dispose,到不了的路径必须重建输入运行时,释放写在 finally 里)检查。定稿方案见 [docs/host/client-mode-account-switch.md](client-mode-account-switch.md)**并入的一项:error 状态下退出登录不写墓碑、不移出保管库**(审核方 2026-11-17 定为乙):Host 启动失败后 `accountUser` 已清空,此时调用退出登录只删会话记录、尽力吊销,不写退出墓碑、不把账号移出保管库。后果:这个账号在保管库里仍显示为已保存,但它的凭据已被吊销,之后切换到它会要求重新登录。按定稿方案第九节第 7 项改为按会话记录里的账号写墓碑 | +| 乙:Host 开机自启时网络还没就绪,会停在 error,只能手动重启(2026-11-17 登记) | 启动时连不上登录服务(`HOST_SIGN_IN_SERVICE_UNREACHABLE`)的那次启动直接失败、停在 error,不重试;窗口现在会说明原因并让用户检查网络后重启 Host。桌面在同样情况下按冷启动退避一直重试(`authManager.ts` 的 `runColdStartRefreshFlow`)。目标:照桌面的冷启动重试,网络恢复后自动起来。迁移前必须解决:个人版由开机自启或桌面拉起 Host,网络晚于 Host 就绪是常见情况 | +| 第一阶段剩余桌面事项(随下一个桌面准备单元处理) | 1. `apps/desktop/src/renderer/vite-env.d.ts:6797` 的注释说“DB 持久化由调用方另调 `sessionService.update({ planModeEnabled })`”,代码里已无这种调用(桌面 `SET_PLAN_MODE` 自己写库),是过时注释,改文字。2. 桌面 `updateSessionInDb` 对 `effort`、`fastMode`、`permissionMode`、`planModeEnabled` 是否也改为拒绝:审核方 2026-11-18 定:不改;以后如果有客户端要走这条入口再议(见第四节)。3. 桌面原有缺陷,严重度低,只登记不修(审核方 3b-2 定,由审核方告知用户):`updateSessionInDb` 只带预算、偏好文件写不进去时,先广播了没保存的值 `{ contextWindowBudget }` 再抛错。origin/main(9805049156)上用对照测试复现;控制端只是渲染层内存里多一个没人读的值(芯片读被控端的权威值),刷新即消失 | +| 桌面事项:非 Pi 凭据切换失败的提示 | 桌面仅 Pi 的切换失败会广播 `maker:session-credential-switch-failed`。非 Pi 切换复核或写入失败时记录日志并保留重试,用户看不到失败提示。Host 解闸复核发现选择已失效时也只记日志,不写回旧路线。**用户已定(2026-11-18):补上提示,桌面和后台服务都补,文案到时给用户选,见第四节。** | +| 桌面已知现象:自动 Git 保存点超时 | 桌面和 Host 使用同一个 `GitSnapshotCoordinator`。回合开始和结束各有 8 秒预算,包含等候仓库写队列的时间;单次自动捕获的内部预算为 5 秒。慢盘或队列占用时,回合可以正常结束且没有编辑后的保存点。超时会留下 `Snapshot operation deadline exceeded` 日志,已经发布的基线仍可用。自有 Windows 上曾实际观察到只留下基线。 | +| 后续阶段的桌面事项(不在第一阶段,随对应能力上 Host 时处理) | 1. 定时任务上 Host 时:`im/shared/imText.ts` 不能在模块顶层拿 Electron(经 `i18n.desktop.ts`);现在桌面的定时任务 runner 经 `turnRetryNotice.ts` 走到它,Node 进程加载即失败(见乙 1,2026-11-17 记)。2. 要问用户的桌面产品行为(审核方汇总桌面事项时一并请用户定,2026-11-17 记):一条消息把上下文撑爆、后面已经排着另一条时,撑爆的那条没有回复也没有任何错误痕迹,这是 #4170(`b3a957b98d`,`contextRecoveryAssembly.ts` 的 `contextRecoveryAbortSignal`)的设计结果;要不要留痕或先重放,见第五节“溢出错误时后面已排着输入”。**用户已定(2026-11-18):留一句提示,不重放,见第四节。**3. 疑似桌面缺陷,严重度低,只登记不复现不修(只读清点 A 发现):输入框改工作目录失败时什么都不提示(`renderer/components/new-chat/ChatInput.tsx` 的 `handleFolderSelect` 吞掉错误);附件归一化失败时附件被静默丢弃、消息照发(`maker-ipc/normalizeAttachments.ts` 的 `normalizeUserMessage`,Host 改为整条拒绝,见第二节)。**附件这一处用户已定(2026-11-18):桌面改为整条拒绝,见第四节。**4. 桌面 P2,只登记(审核方 2026-11-17 定):企业额度和 ChatGPT 用量刷新失败时没有退避(企业额度失败时 5 分钟空闲轮询照常跑),第 13 行不改。5. 要问用户的桌面产品行为(甲 5 发现,审核方定以后一并问):移动 Claude 任务时不检查是否在回合中,转录迁移直接关闭活实例(`claude-transcript-relocation.ts` 第 4 步,`register.ts` `setLiveCcSessionBridge`),正在跑的 Claude 回合被中断(Maker 以关闭中断的终态结束它);Pi/Codex 在回合中则拒绝移动。Host 照搬。**用户已定(2026-11-18):Claude 也改为拒绝移动,两边一起改,见第四节。**6. 桌面运行时续期判失败前只比最后试的那枚令牌(`authManager.ts` refresh() 的 `stillOwnsRequestedSession`,冷启动同理):v1 那枚被拒、最后试的是账号库或旧版令牌里另一枚也被拒时,v1 仍是被拒过的令牌却被当成“盘上已换”,丢掉这次失败、一直按暂时失败重试,不登出也不提示。只在 v1 与账号库不同步时出现;Host 改为比对整轮被拒过的令牌(C 的差别 b,审核方 2026-11-17 记进这里)。7. 桌面列表活动时间的两处漏写,只登记(甲 10 发现,审核方 2026-11-18 记):若将来有与当前前台回合同实例、同代次的后台终态错误进入桌面失败收口,并且前台活动项尚无结束时间,失败收口会提前将该活动项标为已结算,导致前台的结束时间漏写;本快照未发现该输入的生产路径,Host 已按范围过滤(2026-11-19 复查改写,见第二节“后台回合终态的产品回合收口”);同一轮被自动续跑接住两次或更多、最后放弃时,闸门里留下两个候选,结算拒绝(`createDeferredProductTurnFailureGate` 的 settle 在候选不止一个时不结算),这一轮的活动时间不写。后一处 Host 与桌面一致。8. **辅助模型用量(2026-11-19 核对)**。自动复核、工具循环复核在两端按请求记 Token,来源为 `auto-review`、`tool-loop-review`。占用期间在途回合的辅助收据照写,见第二节。记忆自审在桌面和 Cindy 后台服务都通过同一辅助模型链,以 `memory-review` 记账。读取及推送按第一节第 13 行推进。 9. 桌面回合中途换账号时,迟到的用量会写进新账号的库(审核方 2026-11-18 记):回合记录器写库时取写那一刻的 `getDbClient()`,只在广播前查 owner 范围;Host 按发起回合的账号写,见第二节“回合中途换账号后迟到的用量”。**用户已定(2026-11-18):桌面改为按发起回合的账号记,见第四节。**10. 静默停止续跑的两处,只登记(8g B 评审,2026-11-18 记):一是决策在结算之前失败时(`silentStopTurnEnd.ts` 某一步抛错,例如广播耗尽横幅时抛错;写耗尽标记被拒会被接住、照常结算),`settleSilentStopDone` 不执行,被推迟的空闲与协调器的 done 补发不出来;Host 在这条路上逐步收尾(`agent/silent-stop.ts` 的 `failClosed`)。二是静默停止的 done 就写回合结束、续跑开始不再记回合开始,决策期间或续跑进行中崩溃、退出登录或关闭的任务不进“继续上次中断的任务”;Host 不在 done 上写结束(第二节“静默停止续跑期间的回合标记”)。**第二处用户已定(2026-11-18):桌面改为这类任务进“继续上次中断的任务”,见第四节。** | +| 桌面准备 PR 里唯一的行为修复:待切模型落到无推理档位的模型 | 用户定:并进桌面准备 PR,不单独发(审核方转达,2026-11-16)。提交 `7f86f08f2c`(`fix(desktop)`,桌面准备分支,只改 `pendingCredentialSwitchAssembly.ts` 的 `persistRoute` 与测试,不含任何搬移)。现象:回合中换模型登记的待切,回合结束落地时 `persistRoute` 把解析出的 `effort: null` 写进 `sessions.effort`,该列在已安装的库上 NOT NULL(`drizzle/0000_init.sql`),写库失败,待切一直挂着、每次回合结束重试,任务的输入队列一直不被唤醒。触发条件:目标模型没有推理档位;影响面:目录里 19 个这样的模型(如 `anthropic/claude-haiku-4-5`、`claude-sonnet-4-5`、`xai/grok-4.20` 两个、qwen3.6/3.7 几个、kimi-k2.6/k2.7-code、glm-5.1、mimo-v2.6 系列)。origin/main 上的复现原文:`NOT NULL constraint failed: sessions.effort`。修复:经 `persistableSessionEffort`,空值不写这一列(与 `persistSessionFieldsWith` 相同),库里保留旧档位,进程内档位仍置空。**发布时必须做到**:① PR 正文单列一节“本 PR 唯一的行为修复”,写现象、触发条件、影响面、origin/main 上的复现原文、修复后的结果、为什么并在这里;摘要第一段说明“除这一处修复外桌面行为不变”;变更类型同时勾 refactor 和 fix。② 累计逐行对照里这个提交单列为“非搬移”,不计入“搬走的行都能找到”。③ 以后再发现桌面原有缺陷,照这次的流程:先在 origin/main 上复现并报审核方,由审核方问用户,不默认并进来。Host 侧:修复合进集成分支后,Host 的 settle 测试补一条“目标模型没有推理档位也能落地” | +| 搬移纪律(检查点 3b-1 记) | 工厂产物不用和 `register.ts` 已有导入同名的名字(`setSessionEffort` 曾遮住同名导入,四处调用会指向新常量);交付前把 lint 的“导入未使用”当必查项,它是同名遮蔽的报警信号。改写本地提交后,新旧两端各做一次 `git diff`,只剩预期的差别再报 | +| `plugin_push` 事件 | Host 通用的“推给客户端某个频道”机制,不只管插件:模型访问状态、登录、Codex 路线、插件、确认请求、待切凭据的生效与失败、思考偏好都走它。web shim 按频道白名单转给对应订阅,不在表里的频道丢弃 | +| 合 main 后 Host 测试变红的记法 | 每次合 main 后,Host 测试里因主干改动变红的条目单列:哪个提交引起的、改的是测试还是产品代码。2026-11-16 第一次:主干让队列在归属变化后拦住收尾写入(`input-queue.mjs` `dispose`),本分支 4 个夹具先删数据库、后关队列,8 条在收尾失败;改的是测试(e04357a456,改用 `lifoCleanup`) | | Host 改任务路由的四个入口(`updateSession`、删除、丢弃、插件页面会话恢复) | 未经真实装配的自动测试:这几个函数在 `main.ts` 组合根里,单元测试与 e2e 都不经过它们(插件测试用的是假的恢复函数)。检查点 3 给它们包上发送锁时,函数体没改,只有包装本身有测试(`input-queue.test.mjs` “a task route without contention …”)。补一条经真实装配的测试,不在这一批 | | `apps/host/scripts/plugins-installed.e2e.mjs` | 未完整运行:缺 Playwright `chromium_headless_shell-1243`,`cdn.playwright.dev` 下载超时。自 Pi 桥修复起一直只跑到打开插件页面之前。网络恢复后安装并完整运行;在此之前引用它的验证都写「未完整运行」 | | 迁移后 Host 用哪个 profile 目录 | 已由交接任务确认(m1-cp18b 记录):迁移器把 Host 固定在用户现有的桌面 profile 上,原地使用,不搬到 `/CindyHost/<区域>`、不复制数据;启动 Host 时显式设 `CINDY_HOST_DATA_DIR` 为这个 profile,去掉继承来的 `XDT_USER_DATA_DIR` 等隔离变量,核对目录身份;客户端窗口仍用同一个桌面 userData。`/CindyHost/<区域>` 只是独立启动的 Host 的默认值。依据是交接任务对其分支实现的只读核对,不是真实迁移的验收结果;M4 联合验收时实测。本表各处“两边共用一个 profile”的前提与之前的对照测试据此成立。同一目录不等于每类旧文件与凭据都兼容:Host 在试运行期间写下的东西,激活前试运行失败、回到旧桌面时必须能被旧桌面读懂,逐类依据记在第三节「Host 在 profile 内与窗口进程共用的文件」,其余各类补齐中。账号库只能有一个业务写者,由 profile lease 保证 | | 登录凭据的联合验收 | **未验证,M4 联合验收,归属:交接任务主导、我们提供 Host 侧读取与写回的事实。** 共享路径和格式只是必要条件,不是兼容证明;刚完成的普通个人版升级不能替代这次验收。验收四项:① 实际签名的辅助进程解密旧凭据,以及系统授权的表现(不能承诺辅助进程不弹钥匙串授权);② Host 写入之后桌面反向解密;③ 真实轮换后失败回退并继续刷新;④ 刷新请求在途、远端已轮换但本地落盘失败或进程崩溃时的恢复(不能默认保证无损登录,也不能把失败处理成覆盖旧令牌)。设计要求(交接任务答复):「接管会话」是交出唯一写权和运行归属,不是明文通道,联合验收沿用同一个 `AUTH_SESSION_KEY`、同一个加密文件;回退前先停掉 Host 的全部登录写入与刷新、把写权还给桌面,旧桌面重读当前文件,不得恢复旧快照,也不得用内存里的旧刷新令牌。第 ④ 项两边现在的做法见下面三行(只记事实,按代码阅读,未运行;要不要在 M4 之前对齐由审核方定) | | ④ 现状:Host | 只有一个来源:`apps/host/src/auth/refresh.mjs` 读 `AUTH_SESSION_KEY` → 发刷新请求 → 令牌轮换时先原子写回 `AUTH_SESSION_KEY`(同目录临时文件再改名,保留原记录的 `hostDeviceId`),写成功才返回新访问令牌;`main.ts` 的 `resolveAccountUser` 再用它调 `getMe`、核对 owner,都通过后才设 `currentSessionToken`。即先落盘、后使用。**落盘失败**:写入抛错(不是确定性失效),`performAuthRefresh` 只记警告、返回 false;新的刷新令牌与访问令牌都丢弃,内存里留的是上一次的访问令牌(到期前仍可用),盘上是远端已作废的旧刷新令牌。没有专门的重试,下一次刷新来自 30 分钟定时器或请求遇到 401;那次读到旧令牌,服务端拒绝(`INVALID_REFRESH_TOKEN`,与桌面同一个 `isDefinitiveRefreshError`),`invalidateHostSession('account-unavailable')` 把 Host 置为未登录,需重新登录;作废流程不删盘上记录。**崩溃**:远端轮换后、写回前崩溃,盘上是旧令牌,下次启动同上;写回是单文件原子替换,不存在写了一半的记录。写回成功后 `getMe` 或 owner 核对失败时,盘上已是新令牌,下次刷新用它。刷新前后不重读、被拒后不复查,不读账号库,也不读旧版独立刷新令牌;不拿账号库的跨进程锁,唯一写者靠 profile 租约保证 | | ④ 现状:桌面 | 运行时刷新与冷启动都走 `runRefreshWithReplacementRetry`(`authRefreshFailure.ts:285`)。候选来源三个(`readStoredRefreshTokenCandidates`:v1 `AUTH_SESSION_KEY`、账号库当前账号的资源令牌、旧版独立刷新令牌),本轮被拒过的不再选;被拒而盘上没变时按延时重读(覆盖“远端已消费、写回的一方还没落盘”的窗口),最多 2 次替换重试。成功后 `commitDesktopRefreshCredentials`:在账号库的跨进程锁里先写账号库,再在同一把锁里写 v1 记录并镜像旧版独立令牌;锁忙时一直等(注释:远端已轮换,锁忙不能当作可放弃的失败),存储不可用立即失败。写成功才把新访问令牌放进内存,也是先落盘、后使用。**落盘失败**:v1 写不进时,`transactAuthAccountVault` 把账号库恢复成写前原文,抛 `CREDENTIAL_STORE_UNAVAILABLE`;运行时被外层捕获,按瞬时失败排重试,新令牌丢弃,内存留旧访问令牌;冷启动则以未登录返回(该处注释假定新令牌已落盘,提交本身失败时不成立)。盘上三处都是旧令牌,下一次刷新被拒、重读后无替换候选,判为确定性失效:运行时 `expireRuntimeAuth` 登出,冷启动清掉已确认被拒的令牌。恢复写前原文也失败时,账号库留着新令牌,下一次刷新可经替换重试取回。**崩溃**:拿到响应、写账号库之前崩溃,全是旧令牌,结局同上;写完账号库、写 v1 之前崩溃(回滚不会执行),账号库新、v1 旧,下次 v1 被拒后经替换重试取到账号库的新令牌,登录保住;写完 v1、镜像旧版之前崩溃,下次直接用 v1 | -| ④ 现状:两边的差别 | 1. 两边都先落盘、后使用,都不会把落盘失败处理成覆盖或删除旧令牌(Host 不写,桌面恢复写前原文);远端已轮换而本地没落下新令牌时,两边都保不住登录,下次刷新被拒后需重新登录。2. 桌面多一个可恢复的崩溃窗口:写完账号库、写 v1 之前崩溃可经替换重试恢复;Host 只写一处,没有这个窗口,也没有对应的恢复。3. 被拒后的重读与替换重试只有桌面有;Host 靠 profile 租约保证同一时刻只有一个刷新者,租约内不影响结果,但写权交接前后对方刚写下的新令牌,Host 不会重读。4. Host 轮换时只写 `AUTH_SESSION_KEY`,不更新账号库里当前账号的资源令牌,也不镜像旧版独立令牌;回退到旧桌面后,桌面优先读 v1(新令牌),提交时以 v1 匹配认定仍持有会话,随后把账号库更新为新值(按代码阅读);账号库与旧版独立令牌在此之前停在 Host 轮换前的值。5. 失败后的重试节奏:桌面运行时按瞬时失败排重试、冷启动有退避循环;Host 只有 30 分钟定时器与 401 触发。6. 设备身份:Host 写回保留记录里的 `hostDeviceId`;桌面轮换写回不带它,之后 Host 的设备身份回落到覆盖值或物理设备号;采用桌面已有登录时记录本来没有这个字段,不受影响(见第三节「账号会话记录」) | -| ④ M4 联合验收时要回答的问题 | 审核方 m1-cp18b2 前决定:M4 之前不对齐,保持现状,记录在案;理由是远端已轮换而本地没落盘时两边结局相同,Host 少的“被拒后重读盘、换候选重试”与“同步更新账号库”在 Host 持有 profile 租约、是唯一刷新者期间不起作用,有影响的只在写权交接前后,要靠 M4 用真实产物实测。要回答:1. 写权从桌面交给 Host 的那一刻,Host 读到的是否一定是桌面最后写下的那份。代码上的事实(m1-cp18b2 核对):Host 每次刷新都重新读盘,不用启动时读进内存的那份:`main.ts` 的 `resolveAccountUser` 每次新建凭据库,`refresh.mjs` 每次从 `AUTH_SESSION_KEY` 读、`store.mjs` 的 `read` 每次读文件并解密,没有缓存;内存里只留访问令牌(`currentSessionToken`),不留刷新令牌;设备身份也每次从同一份记录读。交接时刻的实际表现待实测。2. Host 轮换过之后回退,旧桌面按“v1 优先、账号库那份被拒后不再选用”能否继续刷新:上面“两边的差别”第 4 条是按代码推断,**待实测**。3. 如果实测掉登录,候选补法:Host 被拒后重读盘一次再判失效;Host 轮换时同步更新账号库里的资源令牌。只列为候选,不预做 | +| ④ 现状:两边的差别 | 1. 两边都先落盘、后使用,都不会把落盘失败处理成覆盖或删除旧令牌(Host 不写,桌面恢复写前原文);远端已轮换而本地没落下新令牌时,两边都保不住登录,下次刷新被拒后需重新登录。2. 桌面多一个可恢复的崩溃窗口:写完账号库、写 v1 之前崩溃可经替换重试恢复;Host 只写一处,没有这个窗口,也没有对应的恢复。3. 被拒后的重读与替换重试只有桌面有;Host 靠 profile 租约保证同一时刻只有一个刷新者,租约内不影响结果,但写权交接前后对方刚写下的新令牌,Host 不会重读。4. Host 轮换时只写 `AUTH_SESSION_KEY`,不更新账号库里当前账号的资源令牌,也不镜像旧版独立令牌;回退到旧桌面后,桌面优先读 v1(新令牌),提交时以 v1 匹配认定仍持有会话,随后把账号库更新为新值(按代码阅读);账号库与旧版独立令牌在此之前停在 Host 轮换前的值。5. 失败后的重试节奏:桌面运行时按瞬时失败排重试、冷启动有退避循环;Host 只有 30 分钟定时器与 401 触发(2026-11-17 起已与桌面对齐,见第五节并存行后续九)。6. 设备身份:Host 写回保留记录里的 `hostDeviceId`;桌面轮换写回不带它,之后 Host 的设备身份回落到覆盖值或物理设备号;采用桌面已有登录时记录本来没有这个字段,不受影响(见第三节「账号会话记录」) | +| ④ 窗口的三个写入点(客户端模式下窗口本地切换、添加账号时的第二个写方;2026-11-17 按代码逐个核对,未运行) | 三处都拿同一把跨进程锁 `.cindy-auth-accounts-v1.lock`(`AUTH_ACCOUNT_VAULT_LOCK_FILE`,经 `transactAuthAccountVault`,`authManager.ts:1207`),都在锁内先重读再写,**没有不拿锁直接写的**。窗口与 Host 用的是同一个 profile(第五节「迁移后 Host 用哪个 profile 目录」),所以是同一个锁文件;凭据层面由 C 兜住(Host 在同一把锁里重读、按同一条规则写,见并存行后续九)。① `switchSavedAccount`(`:4106`):选账号时在锁外读一次账号库,只读;续这个账号经 `refreshSavedResourceSession`(`:1782`),成功写回 `replaceResourceSessionIfCurrent`(`:1413`)、被拒删除 `removeRejectedResourceSession`(`:1439`),都经 `mutateAuthAccountVault`(`:1308`):锁内 `readAuthAccountVault` 重读,与这次请求用的令牌比对,不一致不写;没有资源令牌时走 passport:`refreshPassportSessionSingleFlight` → `replacePassportSessionIfCurrent`(`:1576`,同锁、锁内重读、比对 passport 令牌);最后进 `completeLogin`。② `completeLogin`(`:5299`):`commitDesktopLoginSessions`(`:1502`)经 `transactAuthAccountVault`,锁内重读账号库后写资源令牌与 passport;v1 在同一把锁里写:先重读 v1(留作回滚),再 `writePersistedAuthSessionOrThrow`(并镜像旧版令牌),后续失败在锁内回滚。显式登录,不比对旧令牌,直接取代。③ `rememberResourceSession`(`:1387`):`mutateAuthAccountVault`,锁内重读后写;不比对令牌(写的是刚经 passport 换来的令牌)。注:窗口写 v1 不带 `hostDeviceId`(第三节「账号会话记录」)。窗口切到 B 而 Host 还在跑 A 的语义问题已另立项,不在这里 | +| ④ M4 联合验收时要回答的问题 | 审核方 m1-cp18b2 前决定:M4 之前不对齐,保持现状,记录在案;理由是远端已轮换而本地没落盘时两边结局相同,Host 少的“被拒后重读盘、换候选重试”与“同步更新账号库”在 Host 持有 profile 租约、是唯一刷新者期间不起作用,有影响的只在写权交接前后,要靠 M4 用真实产物实测。要回答:1. 写权从桌面交给 Host 的那一刻,Host 读到的是否一定是桌面最后写下的那份。代码上的事实(m1-cp18b2 核对):Host 每次刷新都重新读盘,不用启动时读进内存的那份:`main.ts` 的 `resolveAccountUser` 每次新建凭据库,`refresh.mjs` 每次从 `AUTH_SESSION_KEY` 读、`store.mjs` 的 `read` 每次读文件并解密,没有缓存;内存里只留访问令牌(`currentSessionToken`),不留刷新令牌;设备身份也每次从同一份记录读。交接时刻的实际表现待实测。2. Host 轮换过之后回退,旧桌面按“v1 优先、账号库那份被拒后不再选用”能否继续刷新:上面“两边的差别”第 4 条是按代码推断,**待实测**。复现结论(2026-11-17,审核方接受;桌面 `authColdStartRecovery.test.ts` 的场景 2,C 之前也成立):**桌面冷启动从 v1 起步,续期成功后在锁里把保管库补回来;前提是保管库的当前账号仍是 A**(`applyRefreshedCredentialsToVault` 要 v1 仍是这枚令牌且 `activeAccountKey` 是 A 才认作仍持有会话)。这回答了“迁移后能不能回退”里和登录有关的那一半;实际产物上的表现仍待 M4 实测。保管库里没有任何账号时(账号只在 Host 上登录过),冷启动经 `canClaimUninitializedVault` 认领空保管库,同样接上(同一文件的第三条用例)。3. 如果实测掉登录,候选补法:Host 被拒后重读盘一次再判失效;Host 轮换时同步更新账号库里的资源令牌。只列为候选,不预做(2026-11-17 已按 C 做了:被拒后替换重试、写回账号库与旧版令牌,见并存行后续九;上面两行“现状”是那之前的记录) | | 引擎版本目录的联合验收 | **未验证,M4 联合验收**:旧 Host 持续运行期间安装新版本,在用的引擎版本目录不被覆盖或删除(随包路径与管理器下载路径两类都要覆盖)。与第 34 行“引擎二进制管理(8k)”一起 | | Host 源码运行下的 Pi 持久子代理(m1-cp18c 发现) | Host 用 tsx 跑源码(开发、测试、e2e)时,maker-core 写出的 runner.cjs 里嵌入的 `createPiCacheInputTracker.toString()` 带 tsx 的 `__name` 辅助函数,runner 进程里没有它,真实 runner 一启动就以 `ReferenceError: __name is not defined` 失败。发布构建(esbuild,不保留函数名)不受影响;`pi-subagent-runner.test.mjs` 按发布构建的方式先用 esbuild 打包这份源码再取用。源码运行下的 Pi 持久子代理因此不可用,未改(审核方:现在不修,记录在案)。桌面开发时是否受影响是推断,没有实测。M4 联合验收时用发布构建真实起一次持久子代理;以后给持久子代理加走真实 Pi 的 e2e,不能在 tsx 下跑 | | 基线缺口:`apps/host/scripts/codex-runtime.e2e.mjs` 在 Ubuntu 上跑不完 | 上下文恢复检查点 7 在自有电脑 ubuntu-211(Ubuntu x64,快照 `ce4d7cf79e`)上运行:前 9 段全过(含新的 Codex 溢出恢复),在“a Codex tool command ran inside the task”一段失败,日志里 17 处 bubblewrap 不能创建用户命名空间。同一台机器上换回 `5cb79e5dc2`(上下文恢复开始之前)跑同一脚本,同一处失败,按那台机器的环境限制记录,不修。这一段之后的几段(memory、自动审核等)在 Ubuntu 上未覆盖;macOS 上完整通过 | @@ -259,22 +436,383 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | 通道清单重新生成(合并 main 后为 1466 个) | 在下一个确实需要的检查点提交,写明新增的 10 个通道及归类 | | 带界面的验证 | 用户已允许(隔离沙箱、复用 host-usage);2e 之前客户端模式只做导航与读取 | | 测试纪律:会碰到 Codex 登录的运行 | host-usage 沙箱的 codex-home/auth.json 链着本机真实的 Codex 登录,Host 在那里走到 Codex、订阅桥或作废逻辑就可能经链接改写它。凡是会让这些跑起来的运行,一律用 HOME 隔离、假登录的 profile;host-usage 只做不触发这些路径的只读检查,拿不准就不用 | -| 合并 main 之后的核对 | 每次合并 main,检查这次合并改到的桌面函数里有没有 Host 重写过的对应实现(范围是 C3 盘点的丙类清单),有就在汇报里列出并跟上(审核方 m1-cp18e 定)。m1-cp18e 对本分支已有的合并补查:`d142106052` 已跟上,`b1c5d88705` 见第二节「引擎二进制的路径」,`c783b679b9` 属 M2 的供应商视图,`73270d8f06`(Codex 线程历史目录)归 m1-cp18d | +| 合并 main 之后的核对 | 每次合并 main,检查这次合并改到的桌面函数里有没有 Host 重写过的对应实现(范围是 C3 盘点的丙类清单),有就在汇报里列出并跟上(审核方 m1-cp18e 定)。m1-cp18e 对本分支已有的合并补查:`d142106052` 已跟上,`b1c5d88705` 见第二节「引擎二进制的路径」,`c783b679b9` 属 M2 的供应商视图,`73270d8f06`(Codex 线程历史目录)归 m1-cp18d。2026-11-17 合并 main(落后 243 个提交,合到 fb2b13ab5d):改到 Host 重写过的桌面函数的有四个提交——`e322628568` 给共用的工作目录恢复加了端口 `canRecreateDirectory`(只在当前 owner 的命名空间里重建),Host 没绑,已跟上(`agent/working-directory.ts`,测试 `input-queue.test.mjs`“another owner's namespace”);`b276229eae`(本机代理路由就绪后再启动)提交本身已改了 Host 的 `runtime.ts`;`c743604b79`(只读开发快照复用)只改桌面 `auth-adapters.ts` 与 `codex-auth-link.ts` 内部,Host 用的 `codex-auth-link` 导出没变;`d4a65f3cd1` 只动历史读取,与 Host 重写无关 | +| 显式端口(2026-11-17,起因 main `e322628568`) | Host 传给共用工厂的端口一律经 `explicitPorts()`(`agent/explicit-ports.ts`):T 的每个可选端口都要写出来,接真或写 `undefined` 并注明为什么可以不绑;桌面以后新加可选端口,Host 在绑定处类型检查报错。已覆盖 `working-directory.ts`、`runtime-selection.ts`、`context-recovery-assembly.ts`、`context-recovery.ts`、`context-usage.ts`(32 处调用、6 个带类型的端口对象);检查点 4 新接的工厂直接这样写。这一遍查出的未绑可选端口与结论:换引擎处理器的五个换电脑端口(乙 5,Host 入口拒绝,走不到);上下文恢复的伙伴会话清单(Host 不跑伙伴)、订阅账号的原生会话交接(第 30 行,Host 未做发送前换号);上下文恢复的冷启动 Pi 窗口核实——桌面把同一个绑定给了改模型与恢复两处,Host 只给了改模型,已接真(`fc3a113f03`,测试“the context rollover resumes a released Pi task”)。memory.mjs 一批(2026-11-17):记忆管理器的端口包挪到 `agent/memory-manager-ports.ts`(第 11 行);cindy_memory 的 `memory` 依赖(`createHostMemoryMcpProviders`)也已挪到 `agent/memory-mcp-ports.ts`,经 `explicitPorts`(2026-11-17):`searchSessions` 接真(第 11 行);`searchProviders`(插件提供的记忆,第 33 行)、`beginWrite`(只记伙伴学习)、`getSessionContext`(provider 按任务自己补)写 `undefined`;`withAccountDataAccess` 接真(照抄桌面,第七节第 26 项;审核方 2026-11-17 定甲类)。其余 Host 文件尚未改写:类型扫描(scratchpad 脚本,按上下文类型找桌面或共用包里声明的可选成员)在 Host 其余文件里还有约 200 个对象字面量留着未写的可选成员,多数是每次调用的选项或数据形状,不是端口;待按“端口包”筛出后分批改写。runtime.ts 一批(2026-11-17):三个引擎的 AgentDeps 与 Maker 的 MakerDeps、生命周期钩子都经 `explicitPorts`。AgentDeps 是三个引擎共用的一个接口(87 个可选端口),按 maker-core 里哪个引擎的代码读它归类(`agent/agent-deps-engines.ts`:只有 Codex 读的 30 个、只有 Pi 读的 27 个、只有 Claude 读的 13 个、Claude 与 Pi 读的 2 个、Claude 与 Codex 读的 2 个;基类读的 13 个算三个引擎都读),每个引擎的端口包先写进别的引擎才读的那几组,再写自己读的每一个;引擎保存传入的对象原样、成员一律用 `?.` 或 `??` 读,所以显式写 `undefined` 与不写相同。条件展开改成直接写值(`getManagedSkills`、`getGhostRosterPrompt`、`makerMemory`、`resolveLocalMcpDuplicateChoices`、`registerPiProxySession`、`mcpProviders`);Codex 运行时的端口包改按字面量定型(原来是 `Partial`,会把所有键都算成已写),MCP 运行时的两包改为 `Required>`。这一遍查出、桌面绑了而 Host 没绑的端口与结论:远程执行那一组(Claude 3 个、Codex 2 个、Pi 7 个,含远端 Pi 的代理令牌派生)——send-preflight 拒绝远程任务(第七节第 18 行);伙伴的会话环境(第四节,M3);SkillHub 发现隔离(第四节,M2);Codex 的 Skill 投影(第 25 行)与 host-tools-only 工具目录(第 29 行);Pi 的项目信任输入——桌面也没绑(`pi-host.ts` 收这个选项,`maker-host/index.ts` 不传),两边一样;换电脑启动 Agent(乙 5);生命周期的 `onStartSucceeded`(桌面只做协同与伙伴的事)与 `isTransientCloseRequest`(只让瞬态重建跳过暂存附件与工作树池的清理,Host 的 onClose 没有这两样);Codex 的出站路径事实——当时 Host 的出站解析不记判定,记为第二节已知差别;28a 已接上(第 28 行)。真缺口一个,已接上:Codex 的服务端压缩选择(`getCodexServerCompactionPreference`),桌面每次启动 Codex 读用户在窗口里的选择,Host 原来不传、选择被忽略;现在读 owner 目录里同一个文件(测试 `engine-deps.test.mjs`“server-compaction”,改坏会红) | +| 验证纪律:Host 类型检查的堆 | 本机跑 `NODE_OPTIONS=--max-old-space-size=8192 pnpm --filter @cindy/host typecheck`(与 CI 相同;12288 也可);不设时默认堆会 OOM(rc 134)。CI(`.github/workflows/ci.yml`)的 Host 作业不单独设,靠工作流全局的 `NODE_OPTIONS: '--max-old-space-size=8192'`;发布 Host PR 前若工作流的全局值改了,要回头核 | +| 验证纪律:改 Host 文件时连读 Host 文件的桌面测试一起跑(2026-11-17) | 桌面有 36 个测试文件读 `apps/host` 的源码(guard 层的 `hostDesktopSourceContracts.guard.test.ts` 等,清单用 `grep -rlE "apps/host\|hostAgent\|host/src" apps/desktop/src --include="*.test.ts"` 取)。显式端口那一批(`70ae7d471c`)只跑了 Host 全量,漏了其中一条 guard(`40dd1413de` 补)。以后凡改 Host 文件,交付前连这批一起跑 | +| 准备分支与集成分支的桌面差异(2026-11-19) | 两个分支之间 `apps/desktop` 和 `packages` 只差三个只在集成分支的桌面测试文件:`src/main/__tests__/authColdStartRecovery.test.ts`、`hostDesktopSourceContracts.guard.test.ts` 读 Host 源码;`cindy-brain/__tests__/hostToolSlot.test.ts` 不读 Host 源码,是随第七节第 44 项新增的静默端口补桌面测试夹具一行(2026-11-19 复查更正)。它们要配集成分支上的 Host 代码,所以只留在集成分支。落地核对时以这三个文件为准,Host PR 正文写明 | +| 验证纪律:改坏能红之前先保存本单元的改动 | 做“故意改坏、看测试变红”之前,先把本单元的改动提交成一个本地临时提交,或存一份补丁文件;还原只用“回到那个提交 / 应用那份补丁”(或事先复制的备份文件),不对有未提交改动的文件用 `git checkout --`。3b-2 时曾用它还原改坏的文件,连带还原了自己未提交的改动,重新应用后逐字核对(`git diff` 与备份相同)才没有后果(审核方 3b-2 定) | | 测试纪律:用发布构建跑 Host | 发布构建(带发布清单)会被认成安装版,与运行它的系统用户的 `~/.codex/auth.json` 对账、链接(与打包后的桌面在沙箱 profile 里的行为相同;m1-cp13 之前 Host 不读系统登录)。凡是用发布构建跑 Host 的测试(验证安装包、M4 的联合验收等),HOME 必须隔离 | | 移交交接任务:发布构建与系统 Codex 登录 | 上一行的情况由审核方在 M1 发布时通知交接任务 | +| 基线缺口:`apps/host/scripts/scheduler-runtime.e2e.mjs` 加载即失败 | 不在 CI,自 main `41ed3b9f40`(2026-11-12)起坏了五天没人发现,2026-11-17 同步 main 后跑本机验收时才看到;原因与导入链见乙 1。不在 CI 的验收脚本会这样悄悄坏掉:4b 交付时附 `apps/host/scripts` 下所有不在 CI 的验收与 e2e 脚本能否加载并开始的清单 | +| 基线失败:`apps/desktop/src/main/maker-ipc/__tests__/chatServer.test.ts`“settles the group alert through stopping a failed plan without needing its Session” | 2026-11-17 同步 main 时发现:单独跑、每次都失败(`dismissPlan` 返回不 ok);在干净的 origin/main `e92a1b5947` 上同样失败,与本线改动无关(这个测试和被测文件都与 main 逐字相同)。不在本线修 | | 基线抖动:`apps/desktop/src/main/__tests__/worktreeRecycleJournalFilesystem.test.ts`“detects atomic replacements from an independent file writer” | m1-cp18c 门禁里失败一次(文件监听在负载下 1 秒内没收到变更通知);文件与被测代码本分支没有改动,单文件重跑 5 次全过,整组桌面测试重跑全过。以后门禁里它再失败,先单文件重跑,过了按基线记(审核方 m1-cp18c 复核时定) | | 基线抖动:`packages/anthropic-compat-proxy/src/server-websocket.test.ts`“forwards the upgrade handshake, strips /v1, and pipes buffered bytes both ways” | m1-cp15a 门禁里失败一次(断言 SERVER_HEAD 时缓冲为空,5ms),该包自 m1-cp14 起没有改动;单文件重跑 5 次全过、整包重跑 578/578。以后门禁里它再失败,先单文件重跑,过了按基线记 | | 负载下超时:`apps/desktop/src/main/maker-host/__tests__/authAdaptersImportPurity.test.ts` | main 上已有的测试,自带 20 秒超时。m1-cp6 把 cindy-brain、maker-host、plugin-market 三个目录一起跑时超时,单独跑 6 秒通过。不归本分支 | +| 偶发、未复现:`session-import/__tests__/foreignSourceAdapters.test.ts` 的 OpenCode 一条 | 25a 的 Worker 在临时 HOME 下、和 400 多个文件一起并发跑 `vitest related` 时失败过一次。之后 origin/main d2c09ff142 单独跑 9/9、同一 related 集合(421 个文件)通过;准备分支与 25a 分支各单独 3 遍(审核方)都 9/9。不算基线也不算本线引入;再出现时先怀疑并发或共享临时目录,不是 OpenCode 本身 | +| 负载下超时(第二次):`plugin-market/__tests__/service.test.ts` “hides counts instead of unbounded installed-count resolution” | 准备分支第四轮同步时与另一组 vitest 并发运行,5 秒超时;单独跑 3 次各约 220 ms、整个文件 379/379。本线未改 plugin-market(与 origin/main 的 diff 为空)。第二次出现,不再判偶发:是主干测试对负载敏感(默认 5 秒超时),归主干测试问题,不在本线修 | +| 负载下超时(第三次):`plugin-market/__tests__/service.test.ts` “hides counts instead of unbounded installed-count resolution” | 2026-11-17 集成分支验证时在高负载下 5000 ms 超时,单独重跑整个文件 379/379 通过。第三次出现,与第二次同一结论:主干测试对负载敏感(默认 5 秒超时),归主干测试问题,不在本线修 | +| 基线问题,在高负载下不稳定:`apps/desktop/src/main/remote-agent/__tests__/groupRelayClaudeFork.e2e.test.ts` 2 项(“forks native history on M with relay routing / direct routing and preserves native failures”) | 已知的主干基线问题,在高负载下不稳定。2026-11-17 在 4b 桌面提交的 `vitest related`(451 个文件并发)里 2 项失败(`[REMOTE_AGENT_FORK_FAILED] the conversation could not be forked on the computer running this task`),单独重跑 2/2 通过,合并后整轮重跑也通过;本线没有改 remote-agent。不在本线修;以后门禁里它再失败,先单文件重跑,过了按基线记 | +| 测试写法的已知风险:`apps/host/src/agent/input-queue.test.mjs` 里按次数轮询的 `waitFor`(2026-11-17,审核方定) | **不是生产问题,是测试写法**:`waitFor` 每 5 ms 看一次、最多看 200 次,按次数而不是按真实时间放弃;凡是要等的事经过后台线程(例如一条消息到达假引擎之前,发送的工作目录检查要经 libuv 线程池 stat profile 里的恢复目录,`dialogueRecoveryWorkspace.ts`,目录探测自己另有 5 秒上限),负载高时次数先用完,测试就“少数了一个”。清单不放在仓库里,按需重新生成:`grep -n 'waitFor(' apps/host/src/agent/input-queue.test.mjs` 列出的每一行就是一处(定义写作 `const waitFor = …`,不在其中),所在的测试是它上方最近的一个 `test(`;判定标准是 `waitFor(() => …length === N)`、`…sent.length > 0` 这类按次数轮询、去等经过后台线程才会发生的事的写法。2026-11-17 统计为 199 处,分布在 120 条用例或辅助函数里。以后这个文件里再出现“少数了一个”的偶发失败,先对照这份清单查。规矩:这个文件里新写的测试,凡是要等“消息到达引擎”这类经过后台线程的事,一律用事件等待的辅助函数(`enqueueUntilSent` 一类:等假引擎的 `onSent` 或输入落定的事件,30 秒真实时间上限只防挂住,报红时写明是哪个事件没等到;这个上限是真实计时器,`check:test-hygiene` 的 realWaits 规则会把它算作真实等待,所以它上一行写着 `// real-wait: <原因>`,新的防挂住上限照此标注,不改基线),不再新增按次数轮询的写法;自动续跑一族与 mock 时钟下的等待用 `settleUntil` / `resumeHarness` 的 `dispatched`。本次已改的两处(`cb43b9ce17`、`b3d2417f58`):`enqueue` 辅助函数,以及“a send to a task whose ordinary directory was deleted recreates it”里的第二次发送。证据摘要:受控负载窗口(每边 36 份同时跑、2 轮、72 次)修前 0/72、修后 0/72,自然负载下没有复现(此前一次 4/72 出现在负载中位约 23.6 时);确定性复现只拖慢恢复目录的那一个 stat 1.5 秒,修前 3/3 失败,`waitFor` 放弃后约 1.8 秒(1820–1888 ms)消息确实到达了引擎,修后 3/3 通过;三种改坏都报红:第一次发送被吞掉、第二次发送被吞掉(都在 30 秒上限报出是第几条消息没到),引擎抛错(约 2 秒就报“输入没到引擎就落定”) | +| 主干测试的环境依赖(macOS 临时目录):`cindy-make/__tests__/personalBuild.git-integration.test.ts` 10 项、`taskCleanup.git-integration.test.ts` 1 项 | **CI(Linux、英文环境)不受影响,只在 macOS 或中文系统语言的本机上出现。** 2026-11-17 准备分支扩大读者集合时出现,拿主干 `e8b5e2fd96` 在同样环境下对照,两边失败相同、报错相同(“Unexpected Cindy Make worktree”“Cindy Make task unavailable”)。原因:macOS 的 `os.tmpdir()` 是 `/var/folders/…`,真实路径在 `/private/var/…`;两个测试用 `mkdtemp(os.tmpdir())` 建目录不取真实路径,生产代码(`completion.ts` 的 worktree 真实路径比对、`taskCleanup.ts` 拿 `git worktree list` 的真实路径比对)对不上就拒绝。把 TMPDIR 设成真实路径后两边都通过。修复建议:两个测试取 `realpath(os.tmpdir())`,或 git-integration 这一档统一把 TMPDIR 设成真实路径。不在本线修;本机的准备分支读者集合脚本暂时带 TMPDIR=真实路径,主干修掉后去掉 | +| 主干测试的环境依赖(系统语言):`localDb/ipc/__tests__/botRemoteEditors.test.ts` “lists and switches only the automations of the teammate project” | **CI(Linux、英文环境)不受影响,只在 macOS 或中文系统语言的本机上出现。** 生产代码 `botRemoteAutomations.ts` 按 `localeCompare` 排序,中文系统语言下按拼音(“早报”在前),英文或 C 下“周报”在前;测试期望英文顺序。拿主干 `e8b5e2fd96` 对照两边相同,LANG=en_US.UTF-8 后两边都通过。修复建议:排序固定语言或按码点比较,或只在测试里固定 LANG。不在本线修;本机读者集合脚本暂时带 LANG=en_US.UTF-8,主干修掉后去掉 | +| 主干测试等待太短(文件监听):`local-themes/__tests__/omarchy.test.ts` “未装 Omarchy 不监听;主题目录整体替换后仍回调” | **CI(Linux、英文环境)不受影响,只在 macOS 或中文系统语言的本机上出现。** `vi.waitFor` 默认只等 1 秒,本机文件监听事件实测 410–592 ms、有一次 1184 ms;并行跑时与 git 集成测试同压文件系统就超过 1 秒。拿主干 `e8b5e2fd96` 对照两边相同;单独或串行跑两边都通过。修复建议:把等待加到约 5 秒。不在本线修 | +| 主干既有的不稳定:`maker-host/__tests__/pi-package-store-security.test.ts` 三个用例 | 2026-11-17 拿主干 `e8b5e2fd96` 与准备分支在同样环境(TMPDIR 为真实路径、英文语言、临时 HOME 放假 git 身份)下只跑这一个文件,一个槽、两边交替各 20 次,开始时负载都低于 12:整个文件主干 13/20 次失败、准备分支 8/20(Fisher 双侧 p=0.205)。“reattaches the directory watcher after the package home is replaced”主干 6/20、准备分支 4/20(断言“expected 2 to be greater than or equal to 3”或“0 >= 1”);“converges local runtimes when a failed initial runtime-token read recovers after a peer-only edge”主干 9/20、准备分支 3/20;“shares deterministic snapshot failures and clears them through a production update”主干 4/20、准备分支 2/20(5000 ms 超时)。准备分支的失败率不高于主干,所以不是我们的搬移或合并引起的;另外这个测试 mock 掉了 `agent-binaries/index.js`,去掉被 mock 的模块后它的导入闭包里没有准备分支改过的文件。此前一次“串行时准备分支 2/2 失败、主干 2/2 通过”是小样本碰巧。不在本线修。**发布前检查的两条规则(审核方 2026-11-17)**:一、跑“读到我们改动的测试”时,这个文件只豁免上面三个用例名;它里面别的用例失败,或这三个用例出现新的断言原文,仍按我们的问题查。二、“导入闭包里没有我们改过的文件”是在准备分支 `314ca7960c` 上算的;最后一次合并主干之后重算这个交集(之后又加了 `messages.ts` / `messagePrRefs.ts` 等改动),不为空就重新对照 | +| 发布前验证的环境要求:文件监听(审核方 2026-11-18 定) | 2026-11-18 起开发机的 macOS FSEvents 不投递事件(`fs.watch` 与 `@parcel/watcher` 默认后端都收不到,kqueue 后端正常;前一天同机正常),依赖文件监听的测试(例如 `file-browser/__tests__/deviceOp.test.ts` 的 watch 用例、`local-themes/__tests__/omarchy.test.ts`、`pi-package-store-security.test.ts` 的监听用例)在这样的环境里一律失败,拿主干与准备分支各 20 次对照,三点失败率相同,与代码无关。同一原因也影响 `remote-agent/__tests__/codexHosted.e2e.test.ts` 的 “releases an idle task under slot pressure and resumes the same Codex thread”:Codex 二进制内置 notify-rs 的 FSEvents 后端,`thread/resume` 期间那个线程一直停在 `FSEventStreamStop` 等 fseventsd 回应(2026-11-18 用 `sample` 抓到),用例在 60 秒超时上失败或贴着超时通过;集成分支 505271b077、9f559bdfc6、9c8eed10a0 上都一样,不是回归,记“未验证”,FSEvents 恢复后在 505271b077 与当时的集成分支上各跑 3 次复核。FSEvents 卡住时 codex 进程收到 SIGTERM 也可能不退,跑完要按 PID 核对有没有残留。规则:环境异常期间,这类失败既不算我们的问题也不算通过,报告里标“本机 FSEvents 异常,未验证”;**发布前最后一轮验证(读者集合、related、整套)必须在 FSEvents 正常的环境里跑**,并且用仓库 `.nvmrc` 指定的 Node 版本(现为 22.22.3)和当时 CI 的 setup-node `22` 实际安装的 22.x 最新版(2026-11-18 主干 CI 实装 22.23.4,也出现过 22.23.5)各跑一轮,报告写明版本号(审核方 2026-11-18 定)(用户 2026-11-18 决定不重启这台机器,原话“最好不要重启,像其他办法解决”(“像”应为“想”);整批验证改在文件监听正常的自有 macOS 机器上做:只在任务目录里,不装系统级东西,下载先报清单,跑完清理;这台机器上不重启 fseventsd,也不要求用户操作),先用 `fs.watch` 探针确认几百毫秒内能收到事件;不能带着“未验证”的监听用例发 PR | +| 发布前最后一轮验证结果(2026-11-19) | 两轮都在文件监听正常的自有 macOS 机器上跑(`fs.watch` 探针十几毫秒收到事件),测试 HOME 用临时目录、不带登录凭据;除真实浏览器用例外,测试全在只放行回环网络的隔离里跑,真实 CLI(Claude、Codex、Pi)只在这层隔离里跑。**第一轮(主干同步 3 之前)**:Node 22.22.3 与 22.23.4 各一轮,集成分支 `d3b1cd17ba`、准备分支 `e5562035b9`、主干 `8ba68e1e1c`,锁文件三处相同。Host 全量、类型检查、ipc-route、provider-config、lifecycle 两版通过;依赖文件监听的用例(deviceOp watch、omarchy、`pi-package-store-security.test.ts` 199 项)两版通过;以前因读不到进程信息失败的五条两版通过。桌面 related 与读者集合的失败与同版主干相同,两处例外:omarchy 目录替换在候选分支的两批里超时(集成分支 22.22.3 读者集合、准备分支 22.23.4 related),同批主干通过,定向与真实路径复跑通过,记为“定向通过,批量里出现过两次超时”;`execServerProjection.e2e` 的别名用例两版方向相反(主干在 22.22.3 失败、集成分支在 22.23.4 失败),复跑通过。这台机器当时没有 Electron 运行时,依赖 Electron 的桌面文件由审核方在另一台 Mac 上补跑了 87 个(86 个通过,`claudeGrokSessionAffinity.integration` 按自身条件跳过 1 个;那台机器文件监听有故障),已被第二轮覆盖。**第二轮(主干同步 3 之后,Node 22.22.3)**:集成分支 `868941897a`、准备分支 `43a545067c`、主干 `af8bd193a3`,锁文件三处相同。集成分支 Host 全量 1055/0/0(隔离内 1040 条,加隔离外的浏览器两个文件 15 条)、lifecycle 通过。桌面 unit 全量用进程池跑(命令只把线程池换成进程池):准备分支与主干的失败项相同 134 项,准备分支独有 0,跳过 47 对 47;主干多出 4 条 `deviceLinkRemoteRecovery`,那次主干负载 50,属定时类用例。装上 Electron 42.11.12(官方发布页,两处校验值一致)后,依赖 Electron 的桌面文件在两个分支上全部执行:91 和 85 两份收集失败名单合计 96 个文件,加同步后新增依赖 Electron 的 3 个文件(`ghostUnreadStore`、`myIssuesSnapshotStore`、`anthropicCompatProxyStartup`)。其中 CI 不跑的 7 个文件(`piGatewaySessionAffinity.integration`、`piSharedSubscription.e2e`、`claudeHosted.e2e`、`codexHosted.e2e`、`groupRelayClaudeFork.e2e`、`piHosted.e2e`、`startupProbe.e2e`)已在自有电脑上实际执行;Pi 三个文件 18 条用仓库钉住的 Pi 版本(摘要核对一致)实际执行并通过,`claudeGrokSessionAffinity` 1 条指定 Claude 程序后通过。plugin-market 的 `agentTools`、`defaultMarketPluginSyncOutcome` 属 unit 档,CI 也会跑。依赖 Electron 的这批文件里,两个分支只有两条失败,主干同样失败,见本节“主干上发现的问题”。子进程记录(只记测试进程直接起的子进程)里没有 Electron 进程,也没有图形界面。文件监听登记的两条用例在两个分支上都通过:`codexHosted` 的 “releases an idle task under slot pressure and resumes the same Codex thread” 各 6 次(单跑 3 次、整文件 3 次),`claudeHosted` 的共享账号 A 冷启动各 3 次。真实浏览器用例(8i 夹具 1 条、`profile-pause.test.mjs` 真实页面 6 条、`scripts/plugin-sandbox.e2e.mjs`)在隔离里创建页面就崩,原因是浏览器自身沙箱不能套在外层隔离里;移到隔离外(临时 HOME、不带凭据、代理变量指向无人监听的回环端口)后两轮全部通过、0 跳过。隔离外这一层没有硬隔离:会读代理变量的请求被挡住,其他请求不受限。Cindy Make 七个文件 99 条在默认临时目录失败、真实路径通过,原因见上面的 macOS 临时目录一行,主干同样。桌面 unit 全量的偶发段错误见本节“主干上发现的问题” | +| 最后一轮自有电脑验证之后的改动(2026-11-19) | 自有电脑最后一轮验证在集成分支 `868941897a`、准备分支 `43a545067c` 上做。之后的改动只在开发机上复跑过(Host 全量 1058/0/0、两边类型检查、桌面读者集合无新增失败;这台机器的文件监听有故障):删一条只查表格式的 guard 用例(`434ed14264`);占用期间拒绝开启远程控制(`1f8420cd21`,`apps/host/src/device-link.ts`);不经 service 入口的分类守护(`640fef4859` 加在 `server.test.mjs`,后移到 `scripts/__tests__/host-server-hold-classification.test.mjs` 并进 `test:runner`);`/chat` 建任务前的占用检查(`85186f72b9`,`apps/host/src/chat.mjs`、`main.ts`);暂停续跑恢复主干行为、只在后台服务启用(准备分支 `97af5ce056` 的 `interruptedTurnAutoResumeHooks.ts` 与测试,集成分支 `5b53963b09` 的 `agent/auto-resume.ts`);三处测试小改(准备分支 `ca1232f084`:`authService.test.ts` 改严格相等,`authPassiveSharedInstance.test.ts` 挪注释)。都不涉及文件监听 | +| 主干同步 4 之后的验证(2026-11-19) | 主干钉在 `9354a65d1a`,集成分支 `eec45e4d65`、准备分支 `c09ea9369c`,锁文件与 `.nvmrc` 未变。**自有 macOS**(文件监听正常,Node 22.22.3;除浏览器三项外都在只放行回环网络的隔离里跑,测试用临时 HOME、不带登录凭据):集成分支 Host 全量隔离内 1042/0/0、浏览器两个文件隔离外 15/0/0、`scripts/plugin-sandbox.e2e.mjs` 与 lifecycle 通过,均 0 跳过;准备分支桌面 unit 全量(进程池)对同一主干逐条比对,失败 134 条与主干相同,准备分支独有 0,跳过集合相同;`pi-package-store-security.test.ts` 两边 199/0/0;开发机上因文件监听故障失败的 4 条(deviceOp watch、botSkillQueryIndex、botSkillRuntimeProjection 手动编辑刷新、botSkillService 跟随项目编辑)在自有 macOS 上两边都通过。装 Electron 42.11.12 与仓库钉住的 Pi 后,CI 不跑的 7 个文件加 `claudeGrokSessionAffinity` 两个分支结果相同、0 跳过,只有 `codexHosted` 风险命令与 `startupProbe` 两条失败,主干同机同命令同样失败(见“主干上发现的问题”);按新 SHA 重算依赖 Electron 的文件没有新增,但这一批文件本身同步 4 之后**没有在自有电脑上装 Electron 重跑**(最小集只要求跑新增的):准备分支进程池全量里因缺 Electron 没执行的 unit 文件共 88 个(86 个收集失败,加 `git-review/__tests__/deviceOp.test.ts` 与 `anthropicCompatProxyStartup`),审核方在开发机上对两个最终快照补跑:准备分支读者集合覆盖 43 个全过、另 43 个单独补跑 834 条全过;集成分支读者集合覆盖 45 个全过、另 41 个补跑 825 条全过(开发机文件监听有故障,这批不依赖监听);剩 plugin-market 的 `agentTools`、`defaultMarketPluginSyncOutcome` 两个 unit 文件留给 CI,它们上一次在自有电脑上跑是同步 3 那轮;子进程记录里没有 Electron 进程、没有图形界面。**开发机**:集成分支 Host 全量 1057/0/0、两边类型检查 0 错误;审核方宽模式读者集合集成分支 990 个文件 30293/41/47、准备分支 985 个文件 30287/41/47,41 条都是开发机已知的环境失败;`check:dco`、`check:test-hygiene`、`check:dev-docs`、`test:runner`、`test:guard` 等整串门禁两个分支都通过。之后准备分支只多一个法语文案提交 `f9af4fa0aa`(集成分支合并为 `aeea57da11`),只在开发机上复跑 i18n、术语表、`hostWordInCopy` 守护、登录页测试并重新生成截图 | +| 主干同步 5 之后的验证(2026-11-19) | 主干钉在 `5a92f62d24`,集成分支 `7b068f570a`、准备分支 `b9fa89f919`,锁文件与 `.nvmrc` 未变。**只在开发机上验证过**(用户 2026-11-19 定:本机验证通过就发,自有 macOS 的最小集在 PR 开出后补跑,结果补进来):集成分支 Host 全量 1057/0/0(带浏览器夹具)、两边类型检查 0 错误;审核方宽模式读者集合集成分支 996 个文件 30488/43/47、准备分支 991 个文件 30485/40/47,失败都是开发机已知的 38 条环境失败加 `pi-package-store-security` 的目录监听用例;同步清单读者集合两边只有 `deviceOp` 与 `omarchy` 的文件监听用例失败,主干同样失败;`vitest related`(45 个输入,`--maxWorkers=3`)两边各约 35 条失败,与主干同批对照同名的是 `runtime.integration` 21 条、两条数据库夹具、文件监听与并发超时,另有几条只在某一边整批出错、单独复跑通过(例如 `GhostManager.test.ts` 一条钩子超时,文件与主干相同),属并发下不稳定,不算已解决;`botCandidateRecovery` 两边 100/0;整串门禁两个分支都通过(集成分支 DCO 698/104、准备分支 99/18,`test:runner` 780/778)。开发机文件监听有故障,依赖监听的用例以上一轮自有 macOS 的结果和这次补跑的结果为准 | +| 主干同步 6 之后的验证(2026-11-19) | 主干钉在 `3ef44274d6`,集成分支 `1dd89e2966`、准备分支 `d76c822a05`,`.nvmrc` 未变;锁文件只多桌面渲染进程的两个依赖,两个工作区按锁文件重装(本机缓存已有,没有下载),重装同时去掉了 138 个当前锁文件里已经没有的陈旧包,此后依赖与锁文件一致。**开发机验证**(用户 2026-11-19 定:本机验证通过就发):集成分支 Host 全量 1057/0/0(带浏览器夹具)、Host 类型检查与两边桌面类型检查 0 错误;审核方宽模式读者集合集成分支 1020 个文件 31330/43/53、准备分支 1015 个文件 31324/43/53,失败是开发机已知的 38 条环境失败加文件监听类(`pi-package-store-security` 4~5 条,集成分支另有 `botSkillService` 一条,上一轮自有 macOS 上两边都通过),重装前后那 38 条不变;`deepLink.ts`、`sessionDeepLink.ts` 的读者集合 13 个文件两边各 484/0,`vitest related` 两边各 16229 过 / 2 失败 / 37 跳过,失败都是 `deviceOp.test.ts` 的文件监听用例,主干同样失败;整串门禁两个分支都通过(集成分支 DCO 699/106、准备分支 99/19,`test:runner` 781/779)。开发机文件监听有故障,依赖监听的用例以上一轮自有 macOS 的结果和这次补跑的结果为准。**自有 macOS 补跑**(Apple Silicon arm64,Node 22.22.3):准备分支 `d76c822a05`、集成分支 `49b01543ef` 对照主干 `3ef44274d6`。集成分支 Host 全量 1042/0/0,lifecycle 通过;第 2 层两个浏览器文件(Chromium 1243)15/0/0,plugin-sandbox e2e 通过。桌面 unit 全量(进程池,未装 Electron),准备分支 74523 通过、47 失败、44 跳过,主干 74455 通过、47 失败、44 跳过,失败和跳过逐条相同。装 Electron 后补跑原先收集失败的 88 个文件,两边都是 2628/0/0。剩余 46 条失败两边相同,都是测试环境问题:forge 15 条(12 条是 macOS `/tmp` 软链接)、builtinGhostProvisioner 23 条、llamaCppDownloads 7 条(临时目录下 `ENOENT`)、foreignSourceAdapters 1 条。Electron 与 Pi 批:准备分支和集成分支的 claudeHosted 均 15/0/0,piGateway、piShared、piHosted、groupRelay、claudeGrok 全过;仅登记过的 codexHosted 风险命令审批、startupProbe 原生启动对比失败,主干同样失败。没有启动图形界面的 Electron。下载的 Electron 42.11.12 来自 GitHub Releases,已校验官方哈希。npm 包(含新增的两个)按锁文件的 SHA-512 校验。除此之外没有别的下载。用临时 HOME 隔离,第 1 层只放行回环网络。这一轮没有做凭据存在性探测。前提重验和接线清单见本节“主干同步 6 的 Host 接线”。 | +| 主干同步 7 之后的验证(2026-11-20) | 主干钉在 `43fb1df105`,审阅副本合并 `915dcd9847`、Host 接线 `5feea98573`,锁文件与 `.nvmrc` 未变。开发机(Node 22.22.3,临时 HOME):Host 全量 1067 通过、0 失败、0 跳过(Chromium 1243),Host 类型检查和 Desktop、Mobile、Maker Core 三档守护通过,`test:runner` 781 通过、0 失败、2 跳过。桌面 `vitest related` 16,767 通过、2 失败、73 跳过,两条失败均为本机既有的 `deviceOp.test.ts` 文件监听用例,未验证。开发机离线复用缓存,补齐两份锁文件已有的 Solidity 依赖,下载 0,复跑桌面主进程与渲染进程类型检查通过。Pi 接线用例在合并后未补端口时因 `getProxy is not a function` 失败,补接后通过。PR 首轮 Ubuntu `test:lifecycle` 通过,CI 步骤约 41 秒,低于复评线 60 秒,Ubuntu 这一耗时项关闭。第三轮 CI 在 macOS 和 Windows 上等待源码 Host 写出 endpoint 耗时约 30 秒,本机两快照对照约 8 到 9 秒。`startup-account` 的两处源码启动等待因此统一为与 `test:lifecycle` 一样的 90 秒,并记录从启动到 endpoint 就绪的实测耗时。这些数据只衡量源码启动,发行包另计。Ubuntu 的凭据等待者测试过早读取异步派发结果(`206bc30b37`),已改为等待引擎收到输入,生产派发顺序与桌面一致。逐项日志见同步 7 审阅回执。 | +| PR 首轮 CI 与评审修复(2026-11-19) | ① Ubuntu、Windows 的 Codex 出站测试缺打包用 ripgrep,给测试的运行时装配注入临时搜索程序替身,正式运行的缺文件检查照旧(`7743e6f406`)。② Windows 用量记录测试删库遇到 `EBUSY`,先关两份 SQLite 句柄再清理(`a7fa893117`)。③ Windows 代理辅助进程验收脚本把空行交给 `JSON.parse`,改为只收协议帧。生产客户端已有非协议输出过滤(`d681f5252a`)。④ macOS 认证代理的拒绝路径由 `macos-system-proxy.test.mjs` 的“a proxy that names a user is unresolved, and the user is in no log or judgement”覆盖。托管 runner 的系统接口没有发布 `HTTPSUser`,CI 对照无法验证拒绝路径,将 17 条原先要求拒绝的结果记为 `skipped-precondition`。这 17 条的 Host 与 Electron 路由一致,其他 9 条也一致。⑤ 占用期间历史读取会重试未交付图片,改为解闸后只为同一打开的账号库补交付(`79a6e4b526`)。⑥ 模型清单请求发出后才开始占用时会写共享报价和账本币种,写入前复核占用,丢弃该回包,解闸后可重刷(`caf94959b0`)。⑦ 解闸重建输入运行时后恢复空闲回收,任务仍按期释放(`5d0cec971a`)。⑧ 取消的 done 原先可能给半截回复盖成功章,改用桌面的同一成功判据并保留 Codex 原始状态检查(`59ea890ff5`,见甲 9)。⑨ Windows 的 Skill 投影守护按本机分隔符生成路径,在收集时统一成 `/`(`49f68d81ef`)。⑩ macOS 的例外列表一项带逗号时,按 Chromium 148.0.7778.280 复制代理配置的规则,重解析已成功解析、带逗号或分号的主机名项,CI 保存的 26 条路由全部与 Electron 一致(`4f4e44ab8b`)。源码见 [macOS 读取器](https://github.com/chromium/chromium/blob/148.0.7778.280/net/proxy_resolution/proxy_config_service_mac.cc#L115-L143) 和 [规则复制与重解析](https://github.com/chromium/chromium/blob/148.0.7778.280/net/proxy_resolution/proxy_host_matching_rules.cc#L118-L132)。⑪ `host-server-hold-classification.test.mjs` 的 CodeQL 正则告警要求消除空白回溯歧义,元素之间改为必有逗号,改前改后收集的 25 项完全相同(`b4ca7a6873`)。DCO:#11536 初始的 806 个提交超出接口上限,线上评估失败;本机 `check:dco` 对 `3ef44274d6..49b01543ef` 验到 700 个普通提交全部签署、106 个合并豁免,对首轮修复后的 `b4ca7a6873` 验到 710 个普通提交全部签署、106 个合并豁免。#11536 的 Windows db 档首轮因 runner 自测先失败而未跑到,随这批修复推送后补跑。⑫ 本 PR 引入的 Chromium 代理辅助进程在 Windows 上启动即退出。Electron 把 `process.stdin` 设成一开始就 EOF,worker 将关闭输入视为退出,导致无法读到系统代理并按现有策略回退直连,启动仍有期限。Windows 改用子进程 IPC,沿用同一协议、就绪口径和回退策略(`9001d67bf8`)。⑬ 保留关通道、SIGTERM、SIGKILL 的顺序,辅助进程关闭等待最多 3 秒,到期记日志并返回(`a6d3182bf6`)。⑭ 验收从 spawn 时记录退出,各组即时输出结果,失败时收尾临时 PAC 服务和测试子进程。20 轮和各组的验收断言均保留,Windows 父进程退出场景覆盖 IPC 断开(`7b38ff47e3`)。⑮ Windows 验收的清理判据曾等待 Node 的进程聚合 `close`,父端主动断开 IPC 后,这个事件可能漏发,即使辅助进程已退出、stderr 已关闭。IPC 验收改等进程 `exit` 和已有 stderr 流自己的 `close`,强杀仍失败。生产一直按 `exit` 判断退出,协议、回退和关闭期限沿用(`411cc62dd7`)。 | +| 待办:startup-account 测试改为导入生产模块(M2 之前) | `startup-account.test.mjs` 的启动阻断、关库、跨区采用、续期排期几段从 `main.ts` 提取函数源码再执行,不经过 `serve` 装配。把这些函数移到可以直接 import 的模块,测试改为导入生产模块。不在这个 PR 做 | +| 待办:占用期间 `executeTaskTags` 的行为用例 | 入站分发端口里 service-gate 一类的 `executeTaskTags`,目前只有 `device-link.test.mjs` 的分类对照,没有经真实入口、在桌面占用期间被拒的行为用例。补一条:占用期间远端执行任务标签被拒,处理函数没有被调用。不在这个 PR 做 | +| 待办:界面检查补上行数上限截断的自动检测 | `ui:check` 的裁切检查看不出 line-clamp 造成的省略号截断(法语启动原因面板就是这样漏过去的)。给 `ui:check` 的通用检查或登录页测试加一条:副标题等限制行数的节点,内容高度大于可见高度就报。不在这个 PR 做 | +| 迁移前要解决:任务里缺失插件的安装途径(2026-11-19) | 两件,都涉及插件基座,需要放行人确认:① 后台服务接入任务内的插件搜索与安装(安装确认走哪条通道、桌面占用期间拒绝),本线后续要做;② 客户端模式的安装确认通道(主干 `a7f5289e84` 既有问题),列进 issue,由谁修待定。在这两件解决前,见第二节“任务里遇到缺失插件” | +| `host-skill-projection-owner.test.mjs` 进 `test:runner`(2026-11-19) | 这个根目录源码契约随 Host PR 加入,登记在 `check-test-hygiene.mjs`,但原来没有任何 CI 命令执行它;现在和分类守护一起列进 `test:runner` | +| 验证用的 Node 版本(审核方 2026-11-18 定) | 事实:2026-11-18 之前本机所有 Host 与桌面验证(各 worker 与审核方的每一轮)用的都是开发机系统里的 Node 22.21.1,不是仓库 `.nvmrc` 指定的 22.22.3;CI 的 setup-node 写 `node-version: 22`,装当时最新的 22.x。自有机器上用官方 22.22.3 跑时才发现源码方式的 Host 在 22.22.3 上加载 `?raw` 失败(见下一行)。从 2026-11-18 起本机验证一律在 22.22.3 上跑(官方包解压在任务临时目录,按 nodejs.org SHASUMS256 校验,不装进系统、不动用户的 Node),报告写明版本;换版本后重跑的第一轮完整验证作为新基线,此前 22.21.1 上的结果只作参考。桌面类型检查、读源码的测试与 related 也在 22.22.3 上各跑一轮,只在新版本上出现的失败按“只在我们这边”或“主干同样”分类。新基线(2026-11-18,集成分支 `17f308256f`,开跑负载 ≤16):22.22.3 与 22.23.4 上 Host 全量均 875/875,raw 加载器测试、e2e imports、IPC 路由、lifecycle 均通过,根守护、读 Host 的桌面测试、桌面类型检查、hygiene、dev-docs 均通过。 | +| 验证环境:共用排队脚本的改动与批量结果的可信度(审核方 2026-11-18 要求记录) | 共用排队脚本(两个槽、记录开跑负载)2026-11-18 改了三次:① 约 10:38 起默认把官方 Node 22.22.3 放到 PATH 最前(此前用开发机的 22.21.1),日志头打印 `node=`;这一次是原地改写,改写时正在跑的几轮在结尾多报一行脚本语法错误、退出码失真,结果取自被测命令自己的日志;② 随后把脚本主体改成整段读入再执行,并改为写新文件后原子替换,以后改写不影响正在跑的一轮;③ 11:35:52 起拿到槽后先等 1 分钟负载 ≤16 再开跑(最多 45 分钟),日志头打印 `load-waited=`。以后改它照②的办法,并先确认两个槽都空。可信度:同一棵树上准备分支 readers 三轮失败数为 40、54、41,差别全在超时类(本机 FSEvents 异常加负载),所以任何一轮“整批全过”或“多了几条”都不能单独下结论;能下结论的只有单独跑的结果、与主干的对照、以及发布前在正常机器上的整批。 | +| 验证环境:自有 Windows 定向验证 | **Windows 全量未在发布前验证,以 PR 的 CI 首轮为准。** 自有 Windows 只跑定向项,两处 chmod 故障注入见本节未覆盖清单。定向验证的隔离规则仅放行两项固定的本地探针:跨进程锁读取本进程创建时间时匹配系统命令、固定参数和调用方自己的 PID,数据库 schema 租约读取本次系统启动代次时匹配固定 PowerShell 脚本的 SHA256。两项都是执行在先、评审确认在后。MachineGuid 查询许可已撤销。以后新增放行项须先报评审,获得确认再执行。 | +| 甲,Host PR 发布前关闭:源码方式的 Host 在 Node 22.22.3 上加载 `?raw` 失败(审核方 2026-11-18 定为甲) | 未关闭(修复中)。事实:同一快照、同一依赖树、同一命令只换 node,22.21.1 通过、官方 22.22.3 报 `ERR_UNKNOWN_FILE_EXTENSION (.html)`,`check-e2e-imports`、`startup-account`、`ipc-route`、`lifecycle` 均失败,真实 serve 在监听前崩溃。根因:锁定的 tsx 4.23.1 在 Node 22.x 自 22.22.3 起改用同步 `module.registerHooks`,`forge.ts` 引入的 `page.html?raw` 交给 Host 的 resolve 时查询串已被剥掉,`raw-hook.mjs` 只在 resolve 认 `?raw`、load 只认 `cindy-raw:`,于是落回 Node 默认加载器。要求:只动 Host 的加载器,resolve 与 load 两头都认 `?raw`(与 `.md`),不升降 tsx、不改 `.nvmrc` 与 CI 的 Node 版本;测试不依赖运行它的 Node 版本,改坏会红;22.21.1 与 22.22.3 各跑 Host 全量,两边都过;打包产物(构建时由 esbuild 处理 `?raw`)在 22.22.3 上实际起一次 serve,单独报。若主干同样受影响,修复照样放进 Host PR,正文写明主干 CI 的 Host 作业实际装的 Node 版本与结果,不单独对外报告。 | +| 主干已有的进程清理:macOS 更新器测试夹具 | `apps/desktop/src/main/__tests__/updateScriptMacOS.test.ts:264` 在 `finally` 中调用 `/usr/bin/pkill`,以 `-9 -f` 匹配命令行中包含该测试沙箱路径的进程。 | +| 主干已有的进程清理:Windows 开发启动脚本 | `scripts/dev.sh:8–9` 使用 `taskkill`,分别按包含 `electron-forge` 的窗口标题和 `electron.exe` 镜像名强制结束进程。第 16 行另按 PID 结束进程,PID 来自前面 `netstat` 对服务端口监听者的查询。 | +| sync15 主干复现:`botSkillRuntimeCache.test.ts` 淘汰缓存的三项 | 准备分支 `72491884dd` 的读者集合里,旧写入成功、旧写入失败、检查产物时淘汰这三项均失败。主干 `3a713b3bce` 单文件跑两次都是这三项失败,另三项通过。主干 `1dacfdebda` 与准备分支的单文件复跑又都超过 5 分钟,未取得最终断言。主干进程采样显示 Node 主线程在 `watcher.close()` 等待,libuv 的监听线程在 `FSEventStreamStart/Stop` 等系统服务;这些测试各建 33 个根目录触发淘汰,阻塞会连带拖过 5 秒用例和 10 秒清理时限。同文件“构建失败后重试/来源不可监听”在读者集合超时,准备分支单项通过。上述监听环境恢复后复核淘汰三项。 | +| sync15 桌面批量超时:设备恢复与工作树切换 | `deviceLinkRemoteRecovery.test.tsx` 的 32 位期限用例推进 30 亿毫秒模拟时间。准备分支超出 5 秒后,同文件健康设备及冷缓存两种 standby 的三项断言也随之失败;低负载重跑 31/31。主干 `1dacfdebda` 单文件 31/31,其中期限用例耗时 4.4 秒。`checkout.git-integration.test.ts` 的 stash/undo、快进后 undo、还原暂存和工作内容三项均在 5 秒超时,同环境单文件两边均为 14/14。两组均未复现稳定的准备分支专有失败。 | +| sync15 桌面批量超时:Claude 托管与 Pi 包 | `claudeHosted.e2e.test.ts` 的槽位释放/续跑、共享账号 A 冷启动与 B 冷启动/运行中额度用尽、冷启动/发送鉴权拒绝、断开交接写入这七项,在 related 批中等不到完成事件。主干 `1dacfdebda` 单文件 15/15,准备分支定向复跑时六项通过,A 冷启动在等待续跑完成时再超时,随后该项单跑通过。主干真实 CLI 的一次采样看到监听线程在等待 FSEvents 注册,尚不能据此确定每次超时的成因。`pi-package-store-security.test.ts` 的“外部移除后拒绝启用”和“更新失败后重新核对字节”在 related 批超出 5 秒,同环境定向两边均通过。其余监听项仍按本表的文件监听环境要求复核。 | +| 发布前条件:sync15 批量超时的四组整批通过(审核方 2026-11-18 定) | 上面两行“sync15 桌面批量超时”的结论是“单文件两边都过”,不是“同一批在主干上也超时”,所以这四组在那之前算“未验证”,不算“通过”:设备恢复 4 项、`checkout.git-integration` 3 项、Claude 托管 7 项、Pi 包两项非监听用例。发布前最后一轮验证在文件监听正常的机器上整批跑读者集合与 related,这四组必须整批通过;仍有超时的,在同一台机器上用同一批命令跑主干对照,主干同样超时才算主干问题。2026-11-18 在 Node 22.22.3 的批次里另有 5 秒超时、单独跑(`--maxWorkers=1`)通过的,同样列入这一名单:`typographyDiscipline.test.ts`、`plugin-market/__tests__/service.test.ts`“hides counts instead of unbounded installed-count resolution”(已登记的主干负载敏感测试)、`remote-agent/__tests__/mirror.test.ts`“keeps a managed Skill next to a personal one…”、`localDb/__tests__/migrationReplay.test.ts`、`localDb/__tests__/sessionListMessageCount.test.ts`(五个文件在准备分支 `f412d6d3cd` 上单独跑 448/448)。`pi-package-store-security.test.ts` 的“retries a transient snapshot duration limit on the next session”和“converges a committed pending disable when the final state write fails with EIO”在批量里 5 秒超时、在准备分支 `f412d6d3cd` 上单独跑通过(2888 ms、834 ms),同样列入。 | +| 主干测试等待太短:`deviceLinkRemoteRecovery.test.tsx` 的 32 位期限用例(审核方 2026-11-18 登记) | 用例推进 30 亿毫秒模拟时间,主干 `1dacfdebda` 上单文件跑就要 4.4 秒,离 vitest 默认 5 秒门限只差 0.6 秒,负载一高必超时,并连带同文件健康设备与冷缓存两种 standby 的三项断言失败(sync15 准备分支读者集合与 related 各 4 项即此)。低负载单文件准备分支与主干都是 31/31。不在本线修,不调高超时。 | +| 主干偶发:`claudeHosted.e2e.test.ts`“共享账号 A 冷启动”(审核方 2026-11-18 登记) | sync15 准备分支定向复跑时一次等不到续跑完成事件而超时,随后单项跑通过;主干 `1dacfdebda` 单文件 15/15。登记为“本机 FSEvents 异常下的偶发,未验证”,不单独下结论;按上面的发布前条件在文件监听正常的机器上复核。 | +| 基线失败:`apps/desktop/src/main/local-agent/__tests__/runtime.integration.test.ts` 21 项 | 全是 `TypeError: handle.hasRecyclableProjectResourceDrift is not a function`(`local-agent/runtime.ts:576`):主干 `c8ddf4e0f6` 给 runtime 加了这个方法,测试里的假 handle 没跟上。2026-11-17 在 prep `8f8cde1826`(已合 main,`local-agent/` 与 origin/main 差异为 0)上单独跑,同样 21 项失败、16 项通过,与本线改动无关。CI 不跑它:它属于桌面 `integration` 层(`scripts/test-workspaces.config.mjs`,`status: 'manual'`),单元测试分片排除所有 `*.integration.test.ts`,CI 也没有跑这一层的作业,所以主干 CI 是绿的(`15e197fbbe` 那次 8 个 Linux 分片的文件计时清单共 4109 个文件,没有它),本线的 PR 也不会因它变红;只在本地 `vitest related` 带到它时出现。origin/main 最新提交仍未修。不在本线修;合 main 后若自行恢复,删掉这一行 | +| 已由主干 #10332 解决:桌面类型检查贴着堆上限 | 2026-11-17 在 Linux x64(16 核,Node 22.21.1,tsc 5.9.3)实测,拆分前的 origin/main `d2c09ff142`:脚本原样 12288 下 3/3 通过、11776 下 3/3 内存不足(最大常驻约 12.3 GB),余量不到 0.5 GB;本分支类型规模相同,12288 下 6 次里 1 次内存不足。主干 `5703fd82a4`(#10332)把它按进程边界拆成 main / renderer 两片、各 10240,合 main 后 prep 上脚本原样最大常驻 9.4 GB。本线的调上限提交已撤回(见非搬移清单)。不再跟踪 | | 基线失败:`apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts` 10 项 | 报 `SqliteError: no such table: mcp_app_view_states`(`deleteDeletedSessionViewStates`)。对照方法:把本分支改过的桌面源码换回合并的 main 版本(7eaf7788de)、删掉新增模块后单跑该文件,同样 10 项失败,判为 main 上原有问题。合并 main 后若自行恢复,删掉这一行 | | 待定:随包插件在 Host 不标内置 | 桌面的 GhostManager 带 `isTrustedBundledId`(`resources/builtin-ghosts` 下 official、xd 两组种子的 id),根命名空间里的这些安装标 `builtin`;Host 的 `createHostGhostManager` 没有这个选项,任何安装都不标。后果:首方事实的内置官方分支在 Host 上不成立,随包插件按非内置判定(其 Skill 不标官方,依赖内置身份的首方特权被拒)。3c 之前就是这样;也因此 3c 的查找收紧在 Host 上实际只改变托管 Skill 清单。种子 id 从哪里来(Host 发布包不含 `builtin-ghosts`)需要方案,**迁移前必须有结论** | | 待确认:gray-matter 在 Host 发布包里的形态 | 外置:`apps/host/scripts/build.mjs` 把所有第三方包设为外部依赖,按导入方位置解析后整包拷进发布目录的 `node_modules`(解析到仓库根 `node_modules/gray-matter`)。3c 之前已有 5 个导入方在 Host 的加载范围里(maker-core 的 customization-scanner、pinned-skill-invocation、memory/storage,桌面 skillhub/frontmatterValidation、cindy-brain/skillSlot),3c 没有新增依赖。证据用构建脚本原样截取的依赖插件对 `apps/host/src/main.ts` 跑 esbuild 得出(完整构建缺本机 Chromium) | | 待查:客户端模式下的两个 GhostManager | 窗口进程与 Host 共用同一份 owner 目录,两边是否都会构造 GhostManager 并各自跑中断恢复(`recoverInterruptedMutationsSync`),有没有跨进程互斥。既有情况,不挡 3c | +| PR 正文须写:模块初始化顺序靠 CI 启动主进程检验 | U3(`5b60f38846`)把自动续跑的两个守卫和簿记从 register.ts 的模块顶层挪进 `createAutoResumeRuntime`,构造位置后移到供应商组那块之后(它要绑 `settleProviderGroupContinuation`)。已逐个核对:构造之前提到这几个名字的只有函数体内的引用,模块初始化时不读(审核方复核接受,2026-11-17)。但 register.ts 没有单测会整体加载它,这类模块初始化顺序的改动只有应用真正启动才验得出来;桌面准备 PR 正文要写明依赖 CI 里会真正启动桌面主进程的作业做最后一道检查,并在发布前确认它们通过 | +| 迁移前必须解决:非客户端模式的桌面与 Host 不能同开一个 profile(审核方 2026-11-17 定) | 定为“不支持,必须有运行期互斥”,用户已定 Host 在运行时打开桌面版应自动连接它(方案 B,第一阶段之后),在那之前 Host 启动时拒绝并在运行期间定期重扫(见第四节“用户已定的产品形态”);和第 34 行“两者并存”同一类前提。闸门不是停止路径:只挡新输入,在跑的回合照常跑完(`agent/input-queue.mjs` 的 `holdForDesktop`),所以不涉及第五节“甲:账号边界停止提前置位”。现状:客户端模式下窗口进程不开库(`localDb/index.ts:137–147`),只有 Host 写;非客户端模式的桌面与 Host 同开一个 profile 时没有运行期互斥,按使用方的用量账本 `provider-usage-by-party.json` 与定价缓存会被另一方覆盖(第 13 行设计稿)。待只读 Worker 查清:桌面非客户端模式拿了哪些锁、Host 能否据此发现并拒绝启动、反过来会怎样、只靠 Host 能做到哪一步;要改桌面的部分归第一阶段之后的桌面 PR 或迁移设计,要问用户(已查清,按下面的方案 A 做)。**方案 A 已做(2026-11-17,审核方定的六项)**:桌面两处准备(判定函数原样拆到 `concurrentInstanceScan.ts`;启动登记多写 `runtime: 'client' | 'embedded'`,没有这个字段的旧记录按 embedded);Host `agent/profile-coexistence.ts` 用桌面那份扫描查 `.dev-instances` 与 SingletonLock,`runtime: 'client'` 与 `passive: true` 放行,同一份记录只问一次进程身份。启动时有开库的桌面:释放运行时租约、停在 blocked、不自动重试(重启 Host)。运行中每 10 秒加目录监听重扫,发现开库的桌面就关闸门:新的发送(输入入队、插话、继续、重试、调度入队、device-link 新建任务)回 `[PRECONDITION_FAILED] HOST_PROFILE_IN_USE_BY_DESKTOP: …`(文案 `logic.errors.hostProfileInUseByDesktop`),每个任务加交互锁 `profile-coexistence` 与 execution-pause,排队的不开始,中断自动续跑与快照恢复都不发出,在跑的回合跑完,上下文恢复的重放不算新的发送;连续两次干净扫描、在跑的回合都结束后,重建输入队列运行时、按库里的快照恢复,再解锁。状态在 `/api/probe` 的 `runtime.coexistence`(只有 PID)。Host 还没有用量上限后的自动继续(第三批),协调器的续跑在闸门关着时不发出,已有测试钉住。**后续(2026-11-17,审核方定;2026-11-19 按复查如实改写)**:闸门关着时,经 service 路由的写库或改运行时入口默认拒绝,只放行读取、停止正在跑的回合、回答它的权限询问与提问(含插件确认),以及账号续期;放行清单在 `service.mjs` 的 `HOST_PATHS_ALLOWED_WHILE_HELD`,以后新加的路径没登记也被拒。`server.mjs` 自己应答、不经 service 的入口逐个登记在第二节“桌面占用期间不经 service 的入口”,新增入口必须登记(`scripts/__tests__/host-server-hold-classification.test.mjs` 的分类守护)。**发现延迟**:占用是每 10 秒重扫加目录监听(去抖 250 毫秒)发现的,从桌面开库到后台服务察觉最长约十秒,这期间后台服务照常读写;入口检查之后才开始的占用,可能留下一个空任务行或空对话目录,与发现延迟属于同一类,不单独处理;排队消息的编辑、删除、移动在输入队列里也拒绝;device-link 的新建任务与插件页调用也拒绝。启动被拒改用专用错误码 `HOST_PROFILE_IN_USE_BY_DESKTOP`(`HostProfileInUseError`),不再借用数据库升级锁的 `DB_SCHEMA_LOCKED`(这个码本来也不到达窗口和网页端:被拒的 Host 对 owner 请求回 409 `owner_runtime_unavailable`,窗口显示成“Host account is not ready”)。**(a) 旧版桌面**:登记里没有 `runtime` 字段的记录一律按会开库的桌面处理,所以老版本桌面即使以客户端模式运行,也会被新 Host 当成并存而拒绝;桌面准备里写这个字段的提交(②)必须先于或随 Host 一起到用户手里,准备 PR 先合即满足。**(b) passive 实例**:查证结果与“放行”的前提不符——记录里的 `passive` 来自 `--passive`(`devCliFlags.ts:417`,被动定时任务模式),这种实例照样打开同一个库:`localDb/index.ts:171` 把它当共享被动读者,拿 reader 租约后正常开库(`:184`),只不跑迁移(`index.ts:168–183`)、不跑定时任务;它的只读仅限于 schema,任务和消息照常写(`:197` 的只读判定把 passive 排除在外)。所以“被动实例不自己开库”不成立。**审核方 2026-11-17 定:passive 也按会开库处理,拒绝**(`agent/profile-coexistence.ts` allowedBesideHost 只放行 `runtime: 'client'`)。**后续二(2026-11-17)**:read 组逐条核过零写入(库、profile 文件、对外请求):只有 `/api/providers` 会在读取时拉 /models 并写与桌面共用的价格快照和账本币种,闸门关着时改为不拉、只用已有列表作答;`/api/agent-skills` 的“先刷新再列”由 25b 改成闸门关着时只列不刷新;对话搜索的语义模式会发一次查询向量请求,不写库;`/api/agents/auth-state`、`/api/agents/status` 已查清(**后续三**,见下)。插件安装同意(`/api/ghosts/install-consent/resolve`)闸门关着时只接受“拒绝”,“同意”会往共用 profile 装插件,拒掉;插件确认照常放行。device-link 分发器自己处理的通道里,Host 上只有插件 OAuth(PLUGIN_OAUTH_CHANNEL)会写,在 Host 的 `device-link.ts` 端口处拒绝,共用 dispatch 不动(发起与完成授权都经这一个端口;写入点:签名身份密钥首次生成时写 owner 目录的 `plugin-oauth/.v1.enc`,`plugin-oauth/identityStore.ts:122–128`、`plugins/remote-authorization.ts:20`;授权完成时写插件的连接凭据,`plugins/authorization.ts:201–206` 的 `executeGhostSetupConnectionSubmission`);`invalidatePluginOauth` 放行:它只取消内存里还在进行的授权(`plugin-oauth/runtime.ts:105–115`、`transactions.ts:247–255` 的 `cancelPeer`、`authentication.ts:106–113` 的 `invalidate`),不删也不改已存的授权,和“停止”同类,测试 `device-link.test.mjs` 里闸门关着时断开连接仍取消该设备的授权;Host 传给共用 `createInboundDispatch` 的每个端口都在 `device-link.ts` 的 `HOST_DISPATCH_PORTS_WHILE_HELD` 里标了闸门关着时的归类(只读 / 经 service 闸门 / 入口拒绝 / 未绑定),多传一个没归类的端口、或未绑定的端口被绑上,Host 的 device-link 就起不来,名单另在 `device-link.test.mjs` 钉住(以后接文件互传、任务迁移这类会写的端口,必须先改这张表);其余通道 Host 未绑定、只读或已经过 service 闸门。启动被拒时,owner 请求的 409 带 `reason: HOST_PROFILE_IN_USE_BY_DESKTOP` 和一句说清原因与做法的话(`logic.errors.hostProfileInUseByDesktopAtStart`:退出那个桌面版,然后重启 Host)。闸门之外放行登出、停 Host、网页配对(网页配对的码和会话只在内存里);**闸门关着时登出不清扫,由桌面负责**(清扫属于 25b,由 inv-phase1-b 实现)。**登记为乙**:窗口顶部常驻提示(新 UI,与方案 B 的“桌面自动连接已在运行的 Host”同一块界面,到时一起设计);renderer 里直接显示错误原文的 toast,本轮只改发送失败横幅和公共映射(**D**,见下)。在 D 的基础提交上逐行重扫(`apps/desktop/src/renderer`,`toast.error/warning` 的参数直接是 `err.message`、`String(err)` 一类,或是 `t(…, { …: err.message })`),比盘点时的约 32、约 5 处多:**④ 只显示原文,38 处**:ErrorBanner.tsx:491;AboutSection.tsx:540、552;AuxiliaryModelSection.tsx:70;CollaborationSection.tsx:77;CompactionSection.tsx:38;GitSafetySection.tsx:23、35;ImDefaultSettingsSection.tsx:105、195、215;LspBetaCell.tsx:51;MemorySection.tsx:147、170、204、234、269;SessionImportSection.tsx:316;SessionRuntimeFallbackCell.tsx:38、59;SilentEncryptedRetryCell.tsx:41、61;StorageManagementCard.tsx:207、230、247;TerminalShellSection.tsx:75、91(以上在 `components/settings/`,ErrorBanner 在 `components/chat/`);`features/cc-agent/CCAgentSessionView.tsx:2742、2883、2903`;`features/scheduler/SchedulerPage.tsx:439、451、472、497、527`;`features/scheduler/components/ProjectAutomationNotifyBridge.tsx:67`;`features/skillhub/SkillhubDetailView.tsx:1643`;`features/skillhub/SkillhubHomeView.tsx:291`。**⑤ 本地化外壳里夹着原文,13 处**:`features/bots/BotAutomationsSettings.tsx:65`;`features/cc-agent/CCAgentSidebarUpper.tsx:1098、1167、1205`;`features/cc-agent/sidebar/SessionItem.tsx:517`;`features/cc-agent/workdir-browse/OpenInSystemActions.tsx:27、41`;`features/scheduler/SchedulerPage.tsx:372、408、423`;`features/scheduler/components/RunHistoryPane.tsx:166、188`;`features/scheduler/hooks/useDeleteScheduleWithSessions.tsx:117`。盘点时列的 `ProvidersSection.tsx:1095` 只按原文挑 key、不显示原文,不在其列。**用户可见的后果**:这些文件多是设置页写入,闸门关着时本来就会被拒,用户会在设置页看到带码的原文(`[PRECONDITION_FAILED] HOST_PROFILE_IN_USE_BY_DESKTOP: …`,经窗口时前面还有 Electron 的 `Error invoking remote method …`),⑤ 那类是本地化的一句话里夹着这段原文;看得懂原因,但不是窗口语言的人话。另登记为乙:设置页“浏览器”一项读 get-health 被拒时显示成连接异常(见本节表后三列表的浏览器那一行);审核方 2026-11-17 定不并进 D,和窗口顶部常驻提示、上面 ④⑤ 这批 toast 归同一批,将来一起排。做这批 toast 时换成有翻译的文案,届时也不出现“Host”(用户 2026-11-18 定:界面文字不出现 Host,改称「Cindy 后台服务」,一律写全称);Host 直接抛给界面的英文报错原文里还有约 74 处字符串带“Host”,这次不改,并进这一条乙。**还登记为乙(审核方 2026-11-17)**:启动被拒与运行中被挡的文案(`logic.errors.hostProfileInUseByDesktop`、`…Retry`、`…AtStart`,以及 Host 自己回的那句)里有“Host”“重启 Host”。对个人版用户,Host 是桌面替他启动的,他不认识这个词,也不知道怎么“重启 Host”。现在这几句只在测试期和独立安装的场景出现,可以先这样;等“桌面拉起 Host”的迁移器和“桌面自动连接已运行的 Host”(方案 B)定下来后,按用户实际能做的操作重写,届时由审核方带着候选文案去问用户。**更新(2026-11-18)**:用词已定,用户原话“Host 这个词,建议不要展现给用户,不容易理解”,改称「Cindy 后台服务」/“the Cindy background service”,一律写全称(zh-CN 的“后台服务”、en 的 “background service” 已另指运行中的后台命令等);`…AtStart`、启动失败面板与 `hostConnection.*` 已改成这个用词(见本节表后“非搬移提交”),守护 `hostWordInCopy.guard.test.ts` 防止界面文案再出现 Host。“重新启动后台服务”在个人版里对应什么操作,仍挂在这一条。同一类:甲 16 的 Pi 退役失败提示“请重启 Cindy 后再使用 Pi”(`settings.piPackages.failure.runtimeRetirementFailed`,照桌面原文)——窗口连着后台服务时,真正要重启的是后台服务(Pi 运行时在它里面),只重开窗口不够;届时与这一条一起改(审核方 2026-11-18)。**D(桌面提交,2026-11-17)**:`host-ipc-proxy.ts` 只在 409 `owner_runtime_unavailable` 带 `reason: HOST_PROFILE_IN_USE_BY_DESKTOP` 时改抛 `[PRECONDITION_FAILED] HOST_PROFILE_IN_USE_BY_DESKTOP_AT_START: `,旧 Host(只有 `error`)照旧是“The Host account is not ready”;`shared/ipcError.ts` 的公共映射 `mapIpcErrorToI18nKey` 认出开头的这个标记(可带 `[PRECONDITION_FAILED]` 前缀、可经 Electron 包装),运行中映射到 `logic.errors.hostProfileInUseByDesktopRetry`(新加,“…暂时不能修改。请先退出它,再试一次”,因为公共映射用在设置写入等各处),启动被拒复用 80d9ab7f0b 的 `logic.errors.hostProfileInUseByDesktopAtStart`;不带标记的、标记不在开头的、别的 code 下出现标记的,一律是原来的 key。发送失败横幅(`makerChatStore.ts` remoteErrorMessageForBanner、decodeRemoteErrorMessage、remoteErrorI18nKey)运行中复用 a9b0cac9df 的 `logic.errors.hostProfileInUseByDesktop`(“…再发送”),启动被拒同上;其余错误原样放过。renderer 与 main 取文案是同一套语言文件(`main/i18n.ts` 直接读 `renderer/i18n/locales/*/common.json`),新 key 12 种语言都有,测试两边各取一遍。**W(2026-11-17)**:网页端 `apps/web/shim.js` 的 requestHost 把 typed 错误体 `{ error: 'CODE', message }` 还原成 `[CODE] message`(带 code),启动被拒带原因码时同样加 `_AT_START` 标记;其余错误体(小写的 `owner_runtime_unavailable`、`internal_error`、非 JSON)与之前完全相同,仍是 `HTTP_`。网页端用的是同一份 renderer,所以横幅和公共映射照样生效。**注意范围**:这是网页端一个比“并存提示”更宽的行为变化:所有“大写 code + message”的 typed 错误体都改走 renderer 的公共解码(以前网页端对 typed 错误显示 `HTTP_<状态码>` 加原始响应体),网页端从此和窗口读到同样形式的错误(审核方 2026-11-17 要求写明)。**后续四(2026-11-17,审核方定)**:订阅桥(Claude 与 Pi 经 ChatGPT 订阅的请求,共用的 `anthropicResponsesBridgeHostCore.ts`)读本机令牌前的对账,闸门关着时跳过(`agent/codex-runtime.ts` 的 `createBridgeTokenReader`,只改 Host):对账会改写 Codex 的登录文件,那个桌面此刻也在用同一份登录。同理不续期:桥会在令牌离过期不到 120 秒时自己续期并把结果写回 `codex-home/auth.json`(`refreshIfNeeded`),两边各自续期会把对方的 refresh token 挤掉,所以闸门关着时 Host 的取令牌端口在这种令牌上直接报错,请求以认证失败结束,错误写明“ChatGPT 登录已过期,桌面版占用这份数据时不续期,请退出它再试”(`HOST_PROFILE_IN_USE_BY_DESKTOP: …`,经桥包成 `OpenAI/ChatGPT upstream request failed: …`)。宁可这一回合失败。120 秒照桥的 `REFRESH_MARGIN_SEC` 抄了一份,桥改这个值时要一起改。测试 `agent/codex-system-login.test.mjs`(经真实的桥:令牌有效时对账 0 次、不续期、profile 与系统登录逐字节不变;已过期时报这个原因、同样不对账不续期不写;放开后同一次读取会对账并尝试续期)。**后续五(2026-11-17,审核方定)**:Host 交给订阅桥的登录端口合在 `agent/codex-runtime.ts` 的 `createHostBridgeLoginPorts`(`createHostCodexRuntime` 原样装上)。① **上游拒绝令牌(401/403)时,闸门关着也不作废**:桥经 `invalidate`(默认登录)或 `invalidateCodexAccount`(单独账号)作废,放开时分别是 Host 的 `invalidateNative`(写作废标记、解绑、删掉被拒的 `auth.json`)和账号服务的作废(写 `invalidated`、让账号退役,`codex-account-auth.ts:45–53`);闸门关着时这三样都不做,只在 Host 进程里记住“这份登录刚被上游拒绝”(`createHeldLoginRefusals`),闸门关着期间用同一个令牌的后续请求在发上游之前就带同一个原因失败(`HOST_PROFILE_IN_USE_BY_DESKTOP: OpenAI rejected this ChatGPT sign-in (<原因>) …`),不再每个请求都去撞一次 401;登录文件里的令牌换了(例如桌面重新登录)就不再拦。被拒的这一回合本身带上游的拒绝原文失败(桥的 `onUpstreamError` 只记日志,错误照原样回给引擎)。闸门放开后全部忘掉:第一次读取照常对账,登录如果确实已作废,下一次拒绝走正常作废。② **单独添加的 Codex 账号**:Host 支持(账号服务 `createHostCodexAccounts`,`agent/provider-config.ts:45–50`;读状态 `agent/runtime.ts:420`、任务的 CODEX_HOME `:501–503`;桥把它们当 OpenAI 订阅,`anthropicResponsesBridgeHostCore.ts:481`、`:545`;第 145 行,m1-cp19),目录是 `/codex-accounts///`(`codex-account-path.ts:5–10`,Host 与桌面同一路径,`agent/provider-config.ts:45–50`、`codex-account-auth.desktop.ts:6–15`),桌面也在用、也会写(起任务的 CODEX_HOME `auth-adapters.ts:232`、桥续期 `anthropicResponsesBridgeHostCore.ts:324–327`),与默认登录同类风险,同样挡:桥在 `:324` 取账号目录时,Host 的 `codexAccountHome` 端口在闸门关着时先看令牌,快过期就带同一个“不续期”原因失败(早于 `:327` 的续期),被拒过就带“刚被拒绝”的原因失败;作废同 ①。订阅池账号(`NATIVE_SUBSCRIPTION_ACCOUNT`,桥 `:306–320`,会强制续期)在 Host 上走不到:只有桌面 `subscription-accounts/agent.ts:251`、`:372`、`:444`、`:502` 给任务附上池账号,apps/host 里没有引用 `subscription-accounts/runtime`,也不构造池账号;池账号的目录由桌面的订阅账号运行时管理,这次不涉及。③ **120 秒的守护**:`apps/desktop/src/main/maker-host/__tests__/hostDesktopSourceContracts.guard.test.ts` 的“refuses the tokens the subscription bridge would renew, with the bridge's own margin”读两边源码,桥的 `REFRESH_MARGIN_SEC` 必须等于 Host 的 `BRIDGE_REFRESH_MARGIN_SEC`。**后续六(2026-11-17,审核方定)**:Codex 引擎在回合中途报“服务端拒绝了登录”(maker-core `codex/index.ts:3417–3442` 的 onAuthInvalidated → `auth.invalidate(reason, { providerId, credentialAttribution: 'unproven' })`)走的是 Host 自己传的端口(`agent/runtime.ts` createHostAgentGraph 给 createCodexLocalCliAuth 的 `invalidate`,原先直接是 `codexRuntime.invalidateNative`),只改 Host:这个端口现在来自 `agent/codex-runtime.ts` 的 `createHostEngineLoginPorts`,闸门关着时不调 invalidateNative(不写压制或作废标记、不解绑、不删 auth.json——引擎这条走 `invalidateUnattributed`,本来就留着 auth.json),只把拒绝记进和订阅桥**同一份**进程内记忆(`createHeldLoginRefusals`,createHostCodexRuntime 里一份):引擎报过,桥的请求带同一原因失败;桥报过,起本机 Codex(`getAuthEnv` 的 oauth-bearer / openai 分支,`assertNativeLoginUsable`)也带同一原因失败;单独账号的报告在这里本来就什么都不写,照旧。放开后同样的报告走正常作废。被拒的那一回合本身带 app-server 原文失败:错误在 maker-core `app-server/client.ts:799–805` 先定下,端口晚一个 microtask 才被调,它抛的错只记日志(`:3441`),要带上我们的原因得改 maker-core,未做。同时补上:闸门关着时**起本机 Codex 也不对账**(`getAuthEnv` 里的 reconcile,和读状态、订阅桥同一条规则)。**查全(2026-11-17)**:在 Host 的导入图(esbuild 从 `apps/host/src/main.ts` 与 `login-cli.mjs` 打包解析出的全部输入)里按函数名搜(invalidateNative、invalidateHostCodexLogin、invalidateCodexAccount、unbindNativeProviderAuth、writeInvalidatedSystemCodexAuthMarker、writeUnprovenCodexAuthSuppressionMarker、retireCodexAccount、logoutCodexAccount、removeCodexAccountCredentialsReversibly、commitHostCodexDisconnectBoundary),除桥与引擎两条外,能走到作废标记、解绑、删 auth.json 的只有:Codex 显式登出(`runtime.ts` runLogout,只经 `/api/agents/logout` 及其 device-link 契约通道 `maker:auth:logout`,闸门关着时被 service 闸门拒绝)、登录(`loginCodexAccount` 里的 retireAccount,只经 `/api/agents/login`,同样被拒)、Claude 的断开(`runtime.ts:209`,只解绑 anthropic,经同一个 logout 入口,被拒);Host 的账号登出不调引擎登出。maker-core 里调 `auth.invalidate` 的只有 `codex/index.ts:3436` 一处;Pi 的订阅 WebSocket 经同一个桥作废,已覆盖。**另外两处同类写入,未挡,待定**:xAI(SuperGrok)登录被桥判失效时会解绑 xai(`grok-oauth-login.ts:690`、`:699`,经 Host 传给桥的 `invalidateXaiBridgeAuth`);运行时启动时的一次对账(`codex-runtime.ts` 的 warmUp,Host 启动被拒时不会走到,只在闸门开着时建运行时)。**后续七(2026-11-17,审核方定)**:① **Host 传给订阅桥的端口全清单**(`anthropicResponsesBridgeHostCore.ts:79–89`):`desktopCodexAuthAdapter.invalidate`(默认登录被拒;作废标记、解绑、删 auth.json;共用)已挡;`invalidateCodexAccount`(单独账号被拒;`invalidated`、退役;共用)已挡;`desktopCodexAuthAdapter.getAccessToken`(对账:改写链接、写绑定;共用)已挡;`codexAccountHome`(桥随后续期写回账号 auth.json;共用)已挡;`invalidateXaiBridgeAuth`(xAI 被拒:强制续期写回,续不上就删登录并解绑;共用)与 `getGrokAccessToken`(到期续期写回;共用)**这次挡**;`peekGrokAccessToken`、`codexAccountState`、`captureOAuthDispatchProof`、`chatgptAccountIdFromTokens` 只读;`recordXaiRateLimitSnapshot` 只在内存广播。② **xAI(SuperGrok)**:登录是 provider secret `xai`(或单独添加的 xAI 账号的 generic OAuth 槽)里的一整块,存在 `/safe-storage/owner__.enc`(Host `agent/provider-config.ts:88–96`,桌面 `secrets/providerSecretStore.ts:91`,同一文件),绑定在同一 profile。Host 的所有消费方(订阅桥 `codex-runtime.ts:283`、Codex 代理与桥的失效收口 `createXaiAuthInvalidationHost(config.grok)` `:235`、供应商 OAuth 令牌读取 `provider-config.ts:217–221`、自动审查 `auto-review.ts:53`)都经 provider-config 里同一个 Grok 服务,所以只在那里包一层(`agent/xai-held-login.ts` 的 `holdGrokLoginWrites`,不动共用代码):闸门关着时快过期的令牌(照抄 `grok-oauth-login.ts` 的 `REFRESH_MARGIN_SEC` 120 秒,守护见下)不续期、带原因失败;上游拒绝时不强制续期、不登出、不解绑,回 `'unchanged'`,进程内记住,之后同一令牌带原因失败;放开后照常。120 秒的守护:`hostDesktopSourceContracts.guard.test.ts` 的“refuses the xAI tokens …”,`grok-oauth-login.ts` 的 `REFRESH_MARGIN_SEC` 必须等于 `agent/xai-held-login.ts` 的 `GROK_REFRESH_MARGIN_SEC`。③ **同一份记忆**:生产的 `createHostCodexRuntime` 实例里,引擎报过的拒绝让同一实例的桥带同一原因失败,桥报过的让起本机 Codex 带同一原因失败(`agent/codex-system-login.test.mjs` 建真实实例的那条)。④ **warmUp 那次对账**(`codex-runtime.ts` 建运行时时一次):只登记,Host 启动被拒时走不到,只在闸门开着时建运行时。⑤ **清单之外、同类的两处,待定**:Cindy 网关 key 被拒后的重新同步会写 safe-storage 里的 xd key 与元数据(`model-access.ts:51–57`,经 Codex 代理、引擎图与输入队列的拒绝报告);自定义供应商 OAuth 的续期会写回 safe-storage(`provider-config.ts:212–216` `setOAuthTokenReader`、`auto-review.ts:56`,`generic-oauth.ts:386–395`)。**后续八(2026-11-17,审核方逐项定的共用凭据清单)**:**闸门关着时 Host 不写共用凭据;C(账号会话续期)是唯一例外,因为 Host 不续就会掉线**(C 照桌面 `authManager.ts` 的整套续期对齐,另做)。判断与文案统一在 `agent/held-credentials.ts`(`heldCredentialMessage`、`holdCredentialFetch`;Codex 与 xAI 的“已过期”文案也改用它,字面不变)。**D 插件 OAuth:挡**。`plugins/authorization.ts` 给 GhostOauthAccountManager 的 fetch 经 `holdCredentialFetch`:闸门关着时续期、401 后的强制续期、身份回填的请求都不发出,回 503 和原因;broker 调用直接带原因失败;账号保险库(只这一个 manager 的)不写不删——所以不续期、不写轮换的 refresh token、不标 expired、不删 refresh token、不写 insufficientScopes。工具调用得到“凭证「X」刷新令牌失败:HTTP 503 HOST_PROFILE_IN_USE_BY_DESKTOP: this plugin sign-in is not renewed while …,请稍后重试”,不提示重新连接;还没过期的令牌照用;放开后照常。`main.ts` 建插件运行时时传入 `isProfileHeld`。边界:闸门关着时,经插件页面发起的新 OAuth 连接在换令牌那一步也会被拒(连接本身就是写入)。测试 `plugins.test.mjs`“plugin OAuth renews and writes nothing”。**B 自定义供应商 OAuth:挡**。`provider-config.ts` 给 `createGenericOAuthService` 的 fetch 经 `holdCredentialFetch`:闸门关着时续期请求不发出,不消耗 refresh token、不写回;还在 120 秒提前量里的令牌照用,真正过期后走现有的 `provider_oauth_refresh_failed`。**登记为乙**:共用路由(`provider-route.ts:292–300`、`:1029`、`:955–957`)会吞掉原因,用户只看到 “Provider authentication refresh failed.”,不改共用路由。测试 `agent/codex-system-login.test.mjs`“a custom provider OAuth sign-in is not renewed”。**桌面多实例本来就有的问题(与闸门无关,已读代码确认,记入桌面事项)**:generic OAuth 的令牌整块缓存在进程内存里,读过一次就不再重读磁盘(`generic-oauth.ts:177–206` 的 `blobCache`,只在 `resetGenericOAuthMemoryCache` 即换账号时清空,`:260–270`),续期前的“重读”也是读这份缓存(`doRefresh` `:311–313`),所以另一个进程轮换了 refresh token 之后,这一方会拿旧的去续,续期失败只记日志(`:340–343`),令牌过期后一直报 `provider_oauth_refresh_failed`(`:391–395`)直到重启。插件 OAuth 每次续期都从保险库重读 refresh token(`ghostOauthAccounts.ts:1416`),没有这个问题。**E 浏览器配方密钥(审核方 2026-11-17 定 (a),只对小宇宙)**:名单只在一处——`agent/held-credentials.ts` 的 `RECIPE_SECRETS_UNREADABLE_WHILE_HELD`,判断标准写在它旁边:配方的续期会轮换 refresh token,就列进来(这类配方先自己发续期请求、再写回,只挡写回会让服务端已轮换、本地没存,两边都失效),以后新增配方照这个标准归类。现在只有小宇宙(`opencli-vendor/clis/xiaoyuzhou/auth.js:120–145` 换 x-jike-refresh-token,`:188–192` 401 后强制续期)。闸门关着时,名单里的配方读密钥直接带原因失败(`holdRecipeSecrets` 包在 `provider-config.ts` 的 `recipeSecretIo` 上,措辞复用 held-credentials),挡在它第一个请求之前;放开后照常。**Spotify 只登记**:闸门期间它可能续期并写回一个新的 access token,不轮换 refresh token(`spotify.js:33–64` 保留 `data.refresh_token || refreshToken`),不伤桌面。测试 `agent/codex-system-login.test.mjs`“the Xiaoyuzhou recipe reads no secret and sends nothing”(真实的小宇宙与 Spotify 配方代码)。名单需随 vendored 配方(`opencli-vendor`)的上游更新复核:判断“续期会不会轮换 refresh token”要看配方源码,上游改了这里不会有任何提醒(审核方 2026-11-17)。**A 网关 key 重新同步:只登记**。(a) 每次拉取成功都会非原子地重写 `/owners//model-access-credentials.json`(`credentialsStore.ts:63–66`、`credentialsSync.ts:246`),这是共用代码的既有写法;(b) Host 的 Codex 对 xd:没有 ChatGPT 登录时是 env-key(`runtime.ts:550` 把 key 放进进程环境,`codex-runtime.ts` readRoute:`native.hasLogin() ? 'oauth-bearer' : 'env-key'`),只换“本进程已替换集合”里的 key(`codex-proxy-host.ts:2645–2651`),用不上对方写的新 key;有 ChatGPT 登录时是 oauth-bearer,每次现读 key(`:2655–2657`)。**F 远程 MCP 桥 token:只登记**;边界:两边同时发现缺失、各自生成一份会互相覆盖,属于极少见的启动竞争(`provider-config.ts:166–172`)。**G 插件密钥尾号:只登记**(`ghostSecretStoreCore.ts:104–116`,4 个字符的指纹,不是密钥)。**后续九(2026-11-17,C 账号会话续期,照审核方定的六步与桌面对齐)**:Host 只有一个续期函数 `auth/refresh.mjs` 的 `refreshHostSession`,`main.ts` 的五个调用方都经它:续期定时器(`scheduleAuthRefresh` / `armAuthRefreshTimer` → `refreshAuthSession`)、服务端接口 401 后的重试(`createHostServerApi` 的 `refresh: refreshAuthSession`)、Device Link 认证失败(`startDeviceLink` 的 `refreshToken`)、第一次启动(`ensureRuntime` 与新预览的 `resolveAccountUser`,不经单飞与退避,也不看闸门)、`/api/auth/refresh`(`refreshAuth`)。闸门关着时续期照常,不被挡;`/api/auth/refresh` 这个外部入口原在 service 闸门的拒绝名单里,审核方 2026-11-17 定放开:移进 `HOST_PATHS_ALLOWED_WHILE_HELD` 的 `renew` 一类(理由写在旁边:续期是闸门期间唯一允许 Host 写的共用凭据(Agent-Net 设备身份是后台服务自己的记录,在 profile 根的 `safe-storage`,桌面用 owner 目录下的 `device-link-relay/secrets`,不读写它);客户端模式的窗口正是经这个接口请 Host 续期,继续拒绝的话窗口会当成续期失败),`service.test.mjs` 的 REFUSED 去掉它、点名放行的那条加上它;三列表加了一行。① 被拒后的替换重试:桌面共用的 `runRefreshWithReplacementRetry`,候选三处、顺序同桌面(v1 记录、账号库当前账号的资源令牌、构建区的旧版独立令牌),最多 2 次替换、被拒后按 250 ms 与 1 s 重读(同桌面运行时)。② 请求之后、判失败之前重读 v1;已不是这一轮被拒过的令牌就丢掉这次失败、稍后再续(**b 同意**,比桌面严;与桌面的差别:桌面只比最后试的那枚,桌面这个潜在问题记进第五节“后续阶段的桌面事项”第 6 条;`cindy-host login` 之后账号库里留着同一账号的旧令牌,v1 那枚被拒、最后试的是账号库那枚时,只比最后一枚会把真失效当成别人的、永远重试)。③ 只有确定失败且 v1 仍是这枚令牌才登出(只登出本进程:`invalidateHostSession`,不删任何凭据);DEVICE_MISMATCH 同样只登出本进程、保留凭据;替换用完仍被拒的按暂时失败。④ 写回:桌面的规则搬到共用模块 `authRefreshCommit.ts` 的 `applyRefreshedCredentialsToVault`(存储读取是端口),Host 在同一把跨进程锁 `.cindy-auth-accounts-v1.lock` 里(锁忙时一直等,同桌面的 waitWhileBusyAfterRotation)重读 v1、账号库与登出墓碑,按这条规则写账号库(只改这个账号那一项,别的原样写回,版本写 1 同桌面),再写 v1(保留 `hostDeviceId`)并镜像已存在的旧版独立令牌(不在就不建);已不持有这枚令牌就不写 v1。锁和存储各用各的(桌面的事务带回滚,Host 用自己的凭据库),规则与锁文件名(`AUTH_ACCOUNT_VAULT_LOCK_FILE`,Host 的登出与 `cindy-host login` 也改用它)是同一份。**e 接受**,与桌面一致的已知边界:锁不可用、写入失败,或账号库读不出而这枚令牌来自账号库或旧版令牌时,服务端已轮换的新令牌没有落盘,下次续期被拒后登出(原来 Host 不拿锁直接写 v1,没有锁不可用这一种);续期接口回 ACCOUNT_UNAVAILABLE 时按暂时失败(桌面运行时续期同样,原来 Host 判确定失败)。**与桌面的差别(审核方 2026-11-17 逐条裁决)**:**a 同意**:账号库没有当前账号或当前是别的账号时,v1 仍是这枚令牌,Host 也写 v1——`cindy-host login` 只写 v1(见下),照桌面只认账号库的话,桌面登出过再用 `cindy-host login` 登录的 Host 第一次续期就会丢掉轮换出的令牌、下次续期被登出。这条差别其实在补另一个缺口,另登记为乙(第五节“乙:`cindy-host login` 写出与桌面登录相同的存储状态”);那条做完后 a 应当可以去掉。**c 接受,登记为差别**:Host 确定失败后不清盘上已确认被拒的令牌(桌面 `clearConfirmedDeadRefreshTokens` 会清);理由:Host 不删共用凭据这条规则优先,留下的死令牌最多让下次启动再判一次失败。⑤ v1 文件在但读不出(钥匙串锁着等)或解析不了:按暂时失败重排;文件不在才结束会话(`HostSessionMissingError`)。⑥ 排期:access token 的 exp 减 300 秒,用桌面 `scheduleRefresh` 同一个纯函数 `authTokenClaims.ts` 的 `accessTokenRefreshDelayMs`(access token 约 60 分钟(推算,未在服务端核实));暂时失败按桌面的 `AuthRefreshBackoff` 退避(1–2、2–4、4–8、之后 5–10 分钟),等待期间来的调用方拿 false、不发请求,网络失败后的等待里服务端接口的 401 可提前一次(`serverRejectedToken`,`server-api.ts` 现在把这个参数传过来;同桌面);固定 30 分钟的定时器已删。**d 接受**:拿到时已到期的令牌 60 秒后再续(桌面立即续),比立即续更不容易打成循环;exp 不是数字时不排(桌面会立即续),由 401 那条路兜住(`startup-account.test.mjs`“a token without a numeric exp arms no renewal; the server API's 401 still renews”)。**`cindy-host login` 写不写 passport:不写**。`auth/login.mjs` 换码得到的结果里可能带 `accountRefreshToken`(`loginOutcomeSchema` 的可选字段),Host 丢弃它,只经 `skill-projection-owner.ts` 的 `commitLoginSessionAndOwner` 在账号库锁里写 v1(`AUTH_SESSION_KEY`),不写账号库的资源令牌与 passport,也不写旧版独立令牌。所以 Host 登录之后、第一次续期之前,账号库里这个账号仍是登录前的旧令牌;桌面切换账号时 passport 兜底不可用(`switchSavedAccount` 没有 passport 就是 `ACCOUNT_REAUTH_REQUIRED`)。第一次续期后账号库这一项就是新的(④)。**测试**:`auth/refresh.test.mjs`(两个进程共用一份存储同时与交替续期都不登出;三处来源各自已有新令牌时被拒后改用它续上;盘上就是被拒的那枚才判确定失败、什么都不删;`cindy-host login` 后 v1 与账号库旧令牌都被拒仍判确定失败;DEVICE_MISMATCH;盘上已换时丢掉失败;替换用完;写回三处与设备绑定、只有 v1 的 profile 不新建记录、桌面登出后的 Host 登录照样保住;不再持有就不写;读不出与不在;写回等另一进程的锁),`startup-account.test.mjs`(定时器落在 exp 减 300 秒、新令牌接着排;同时来的调用方共用一次;暂时失败按退避重试、等待期间不发请求、401 可提前一次,`server-api.test.mjs` 钉住 401 把这个信号传到续期;确定失败结束会话、不再排);桌面 `authColdStartRecovery.test.ts` 由复现改成回归:场景 1 经 `refreshSavedResourceSession`(`switchSavedAccount` 从账号库续这个账号的那一步;`switchSavedAccount` 本身编不进这个夹具,它的 `completeLogin` 要跑 owner 提交、拆除与渲染进程,这是最近的生产入口),场景 2 经冷启动;另加账号只在 Host 上登录过、保管库里没有它时,桌面冷启动经 `canClaimUninitializedVault` 认领空保管库、接上这份登录。**保管库保真**(审核方 2026-11-17 要求,整条线上风险最高的一次写入):桌面 `authColdStartRecovery.test.ts`“keeps every other account, the passport, unknown fields and the tombstones byte for byte”用桌面生产的写入与读取函数(`writePassportSessionToVault`、`writeAuthAccountVault`、`readAuthAccountVault`、`listSavedAccounts`,从 `authManager.ts` 编译出来,只有底下的加密记录换成内存)做一份三个账号(A 当前、B 已存、C 本机登出,有墓碑与 `loggedOutAccountKeys`)、一个 passport、一个 Host 不认识的顶层字段和 B 里一个未知字段的保管库;Host 续期一次后,除 A 的 refreshToken、metadata、lastUsedAt 外逐字节不变,墓碑记录不变,桌面读回的账号列表不变、A 是新令牌;把写回改成写整个规整后的视图,这条红。`readVault` 认的版本改成 1 与 `AUTH_ACCOUNT_VAULT_VERSION`,不再写死 `[1, 2]`。改坏:18 项全红(第一轮 15 项里 13 红 2 绿——替换用完判登出、不拿锁——补了最后两条测试后变红;评审后加的 3 项:②只比最后一枚、去掉 401 提前、`server-api.ts` 不传这个信号,也红。前 15 项是:不写账号库、只读 v1、去掉②、DEVICE_MISMATCH 当暂时、替换用完判登出、读不出当不在、去掉 Host 差别、不持有也写、不在也建旧版令牌、丢设备绑定、不拿锁、固定 30 分钟、失败不重排、等待期间照发、确定失败当暂时)。**后续十(2026-11-18,用量记录的两项查证)**:① **库里的用量是原地累加**:三张日用量表都是 `INSERT … ON CONFLICT DO UPDATE SET 列 = 列 + 增量`(`localDb/dailySpend.ts:131–147`、`dailyModelUsage.ts:92–109`、`dailySessionUsage.ts:38–42`,Pi 回执事务 `localDb/worker/opHandlers/piUsageTx.ts` 同样),任务行的累计花费与 token 是 `UPDATE sessions SET 列 = 列 + 增量`(`sessionSpendBroadcasterCore.ts:111–119`、`:192`),定时任务运行的花费也是库内一条语句(`scheduler-host/runCostLedger.ts` 的 `CASE` 更新),没有读出来改了再写回的;闸门期间桌面和 Host 同时写同一个库,增量不会互相吃掉。消息上的本回合花费(`agent_meta`)是读改写,但只有跑这个回合的进程写自己的消息;客户端模式下窗口不跑回合,这个前提成立。② **客户端模式下窗口进程会写 `provider-usage-by-party.json`**:窗口照常起设备互联(`bootstrap-electron.ts:10729` `initDeviceLinkService`,不看客户端模式)并注册供应商组的远程处理(`:10766` `registerProviderGroupRemoteHandler`),这台电脑是供应商组所在电脑时,组内电脑送来的用量报告经 `provider-group/remoteRegistration.ts:41–42` 的 `replaceReported` 写进这个文件(`usage/providerPartyUsageStore.ts:265–291`,1 秒后整份覆盖,`:178–199`,写前不重读)。窗口其余的写方在客户端模式下不跑:`register.ts` 的按任务记账不注册(`bootstrap-electron.ts:7088–7099`),远程 Agent 主机的 `device`/`relay` 行要 Maker(`maker-host/index.ts:1038` 客户端模式下 `getMaker` 抛错),共享页只读(`device-link/providerShareRuntime.ts:792`、`:907`)。所以 Host 若记本机用量,窗口是第二个写方(只在这台电脑是组所在电脑、有组内报告进来时)。审核方 2026-11-18 定:第一阶段 Host 不写这个文件,谁来写归乙(第一节第 13 行)。**已知现状(不是乙的待办)**:闸门期间允许跑完的回合,引擎自己仍可能刷新共用登录;这和桌面单独运行时多个任务并存的情况相同,不是 Host 引入的。测试 `agent/codex-system-login.test.mjs`:默认登录与单独账号各两条,经真实的桥与 Host 端口——不对账、不续期(有效、已过期、快过期)、文件快照不变;上游拒绝时三样都不做、后续请求带同一原因失败、放开后第一次读取对账、再被拒绝走正常作废。**后续三(2026-11-17,审核方定)**:读取路径查清后的处理,逐条见本节表后的“闸门关着时读取路径的三列表”。Codex 读登录状态时不再对账(`agent/runtime.ts` 两处 reconcile),只按现有的 `codex-home/auth.json` 与作废标记作答;Pi 不另改,它的 openai 分支转给同一个 Codex 适配器(`maker-host/pi-auth.ts:34` → `agent/runtime.ts` 里 `createPiAuthAdapter` 的 `desktopCodexAuthAdapter: codexAuth`),**以后 Pi 换认证路径时要重新核这一条**;Claude 闸门关着时不起 `claude auth status`,只用已读到的状态,从没读到过时报原因码 `HOST_PROFILE_IN_USE_BY_DESKTOP`(暂不可用),不报未登录;`/api/browser-backend/get-health` 移出放行清单,闸门关着时拒绝。测试:Host `agent/profile-coexistence.test.mjs`、`startup-account.test.mjs`(启动被拒)、`agent/input-queue.test.mjs`“profile hold”五条、`agent/codex-system-login.test.mjs`(闸门关着时不对账、profile 下逐字节不变、没有绑定;放开后同一次读取会对账并绑定)、`agent/native-auth.test.mjs`(Claude 两条线:缓存空报暂不可用、缓存有值照答,都不起 CLI)、`service.test.mjs`(get-health 被拒)、`device-link.test.mjs`(端口归类、取消授权放行)、`web-shim.test.mjs`(W:typed 错误体还原、启动被拒加标记、其余照旧);desktop `devStartupStatus.test.ts`(runtime 字段)、`hostIpcProxy.test.ts`(D:带原因码与不带两种)、`renderer/__tests__/ipcErrorHostProfileInUse.test.ts`(D:公共映射认出标记、其余 key 照旧含边界、新旧三个 key 在 12 种语言里 renderer 与 main 各取到)、`renderer/__tests__/remoteErrorDecode.test.ts`(D:经真实 sendMessage 的发送失败横幅显示人话,其余错误原样) | +| 发布 Host PR 前必须完成(甲类,审核方 2026-11-17 定):凭据状态变化时模型列表对齐桌面 | 桌面 `model-access/index.ts` onStatusChange 的四个效果:failed 清掉模型、保留最近一次“需要付费”的拒绝(不让已有任务绕过路由守卫);disabled / unsupported / idle 清掉模型和拒绝记录,不再回退到内置嵌入模型列表(suppressEmbeddingFallback);四种状态都清账号档位;disabled / unsupported 之后不再用失效的 Key 拉 /models(桌面只在 ok 时发起,`:432`;聚焦刷新也要求 ok,`:603`)。价格部分已在第 13 行 3a 做完。**已做(2026-11-17)**,Host 的对应(`agent/providers.mjs` 的 noteCredentialStatus 与 HELD_MODELS):① failed:模型清空,`preservePaymentRequiredRoutes: true` 保留付费拒绝,非权威;路由守卫(`tombstoneGuardOptions` 的 isPaymentRequiredTombstone)照旧拒绝之前被付费拒绝的路由;② disabled / unsupported / idle:模型与拒绝一起清空,`suppressEmbeddingFallback: true`,不回退内置嵌入模型;这之后模型列表为空且非权威,路由守卫不再拒绝之前被付费拒绝的那条路线:这与桌面行为相同(桌面同样清掉拒绝记录),实际请求会在网关被拒,不是 Host 放松了守卫;③ 账号档位:Host 没有对应状态(main.ts 的 fetchModels 只取 /models 的 models,状态里的 accountTier 恒为 null),无事可清;④ 不拉 /models:四种状态下读取都不发起新的一轮(包括 force),在途的一轮回来时丢弃(不写列表、不写价格、不进缓存,`provider-credentials.test.mjs`“in flight”用例);ok 之后把上一轮标为过期,下一次读取重拉。failed 期间也不拉,与桌面一致(桌面同样只在 ok 时发起)。测试:Host `agent/provider-credentials.test.mjs` 两条(真实 active-catalog 加 createHostModelAccess)、`agent/usage-pricing.test.mjs` 凭据两条(失败期间 force 读取也不发 /models) | +| Host 历史读取器(甲类,2026-11-17 只读 Worker 发现、审核方定) | Host 的 `agent/history.ts`(`createHostHistoryReader`)是 Host 自己写的装配,不在第七节,一并加入第七节。① 锚点不排除清空线之前的消息:清空后,清空前的回复正文仍能经 `/api/messages/work-details` 读出(复现测试见 impl-mem-history 的分支),甲类,照桌面 `localDb/ipc/messages.ts` 的 anchor/validate 语义修,红测试和修复压成一个提交,单独做;② 没有 outline/hydrate,长任务读历史超过 2000 行或 8MB 直接报 UNSUPPORTED_CAPABILITY,甲类;③ `running` 绑的是 `isProvisionalSession`(“还没发送的任务”),桌面是 `isSessionTurnPendingCompletion`,甲类;④ `live` 恒为空、读时补齐(`restoreTaskImageRows`、`hydrateLegacyUserTurnCosts`)没做,甲类次要;⑤ revision 固定为 '1',随 outline 一起改。②–⑤ 不在 Host 上逐项补:先出可行性报告,看桌面 `messages.ts` 404–456 的读取器装配能否搬成共用工厂、Host 只绑端口。结论(2026-11-17):桌面的读取器装配已搬成共用工厂(`localDb/ipc/localHistoryViewReader.ts` `createLocalHistoryViewReader`,桌面 `728b61ab69`),Host 的 `createHostHistoryReader` 只绑端口(经 `explicitPorts`),Host 自己的 anchor 已删,第七节第 27 项关闭。①:Host 用桌面的 anchor 与 validate(测试 `sessions.test.mjs`“refuses a message from before the clear line, or rewound”“refuses a page whose rows were cleared while it was read”)。② 已解决:outline/hydrate 随共用读取器接上,扫描预算按大纲 100000 行,正文在展开时读(测试“reads a task longer than the full-row scan budget”,2100 行的一轮)。③ 已解决:`running` 绑执行器的 `isRunning`(经输入队列 `isTurnRunning`),回合的行落定前都算运行中,对应桌面 `isSessionTurnPendingCompletion`(测试 `input-queue.test.mjs`“the history view of a running turn shows its in-flight rows as running”)。④ `live` 已解决:绑执行器新加的只读 `liveHistory`(该任务消息持久化的 `getSessionThinkingSnapshots`,桌面同一个函数),同一条测试;`hydrateLegacyUserTurnCosts` 随共用读取器做了;补图(`restoreTaskImageRows`)与外部历史导入(`importBeforeList`)不接,各自的事实与定类见下面两行。⑤ 已解决:revision 用桌面同一个表达式(`clientEpoch:data_version:total_changes`)。`isDeviceLinkCaller` 与桌面一样读 `isDeviceLinkInvoke()`:Host 的 Device Link 入站在共用分发的 device-link 上下文里进程内调服务(`local-db:messages:view` 经 `HOST_CONTRACT_CHANNELS`),只用于把对端与本地正在读的页分开。`/api/messages/list` 与 `/api/sessions/messages` 仍用 Host 自己的 `readMessagesList`(审核方定) | +| Host 历史读取器的 `importBeforeList` 留空(2026-11-17 查清,建议乙,待审核方定) | **桌面做什么**:不分页读历史之前调 `runMessagesListImportSideEffects`(`localDb/ipc/messages.ts:684-702`)。它只处理 id 以 `codex-`、`claude-` 开头、还没有导入来源记录(`session_imports`)的任务,也就是旧版 Cindy 导入、升级后还没接入新导入器的任务。做法是 `adoptLegacySessionBeforeOpen`(`session-import/legacy.ts:104-115`):补写来源记录;Codex 把原生历史放进 Cindy 的 codex-home;没在 Cindy 里续做过的,补齐旧版没导入的内容(例如 Codex 的工具调用);Claude Code 另建一份 Cindy 自己的原生副本。第一次这样打开时,顺带在后台一次性接入其余旧任务(`ensureLegacyImportsAdopted`,做完写 `migration_meta` 标记)。启动时不会自动扫,只有在桌面上打开过一个旧导入任务才会触发。普通任务和新导入器导入的任务不受影响:新导入器在导入时就把完整历史写进库,打开时不读来源文件。**用户看得见的差别**:旧版导入、升级后从没在桌面上打开过的任务(只要桌面上也从没打开过任何一个旧导入任务,全部旧导入任务都在内),在 Host 上打开时只能看到旧版当时写进库的消息。旧版是打开时才导入(`legacy.ts:104` 注释),从没在旧版里打开过的任务,库里可能一条都没有,历史视图就是空的;实测:临时库里放一条这样的任务行、不放消息,用 Host 的读取器读首页,得到 0 项。在旧版里打开过的,有旧版写的行,但缺补齐的那部分。Claude Code 的这类任务在 Host 上续做时没有 Cindy 自己的副本,会接着原工具里的那条会话写。这一点是读代码得出的,没有实测。**定类依据**:这类任务只能由旧版桌面创建;Host 上没有导入入口(`local-db:session-import:*` 是 A 类、转发 0,cindy_helper 的导入回调 `sessionImport` Host 也没接),所以 Host 上不会产生新的这类任务。`prepareExternalCodexSessionForResume` 虽在 Host 的导入图里(`agent/codex-thread-storage.ts` → `codexThreadStorageCore.ts`),但它只让续做时 Codex 看得见外部线程的原生记录,不往 Cindy 的库里写消息。所以“Host 上续接外部 Codex 线程后历史为空”这条甲类情形在 Host 上走不到。但“创建时桌面已经导入过一次”也不成立:旧任务要等在新版桌面上打开才接入,迁移前可能一直没接入。建议乙:迁移前要么让 Host 绑上同一个接入,要么在交接前保证桌面的一次性接入已经跑完。**接上要动的**:`legacy.ts` 在 Host 上加载不了,`session-import/scan.ts:13` 导入 electron(用到 `app.getPath` 两处,第 76、155 行),`sources/pi.ts:16` 也导入(第 52 行一处);`writer.ts` 经 `cindy-media/ingest.ts` 与 `chatAttachments.ts`,走到 desktop 版 blobStore。要先把这几处改成 Host 已在用的核心(`userDataPath`、`ingestCore`、`chatAttachmentsCore`),估计桌面 4 到 5 个文件、30 到 50 行;之后 Host 在 `agent/history.ts` 绑一行。其余来源适配器能否加载,改完后要再核一次 | +| Host 历史读取器的 `restoreTaskImages` 留空(甲类次要,2026-11-17 查清;发布 Host PR 前要么接上,要么带着事实回来问是否降级) | **桌面做什么**:`restoreTaskImageRows`(`cindy-media/taskImageDelivery.ts:305-388`)处理已落库的助手行。如果回复里用本机路径引用了图片(Markdown 图片,路径在任务工作目录或 Claude Code 的 scratchpad 里),就把图片导入任务的媒体库,按 CAS 把这条消息改写成媒体地址;导入失败回滚,原行不动。桌面在三处做:落库时(`localDb/ipc/messages.ts:1357` 新建行、1254 改写正文),读历史时(共用读取器的列表、hydrate、anchor,以及“某条消息前后”的读取,messages.ts:427、512)。**Host 现在两处都不做**:Host 的消息落库(`message-store.ts`)不调它,读取器也留空,所以 Host 上这类回复永远保持本机路径。**用户看得见的形态**(读代码得出,未实测):Web 客户端与经 Device Link 看的手机、另一台电脑,本机路径都显示不出来;本机窗口只能按工作目录解析(`MarkdownRenderer.tsx` 的 `WorkspaceMediaSrc`),所以 Claude Code 存在 scratchpad(系统临时目录)里的图在 Host 任务里显示不出来;工作目录里的图在文件被删、被移走或换了工作目录之后也显示不出来。桌面在落库那一刻就把字节复制进了媒体库,不受这些影响。Host 上已经落下的这类行,以后接上之后读历史时仍会补导入,但只限文件还在的。scratchpad 会被清掉,所以拖得越久,丢得越多。**依赖**:`taskImageDelivery.ts` 在 Host 上加载不了,经 `refCompensationJournal.desktop.ts`(导入 electron)和 `ingest.ts` → `blobStore.desktop.ts`。需要先去掉 Electron。**接上要动的(估计)**:桌面把 `taskImageDelivery.ts` 拆出不导入 Electron 的核心,照 `*Core` 的做法:`ingestMedia`、`withMediaRefCompensation`、`captureMediaRefCompensationScope` 三样经端口传入,Host 用 `media-store.ts` 里已有的 `hostMediaIngest`、`hostMediaJournal`。约 370 行原样搬进新文件,改写 3 到 5 行,原文件剩约 25 行绑定;`taskImageMarkdown.ts`、`ledger.ts` 能否加载要再核(`ledger.ts` 已核过能加载)。Host 侧:读取器绑一行,`media-store.ts` 建实例约 5 行,消息落库两处(新建行、改写正文)各补一次约 10 行,外加测试 | +| 发布前条件:CI 新增的 Host 检查在 Linux 与 Windows 上先跑一遍(审核方 2026-11-17 定) | `c3c7251ae7` 在 host-regressions 里加了 4 步(只加载 e2e 导入图、provider-config、ipc-route、lifecycle;lifecycle 在 Windows 上跳过),只在 macOS 上验证过。Host PR 发布之前,用自有电脑(Ubuntu、Windows 各一台,只在任务目录里、不装系统级东西、用完清理)把导入检查、provider-config、ipc-route 各跑一遍,lifecycle 在 Ubuntu 上跑,结果记在这一行;PR 正文单列这一项与增加的 CI 时间(本机约 31 秒,估计每个矩阵 job 多 1–2 分钟)。甲 20 新增(2026-11-17):两个区域各跑一次 `build.mjs --region`(含一份同区域的渲染层构建),对产物跑 `scripts/release-region.e2e.mjs`,并跑 `release-region.test.mjs` 与 `profile-path.test.mjs`;命令见甲 20 的交付。甲(启动失败原因,审核方 2026-11-18)新增:在 Ubuntu 与 Windows 上各跑一次 `apps/host/src/startup-account.test.mjs`(`node --import ./src/loaders/test-region.mjs --import tsx --import ./src/loaders/register-raw.mjs --test src/startup-account.test.mjs`,在 `apps/host` 下)。这个文件对操作系统敏感:要起真实的 `cindy-host serve` 子进程、在 PATH 上放 `secret-tool` 替身(Linux 的 keyring 由它应答)、SIGTERM 收尾后删临时目录(Windows 上进程刚退出时删目录可能遇到占用);子进程环境去掉全部 `XDT_` / `CINDY_` 变量、各类主目录与临时目录指到临时目录。Linux 与 Windows 上的结果记在这一行。发布前在自有机器上跑的真浏览器测试包括 `apps/host/scripts/plugin-sandbox.e2e.mjs`(实际启动 Chromium 的沙箱端到端测试)和 8i 的真实插件沙箱层。现有 `apps/host/scripts/plugin-sandbox.e2e.mjs` 自身没有“找不到浏览器就跳过”的分支,直接执行时断言真实插件启动成功;`.github/workflows/ci.yml` 的 Host regressions 对它只检查导入,未执行脚本主体。真实 Chromium 的沙箱行为属于原有 CI 未验证范围,发 PR 时在正文列明。跑这一层时要设 `CINDY_TEST_CHROMIUM` 指向 Chromium,并核对输出里 8i 的夹具冒烟“the hook fixture plugin answers the hook it is asked…”不是 SKIP;本机 Host 全量里这条在没有配置时跳过,报告写“通过 N、跳过 1”,跳过不算通过(审核方 2026-11-18)。 | +| searchSessions:Host 上 `session_search` 工具不注册(甲类小单元,审核方 2026-11-17 定) | 桌面给记忆工具传全文检索(`mcp-integrations/mcp-providers.ts`),Host 的 `createHostMemoryMcpProviders` 没传;照桌面接,和 Host 已接好的 cindy_helper 历史搜索用同一个检索,端口包挪到 .ts 用 explicitPorts 写 | +| 检查点 4b:Host 绑自动续跑运行时与钩子的端口 | 审核方定(2026-11-17):定时任务来源的端口共 5 个,在 Host 上一律写显式空实现——钩子工厂的 `beginSchedulerAutoResume`、`pendingSchedulerAutoResumeRunBySession`、`notifySchedulerAutoResumeFailed`,加 U3 露出的簿记 `onAutoResumeFailed` 与运行时的 `finishScheduledUsageLimitWait`;注释写明“Host 上定时来源的输入只有‘启动时从共享库恢复的排队快照’这一条来路,且没有执行器”,指向乙 1,用同一条钉住测试(恢复出的定时任务排队项被丢弃时、它上面出现可续跑错误时)。另两项定前要查清:`surfaceSuppressedError` 在桌面除灵动岛外还做 `settleDeferredProductTurnFailure`(产品回合失败的延后结算),Host 有没有对应、不接会少什么,查清再定,不能因灵动岛不适用就整项写 `undefined`;`settleProviderGroupContinuation` 写空前查调用点会不会因它“成功返回”而跳过别的步骤。register.ts 绑定里有两处至今没有测试(中断续跑开关里的“或运行时降级开关”、额度等待按 retryClientId 匹配),Host 对应的绑定在 4b 要有测试。4b 交付时单列:同步 2 冲突的解法(`onPersistedSendRejected` 两边都调)与 main `3792724192` 的两处(`persistTerminalSendError` 的 `attemptToken`、`interruptedTurnAutoResumeHooks.ts` 的改动)。用户行(2026-11-17):Host 的发送事务原来直接写用户行,不走桌面的 `createUserMessageDurably`(`register.ts:17811`),额度用完后人的新消息不会再续跑,自动续跑输入的待确认结果也不登记;改为与协调器同走 `auto-resume.ts` 的 `createUserMessage`。审核方先选的“经会暂停的写入队列、靠 clientId 去重”前提不成立:失败的用户行在恢复时被重放,输入被新消息取代后仍会写出一条从未发给引擎的用户行。改为桌面的失败语义:排在回复行之后写,失败交还调用方、不暂停、不重放(与 `behindDurableWrites` 同一写法),输入留作可重试的错误。测试:额度用完后新消息仍会续跑;失败的用户行可重试或被取代且之后不再写;重试只写一次、只发一次;自动续跑输入的用户行写失败后任务仍能再次续跑(包装吞掉失败就红)。注意区分:**回复行**写失败仍暂停任务、恢复时补写(Host 自己的设计,不变);**用户行**写失败不暂停、不补写(与桌面相同)。检查顺序与桌面一致:回合只在排队前检查一次,排队等回复行期间回合被取消,用户行照样写下(桌面 `register.ts:17811` 直接传 `createUserMessageDurably`,同样如此)。执行器没有自动续跑运行时就拒绝写用户行,不留直接写库的兜底路径;回复行写入暂停期间,下一条输入不会派发,也就不会排到暂停的写入后面挂住(“failed reply persistence pauses the queue…”断言没有 b 的用户行)。换路线(2026-11-17):开了“自动换路线”设置时,同一轮第二次中断先换到另一个供应商再续跑,续跑跑在新路线上(行为测试见第七节第 28 项);写这条测试时查出 Host 启动运行时没用已接受的运行时调整(第七节第 28 项,已修)。另:续跑测试夹具原来不给事件盖续跑令牌,第二次中断永远被当作“续跑待确认”跳过,exit 2 只验了流结束,没验连续续跑;夹具已照 Maker 盖令牌,exit 2 断言确实续跑多次 | +| 溢出错误时后面已排着输入(4a 时发现,2026-11-17 查清,发送前预处理已于线 A ③ 对齐) | **桌面(共用代码,设计如此)**:协调器先收到溢出错误,设错误和恢复点;终态阶段认领;恢复工厂 `tryRecover` 开始前取中止信号 `contextRecoveryAbortSignal`(`maker-ipc/contextRecoveryAssembly.ts`,桌面经 `register.ts:18162` 接,Host 经 `context-recovery-assembly.ts:151` 接):协调器有排队的输入时,先 `clearError` 再返回已中止的信号,`tryRecover` 在中止时返回“已恢复”(`contextOverflowRollover.ts` 的 `if (signal?.aborted) return true`),于是既不重放、也不写错误行、也不发布这条错误;排着的输入随后派发。这条规则来自 #4170(`b3a957b98d`,2026-09-09,“续接尊重新输入”),用户已经继续发了新消息就不再重放旧的。桌面派发那条排着的输入时,发送事务先调 `prepareUnhealthySession`(`makerSendTransaction.ts:1139` → `register.ts:5100` `prepareUnhealthySessionForSend` → 恢复工厂 `runPrepare`):按历史里最后一条可重建的错误、实时占用对窗口的压力、压缩失败标记判断,需要时先重建再发;这里错误行没写,是否重建取决于占用读数(读代码所得,没有桌面测试覆盖这个场景)。**Host(线 A ③)**:排队输入经同一发送前检查。原回合没有重放、错误行或错误推送。已满窗时,下一条在新实例发送并带一次摘要;有余量且没有其他重建依据时,仍由原实例发送。测试 `input-queue.test.mjs` 的两条 “queued overflow gives way without replay or error”。**和检查点 4 设计的出入**:设计里“重放期间新输入要等,协调器的恢复点让边界算忙”只对重建之后、重放期间入队的输入成立;重建之前已经排着的输入,按 #4170 的规则由中止信号清掉错误放行。 | ① 已随第 30 行对齐。其余仍是桌面产品选择:② 让“被排队输入取代的溢出”留下痕迹(错误行或说明),改共用代码,是桌面产品行为的改动:**用户已定(2026-11-18)**,留一句提示,两边一起改,进后面的桌面行为变更 PR,见第四节;③ 先重放旧消息、再发排着的输入,推翻 #4170:**不采用** | | PR 正文须写:桌面提示前后哈希 | 重构前(7eaf7788de)与 m1-cp5c 之后,桌面三个引擎最终 systemPrompt / answerDeliveryPrompt 的 sha256 前 16 位相同:Claude `cb41d06b15ad7128` / `6084849accb05a45`,Codex 同 Claude(两份引擎补充提示目前为空),Pi `be3d281b8d83ea42` / `e6057c54763111fc`。结论:桌面提示前缀逐字节不变,缓存率不受影响 | +| 甲:28c 未验证项 | 钥匙串增量与 Windows 系统代理比对只在 GitHub 一次性 runner 上验证,PR 发出后才首次跑;首次运行全绿后划掉 CI 项;Windows 实测回填后三项全部完成,28c 才关闭。自有 Windows 机器就绪后另测冷启动到 ready 的时间及内存,并在自动检测开启但没有 WPAD 的环境再测一遍;两组待测,超过 10 秒报审核方。 | +| 甲:28b 的 macOS CI 比对,28c 扩到 Windows(2026-11-17,28c 2026-11-18,审核方定甲类) | 未关闭。28c 起这份 workflow(名字改为 System proxy comparison)有两个 job:macOS 上先跑辅助进程验收(`scripts/chromium-proxy-worker.e2e.mjs`),再比对,PAC 与自动发现两组现在要求与 Electron 完全一致(Host 经辅助进程问 Chromium,辅助进程按生产方式启动、不带测试开关),在辅助进程运行前后比对所有名称以 Safe Storage 结尾的钥匙串条目,断言没有新增(审核方 2026-11-18 要求的“生产启动不碰钥匙串”实测);Windows 上先跑同一份验收,再改当前用户的 Internet 设置逐组比对(`scripts/windows-system-proxy-compare.mjs`:无代理、手动、按协议、例外、PAC、PAC 加手动;手动一组要求 Electron 确实给出代理,否则判为设置没生效;自动检测存在二进制的连接设置里,这次不设)。两个 job 都要装 Electron 二进制,CI 主流程的 Host 任务不装(`ELECTRON_SKIP_BINARY_DOWNLOAD`),所以验收放在这里。CI 首次运行要等 Host PR 发出之后(本分支不推送),第一次就要全绿才关闭。关闭条件:Host PR 上那次比对全绿。只能在发出 Host PR 之后关闭:`.github/workflows/macos-system-proxy-compare.yml` 只在 GitHub 托管的 macOS runner 上跑,触发方式是手动运行,或改到这份实现的 PR(`apps/host/src/macos-system-proxy.ts`、`apps/host/scripts/macos-system-proxy-*`、这个 workflow 本身;Host PR 正好是第一次),普通 PR 不跑;手动运行要等它进了默认分支。Electron 升级由守护带到这里:`macos-system-proxy.ts` 的 `CHROMIUM_RULES_ELECTRON_VERSION` 必须等于 `apps/desktop/package.json` 的 Electron 版本(`hostDesktopSourceContracts.guard.test.ts`“follows the Electron version the desktop ships”),升级的人改这个常量就会改到实现文件,比对随之在那个 PR 上运行。Host PR 正文要写:这一项要等 PR 上的比对全绿才关闭,`169.254/16` 等第七节第 29 项里的几条待实测;比对出现不一致就在这个 PR 里修,与 Chromium 不符的照 Chromium 改。跑完还要把各组的 scutil 样本回填到 `macos-system-proxy.test.mjs` | +| 甲:失败回合的配对 done 不算成功完成(`noteFailedTurnCompletionTail`,3d 发现,审核方 2026-11-18 定甲类) | 已关闭(2026-11-18,结论:Host 的结构走不到,不改代码;登记为第二节差别“失败回合的配对 done”)。桌面在终止性 error 时记下这条尾巴(`sessionEventTerminal.ts:200–205`),配对的 done 据此不算成功完成(`:554–566`、`:595`,不调 onSuccessfulProductTurn、跳过 Orca Worker 终态上报)。Host 没有尾巴,靠的是三点:① 前台的终止性 error(不是续接边界)一定走 `finish`,Host 的回合就此结束,自动续跑接管、上下文恢复认领、错误被压下都一样(`finish` 照常调,压下的只是错误行);② 同一代随后的 done 走 `turn.terminal` 那一段,只结 Git 基线和记用量,不进成功判定(`settleProductTurn`),不落行、不发客户端;③ 下一轮已经开始时,上一代的 done 被代次过滤挡下。引擎差异:Codex 中断是带 interrupted 状态的 done,本来就不算成功;Pi、Claude 的失败轮同样先发终止性 error;续接边界的 error 不结束回合,桌面也不记尾巴,两边一致;当前引擎发出的 `turnScope: 'background'` 事件是后台任务更新、工具边界、压缩状态或边界、独立文本,实际不带 `done` 或终止性 `error`。Host 在产品回合收口处显式排除后台终态。桌面成功及失败分支未加范围条件,当前由引擎事件生产形状保证不触发(原来写“两边都不进”没有依据,2026-11-19 复查改写)。没有 generation 的迟到 done 在新一轮已开始时会被当成新一轮的 done,桌面同样如此(尾巴只按 generation 消费)。测试 Host `agent/input-queue.test.mjs`“failed turn tail: …”两条(自动续跑接管的失败轮,其配对 done 之后失败仍被扣住、放弃时只结算一次、不发给客户端;上一代的 done 不结束下一轮);改坏三处都红:放开 `turn.terminal` 那段、放开代次过滤、接管的终止性 error 不结束回合 | +| 甲:账号切换时清运行时选择(4b,审核方 2026-11-17 定甲类) | 已关闭(`69bcff4996`)。桌面在 owner 提交边界(`appSessionState.ts` `setAppSessionCommitBoundaryHook`,桌面的钩子在 `bootstrap-electron.ts`)清每个任务的来源、运行时轴与运行时控制状态(共用 `clearOwnerScopedSessionRuntimeSelection`,owner 纪元加 1);Host 原来不绑这个钩子,同一账号退出再登录后,下一次启动会用登出前自动换到的路线,owner 纪元的作废检查也不触发。现在 `bindHostSessionRuntimeHooks`(`agent/runtime-selection.ts`)绑同一个共用函数,`main.ts` 在建好运行时选择之后、第一次提交 owner(`ensureRuntime` 的 `configureHostOwner`)之前调一次。桌面钩子里的其余五行在 Host 上:本机 Agent 确认(`cancelLocalAgentConfirmations`)——Host 不跑本机 Agent 服务(第 29 行);Host 自己的工具确认在 `disposeOwnerRuntime` 里 `hostConfirmations.close()` 取消(`main.ts:1769`),每次提交别的 owner 都在它之后。进行中的 Claude Code 登录(`cancelClaudeCliLogin`)——Host 能在登录进行中换账号,但每次提交别的 owner 都先经 `disposeOwnerRuntime` → `providerConfig.close()`(`main.ts:1775`)→ `cancelLogins()`(`agent/provider-config.ts:146-151`)→ `claudeNative.cancelClaudeCliLogin()`,中止登录信号,`runCli` 收到后 `child.kill()` 结束 CLI 子进程(`claude-native-cli.ts:125-133`),等登录的 `triggerLogin` 返回 `login_cancelled`(`agent/runtime.ts:164-173`)。这条结论成立的前提:已有 owner 时 `ensureRuntime` 拒绝换 owner(`main.ts:563–566`),只在 `disposeOwnerRuntime` 把 `activeOwner` 置空(`main.ts:1823`)之后才提交新 owner(`main.ts:617`);退出登录和隔离的四处都是先 dispose 再提交(`main.ts:472–474`、`:1385–1387`、`:1946–1948`、`:1974–1979`;行号以 host-m1 `149e6f4652` 为准)。**以后改 `ensureRuntime` 的换号路径时要重核这一条**:一旦允许不经 dispose 直接提交别的 owner,进行中的 Claude Code 登录就不会被结束,需要在提交边界钩子里补上 `cancelClaudeCliLogin`。任务提醒角标(`clearAllSessionAttention`,`appBadgeService.ts` 导入 electron)、远程桌面窗口、弹出的页签窗口——窗口的状态,Host 没有。测试:Host `input-queue.test.mjs`“after signing out and in again a task starts on its saved route”(改坏能红:钩子写空即红)、“a model the user picks after an automatic fallback is what the next start uses”(覆盖已有行为:用户改选择会清掉调整,两条清理路径同时去掉才红);三个槽在 `main.ts` 顶层只装一次、删除任务调清理,由 guard 层 `hostDesktopSourceContracts.guard.test.ts`“binds the runtime selection slots once at top level and cleans a deleted task”看住(行为测试经 `bindHostSessionRuntimeHooks` 本身,走不到 `main.ts`) | +| 甲:任务读取投影运行时调整(4b,审核方 2026-11-17 定甲类) | 已关闭(桌面 `6f3cdb7689`、Host `a812b95e69`)。桌面所有任务读取经 `setSessionRuntimeProjector` 的投影器(`mapper.ts` `projectSessionRuntimeFields`)把模型、来源、努力、Fast 投影成实际在跑的路线,并带 `runtimeEffective`、`runtimePending`、`runtimeGeneration`;Host 原来不装,读到的是任务行:自动换路线之后,窗口一重读,模型标签就跳回保存的路线,和实际在跑、在计费的路线不一致。投影器原样搬成共用 `createSessionRuntimeProjector`(`maker-ipc/sessionRuntimeProjection.ts`),桌面原处只传端口;Host 在运行时选择里用同一个 `projectScheduledPreferences` 建它,`bindHostSessionRuntimeHooks` 装上。`runtimePluginsSelected` 在 Host 上经 `readRuntimePluginSettings` 查询任务是否有插件选择(`agent/runtime-selection.ts:276`;2026-11-19 复查更正,原文说恒为 false)。测试:Host `input-queue.test.mjs`“a task read shows the fallback route”、反向的“with no runtime change a task read is its row, in the desktop's runtime shape”(不装投影器或插件选择写 true 都红) | +| 甲:归档与删除时清运行时调整(4b,审核方 2026-11-17 定甲类) | 已关闭(桌面 `03e1c1ab76`、Host `1583a6f8a6`)。桌面的状态写入在归档、删除时调 `cleanupSessionRuntimeForTerminalStatus`,它跑 `setSessionRuntimeCleanup` 装的清理(任务的运行时控制状态、来源、努力、Fast,再推送投影);Host 的归档只改列、也没装清理,归档前自动换到的路线在恢复后的下一次启动生效(第七节第 28 项修完之后启动会读它)。清理原样搬成共用 `createSessionRuntimeCleanup`(同一个文件),桌面原处只传端口;Host 在运行时选择里建它,`bindHostSessionRuntimeHooks` 装上;`cancelPendingRemoteStart` 写空(Host 不在另一台电脑上启动任务,send-preflight 拒绝远程任务);`workingDirectoryRecovery.discard` 接 Host 执行器的同一个恢复(`working-directory.ts` → `turn-executor.mjs` → `input-queue.mjs`)。Host 的归档(`agent/session-update.ts`)与删除(`main.ts` `deleteSession`)在任务路线锁里调 `cleanupSessionRuntimeForTerminalStatus`,与桌面写入方相同。测试:Host `input-queue.test.mjs`“a task archived after a fallback and restored starts on its saved route”(归档不调清理、不装清理都红);“a task archived with an unsent recovery note does not carry it after the restore”(目录不见了的任务第一次发送被引擎拒绝,恢复说明留着未消费;归档再恢复后,下一次发送不带这条旧说明。清理里的 discard 写空、或 `working-directory.ts` 的 discard 写空,都红) | +| 甲:账号边界停止提前置位(2026-11-17 只读核查发现、审核方定甲类) | 已关闭(本单元)。原来 Host 的停止态(输入队列的 `closing`,执行器据此记 `interruptedByShutdown`、不写结束时间)要到 `disposeOwnerRuntime` 里的 `inputQueue.dispose` 才置位;在它之前,退出登录先在服务端吊销会话,会话失效与有序关闭先暂停请求、关确认窗与插件、关平台客户端,这段时间里因此失败收尾的回合写下结束时间和错误行,界面显示成错误,不是中断;`/chat` 流在边界时收不到任何回执。现在:`agent/owner-boundary.ts` 的 `createOwnerBoundaryStop` 在第一步①置输入队列停止态(`input-queue.mjs` 的 `beginStop`,只置 `closing`:不再收新输入,之后收尾的回合是中断)、②持有共用的 `beginSessionTurnEndedSuppression`(第二道,照桌面 `bootstrap-electron.ts` 账号边界)、③让开着的 `/chat` 流以中断回执收尾;`runOwnerBoundary` 按“开始停止 → 本路径的拆除 → `disposeOwnerRuntime` →(退出登录)登出与吊销”的顺序走,压制到这些都结束后才放。退出登录(`main.ts`,以及 `server.mjs` 的 HTTP 退出登录在关平台客户端、排空请求之前先调一次)、会话失效、有序关闭都经它;切换账号单元以后直接复用。退出登录照桌面 `logout` 的顺序改成先停运行时、再登出并吊销;吊销失败不让退出登录失败(`auth/logout.mjs`,已是尽力而为),本地照样停下并登出。`/chat` 的收尾回执是 `{ type: 'input_receipt', sessionId, inputClientId, clientId, status: 'interrupted' }`,与窗口发起的回合被用户停止时执行器发出的回执字段相同,只是由流自己写出、不经事件中心,没有 `seq`(与它原有的队列头、重连回执一样)。测试 `agent/input-queue.test.mjs` 的“owner boundary”一组:退出登录(停在吊销之前、无错误行、吊销失败照样登出、下次启动列入中断);会话失效、有序关闭、退出登录三条路各一条“边界开始后、dispose 之前收尾的回合不写结束时间、列入中断”;边界开始后不收新输入、压制持有到拆除结束;`/chat` 以中断回执收尾、与用户停止时的回执对照。审核方复核后补(2026-11-17):①不变式写进 `agent/owner-boundary.ts` 头注:begin 之后必须到达 dispose,到不了的路径必须重建输入运行时,释放写在 finally 里;begin 调用点四处(`main.ts` 的退出登录、会话失效、有序关闭都经 `runOwnerBoundary`,`server.mjs` 的 HTTP 退出登录入口一处),逐个对照。②HTTP 退出登录入口原来在取消挂起的登录被拒、或关平台客户端同步抛错时不调 `deps.logout()`(输入运行时停在 closing,之后每次发送都以 "session is closed" 被拒,直到重启)甚至不释放压制(之后所有回合都不写结束时间);改成前置步骤包在 try 里,失败也照样调 `deps.logout()`(它的 `runOwnerBoundary` 会 dispose),释放写在 finally 里;测试 `server.test.mjs`“logout, when cancelPendingAuth rejects / platformClient.close throws”。③行为变化(审核方接受):会话失效时 `pluginGateway.host.reset()` 抛错,原来会跳过 dispose,现在照样 dispose,错误照旧交给调用方。④接线守护 `hostDesktopSourceContracts.guard.test.ts`“begins every owner boundary through runOwnerBoundary, before its teardown”钉住三条路径都经 `runOwnerBoundary`、拆除都在它之后,退出登录的登出在 dispose 之后,HTTP 入口先 begin 再关平台客户端。主干同步 6 后,桌面真退出会提前封口并为未结算的 Claude 合成取消终态;Host 真退出仍先停止队列,关会话后才无参数调用 Maker shutdown。Host 的中断标记、`/chat` 回执和按用户决定继续的规则照旧,帧差异本轮只登记,账号切换、登出和闸门放开仍与真退出分开。 | +| 甲:Host 启动失败时窗口只看到登录页(2026-11-17 只读核查发现、审核方定甲类,做法 (b)) | 已关闭(本单元)。原来启动失败或被拒绝启动时,收尾的 dispose 把账号清成未登录,`/api/auth/state` 和“没有会话”一模一样,窗口显示普通登录页;而窗口里的登录与跳过登录在窗口本地执行,正是第二节“已知限制(仅限测试期)”里写着不要做的那条路(本地写会话、写保管库、提交 owner,Host 还停在 error)。**Host**(集成分支):启动收尾按错误类型或明确错误码归类(`apps/host/src/start-failure.ts`,不按 message 文本),存进 `runtime.unavailable`;`projectHostAuthState` 只在未登录时投影 `hostUnavailable: { reason }`,不带 `runtime.detail`;`ownerUnavailableReason` 改为从 `runtime.unavailable` 取,owner 请求的 409 带同一个码,被桌面占用那一码仍带原来的 message,并存 D 的映射不变;只在开库成功、显式退出登录、登录完成时清掉,dispose 不清(审核方 2026-11-18:没有会话或会话被拒时,窗口启动时那次 `/api/auth/refresh` 会结束会话、再 dispose 一次,原来因此把原因清掉,窗口回到登录表单;`startup-account.test.mjs` 用真实的 `cindy-host serve` 子进程钉住(只测了“没有已存会话”;子进程不读系统钥匙串,Linux 上由测试自带的 `secret-tool` 替身应答)。两处**按代码推断,未测**:“会话被明确拒绝”没有端到端覆盖(已存会话要经系统凭据库,认证地址必须是 https;它与“没有会话”走 `performAuthRefresh` 的同一分支,`main.ts` 555–557,已有续期测试断言拒绝会走到这一步);“已登录用户”那条没有测试(启动失败后 `runtime.owner` 为 null,续期成功也投影为未登录、带原因,且不走 dispose);登录今天在 serve 之外完成(`cindy-host login`),下一次启动重新报);`getAuthState` 仍等启动结束,启动过程中不会闪出标记。六个码:`HOST_PROFILE_IN_USE_BY_DESKTOP`、`HOST_ACCOUNT_MISMATCH`、`HOST_DATABASE_LOCKED`(租约或 schema 锁被占)、`HOST_DATABASE_UNAVAILABLE`(其余库错误,含“库版本比 Host 新”:Host 的开库路径不跑兼容检查、直接迁移,失败一律是 `MIGRATE_FAILED`,区分不了,不单列)、`HOST_SIGN_IN_SERVICE_UNREACHABLE`(认证客户端的传输失败:`HostRefreshDeferredError` 带 `networkFailure`,或 status 0 的 `AuthApiError` `NETWORK_ERROR` / `REQUEST_TIMEOUT`)、`HOST_START_FAILED`。不带标记的正常未登录:没有会话、会话被拒或已不在、跨区个人账号(与运行期结束会话的判定相同)。**桌面**(准备分支,见本节表后“非搬移提交”):码与文案 key 在 `apps/desktop/src/shared/hostStartFailure.ts`;登录页把标记接进已有的错误面板分支,显示原因与怎么办,不显示登录表单和跳过登录,面板上没有按钮(“重新检查”已去掉,审核方 2026-11-18:同一实例里后台服务不重试启动、原因不变,实例一换请求一律 409,没有一种情况能成功);主进程 `dispatchLoginAction`、`enterLocalMode` 开头在 `authRefreshOverride !== null` 且 Host 带标记时以固定码 `HOST_NOT_STARTED` 拒绝。**文案**:用词已定(「Cindy 后台服务」,用户 2026-11-18,一律写全称),12 种语言已改,面板上不出现“Host”;每条“怎么办”都先让用户重新打开 Cindy(数据库不可用和通用启动失败两类,之后另给 `cindy-host status` 的排查说明;2026-11-19 复查补全)(中文由审核方 2026-11-18 定稿,英文照意思写,其余语言跟随),被单独运行的桌面占用那一句写“重新打开当前这个 Cindy 窗口”;“重新启动后台服务”在个人版里对应什么操作,仍挂在本节“含 Host 字样的文案”那条乙上。**解除条件**:3.5(登录改由 Host 做)落地后,去掉主进程那两个条件,原因面板保留(`docs/host/client-mode-account-switch.md` 3.5、第十节)。 | +| 甲,发布前必须回答:后台服务修好并重启后,已经开着的窗口会怎样(审核方 2026-11-18 登记,不挡本单元落地) | 未关闭(落地后走查确认)。落地前的一次替身实测(2026-11-18,真实后台服务加窗口主进程的真实连接代码,没有跑 Electron 界面):重启后后台服务换了实例号,窗口启动时钉住的旧实例号让它通过鉴权的请求都得到 409 `host_instance_changed`(`server.mjs` 143–148),事件流对旧实例的 409 以一秒间隔重试、401 转入等待鉴权、主动关闭会停止(`hostEventStream.ts` 62、80、90、176、188、191;2026-11-19 复查更正),`auth:get-state` 与 `/api/auth/refresh` 同样被拒,主进程的原因一直不清;重开窗口后立即回到登录表单。审核方据此定(2026-11-18):去掉“重新检查”,每条“怎么办”先让用户重新打开 Cindy(2026-11-19 复查:数据库不可用和通用启动失败两类另附 `cindy-host status` 排查),第二节登记已知限制。本单元落地之后再实际走一遍:让后台服务以某个原因启动失败、窗口显示面板,修好原因并重启后台服务,不重启窗口,看窗口是否、多久、经哪条路回到正常或登录表单。结论相同就关闭本行;窗口能自己恢复,就报审核方重看文案与第二节那一行 | +| 守护:Host 加载的模块级设置函数(审核方 2026-11-17 定) | 已落地(集成分支 `c6cf7f4cb9`、`9719906e05`、`8019eba1f6`、`ec2efeac6b`、`3437ac5b6f`、`88b0d5ff29`,之后本提交按审核方的决定改表)。桌面 guard `hostDesktopSourceContracts.guard.test.ts` 的“module-level port setters the Host loads”用 esbuild 只解析 Host 的导入图(`apps/host/scripts/build.mjs` 的入口加验收脚本),收集桌面与共用包里写模块级槽的设置函数(槽的初值为空、任意函数,或空的 Map/Set/数组),和 `apps/host/src/desktop-module-setters.ts` 双向比对:新出现的没归类、表里的已不存在,都红;`bound` 要在所指的 Host 文件里真有调用、容器变更或作为端口值交出(语法树判断,注释和类型不算);`pending` 必须指向本表的行号或甲、乙编号;理由里不许写本表的文件行。这次按最新代码归类:`setAppSessionCommitBoundaryHook`、`setSessionRuntimeProjector`、`setSessionRuntimeCleanup` 已绑(`agent/runtime-selection.ts` 的 `bindHostSessionRuntimeHooks`,见上面三行 4b),`setLiveCcSessionBridge` 已绑(`main.ts`);`configureProjectionBoundaryOwnerCommit` 已绑(第 25 行 25b:默认放行 owner 提交;`agent/skill-projection-owner.ts` 的 `refuseSkillProjectionOwnerCommit` 注入拒绝,`main.ts` 启动 serve 时调用,`cindy-host login`(`login-cli.mjs`)经同一文件的 `allowSkillProjectionOwnerCommit` 注入允许;表里的 `where` 写成 `文件#函数`,守护只认拒绝那个函数里的调用,去掉它就红);`configureProjectionBoundaryPassive` 不适用(只有未打包、带 `XDT_PASSIVE_SHARED_USER_DATA=1` 的桌面开发实例是被动的,Host 用默认 false);`setGeneratedImageRecovery` 待绑(甲类次要,随上面“Host 历史读取器的 `importBeforeList` 留空”“`restoreTaskImages` 留空”两行:Host 没注册恢复函数,共用历史读取器调 `recoverGeneratedImagesForHistory` 时什么都不做);`setSessionArchiveSyncRequester` 待绑(乙 11:原生归档同步,第二节“恢复已归档任务”“手动归档”两行);`setActiveLedgerCurrency` 属共用代码内部调用(`usage/modelPricingCore.ts`)。审核方第二轮(2026-11-17):`setSessionRestoreObserver`(甲 22)、`configureUiText`(甲 23)在 Host 上绑上,改为已绑;not-applicable 只留给 Host 按设计永远用不到的(窗口专有、Electron 专有、Host 准入时就拒绝的任务类型),原来 34 项里写着 M2、M3 或以后接的 24 项改为 pending 并挂编号:第六节新补的三行推送(`setHistoryWorkPageReader`、`setOnSessionTurnEndedPersisted`、`setProviderUpstreamErrorBroadcaster`)与已有的 `maker:session-background-activity` 一行(两项);第 22 行(共享任务三项、代输入、订阅用量);乙 6(device-link 控制端入口:文件浏览的两个订阅监听、供应商分享的访客路由);第 33 行(嵌入服务);第 6d 行、第 7 行;新编的乙 12(模型发现与供应商视图,8 项)。留下的 10 项不适用:被动实例判定、下载默认请求、活动目录变更监听(Host 按设计自己刷新)、Orca 默认值、远程托管、伙伴授权、插件宿主工具、定时脚本的默认拉起、文件浏览包的日志、图片缩放的日志。守护另外拒绝理由里的“to be assigned/decided/added”,表里不再有悬空项。守护看不到的:初值是对象或数字的槽、名字不以 set/register/bind/configure/install/init 开头的、工厂的闭包状态、运行期 `createRequire` 加载的模块,以及交出去的端口值接收方是否真的调用 | + +### 主干同步 2 的 Host 接线(2026-11-19) + +- 甲(已补):主干 `d9d979da86`、`7a052e497d`、`b5dd6bdc1c` 新增相同账号 Device Link 的 Pi Skill 启动准备。该入口绕过 HTTP 服务闸门,Host 在入口、任务锁内、启动及写入前复核占用与发起方。先用共用工具落定同一条意图,再启动已持久化的本机路线。被拒时沿用 `PRECONDITION_FAILED`,未落定的路线不应用。已经运行的回合仍按原来的插件静默与记忆规则收尾。 +- 本机换引擎交接与上下文重建复用主干的已验证目标窗口与重放历史。Device Link 的控制端模型选择沿用当前 Host 的共用落定;拒绝控制端传入窗口确认值。跨设备运行和原生历史传输仍不在 Host 的实现范围内,沿用 B5。 伙伴的跨任务历史索引沿用 M3 乙项。 +- `8bee8af5eb` 的行为清单(2026-11-19)。Device Link 换引擎改在 registry 入口核对所有者,原先主干在 `main.ts` 判断 scoped 来源。入口同时透传 `options` 和 `thinking`。能力表补回了在合并提交中删除的 `supportsRemoteModelWindowRebuild`。Pi `agentCommands` 在异步读完任务后复核账号及运行时。Pi 的 Skill 列表接收 `forceReload`,占用期间忽略强制重载。换引擎交接由最近 400 条改为按已验证窗口重放历史,`confirmNativeHistoryFallback` 端口随主干移除。合并提交 `65619a35d3` 本身不可构建,需连同紧随的端口补齐提交 `8bee8af5eb` 一起使用。 +- 甲(复审补齐,2026-11-19)。prewarm 先检查任务和旧运行时,再落定,拒绝用主干的 `PRECONDITION_FAILED`。本机入口选好的 Pi 意图也可由同账号远端请求落定并换掉旧引擎。普通发送在进入窗口核验后才遇到占用时,取消这次落定,保留待选和原路线,以占用提示拒绝当前发送。继续发送可能需要重新启动原运行时并写入共享任务行。用于核验的冷启动接入 Maker 的原生会话写入前取消信号,已经获准的在途回合仍照常收尾。普通发送现在凡是有待选,都经过 Host 的 `applyPendingPick`(以前直接调共用落定),这是这次主干同步里 Host 发送路径上唯一的结构变化;不占用时行为不变(“model change at send” 那一组测试),排查发送时选型问题先看这里(审核方 2026-11-19)。 +- 调度快照的取消沿用主干的等待信号合并。快照 deadline 原因通过既有回执交回 scheduler,由原有退避负责恢复(`d0fe38cf63`)。这两条保留已发起回合的账号边界。 + +### 主干同步 3 的 Host 接线(2026-11-19) + +- 主干 `48f3597f05` 新增项目归档与恢复的远程入口,Host 一并接上。桌面占用期间预览照常(只读),应用被拒:入口先 `refuseWhileHeld`,进入任务锁后依次 `beforeWrite`、`assertCurrent`、`refuseWhileHeld`,再开事务。Device Link 传来的 `archiveOnRemoval` 按主干的共用逻辑(`runProjectArchive(input, true, …)`)不生效。测试见 `apps/host/src/device-link.test.mjs`。 +- 这次同步里主干对定时任务(换线前先落定待选路线再写模型基线、路线落定前推迟排队的运行)、伙伴群聊(普通 @ 协调、强制排队)和 IM(派发前重建不可用的运行时、取消与收尾)的改动,Host 都还没有对应入口:定时任务和伙伴任务见第四节,IM 通道不在第一阶段。不新增待办。 +- 主干同步的合并提交:同步 2 是 `65619a35d3` 加端口补齐 `8bee8af5eb`;同步 3 是集成分支的 `7f09da233d`(准备分支 `43a545067c`)。主干其后已到 `54ca25e04b`,按约定不再追,除非出现新冲突。 + +### 主干同步 4 的 Host 接线(2026-11-19) + +- 主干钉在 `9354a65d1a`(相对 `af8bd193a3` 多 71 个普通提交、43 个合并提交),锁文件与 `.nvmrc` 未变。合并提交:准备分支 `1db8b978a4`(冲突只在 `localDb/ipc/sessions.ts`,见第五节“改到主干已有代码的地方”),集成分支 `679b799da5`(无冲突)。之后不再追主干,除非再出冲突。 +- 35 个改到生产代码的提交:9 个走共用代码,后台服务随合并得到(Codex 原生资源与清理归属一组 8 个,项目工具改用 Electron 无关的项目上下文 1 个);5 个后台服务已有对应入口并已对齐:`ccda86c776` 无限期稍后处理(`eec45e4d65` 把共用常量 `INDEFINITE_SNOOZE_UNTIL` 纳入 Host 的任务更新校验)、`df520e3564` 发送和移动只刷新已登记项目(`eec45e4d65` 绑定 `touchRecentWorkdir`)、`ea784680aa` 主干在 Host 发送路径绑定的两个读端口 `readReplyQuoteNote`、`readBotThreadNote`(`turn-executor.mjs:950–955`,伙伴与 IM 通道本身仍在 M3)、`54ca25e04b` 与 `87f69a5e2d` 的 Codex 共享登录提示(Host 已产生同一个 reason)。 +- 21 个后台服务没有对应入口,不新增待办:灵动岛与显示器(`48437f6897`、`7b46db9f9c`)、CUA 驱动查更与缓存(`2bfbee09c8`、`a85de58b7d`、`f955833926`、`e29f30f506`)、额度小组件(`e481388cb8`)、个人构建冷启探针(`4f562e2df6`)、iMessage 图片(`f7e71abb11`)、定时任务 webhook 授权(`a09215b9c8`,M2)、账单页(`1ac287afd2`、`57feaa0c8c`)、媒体 Guide 与视频执行器(`de481656ba`、`6e76c08499`、`7cede174aa`、`a7a8c43732`、`30f2188761`,既有乙 12)、GitHub 账户检查与本机签入恢复(`c6c37061d4`、`e5da6dacc9`,本机 GitHub 端口在第一节第 22 行列为 M1)、缺失插件的任务内搜索与安装(`089105c276`、`d9fc65bd15`,见第二节“任务里遇到缺失插件”,这是同步带来的退化)。 +- `apps/host/src/server.mjs`、`service.mjs` 主干没有改,不经 service 入口的分类守护仍通过。 + +### 主干同步 5 的 Host 接线(2026-11-19) + +- 主干钉在 `5a92f62d24`(相对 `9354a65d1a` 多 17 个提交),锁文件与 `.nvmrc` 未变。合并提交:准备分支 `b9fa89f919`(冲突在 `interruptedTurnAutoResumeHooks.ts` 两段、`register.ts` 一段),集成分支 `3ba205779d`(无冲突)。 +- 主干 #11406(`ac9aceb0b8`、`e1676daba1`、`73b901d196`、`65b590871b`、`0db6975b9f`)让桌面任务失败时按已配置的模型组候选恢复,保留原输入归属、图片能力和推理强度。**后台服务没有对应入口**:这需要桌面在首条输入前登记模型组(`model-groups/ipc.ts:81`)并给普通任务输入打标记(`register.ts:17001–17038,18109–18112`),后台服务没有这两样;`7b068f570a` 把主干新加的可选端口在 `agent/auto-resume.ts`、`agent/runtime-selection.ts` 显式写成不绑定。普通中断后的同 Agent 或其他来源备用路线仍经共用工厂(`sessionRuntimeFallback.ts:131–143`)。 +- 主干 Agent-Net 三个提交(`60390abbce`、`c8b0d7a605`、`cab943bb73`)的共享传输随合并进入;备用执行机交接走桌面的供应商分享服务,后台服务继续不绑定委派,新增的 `locallyProvenProviderShareDelegation` 归入入站分发端口的 unbound 一类(`device-link.test.mjs` 分类表)。 +- `apps/host/src/server.mjs`、`service.mjs` 主干没有改,不经 service 入口的分类守护仍通过。启动原因面板文案没有变化(主干 `6115ebf8d5` 只改法语另一条),144 个变体重新测量 0 截断,截图沿用。 + +### 主干同步 6 的 Host 接线(2026-11-19) + +- 主干钉在 `3ef44274d6`(相对 `5a92f62d24` 多 61 个提交),`.nvmrc` 未变;锁文件只多桌面渲染进程的两个依赖(`@replit/codemirror-lang-solidity@6.0.2`、`highlightjs-solidity@2.0.6`,主干 `1217996455`),后台服务不引用。合并提交:准备分支 `d76c822a05`(冲突只在 `deepLink.ts`,见“改到主干已有代码的地方”),集成分支 `1dd89e2966`(无冲突)。主干这批提交没有改 `apps/host`、各引擎的版本钉和根目录 `package.json`。 +- 61 个提交含 38 个普通提交、23 个合并提交。32 个普通提交改到生产代码或随产品发出的文案,另 6 个只改测试、文档、作者手册或许可证生成材料。逐条复核本表受影响的 54 条结论:甲 9 的历史盖章需接上主干新增判据,已在 PR 首轮修复;Claude 退出帧另有差异,这轮只登记。合并提交按所合入的改动核对,不重复计入下面三类。 +- **走共用代码,后台服务随合并得到(9 个)。** `a240ae6167`、`90b9f3edc3`、`94627aec2c` 的供应商拒绝分类由 Host 装配的 Claude/Codex 共用回环代理观察器使用(`providerErrors.ts`、`provider-upstream-error-observer.ts`)。上游错误向窗口推送仍归 M2。`cb5dd67f0a` 把已钉住的 Learn 宿主上下文带进共用 Codex 请求,Host 没有 Learn 消费端。`42caa5a2e5`、`67debe0174`、`129689804c` 的 Pi 大预算请求余量随共用桥进入(`packages/maker-core/src/agents/pi/cindy-bridge-source.ts:4515–4535,4871–4876`)。`362b19e328` 的显式上游账号拒绝由共用 Codex 立即终止、阻止重放,共用续跑白名单也排除该原因;桌面的供应商组认证换机没有 Host 入口。`a88d252986` 的 0153 迁移与 schema 随共用数据库进入,自动任务归属仍依赖桌面调度器和 script broker。 +- **后台服务已有对应入口(4 个)。** `252ae0897a` 的 `session_search` 任务链接已在同步提交里对齐主干构造,跟进同事共享任务所需的远端权限和 `readSharedTaskProgress` 仍未接。工具注册依赖该端口(`packages/lizi-mcps/src/xdt-helper/shared_task.ts:8–13`),见第一节第 22 行。`81c1f8baf2`、`d9d6a9d89e` 的真退出取消帧由桌面专用步骤合成,Host 用既有有序停止保留中断任务,帧差异本轮只登记。`7ace44b2b7` 的非成功 done 判据已在 PR 首轮修复接进 Host 的历史盖章(`59ea890ff5`,见甲 9)。 +- **后台服务没有对应入口,不新增待办(19 个)。** 自动化设置加载(`f5d2d2d099`,生产文件无净差)、Solidity 高亮(`1217996455`,桌面渲染及移动端识别,网页共用桌面渲染构建)、伙伴接管记忆(`7e68e10642`)、收件箱引导(`f3876f968d`)、插件侧栏(`9c03b0fc5e`)、移动用量样式和动效(`7a78a916e4`、`b3a7b25206`)、桌面壁纸(`78a585a47d`)、停止图标(`61e6c2760b`)、Telegram 回传与授权(`ea3c63cd39`、`497430f317`、`cab1f3d4c0`、`0cfd59bda0`)、桌面订阅池运行时与界面(`472bfde0a3`、`71d52b520e`、`fc5e07649d`,沿用 M2)、插件媒体直调(`0887228873`、`c2462db43b`)、IM 设置布局(`4fa07e3ba2`)。媒体直调经桌面 `cindy-brain/index.ts:6072–6096,9874–9879` 注入 Cindy slot,Host 的 `plugins/runtime.ts:337–366` 和共用 `executionPipe.ts:18–36` 没有该消息处理。 +- **端口和分类守护。** 这次同步前后,主干与集成分支各自的 `apps/host` 文件树均无净变化。`server.mjs`、`service.mjs`、共用 Host channel contract、通用 IPC registry、占用分类与源码守护没有随主干改动。桌面调度、共享任务跟进和插件媒体新增端口仍未由 Host 绑定;共用 Session 的异步提问多传 origin,Host 不安装 Telegram dispatcher。没有新增 Host HTTP 或 Device Link 入口、占用分类或网络注入。本次前提重验只读源码和 Git 对象;首轮修复的 `test:runner` 已通过分类守护,自有 macOS 补跑见上方验证行。 + +### 主干同步 7 的 Host 接线(2026-11-20) + +- 主干钉在 `43fb1df105`。从 `3ef44274d6` 到这个钉,排除 #11535 准备分支的历史后,复核了 70 个普通提交。锁文件 blob 仍为 `199a8c40aebcaa618d221ebd399c85d49721e4f2`,`.nvmrc` 仍为 22.22.3。审阅副本从 `8160a6ae86` 合并,`915dcd9847` 无文本冲突。 +- **需要补接、已在 `5feea98573` 对齐。** `e88f240ba6` 将 Claude 的回环 CONNECT 桥改名为 `cli-proxy-bridge.ts`,Host 关闭调用随主干更新。新增的 `getLocalPiHttpsProxy` 只由 Pi 读取,Host 的 Claude 与 Codex 实例通过端口分类明确留空。本机 Pi 按桌面顺序检查子进程代理环境,有显式配置时保留原配置,否则经同一个桥,用 `resolveHostOutboundProxy` 按每条隧道的目标选路。`0819a35164` 的 Windows 混合大小写代理变量归一化随 Pi 启动代码一并生效,远程 Pi 路径保持原样。Host 网络分类已登记新文件名和两个引擎的注入位置。 +- **已有入口、随主干对齐。** `dccd6d6a2e` 让 Host 的任务详情沿用共用 `projectSessionDetail`,返回执行端算出的 `turnElapsedMs`,Host 的任务详情和 Device Link 用例已随主干更新。`9452d7d8fa`、`05ece47fe1` 固定首次完成时刻的共用落库逻辑随 `sessionActiveTurn.ts` 进入 Host;窗口的停采样由桌面负责。 +- **走共用代码。** `55f4072515` 的 Claude 延后加载工具用量标签和 `8d625f1eb3` 的 Codex helper 状态未核实时只留日志随引擎进入。`8a6ba69469`、`3aea8f5457`、`82ff2eda57` 的项目与任务目录合并规则由 Host 的 `beforeTurn` 使用,桌面在运行中改目录的 IPC 回调仍只由桌面装配。`6e77fa0c23`、`48865e50d2` 的 Agent-Net 核及 `b05ef68b87` 的传输分档随共用模块进入;远程执行上传本身仍无 Host 入口。 +- **后台服务没有对应入口。** Discord 与 Hook 任务恢复(#10002、`850cecc70e`、`bc5b048e4b`)不注册桌面 IM 和工具;`4b7a81c32a` 的共用工具批准规则随合并进入。共享订阅文生图(#11466、#11505、#11517)的请求类型可由共用包识别,Host 不提供相应执行器。`3511bb6eff`、`f8f850aded`、`1423d9fd09` 的远程执行拉取、上传和 Windows 执行器仍由桌面负责。`0ac4b1e723`、`224de95029`、`15916967d6` 的群聊、IM、委托命名及桌面标题队列不走 Host 的首条消息占位标题流程。`8166583226` 的单区 SSO 容错只在桌面的显式企业标识入口启用。`49e4965370` 调整代输入工具说明,该工具仍在 M2。`4286c8461c` 的额度重置续跑依赖桌面 Goal 调度和账号用量轮询。 +- **端口和分类守护。** 新增的 `AgentDeps` 端口只有 `getLocalPiHttpsProxy`。`apps/host/src/server.mjs`、`service.mjs`、共用 Host channel contract 与占用分类守护在合并前后内容相同。后台服务其余接线无须补改。 + +### 主干上发现的问题(是否提 issue 由用户定) + +- 2026-11-19,主干同步核查:`c9e1fcd68e` 的 Host 记忆自审接线不读用户的辅助模型设置和停用开关。 +- 2026-11-19,主干同步核查:`8c4fc825b4` 起取远控中转令牌时,即使 Agent-Net 关着也会读取并解密已有签名身份。 +- 2026-11-19,准备分支同步验收:Cindy Make 有 17 条测试在 macOS 默认临时目录经软链接访问时失败。见本节已有的 macOS 临时目录记录。 +- 2026-11-19,发布前最后一轮验证:桌面 unit 用线程池跑全量时偶发段错误,Vitest 子进程拿不到合计。崩溃栈是线程池 worker 退出、释放 isolate 时最后一次弱回调跳到已卸载的地址,崩前刚跑完的是用到 better-sqlite3 的既有测试;这就是 `scripts/test-workspaces.config.mjs` 开头记的“原生模块收尾时段错误”,Node 22 上也会出现。主干(`8ba68e1e1c` 与 `af8bd193a3` 的导出源码,配准备分支的依赖)在另一台 Mac 的同一隔离里合计 4 次崩 3 次(前者 1 次崩 1 次,后者 3 次崩 2 次);在最后一轮验证的机器上主干 2 次未崩、准备分支多数崩溃。改用进程池跑同一批,准备分支与主干的失败项相同,准备分支没有独有失败;进程池对比在同步后的 `af8bd193a3` 上复核,结果相同。与本线无关,不在本线修,是否另开 issue 或小 PR 由用户决定;CI 首跑撞上按主干既有偶发处理,重跑一次,不为它改代码。已起草 issue,待用户决定是否发出。 +- 2026-11-19,发布前最后一轮验证(主干同步 3 之后):`remote-agent/__tests__/codexHosted.e2e.test.ts` 的 “asks on this computer before Codex runs a risky command, and runs only what was approved” 在主干、准备分支、集成分支上同样失败。失败方向是已批准的命令未生效;两条命令都问过用户这一点通过;被拒命令未执行这一点因前一条先失败,本轮没有断言结果,不能当作权限边界已验证。原因未定位,疑与外层隔离下 Codex 自带的命令沙箱不能嵌套有关,未证实。`startupProbe.e2e` 的 “compares native startup with and without shortcuts” 同样三处失败,原因未定位。`apps/desktop/src/main/remote-agent/` 在三处逐字节相同。两条都是主干既有项,另行处理,待用户决定。已起草 issue,待用户决定是否发出。 +- 2026-11-19,主干同步 4 核查:客户端模式的安装确认委托(`a7f5289e84` 把 `ghosts:install-consent:resolve` 委托给后台服务,安装本身不在委托清单里)让窗口本地的安装确认被拒,客户端模式下装不了插件。只影响客户端模式。已起草 issue,待用户决定是否发出。 +- 2026-11-19,主干上有三处按名称或路径匹配结束进程:macOS 更新器的测试夹具按命令行里的沙箱路径匹配,Windows 开发启动脚本分别按窗口标题和镜像名匹配。见本节“主干已有的进程清理”两行。已起草 issue,待用户决定是否发出。 +- 2026-11-19,主干同步 4 核查:`botSkillRuntimeProjection.test.ts` 的 near-16 MiB 与投影目录刷新两条,在主干 `9354a65d1a` 上同样并发跑 related 时同样 5 秒超时,单独跑通过;按响应字节分页一条两边都没复现。 +- 2026-11-19,复查准备分支时发现:主干上桌面任务被 Agent 或插件暂停期间,中断的自动续跑到点会直接返回,中断既不进历史也不续跑。准备分支已恢复与主干一致(只在后台服务写历史),是否修桌面由用户定。已起草 issue,待用户决定是否发出。 +- 2026-11-19,主干同步 3 验收:主干 `af8bd193a3` 上 `runtime.integration.test.ts` 有 21 条失败(含 2 个未处理错误 `handle.hasRecyclableProjectResourceDrift is not a function`),`botRemoteEditors.test.ts` 因缺 `snoozed_until` 列失败,等等。与本线无关。 + +### 并存方案 A:闸门关着时读取路径的三列表(以后白名单加路径照这三列判断) + +接上表“非客户端模式的桌面与 Host 不能同开一个 profile”那一行。放行清单(`service.mjs` 的 `HOST_PATHS_ALLOWED_WHILE_HELD`)里的读取,逐条答三件事:写不写库、写不写与桌面共用的 profile 文件(含引擎自己的目录)、对不对外发请求。处理原则(审核方定):写库的闸门关着时不许;写共用文件的跳过写入,只用内存或磁盘上已有的内容作答;只写 Host 私有位置的写明位置。**以后往白名单加路径,先按这三列填一行。** + +| 路径 | 库 | 文件 | 外部 | 闸门关着时 | +|---|---|---|---|---| +| `/api/providers` | 否 | 是:一轮 /models 写价格快照 `cache/model-pricing.json` 与账本币种 `cache/ledger-currency.json` | 是:/models | 不拉 /models,只用已有列表作答(`agent/providers.mjs`) | +| `/api/model-access`、`/api/usage/model-pricing`、`/api/usage/reference-model-pricing` | 否 | 只读已有快照 | 否 | 放行 | +| `/api/conversations/search` | 否 | 否 | 语义模式会对外发一次查询向量请求 | 放行 | +| `/api/agent-skills` | 否 | 25b 之后“先刷新再列”会写共享 Skill 目录 | 否 | 由 25b 改成只列不刷新(inv-phase1-b) | +| `/api/agents/auth-state`、`/api/agents/status`:Codex | 否 | 是:对账(`agent/codex-system-login.ts` 的 reconcile)会改写 `codex-home/auth.json` 的链接,并把登录绑到账号(`claimDetectedNativeProviderAuth`,绑定记录在 profile 里) | 否 | 跳过两次对账,只读现有 `auth.json`(`readCodexLocalAuthState`)和作废标记(`readHostCodexInvalidation`、`readHostCodexRecoveryRequirement`,都只读)作答 | +| 同上:Pi | 否 | 不带 provider 时只读;openai 分支转给 Codex 适配器,会对账 | 否 | 随 Codex 一起覆盖,不另改。依赖:`maker-host/pi-auth.ts:34` → `agent/runtime.ts` 的 `desktopCodexAuthAdapter: codexAuth`;Pi 换认证路径时重新核 | +| 同上:Claude | 否 | `claude auth status` 是否在 CLI 内部刷新令牌,仓库代码查不到;按会写处理(写也只写 CLI 自己的系统级配置目录,桌面用同一个) | CLI 可能自己联网(`cliEnv({ network: false })` 只是不加 Cindy 的代理变量) | 不起 CLI,只用内存里读到过的状态;从没读到过时回 `{ authenticated: false, errorReason: 'HOST_PROFILE_IN_USE_BY_DESKTOP' }`(暂不可用)。显示端:renderer 与网页端都不拿这两条路径显示 Claude 登录态——`hooks/useVendorReadiness.ts:48–55` 只取 `binaryReady`(`authReady` 不用于显示),`useCodexAuth.ts`、`useCodexSessionExpiredPrompt.ts` 只读 codex;Claude 的连接态来自供应商列表(Host `agent/provider-config.ts:190` 的 `hasClaudeNativeLogin`,同步读同一份内存缓存,不起 CLI)和 `maker:claude-oauth:status`(`hooks/useClaudeOAuthConnected.ts`;不在 Host 通道契约里,网页端是桩 `shim.js:953`)。所以“未知”不会被显示成“未登录”,不需要沿用上一次状态的改动;缓存为空时供应商列表本来就显示未连接,与闸门无关 | +| `/api/browser-backend/get-health` | 否 | 是:内置浏览器(rsb-webview)探测失败时自动恢复,重建后端(`browser-backend/health-service.ts:61–78` → `performRecovery` 的 `restartEmbedded`) | 否 | **拒绝**(移出放行清单)。设置页看到的:`ComputerUseSection.tsx:705–713` 读失败时不走公共映射 `mapIpcErrorToI18nKey`,而是套 `browserBackendHealthFallback`(`:108–117`,`status: 'error'`、`reason: 'status-failed'`),显示“侧边栏浏览器连接异常:无法检查浏览器连接状态。点击「恢复浏览器」重建控制连接。”并带恢复按钮(`BrowserBackendSubsection.tsx:66–85`);选的是“我的浏览器”时显示“「我的浏览器」不可用:无法检查浏览器连接状态。”点恢复也会被闸门拒绝,提示“恢复侧边栏浏览器失败”(`ComputerUseSection.tsx:814`)。也就是用户会被引去修一个没坏的浏览器,**登记为乙**:要显示“暂不可用”,需改这处 renderer 的读失败处理(桌面提交);审核方 2026-11-17 定不并进 D,和窗口顶部常驻提示、直接显示原文的 toast(并存那一行的 ④⑤)归同一批,将来一起排。Host 上的自动恢复本身(平时行为,与闸门无关):Host 自己不起窗口也不起进程,内置浏览器在连着 Host 的那个桌面里(平台客户端,`platform/tools.ts:55–66` 把调用转给它,`host-platform/client.desktop.ts:92–99`);设置页的被动探测用 `recoverEmbedded(false)`,不带 `ensureHost`,不会弹出侧边栏窗口,只有用户点“恢复浏览器”才带 `ensureHost`,在那个桌面上按用户的独立窗口设置打开侧边栏(与桌面单独运行时相同);没有桌面连着时探测排队等待,直到有桌面连上、切换浏览器或账号边界取消(`server.test.mjs` 的 get-health 排队回归),不会自己拉起任何东西 | +| `/api/browser-backend/get-state` | 否 | 只读设置文件与内存 | 否 | 放行 | +| `/api/auth/refresh`(`renew` 一类,审核方 2026-11-17 定) | 否 | 是:续期写账号会话的 v1 记录、账号库里这个账号的资源令牌与已存在的旧版令牌(在账号库跨进程锁里,规则与桌面同一份,见并存行后续九) | 是:向账号服务发续期请求 | 放行:续期是闸门期间唯一允许 Host 写的共用凭据(Agent-Net 设备身份是后台服务自己的记录,在 profile 根的 `safe-storage`,桌面用 owner 目录下的 `device-link-relay/secrets`,不读写它)(不续就掉线);客户端模式的窗口经它请 Host 续期 | +| `/api/project-info/image`、`/api/ghosts/card(s)`、`/api/sessions/get`、`/api/messages/*` 及其余 read 组 | 否(读取时不修补、不导入) | 否 | 否 | 放行(read 组零写入表,2026-11-17) | + +### 桌面准备 PR 里的非搬移提交(审核方 2026-11-17 要求维护) + +桌面准备 PR 的正文“非搬移改动”一节从这张表来;审核方按它逐项核对“桌面正常使用不受影响”。只列不是原样搬移的提交(按提交标题,不写哈希,落分支时哈希会变)。 + +| 提交 | 改了什么 | 影响谁 | 依据 | +|---|---|---|---| +| feat(desktop): accept a Host pause signal in the plugin gateway | 2026-11-19:共用网关在读取熔断位前检查可选的 Host 静默信号。仍在等待裁决的钩子按已有失败方向收口,旁听停投,静默不计入熔断 | 仅传信号的 Host。内嵌桌面沿用原投递、截止和熔断顺序 | 插件基座,走白名单确认。见下节及 `subscriptionGatewayPause.test.ts` | +| feat(desktop): delegate runtime plugin settings and notifications in client mode | 在 `hostChannelContract.ts` 追加可信窗口的 `maker:runtime-plugins`,在 `bootstrap-electron.ts` 转发拦截、改写、熔断三条既有推送 | 只影响客户端模式;上下游沿用原 Renderer 校验,内嵌和网页入口照旧 | 新窗口连接就绪的旧 Host 时新路由返回 `404 not_found`,旧窗口访问新 Host 沿用原调用和事件处理。没有新 Device Link 或 relay 字段。**桌面上观察不到**:转发只在显式的后台服务委托存在时安装,内嵌桌面走原本地 IPC 与推送路径(`bootstrap-electron.ts:1339,1353,1492–1495`)(2026-11-19 复查) | +| fix(desktop): require caller admission for plugin settings | 设置共用工厂要求调用方传准入检查,并在读取任务和 owner 之前同步调用 | 桌面继续传原可信窗口检查,Host 使用当前请求的占用与 owner 复核 | 调用次数及位置保持原桌面处理方式。**桌面上观察不到**:桌面自前一提交起就传这个闭包,调用次数、位置和同步失败时的拒绝不变(`runtimePluginTaskBindings.ts:101–122`)(2026-11-19 复查) | +| feat(desktop): allow rechecking a runtime plugin settings write under lock | 在设置文件锁内、计算补丁前可做一次同步复核;抛错沿用原有释锁和拒绝路径 | Host 可挡住等待锁期间失效的准入。桌面内嵌调用沿用原来的两个参数和写入顺序 | `runtimeControl.test.ts` 用真实锁核对两种调用、原文件字节和随后的一次正常写入 | +| feat(desktop): expose optional settlement permission at credential commit boundaries | 凭据服务在终态、定时器、关闭、Pi 事务和回滚、非 Pi 写库与完成通知前检查同步许可。运行时控制工厂把各代结算的原始 Promise 交给可选观察端口 | Host 在桌面占用期间延后结算。桌面沿用原调用点,不传许可,也没有新增等待 | 桌面五条路径在改前和改后的调用次数、顺序及微任务时点相同。主干 Pi 事务见 `b7cb47b56c`,详见下节。**桌面上观察不到**:桌面不传许可,检查同步放行,不登记等待;测试按微任务序号核对五条凭据路径(`register.ts:19811–19820`、`pendingCredentialSettlementTiming.test.ts:8–41`)。这个提交单独落地时运行时结算的差异可观察,由下一行撤回(2026-11-19 复查) | +| fix(desktop): preserve unhandled settlement errors across generations | 运行时控制工厂沿用原来的 void 入口,递归结算下一代后,当前代的上报异常仍会冒出 | 只有 Host 观察并等待每一代。桌面无观察端口,上报抛错时沿用原有进程日志 | 独立进程测试在端口加入前与修订后核对正常调用顺序,以及历史、广播上报失败时每次恰好一条 fatal 进程日志。**桌面上观察不到**:桌面不传许可也不传 work 回调,不额外挂 Promise handler;进程测试逐项核对各恰好一条 fatal 日志(`pendingSessionRuntimeControlSettlement.ts:27–38,126–136`、`pendingRuntimeSettlementProcess.test.ts:11–26`)(2026-11-19 复查) | +| fix(desktop): settle a paused automatic retry without a banner | 共用续跑回调在选择备用路线之前、之后都检查暂停,仍有效的尝试遇到暂停会把中断写进历史 | 单看这个提交,桌面暂停期间到点的行为会变(桌面也有暂停入口);最终快照桌面不变,只有后台服务启用 | 主干 `8bcdaae10b`,见下节。**最终快照:桌面不变;后台服务启用。** 这个提交原以为桌面从不设执行暂停,实际桌面有暂停入口(`sessionExecutionActions.ts`,Agent 和插件的 pause),所以它改变了桌面:暂停期间续跑到点、尝试仍是当前时,主干直接返回,它会把中断写进历史。由下一行恢复(2026-11-19 复查) | +| fix(desktop): preserve upstream interrupted retry pause behavior | 共用回调加可选的 `settlePausedResumeIntoHistory`。不传时三处判断用的是主干原样的 `isCurrent`,求值顺序相同,不调 `noteResumeSendFailed`、`finalizeSuppressedError`;传了才在暂停时把仍是当前的中断写进历史一次、不弹横幅 | 桌面不传,行为与主干逐句一致;后台服务在 `agent/auto-resume.ts` 传 | `botCandidateRecovery.test.ts`「leaves a current paused desktop retry and its held error alone」经真实钩子工厂钉住桌面行为(改之前红);后台服务那两条历史回归在不传时红、传了绿(2026-11-19)。主干同步 5(`5a92f62d24`,#11406 模型组恢复)之后复核:主干在同一文件加了 `resumeQuotaWait`、`modelGroupInputs` 和传给备用路线的第六个参数,合并时原样保留;不传选项时三处仍是主干原样的 `isCurrent`,差异只剩可选项和它守着的分支 | +| fix(desktop): defer recent project port reads until use | 主干同步 4 之后,发送与移动 helper 在确实要更新项目时才读取并调用注入的 `touchRecentWorkdir`(两处注入改成直接转发的函数) | 内嵌桌面恢复主干 `df520e3564` 的读取时机,没有新增等待;同步前准备分支在这里一直有一处没登记的差异(提前读取端口),这次一并消掉 | `sessionsPerTaskFlags.test.ts` 两条只改静音设置的用例先红后绿(2026-11-19) | +| fix(desktop): fit French Host startup guidance in six lines | 只改 `fr/common.json` 的 `login.hostUnavailable.HOST_DATABASE_UNAVAILABLE.action`:缩短法语处置说明,保留更新 Cindy、重启后台服务、重新打开 Cindy 和 `cindy-host status` 四步 | 只影响客户端模式下显示这个原因的法语面板 | 程序化测量 144 个变体:改前法语这一种深浅两色截断(161/138 px),改后 0/144 截断(2026-11-19) | +| fix(desktop): land a pending model switch to a model without effort levels | 待切到一个没有推理档位的模型时,切换照常落定(原来卡在档位空值上) | 普通桌面用户 | 桌面缺陷修复,审核方已审;累计行对照里单独跳过这个提交 | +| feat(desktop): add an owner-commit gate to the Skill projection boundary, allowed by default | 边界模块新增 `configureProjectionBoundaryOwnerCommit`;判定为否时 owner 提交在取锁、写任何文件之前拒绝 | 不影响桌面:默认允许、桌面不注入、守护钉住桌面入口不做注入 | 第 25 行 25b,审核方定 (a):Host 常驻进程注入拒绝 | +| (不在准备 PR)第 34 行 O3 | 客户端模式下的引擎版本选择 | — | 95 个提交里没有对应交付;未做,按第一节第 34 行在迁移前完成,两个 PR 正文写进“明确不包含”(2026-11-19 核对) | +| (不改)runtimeCapabilities 那句说明 | `hostCapabilitiesNote` 按 `appUpdate` 有条件地出现 | 无 | 95 个提交里没有对应变更,桌面不改:这句只在桌面 `maker-host/index.ts` 的 `get_session_runtime` 返回里,后台服务不输出(cindy_helper 的任务运行时工具在后台服务上未做,第一节第 22b 行),`appUpdate` 也不在 M1–M3(第一节第 22 行);内嵌模式输出不变(2026-11-19 核对) | +| fix(desktop): forward the recent projects push to windows in Host client mode | 客户端模式的频道白名单加一个频道 | 只影响客户端模式 | 内嵌模式不读这张白名单 | +| feat(desktop): show why the Host did not start and refuse local sign-in meanwhile | 登录页在 Host 报“没有启动”时显示原因面板(不显示登录表单和跳过登录);主进程的 `dispatchLoginAction`、`enterLocalMode` 在这时以固定码拒绝;渲染层多读 auth state 的一个可选字段,preload 多暴露已有的 `auth:get-state`;新增文案 12 种语言 | 只影响客户端模式,且只在 Host 带这个标记时 | 字段可选,本进程自己产出的状态里永远没有;主进程的条件以 `authRefreshOverride !== null` 为前提,只有客户端模式设置;登录页现有测试一条未改,另加“没有这个字段时表单和跳过登录都在”的断言。**桌面上观察不到**:主进程条件首先要求装好的后台服务 auth override,内嵌模式为 null,渲染层不进入面板逻辑(`authManager.ts:479,497–502`、`LoginPage.tsx:136–149`)(2026-11-19 复查) | +| fix(desktop): word the start-failure panel as the Cindy background service | 上一行面板的文案改用用户定的用词「Cindy 后台服务」/“Cindy background service”,12 种语言;`cindy-host login`、`cindy-host status` 作为命令原样保留 | 只影响客户端模式,且只在 Host 带启动失败标记时(同上一行) | 用户 2026-11-18 定:界面文字不出现 Host;只改文案值,key 与行为不变 | +| fix(desktop): say "Cindy background service" in the desktop-in-use refusal at start | 改 hostProfileInUseByDesktopAtStart 文案(用户定的用词):改已有文案 `logic.errors.hostProfileInUseByDesktopAtStart`(并存 D:单独运行的桌面占用数据、启动被拒),12 种语言改用「Cindy 后台服务」 | 只影响客户端模式(这句只在 Host 以 `HOST_PROFILE_IN_USE_BY_DESKTOP` 拒绝启动时出现) | 用户定的用词;key、映射(`shared/ipcError.ts`)与出现时机不变,D 的三个测试照过 | +| fix(desktop): always write the full name "Cindy background service" | 上面两行的文案一律写全称「Cindy 后台服务」/“the Cindy background service”(审核方撤回简写:zh-CN 的“后台服务”、en 的 “background service” 已另指运行中的后台命令与电脑操作守护进程);zh-TW 写「Cindy 後台服務」,zh-Hant-x-lzh 用该语言已有的「後臺」 | 同上两行 | 用户 2026-11-18 的用词决定;只改文案值 | +| fix(desktop): fit the start-failure panel's titles and French text in the panel | 写全称后有 7 种语言的面板标题超出单行(en、de、es、fr、ja、pt-BR、pt-PT),法语“数据打不开”那句超过 6 行;按设计规则改文案不改布局:en、de、fr、ja 保留全称、缩短状态词;es、pt-BR、pt-PT 只放得下全称本身,标题只写名称,状态由下面的原因说明;法语那句换成更短的说法 | 同上 | `ui:check` 144 个变体(6 个码 × 12 种语言 × 深浅色)全过、无裁切警告;但 `ui:check` 查不出副标题 6 行上限造成的省略号截断,2026-11-19 另外用程序逐个量副标题的内容高度与可见高度:法语 `HOST_DATABASE_UNAVAILABLE` 深浅两色被截断(161/138 px,处置说明后来加了“重新打开 Cindy”和 `cindy-host status` 又被撑长),由下表“fit French Host startup guidance in six lines”修正后 0/144 截断;es、pt 标题只写名称这一点请审核方定 | +| fix(desktop): call the Host connection's other end "the Cindy background service" | **改主干已有文案**:客户端模式连接提示 `hostConnection.connecting`、`pairingHelp`、`desktopAuthHelp`,12 种语言统一成「Cindy 后台服务」(原来八种语言写 “Cindy Host” / “Host”,中文写「Cindy 后台」,部分语言的 connecting 只写 “Cindy”);desktopAuthHelp 写成“Cindy 后台服务的连接设置” | 只影响客户端模式与网页端(这组提示只在连着 Host 时出现) | 依据是用户 2026-11-18 的用词决定;只改值,不改 key;hostConnection 的其余 key 不指这个东西,未动;请审核方逐行审 | +| test(desktop): guard that no locale calls the Cindy background service "Host" | 新增 guard 测试 `renderer/i18n/__tests__/hostWordInCopy.guard.test.ts`(登记在 `scripts/test-workspaces.config.mjs` 的桌面 guard 名单):扫所有 locale 值里独立的 “Host”;另有含义的 78 处按 locale + key 冻结,按含义分组(SSH 远程主机、共享任务的发起电脑、代输入时被操作的电脑、作为插件宿主的 Cindy),只减不增,失效的项也报 | 无(只加测试) | 用户 2026-11-18 的规则:界面文字不出现 Host | +| test(desktop): note the lowercase "host" blind spot in the background-service wording guard | 只改上一行 guard 的头注:独立的小写 “host” 不匹配(英文里 SSH 的 host 太多,没法全扫),把后台服务写成小写 host 抓不到 | 无(只改注释) | 审核方 2026-11-18 要求写明已知盲区 | +| fix(desktop): remove the start-failure panel's Check Again button | 去掉原因面板的“重新检查”:LoginPage 的按钮与重读、AuthContext 的 `recheckHostUnavailable`、useLogin 的透传、authService 的 `readHostUnavailableReason`、preload 的 `authGetHostState` 与类型声明、12 种语言的 `login.hostUnavailable.checkAgain`,以及对应测试与 ui:check 场景;面板测试与 ui:check 改为确认面板上没有按钮 | 只影响客户端模式,且只在 Host 带启动失败标记时 | 审核方 2026-11-18:没有一种情况能成功(同一实例里原因不变,实例一换一律 409);网页端 shim 里对应的一行在集成分支另删。**桌面上观察不到**:被删的重读只服务带启动失败原因的面板,内嵌登录不经过这个调用点(`authManager.ts:497–502`)(2026-11-19 复查) | +| fix(desktop): end each start-failure remedy with reopening Cindy | 面板上每条“怎么办”都先让用户重新打开 Cindy(数据库不可用和通用启动失败两类,之后另给 `cindy-host status` 的排查说明;2026-11-19 复查补全),被单独运行的桌面占用那一句(`logic.errors.hostProfileInUseByDesktopAtStart`)写“重新打开当前这个 Cindy 窗口”,12 种语言;只改值,key 不变 | 同上 | 中文由审核方 2026-11-18 定稿,英文照意思写,其余语言跟随;依据是已开着的窗口在后台服务重启后不会自动重连 | +| test(desktop): pin which session update fields count as settings only | 只加测试:`sessionSettingsOnlyPatch` 的 15 个设置字段、3 个活动字段、混合补丁 | 无(只加测试) | 准备 PR 单独合进主干后,桌面侧有测试钉住这张表 | +| refactor(desktop): load the Skill projection boundary without Electron | `authBoundaryQuarantine.ts` 去掉 Electron:userData 改读 `getUserDataDir()`;被动实例判定改为启动时注入(`configureProjectionBoundaryPassive`,判定式原样、每次调用现求值);index.ts 加一行注入 | 普通桌面用户 | ① 主进程改 userData 的四处都在 index.ts:318 固定之前或同步还原:index.ts:51 区域目录、index.ts:193 开发覆盖、`versionStartup.ts` 的 applyProfile(三个调用点都在 index.ts:54 的 prepareCindyVersionStartup 里)、bootstrap-electron.ts 4382–4386 单实例锁的临时切换(同一同步块 try/finally 还原),所以之后 `getUserDataDir()` 与 `app.getPath('userData')` 每个时刻相等;② index.ts 静态导入使该模块及其依赖(crossProcessLock、atomicWriteFile、readBoundedFile、userDataPath、logger)提前到入口加载,它们只依赖 Node 内置模块,加载时只做惰性 createLogger 和几个空 Map,不读路径、不碰 Electron、不注册进程事件;③ guard 守住注入是唯一一处、在固定目录之后、在 dispatch 与 bootstrap 导入之前(审核方 2026-11-17 核过)。**桌面上观察不到**:桌面先应用版本与开发 profile 覆盖、固定最终路径,再动态加载生产读取方;单实例锁只在同一个同步 try/finally 里临时切路径;源码守护检查固定与注入的先后(`index.ts:55,194,319–325,351`、`authPassiveSharedInstance.test.ts:476–488`)(2026-11-19 复查) | +| feat(desktop): write one more field in the desktop startup registration: runtime | 桌面启动登记(`.dev-instances/.json`)多写 `runtime: 'client' \| 'embedded'`,`index.ts` 用 `desktopRuntimeKind(process.env)` 取值;`schemaVersion` 仍是 1 | 普通桌面用户:每次启动多写一个字段 | 并存方案 A。读这份登记的各方都按已知键读取,遇到不认识的字段不出错:`concurrentInstanceScan.ts` 的 `parseRegisteredInstanceCandidate`、`findConcurrentLiveInstancePids` 只取 PID、目录、时间和 checkout 根;`ownerNamespaceMigration.ts` 的 `hasConcurrentLiveInstanceSync` 复用同一解析;`devStartupStatus.ts` 只核对 `instanceId`,更新登记时从内存展开复制,`runtime` 随之保留;`worktree/runtimeLeases.ts` 的 `readWorktreeRuntimePaths` 只查 PID、租约协议和 PID 复用证据;脚本 `desktop-whoami.mjs`、`restart-desktop-remote.mjs`、`provider-e2e-profile.mjs`、`host-client-usage-tour.mjs` 逐键读取所需字段。只有后台服务的 `agent/profile-coexistence.ts` 解释这个字段:明确的 `client` 才放行,缺字段、未知值、不能解析或只见 SingletonLock 一律按会开库处理(2026-11-19 对账) | +| (已撤回)ci: raise desktop typecheck heap limit | 曾把 `apps/desktop` 的 typecheck 堆上限 12288 → 14336、ci.yml 那一步同值(`48ab494d69`)。2026-11-17 合 main 时发现主干已自行解决:`5703fd82a4`(#10332)把桌面类型检查按进程边界拆成 main / renderer 两片,各 10240;按审核方事先定的规则(主干自己调过就撤掉)以 `Revert "ci: raise desktop typecheck heap limit"` 撤回,`apps/desktop/package.json` 与 ci.yml 回到主干原样。准备 PR 里这一对提交互相抵消,不计入非搬移改动 | 无 | 撤回前的 Linux 实测仍作主干风险的背景:origin/main(拆分前)12288 下 3/3 通过,不限堆时堆约 12.3 GiB、最大常驻 12.45 GiB;本分支类型规模与主干几乎相同,12288 下两次取样 6 次里 1 次内存不足;14336 下 3/3 通过,最大常驻最高 12.84 GiB。主干 CI 自 2026-10-11 起这一步失败 9 次,全是类型错误,未见内存不足。拆分之后桌面类型检查按主干的脚本原样报 | +| refactor(desktop): compute the runtime refresh delay in authTokenClaims, so the Host can schedule with it | `scheduleRefresh` 里 exp 减 300 秒的算式原样移到 `authTokenClaims.ts` 的 `accessTokenRefreshDelayMs(token, nowMs)`,`scheduleRefresh` 传 `Date.now()` 调它;坏 JWT 照旧抛错、照旧不排 | 普通桌面用户:排期不变 | C ⑥:Host 用同一个函数排期;测试“给定 exp,下一次落在 exp 减 300 秒”。**桌面上观察不到**:取时比解析早一次 `JSON.parse` 的时间,量级是微秒,相当于这次调用早到几微秒;即使正好跨过阈值,一边是立即续期,另一边是延时不到一毫秒的定时器,结果都是马上续期(`authManager.ts:3132–3136`、`authTokenClaims.ts:32–35`)(2026-11-19 复查) | +| refactor(desktop): move the vault types and the refreshed-session commit rule into authRefreshCommit | 账号库类型与版本常量、`writeResourceSessionToVault`、`commitDesktopRefreshCredentials` 的账号库那一步(成为 `applyRefreshedCredentialsToVault`)原样移到 `authRefreshCommit.ts`;v1 与旧版令牌的读取改为端口,桌面照原样传 `readPersistedAuthSession` 与 `readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY)`(仍按原顺序、短路读);`accountVaultKey` 与 `metadataFromMembership` 换成 `@cindy/auth-client` 里逐字相同的两个;事务、锁、`validateBeforeWrite` 与写 v1 留在原处 | 普通桌面用户:续期写回不变 | C ④:Host 在同一把锁里按同一条规则写;读这些源码文字的测试改读新模块 | +| test(desktop): a login the Host renewed stays usable for a switch back and a cold start | 只加测试:`authColdStartRecovery.test.ts` 的复现改成回归(场景 1 经 `refreshSavedResourceSession`,场景 2 经冷启动),用 Host 生产的 `refreshHostSession`(非字面量路径动态导入,不进桌面类型检查) | 无(只加测试) | C:审核方要求把复现补丁改成回归测试 | +| test(desktop): an account signed in only on the Host is taken over by the desktop cold start | 只加测试:同一文件第三条,保管库里没有账号时冷启动经 `canClaimUninitializedVault` 认领 | 无(只加测试) | C 的补充(审核方 2026-11-17) | +| i18n(desktop): add the Host's start refusal while a desktop uses its profile | 12 种语言加 `logic.errors.hostProfileInUseByDesktopAtStart` | 无:桌面不读这个 key(Host 读;D 之后客户端模式的窗口也读) | 并存方案 A 的 H | +| feat(desktop): say why a Host refuses while a Cindy desktop app uses its data(D) | `host-ipc-proxy.ts` 409 带原因码时改抛带标记的 PRECONDITION_FAILED;`shared/ipcError.ts` 公共映射与 `makerChatStore.ts` 发送失败横幅认出标记;12 种语言加 `logic.errors.hostProfileInUseByDesktopRetry` | 只在消息开头带 `HOST_PROFILE_IN_USE_BY_DESKTOP` 标记、code 是 PRECONDITION_FAILED 时才不同,只有 Host 发得出这个标记;普通桌面用户看到的错误逐字不变(测试钉住多种现有错误文本,含 Electron 包装) | 并存方案 A 的 D,审核方 2026-11-17 定 | +| refactor(desktop): compute the runtime refresh delay in authTokenClaims, so the Host can schedule with it(C ⑥) | `authManager.ts` 的 `scheduleRefresh` 里算延迟的两行(解析 JWT payload、`(payload.exp - 300) * 1000 - Date.now()`)换成 `accessTokenRefreshDelayMs(token, Date.now())`;新函数在 `authTokenClaims.ts`,函数体就是原来那两行,只把 `Date.now()` 换成参数 `nowMs` | 普通桌面用户(行为不变:坏令牌照样抛错、被外层 catch 跳过不排;没有数字 exp 时照样得到 NaN、落到立即续期那一支) | C 第 ⑥ 步,Host 用同一个纯函数排期;审核方 2026-11-17 逐行审过 | +| refactor(desktop): move the vault types, its lock file name and the refreshed-session commit rule into authRefreshCommit(C ④) | 新文件 `authRefreshCommit.ts`:`AUTH_ACCOUNT_VAULT_LOCK_FILE`、`AUTH_ACCOUNT_VAULT_VERSION`(连同上方注释)、`StoredResourceSession`、`StoredPassportSession`、`AuthAccountVault`、`ActiveRefreshCredentialCommit`、`writeResourceSessionToVault` 原样移过去(加 export);`commitDesktopRefreshCredentials` 的 mutate 回调体移出成 `applyRefreshedCredentialsToVault(vault, input)`。替换点:`metadataFromMembership` → `@cindy/auth-client` 的 `storedAccountMetadataFromMembership`(十个字段逐一相同);`accountVaultKey` → auth-client 同名函数(两边都是 `JSON.stringify([realm, membershipId])`);`readPersistedAuthSession()` → 端口 `input.readStoredSession()`(桌面传 `readPersistedAuthSession`);`realm === AUTH_REGION && readSafe(LEGACY_RESOURCE_REFRESH_TOKEN_KEY)` → `realm === input.buildRegion && input.readLegacyResourceRefreshToken()`(桌面传 `AUTH_REGION` 与原读取,仍在 `\|\|` 里按原顺序短路);`options.allowUnclaimedVault` → `input.allowUnclaimedVault`。事务、锁、`validateBeforeWrite`、写 v1 都留在 `commitDesktopRefreshCredentials` | 普通桌面用户(行为不变) | C 第 ④ 步,Host 的写回用同一份保管库规则;审核方 2026-11-17 逐行审过。**桌面上观察不到**:仍先在同一事务内复核再读当前凭据,旧令牌仍只在前两项未命中且构建区相同时读;锁名和写 active session 的条件不变(`authRefreshCommit.ts:61–83,107–138`)(2026-11-19 复查) | +| test(desktop): give the owner-reservation test's userData mock the directory getter | 只改测试:`authCloudOwnerReservations.test.ts` 的 `../userDataPath.js` mock 多返回 `getUserDataDir: () => context.root`(与这个测试的 Electron mock 里 `app.getPath` 返回的同一个临时目录) | 无(只改测试,生产代码不动) | 不是我们的改动出了错:主干新加的这个测试(2026-11-17 合 main 带进来)只 mock 了 `userDataPath` 一个导出,又经 authManager 间接加载到边界模块,而准备分支的 25a(`refactor(desktop): load the Skill projection boundary without Electron`)让边界模块改用 `getUserDataDir()`,两者相撞。**准备 PR 合进主干时必须带上这条**,否则主干的这条测试会红。防同类:合 main 之后与发布前,在准备分支加跑“读改过的桌面源文件”的测试集合(文本搜索)和以全部改过的源文件为输入的 `vitest related`(审核方 2026-11-17 定为固定动作;发布前最后一轮必须在负载正常时跑完两轮) | +| refactor(desktop): move the message PR reference hooks into a shared module | 原样搬移,另有新建文件与 4 处调用替换,所以列在这里:新文件 `localDb/messagePrRefs.ts`(`pendingPrRefWrites`、`trackMessagePrRefs`、`reconcileCorrectedMessagePrRefs`、`reconcileUpdatedMessagePrRefs`,logger 用同名 scope `localDb/messages`);`localDb/ipc/messages.ts` 的替换点:import、`pendingPrRefWrites` 常量、`reconcileAssistantDerivedState` 里的重算段、`updateMessageContent` 无原行分支、`createMessage` 末尾的记录段,逐条见提交说明 | 不影响桌面:调用顺序、是否 await、条件判断都不变,两处 await 只多一层 async 函数;日志行逐字不变 | 甲 24:Host 调同一份代码。**桌面上观察不到**:多几个微任务接续,不新增让出点:两处原来就是 `await pendingPrRefWrites…; if (isCurrent()) await recompute…`,现在包进一个 async 函数再 await;`createMessage` 那处仍不等待(`messagePrRefs.ts:35–75`、`assistantFinalRetraction.test.ts:220,291,510`)(2026-11-19 复查) | +| refactor(desktop): move the task list activity write into a shared module | 原样搬移,另有新建文件与 1 处调用替换,所以列在这里:新文件 `localDb/sessionActivityWrite.ts`(`writeSessionListActivity`,`touchSessionActivityInDb` 里那条 update…returning 原样搬过去);`localDb/ipc/sessions.ts` 的替换点:import 一行,原来的 `const db = getDbClient().drizzle;` 与那条语句换成一次调用,逐条见提交说明 | 不影响桌面:结束写入压制、owner 范围、广播、catch 与 warn 都留在原处,`getDbClient()` 在同一处读,调用方不变 | 甲 10:Host 调同一份写入。**桌面上观察不到**:真实 DbClient 查询是自定义 thenable;新 helper 直接 return,由它的 Promise 吸收同一个 thenable 一次,SQL、owner 检查、广播和错误仍在同样的续接上(`sessionActivityWrite.ts:12–31`、`sessionsUpdate.test.ts:1249–1265`)(2026-11-19 复查) | +| refactor(desktop): move the silent-stop settle into a shared module | 原样搬移,另有新建文件与替换点,所以列在这里:新文件 `maker-ipc/silentStopSettle.ts`(`settleSilentStopDoneWithPorts`,`register.ts` 的 `settleSilentStopDone` 函数体 35 行逐字搬过去,端口在参数里按原名解构,函数体不改一行);`register.ts` 的替换点:`settleSilentStopDone` 上方的注释改短了(原注释搬进 `silentStopSettle.ts`;提交说明里写的“doc comment moves with it”不准确,不改写历史),`settleSilentStopDone` 改成调用它并传本文件的追踪器、闸门、租约、`finalizeTurnChangeSet` 等与五个 holder(每次调用时读,与原来相同),import 一行;`silentStopAutoResume.ts` 新增常量 `SILENT_STOP_DECISION_DELAY_MS = 1_500`,`sessionEventPreparation.ts` 的决策定时器用它代替字面量 `1_500`,逐条见提交说明 | 不影响桌面:调用方、顺序与读到的 holder 都不变 | 8g B:Host 走同一份结算。**桌面上观察不到**:同样的值、同一个定时器;wrapper 仍 await 结算主体,传原 holder 和事件代次(`silentStopSettle.ts:41–85`、`register.ts:5787–5793`)(2026-11-19 复查) | +| refactor(desktop): type the model change's object ports as the members their bodies call | 把供应商列表、路线确认与队列端口的形状缩到实际使用的成员。 | 影响编译时的桌面与 Host 装配,桌面仍传原对象,JS 和调用顺序相同。 | 四份生产 TS 文件的端口类型从整对象改为 `Pick`,例如 `AgentInputCoordinator` → `Pick`。(2026-11-19 对账补登) | +| refactor(desktop): move the effort and thinking handlers' bodies verbatim out of register.ts | 抽出推理档位与思考开关处理,让待切凭据 holder 经同步 getter 读取。 | 桌面仍在相同位置校验可信窗口和读取 holder,Host 可从自己的装配传入它。 | `sessionRuntimeAxisSettings.ts` 的 effort 分支把 `pendingCredentialSwitchHolder?.has(sessionId)` 改为 `getPendingCredentialSwitchHolder()?.has(sessionId)`。(2026-11-19 对账补登)。**桌面上观察不到**:在原判断位置同步调用闭包,闭包只读装配赋值的同一个变量;每次请求仍取当时的 holder,校验和原等待点的顺序不变(`register.ts:4652,19819,21966–21974`、`sessionRuntimeAxisSettings.ts:334`)(2026-11-19 复查) | +| refactor(desktop): move the Fast mode handler's body verbatim out of register.ts | 抽出 Fast 入口并显式绑定凭据 holder 和供应商查询。 | 桌面 Fast 的判断值与读取时点沿用原装配,Host 可绑定同一处理。 | `createSetSessionFastMode` 同样将 `pendingCredentialSwitchHolder?.has` 改为 `getPendingCredentialSwitchHolder()?.has`,并接入 Fast 策略与目录端口。(2026-11-19 对账补登)。**桌面上观察不到**:在原 handler 的同步读取点调用同一变量的闭包,没有在工厂创建时捕获旧值(`register.ts:19819,21975–21980`、`sessionRuntimeAxisSettings.ts:585`)(2026-11-19 复查) | +| refactor(desktop): move the terminal error signals out of prepareSessionEvent | 把终态错误的有界字段读取抽给 Host,并前移错误消息和信号构造。 | 共享事件预处理与桌面错误路径受影响,报给协调器的字段和裁剪规则沿用原值。 | `prepareSessionEvent` 现在先算 `terminalErrorMessage` 与 `terminalErrorSignals`,原来这两个表达式只在真正上报错误时求值。(2026-11-19 对账补登)。**桌面上观察不到**:提前的只是对事件对象的属性读取和类型判断,没有副作用、不会抛错,结果仍只在上报错误时使用(`sessionEventPreparation.ts:402–430`、`terminalTurnErrorSignals.ts:12–62`)(2026-11-19 复查) | +| refactor(desktop): assemble the auto-resume runtime in a factory | 把两套续跑守卫和未派发收口装入可接线的工厂。 | Host 可复用守卫,桌面仍读原开关、`=== true` 判据和恢复端口,初始化顺序有实际位移。 | `autoResumeRuntime.ts` 使用 `ports.restoreAutoResumeRecovery(...)` 与 `ports.finishScheduledUsageLimitWait(...)`,构造位置移到供应商组恢复装配之后。(2026-11-19 对账补登)。**桌面上观察不到**:后移区间里没有读取这三项的模块顶层语句;中间的配额回调注册只写监听集合,供应商组工厂只建状态和闭包,都不执行注入回调;恢复是否成功仍由桌面端口的 `=== true` 判定(`register.ts:2013,2118–2128,2175–2243,2272–2280`、`autoResumeRuntime.test.ts:58`)(2026-11-19 复查)。主干同步 5 之后在 `5a92f62d24` 上复核:后移区间仍没有读取这三项的代码,原开关与 `=== true` 判据不变,主干新增的模型组装配在更晚的 `registerMakerIpc` 内 | +| refactor(desktop): move the local route admission into a shared factory | 把本机路线准入改成可绑定工作目录和供应商查询的共享工厂。 | 桌面仍绑定原 Electron 路径和 provider listing,Host 能在自己的装配执行准入。 | `localRouteAdmission.ts` 将 `app.getPath('userData')` 换成 `getUserDataDir()`,独占供应商钉选也改由 provider-listing 函数注入。(2026-11-19 对账补登)。**桌面上观察不到**:多几个微任务接续,不新增让出点:原入口 `pinExclusiveSessionProvider` 本来就是 async 并 await 供应商列表(父提交 `model-route-guard-live.ts:135–147`),这里只多一层 Promise 转发,没有把同步路径变成异步;之后照常复核账号与任务准入(2026-11-19 复查) | +| refactor(desktop): move the outbound proxy resolver into a shared core | 为出站代理解析新增 app readiness 和当前代理会话端口。 | 桌面仍实时查询原 Electron 对象,Host 可绑定自己的解析实现。 | `outboundProxyResolverCore.ts` 中 `app.isReady()`、`session.defaultSession` 分别换成 `ports.isAppReady()`、`ports.getProxySession()`。(2026-11-19 对账补登)。**桌面上观察不到**:桌面只构造一份 resolver 和一套缓存;两个 getter 在原读取位置同步运行,先查 ready 再取默认会话,缓存、限时和回退仍在原边界(`outbound-proxy-resolver.ts:23–31`、`outboundProxyResolverCore.ts:178–181,256–277`)(2026-11-19 复查) | +| refactor(desktop): session_search core without Electron | 抽出不依赖 Electron 的任务搜索与深链构造,并注入设备 ID 读取。 | 桌面搜索仍传原设备 ID,Host 能构造同一类型的结果和链接。 | `sessionSearchCore.ts` 把 `getDeviceId()` 改为 `scopeOptions.readDeviceId()`,`sessionDeepLink.ts` 改从共享 URL 前缀组装链接。(2026-11-19 对账补登)。**桌面上观察不到**:多几个微任务接续,不新增让出点:原入口 `searchSessionsWithBotScope` 本来就是 async 并等待搜索范围与 SQLite 查询(父提交 `session-search.ts:45–69,110–118`),这里只多一层转发;设备号读取时机不变,之后照常复核(2026-11-19 复查)。主干同步 6(`3ef44274d6`)之后复核:主干 `252ae0897a` 把 `buildSessionDeepLink` 的函数体改成共用的 `buildTaskDeepLink`(同时对 `.!'()*` 做百分号编码),合并时把这一改动带进搬走的 `sessionDeepLink.ts`,函数体与主干逐句相同;`deepLink.ts` 仍只再导出,见第五节“改到主干已有代码的地方” | +| refactor(desktop): the local history view reader as a shared factory | 让消息历史读取可分别绑定导入副作用、图片恢复和 Device Link 作用域。 | 桌面绑定原来的导入和图片恢复;Host 可选择不同绑定,缺端口时的路径有新语义。 | `localHistoryViewReader.ts` 新增 `ports.importBeforeList?.(...)` 以及未提供 `restoreTaskImages` 时直接用原行的分支。(2026-11-19 对账补登)。**桌面上观察不到**:所有桌面入口都提供导入和图片恢复两个端口,“未绑定”分支在桌面上走不到;首页导入、后续分页不导入和历史页图片恢复由桌面消息入口的测试钉住(`messages.ts:281–285,293–299`、`messagesListImportSideEffects.test.ts:130,149,160`、`messagesListCursor.test.ts:591`)(2026-11-19 复查) | +| refactor(desktop): move the settings-only check and the send's recent project record to Electron-free modules | 共享只改设置的字段检查和发送成功后的最近项目记录。 | 桌面和 Host 用同一字段及项目写入条件,桌面非项目发送现也跨过一次 async 调用。 | 字段集合和判断仍在函数内部;`touchUserSendInDb` 新用了无条件 `await recordRecentWorkdirForSend(...)`,以前仅通过项目筛选才等待。(2026-11-19 对账补登)。**桌面上观察不到**:`await recordRecentWorkdirForSend` 是 `touchUserSendInDb` 的最后一条语句,之后没有别的语句;非项目发送只是让调用方的后续晚几个微任务,函数内副作用顺序不变(`sessions.ts:893–933`、`sessionsUpdate.test.ts:1275,1351`)(2026-11-19 复查)。主干同步 4(`df520e3564`)之后,发送与移动注入的写入器改为只刷新已登记项目的 `touchRecentWorkdir`,见下一节 | +| refactor(desktop): move the Pi selection and local version choice into Electron-free modules | 把 Pi 选择和版本扫描拆进无 Electron 的模块,保留二进制验证。 | 桌面和 Host 都可复用,桌面扫描少了重复的递归 mkdir。 | `listVerifiedBinaries` 改为一次 `installRoot()` 后 `path.join` 两条路径,Pi reader 把 `this.deps.root/probe` 改为显式参数。(2026-11-19 对账补登)。**桌面上观察不到**:多几个微任务接续,不新增让出点:`findPreferredLocalBinary` 本来就是 async;少几次 mkdir 只在扫描中安装根目录被外部删掉时有差别:旧代码多重建一次空目录,两种写法都读不到候选,扫描结果相同(`local-version-selection.ts:24–43`、`pi-kernel-manager.test.ts:111–121`)(2026-11-19 复查) | +| refactor(desktop): start a runtime on its accepted override through a shared step | 共享已接受的 runtime override,供应商组的决定仍来自调用者。 | 桌面与 Host 的懒启动走相同覆盖规则,桌面无 override 时也读无副作用的供应商组条件。 | `register.ts` 的 `groupDecidesSource` 从 override 存在的分支内部移到 `applySessionRuntimeOverrideForStart` 调用前,每次先求值。(2026-11-19 对账补登)。**桌面上观察不到**:`groupDecidesSource` 的来源只可能是 null 或供应商组构造的普通对象,提前求值只读普通属性,没有 getter、I/O 或可抛点;结果仍只在 override 生效时使用(`register.ts:8734–8765`、`provider-group/service.ts:877–880`)(2026-11-19 复查) | +| refactor(desktop): move the concurrent live-instance scan out of ownerNamespaceMigration.ts | 拆出登记扫描与陈旧 PID 证明,并缩窄所需依赖。 | 桌面同步与异步扫描仍共享一份证明缓存,Host 在自己的进程使用同一算法。 | `findConcurrentLiveInstancePids` 的签名改用 `ConcurrentInstanceScanDeps`,原模块 logger 留存,新模块又构造同 scope 的 logger。(2026-11-19 对账补登)。**桌面上观察不到**:`createLogger` 只构造函数对象,不登记实例、不改全局日志级别;两个扫描入口仍共享陈旧 PID 缓存(`concurrentInstanceScan.ts:43`、`logger.ts:943–952`、`ownerNamespaceMigration.test.ts:3260`)(2026-11-19 复查) | +| i18n(desktop): add the Host's refusal while a desktop uses its profile | 增加运行期间共享 profile 被桌面占用的拒绝文案。 | 供连接 Host 的发送失败提示使用,常规内嵌发送不产生这个 Host 标记。 | 12 份 locale 新增 `logic.errors.hostProfileInUseByDesktop`,不是已有字符串搬移。(2026-11-19 对账补登) | +| refactor(desktop): share the task read runtime projector | 把任务读取投影和运行时插件选中判定分成共用主体与平台端口。 | 桌面仍读取自己的插件设置,Host 可以注入其运行时装配。 | 投影里的 `!!readRuntimePluginSettings(session.id)` 改为 `ports.runtimePluginsSelected(session.id)`。(2026-11-19 对账补登)。**桌面上观察不到**:mapper 在原位置收到同一 projector,最后才按任务 ID 同步读设置并转布尔,工厂创建时不读设置(`register.ts:6527–6531`、`sessionRuntimeProjection.ts:107–124`)(2026-11-19 复查) | +| refactor(desktop): share the archive and delete runtime cleanup | 将归档、删除后的运行时清理拆成工厂并注入工作目录恢复端口。 | 桌面仍清同一份恢复状态后推投影,Host 可使用自身的清理回调。 | 旧 `workingDirectoryRecovery.discard(sessionId)` 在共用清理中变成 `ports.discardWorkingDirectoryRecovery(sessionId)`。(2026-11-19 对账补登)。**桌面上观察不到**:回调保留 `workingDirectoryRecovery` 作接收者,在原位置同步执行,取消、清理、广播的顺序不变(`register.ts:6532–6538`、`sessionRuntimeProjection.ts:142–158`)(2026-11-19 复查) | +| refactor(desktop): move the shared global Skill preparation into a shared core | 将全局 Skill 准备的缓存、持久告警与路径读取抽成共享装配。 | 桌面继续每个 adapter 用一套缓存和原目录,Host 可装配自己的目录。 | `sharedGlobalSkillsPreparationCore.ts` 的缓存从类字段改为工厂闭包,`app.getPath(...)` 以及 preparation scope 改经端口。(2026-11-19 对账补登)。**桌面上观察不到**:多几个微任务接续,不新增让出点:原来的 `ensure` 里本来就有多次磁盘读写的 await,外层再 await 一层;之后的 `account.assertCurrent()` 照常复核(`auth-adapters.ts:465–474,569–581`)(2026-11-19 复查) | +| fix(desktop): shorten the German remedy for data that cannot be opened | 缩短德国用户看到的「数据打不开」处置句,保留原处置步骤。 | 仅影响德语客户端显示该启动失败原因时的文案。 | 只替换 `de/common.json` 的 `login.hostUnavailable.HOST_DATABASE_UNAVAILABLE.action` 德文值。(2026-11-19 对账补登) | +| refactor(desktop): share generated-image storage and delivery with the Node Host | 把生成图字节、存储及交付分层,给交付新增存储、写消息、广播、媒体引用和翻译的宿主绑定。 | 桌面 `.desktop.ts` 仍绑定原功能,Host 可用自己的 IO,不增加原桌面交付主体里的许可或重试分支。 | 保留原生成图交付主体的同时,`generatedImageDelivery.ts` 增 `GeneratedImageDeliveryPlatform` 六端口,存储的范围类型从 `ReturnType` 改为 `GeneratedImageStorageScope`。(2026-11-19 对账补登)。**桌面上观察不到**:所有端口都是直接转发,不是 async 中转;仍在同一次交付调用取 owner 存储快照,原处写消息、关联媒体并广播;测试导入桌面 wrapper(`generatedImageDelivery.desktop.ts:11–25`、`generatedImageDelivery.test.ts:18,463,543`)(2026-11-19 复查) | +| refactor(desktop): move three event-preparation steps where the Node Host can call them | 将独立文本、Opus 计划错误和交互撤回重写为可单独调用的事件准备步骤。 | 桌面在对应分支复用同样的过滤顺序和交互收尾,Host 可针对自己的路径使用函数。 | `routeStandaloneTextEvent` 将静默预判改成 `return true` 供调用点短路,Opus 错误 helper 返回变更的数据或 `null`。(2026-11-19 对账补登)。**桌面上观察不到**:三处仍在原位置同步处理并短路;Opus 路径的日志在同一次同步执行里字段相同(`sessionEventPreparationSteps.ts:97–190`、`sessionEventPipeline.test.ts:705,785`)(2026-11-19 复查) | +| refactor(desktop): move the usage write and broadcast modules into Electron-free cores (3b) | 将用量写入与广播拆成无 Electron 的 core,桌面通过 wrapper 在调用时绑定。 | 桌面使用原窗口、账本及写队列,Host 可选用自己的端口,未装配路径有独立默认。 | `usageBroadcastPorts.ts` 新增可配置端口,默认窗口为空、未绑定的持久化端口返回拒绝。(2026-11-19 对账补登)。**桌面上观察不到**:桌面四个 wrapper 在模块求值时同步绑定端口,再导出入口,“未绑定”在桌面上走不到;`usageCorePortWiring.guard.test.ts` 检查端口全覆盖和加载期不调用端口(`usageBroadcastPorts.ts:46–59`、`usageCorePortWiring.guard.test.ts:254–333`)(2026-11-19 复查) | +| refactor(desktop): move the turn usage recorders into Electron-free cores (3c) | 共享四类引擎回合用量及上下文记账装配。 | 桌面 wrapper 继续委托原报价、订阅刷新和写回,Host 可绑定到自己的账号数据库,未绑定时明确失败。 | `turnUsagePorts.ts` 引入端口表与 `if (!bound) throw new Error(...)`,用量模型键移到 `usageModelKeys.ts`。(2026-11-19 对账补登)。**桌面上观察不到**:桌面 wrapper 同步绑定端口,未绑定抛错在桌面上走不到;与 3b 同一守护钉住(`turnUsagePorts.ts:59–66`、`usageCorePortWiring.guard.test.ts:44–94`)(2026-11-19 复查) | +| refactor(desktop): share plugin control and subscription delivery | 拆出可由桌面和 Host 各自绑定的订阅网关、控制点和工具批准服务。 | 桌面绑定原列表、实例查找和模型来源,Host 可注入自己的投递与权限数据,插件基座的装配和导出形态有变化。 | `cindy-brain/index.ts` 的函数导出改为工厂返回值解构,`dropGhost` 经工厂闭包,工具批准的路线检查改读 `ports.modelRouteSources()`。(2026-11-19 对账补登)。**桌面上观察不到**:11 个导出及内部 `dropGhost` 的生产读取点都在这些模块顶层初始化之后;工厂构造只保存回调,网关在首次请求时才建(`runtimePluginHostCore.ts:43–85`、`cindy-brain/index.ts:2940–2951`)(2026-11-19 复查) | +| refactor(desktop): share task runtime plugin bindings | 共享任务插件提示词、回合准备、设置、消息拦截与通知入口。 | 桌面继续传原窗口校验和回滚函数,Host 可绑定自身准入;可选准入在 `fb9a335a43` 随后变为必填。 | 设置处理从直接 `assertTrustedAppRendererEvent(event ...)` 改为共享工厂内 `assertCaller?.(caller)`,桌面以闭包传原校验。(2026-11-19 对账补登)。**桌面上观察不到**:桌面传同一个同步可信窗口断言,仍在 handler 第一条执行;回合准备保持同步壳(`runtimePluginTaskBindings.ts:73–97,114–132`)(2026-11-19 复查) | + +**对账(2026-11-19,准备分支 `43a545067c` 对主干 `af8bd193a3`;之后又加两个提交,见下)**:95 个非合并提交里,进表 51 条、原样搬移 24 条、只改测试、文档或验证配置 20 条,相加等于 95;另有 16 个合并提交,只含冲突解决。上表按提交标题列:C ④、C ⑥ 与 D 的带后缀行和同名行指同一个提交;`Revert "ci: raise desktop typecheck heap limit"` 和被它撤回的提交都在范围内,各计一次“只改验证配置”,最终无差异;只改测试或注释的四行(“guard that no locale calls…”、“note the lowercase…”、“pin which session update fields…”、“give the owner-reservation test's userData mock…”)计入后一类,留在表里是为了合并时的提醒。“a login the Host renewed…”、“an account signed in only on the Host…”两行的提交在集成分支,不在准备 PR 的范围内。原样搬移的判定:搬出的主体去掉外层缩进、import、export、函数壳和原调用点的绑定后逐行相同,原依赖以同名参数重新绑定。准备分支其后到 `97af5ce056`,多两个非合并提交:“preserve upstream interrupted retry pause behavior”进表,“assert the exact auth state shape and place the 25a note on its case”只改测试;合计 97 条 = 进表 52 + 原样搬移 24 + 只改测试、文档或验证配置 21。主干同步 4(`9354a65d1a`)之后到 `c09ea9369c`,再多一条进表的“defer recent project port reads until use”:合计 98 = 53 + 24 + 21。之后再多一条进表的“fit French Host startup guidance in six lines”:合计 99 = 54 + 24 + 21。**时序与装配差异的写法**(审核方 2026-11-19 定):原来就是一次带真实读写的异步等待、只在它完成后多几个微任务接续、没有新增让出点的,写“多几个微任务接续,不新增让出点”,理由是能插进新间隙的只有外部事件(切账号、清空),它们与这次读写何时完成本来互不相干,等待之后的代码也都重新核对;把原来同步走完的路径变成异步的,要逐条证明或改回去,目前没有这一类。上表 33 行各写了“桌面上观察不到”的理由与证据位置。 + +### 8i 的桌面搬移对照 + +| 原位置 | 共用位置 | 桌面绑定 | +|---|---|---| +| `maker-ipc/register.ts` 的 `setSessionRuntime` | `maker-ipc/sessionControlRuntimeWriter.ts` | 同一处绑定原闭包依赖,`applySessionRuntimeSelection` 保留调用时取值。回调内的 133 行去除外层缩进后逐行相同 | +| `cindy-brain/index.ts` 的订阅网关、运行时控制点、提示、上下文、记忆及逐次工具确认解析 | `cindy-brain/runtimePluginHostCore.ts` | 桌面仍使用原投递函数、实例解析和所有者检查。桌面的模型目录读者在 `runtimePluginHost.desktop.ts` 绑定,远端位置和远端目录仍在调用时读取 | +| `maker-ipc/register.ts` 的任务提示组装、回合准备、运行时插件设置、用户消息拦截和通知 | `maker-ipc/runtimePluginTaskBindings.ts` | 保留原写入主体、桌面窗口校验和 Agent Island 回滚。回合准备仍使用原拒发回执和 Promise 顺序 | + +### 改到主干已有代码的地方(发准备 PR 时搬进正文) + +**主干同步 6:任务深链改用共用构造(`252ae0897a`,2026-11-19)**:主干把 `deepLink.ts` 里 `buildSessionDeepLink` 的函数体改成 `return buildTaskDeepLink(sessionId, opts?.deviceId)`,新的构造在 `@cindy/maker-shared/brand-identity`,编码比原来严。准备分支早先已把这个函数原样搬进不依赖 Electron 的 `sessionDeepLink.ts`,`deepLink.ts` 只再导出它,所以合并时这里有一处冲突。解法:`deepLink.ts` 保留再导出,去掉主干加的、此后不再使用的导入;`sessionDeepLink.ts` 那边没有文本冲突,但同样改成主干的新写法(从 `deepLinkSchemes` 导入 `buildTaskDeepLink`),否则搬走的那份会留在旧编码上。桌面和后台服务构造的任务链接都与主干一致。 + +**主干同步 4:最近项目只刷新已登记项目(`df520e3564`,2026-11-19)**:主干把发送和移动任务后的最近项目写入从 upsert 改成只刷新已登记的项目(`touchRecentWorkdir`)。准备分支已把这两段搬进共用 helper(`touchUserSendRecentWorkdir.ts`、`sessionWorkingDirMove.ts`),合并时保留 helper 调用,在新位置注入主干的只刷新写入器;桌面仍只在同账号且更新到项目时广播,不会把未登记或已移除的目录重新加入。读取时机见非搬移表“defer recent project port reads until use”。 + +**插件网关的 Host 静默信号(2026-11-19)**:主干已有的 `subscriptionGateway.ts` 会把明确投递失败记入熔断。原生工具钩子熔断后后续调用会直接放行(主干的原生工具生命周期与失效处理 `7fd9033a4d`、`4cebb221ac`)。Host 因桌面占用有意关页时,仍按任务的失败策略处理控制节点,消息钩子沿用既有放行。静默不计失败,已有熔断保留。桌面装配不传信号,投递、超时、错误路径和等待顺序保持原样。这一提交属于插件基座,走白名单确认。 + +**Host PR 正文(2026-11-19)**:主干 `c9e1fcd68e` 在 Host 上用固定 Claude 默认路线做记忆自审,未读用户的辅助模型设置和停用开关。Host 接桌面已有辅助模型链及两层停用判断;占用时不派发,已有请求的收据仍记到发起账号。桌面包装保留原默认端口和执行顺序。 + +主干 `c7b3c8511d` 的 `writeRuntimePluginSettings` 通过跨进程锁更新任务的插件设置。Host 等锁期间桌面可能开始占用 profile。写入方现在可以在锁内、计算补丁前同步复核这次准入。复核抛错时文件字节保持原样,原来的拒绝和释锁路径允许随后再次写入。桌面由 `maker-ipc/register.ts` 注册 `maker:runtime-plugins`,唯一的生产写入调用在 `maker-ipc/runtimePluginTaskBindings.ts` 的共用处理函数,只传任务和设置。桌面执行顺序及等待点保持原样。 + +Host PR 修改主干已有的 `scripts/check-test-hygiene.mjs`,文件 URL 的 `.pathname` 规则只扫描 `apps/host/` 下的测试、夹具和脚本。文件 URL 转为本地路径须使用 `fileURLToPath`,HTTP URL 仍可读取 `.pathname`。hygiene 基线没有增加。 + +**Host PR 正文**:主干已有的 `apps/host/scripts/lifecycle.e2e.mjs` 在自有 Ubuntu 上耗时 37.4 秒,集成耗时 39.0 秒,主干 CI 不跑这个脚本。五段断言保持原样,跨平台总期限从 30 秒改为 90 秒,高于最慢实测值的两倍;结束时逐段报告耗时。集成 CI 保留 Ubuntu 和 macOS 步骤,Windows 显式跳过、列为未验证。PR 首轮若 Ubuntu 超过 60 秒,提交实际分段耗时复评。匿名源码启动加载的仓库模块由 3,351 个增至 3,470 个,单次启动约多 0.7 秒;五段合计约多 1.6 秒,登记为源码模式的已知变化。 + +主干 `8bcdaae10b` 在 `interruptedTurnAutoResumeHooks.ts` 的备用路线选择前后新增了暂停检查。后台服务在等待桌面释放数据或写队列时会暂停执行。自动续跑恰在此时到期,回调提前返回,已被续跑接管的中断便没有写进任务历史。 + +这两个检查点现共用同一段判断。已过期的尝试直接结束。仍是当前尝试而执行暂停时,先释放续跑守卫,再把中断写入历史一次,不弹横幅;暂停期间不会启动备用路线。短暂的队列写入如果碰巧赶上到期,会失去本次自动续跑机会,中断记录保留,写完后不重新排期。 + +桌面也有执行暂停的入口:`sessionExecutionActions.ts` 的 `runSessionExecutionAction`(Agent 和插件的任务运行控制)会调 `setExecutionPaused`。所以“暂停时把中断写进历史”只在后台服务启用:共用回调的 `settlePausedResumeIntoHistory` 由后台服务的 `agent/auto-resume.ts` 传,桌面不传,不传时与主干逐句一致,暂停期间到点直接返回(2026-11-19 更正,原文说桌面从不设暂停,不成立)。后台服务另外在 `agent/input-queue.mjs` 用这个接口实现桌面占用闸门和临时写入。桌面测试钉住不传时的主干行为;后台服务从队列和聊天入口覆盖永久闸门与临时写入。 + +主干的 `pendingCredentialSwitch.ts` 会在终态、关闭和十秒定时器里落定凭据,其中 Pi 事务来自 `b7cb47b56c`。后台服务可能在异步查目录时遇到桌面占用。原实现会写任务路线、清待办并通知客户端;同值更新也会触碰共享库。 + +共用服务增加可选的同步结算许可。后台服务在最后一次写入前复核,取得许可后在同一轮同步更新 SQLite 和内存来源;解闸重新核对账号、路线和待办代次。过期选择不回滚,保留桌面刚写的路线。Pi 沿用 `apply-failed`,非 Pi 只记日志。后台服务通过可选端口取得每一代运行时结算的原始 Promise,在自己一侧处理拒绝并等待各代完成。没有占用且账号仍有效时,终态在结算尝试结束后通知重启服务与其他任务,即使待办仍在或结算出错也照常通知。解闸时逐个处理任务,一个任务出错不会挡住后续任务。 + +桌面沿用 void 入口。桌面调用的五条凭据路径已逐项对照调用顺序与微任务时点。运行时控制的历史或广播上报抛错时,每次经原来的进程监听记录一条 fatal 日志,代次前进也如此。 + +### Windows 上未覆盖的测试 + +自有 Windows x64 机器上的 `chmod(0)` 无法制造 POSIX 的目录访问拒绝。以下两项故障路径由自有 macOS 或 Ubuntu 机器运行 `apps/host/src/boundary.test.mjs` 覆盖。 + +| Windows 上跳过的故障注入 | 验证的行为 | Windows 保留的覆盖 | +| --- | --- | --- | +| `a failed sweep rolls back the switch` 子测试 | 清理旧账号的 Skill 链接受阻时,切换保持 pending,登录凭据回滚 | 同一父用例仍验证登录、切换账号、清理两个位置的旧链接与新 owner 发布。 | +| `a login whose commit failed releases every lock, and the next login goes straight through` | 登录提交失败后,心跳停止,三把锁都释放,下一次登录能完成 | 该用例依赖 POSIX 目录权限,Windows 未覆盖这条完整故障路径。 | + +自有 Windows x64 机器上的 Host 全量还包含下列既有跳过项。浏览器夹具取决于本次可用的产物。 + +| 测试文件 | 未覆盖的场景 | 原因 | +| --- | --- | --- | +| `agent/diagnostics.test.mjs` | 退出时仅回收自己登记的 app-server 下的工具进程树 | 这条进程树验收只在 POSIX 启用。 | +| `agent/engine-deps.test.mjs` | Pi 使用指定版本、指定版本不可用、没有指定时选最高版本;Claude Code 和 Codex 选版本;无效 Pi 不报告就绪(5 项) | 假引擎为 shell 脚本。 | +| `agent/profile-coexistence.test.mjs` | 仅从 SingletonLock 得到的 PID 阻止并存 | 夹具以 POSIX 符号链接表达 Chromium 锁。 | +| `agent/learn-capture.test.mjs` | Codex 通过自身 Skill 列表看不到 learn | 假 Codex 是脚本,传输层直接启动可执行文件。 | +| `agent/pi-subagent-runner.test.mjs` | terminate、Host shutdown、忽略 SIGTERM、Host 被杀及清理卡住(5 项) | 假 Pi 是脚本,Windows 也无法发送可由子进程忽略的 POSIX SIGTERM。 | +| `test-support/hook-plugin-fixture.test.mjs` | 插件响应 hook、停止后不接收请求且浏览器退出 | 缺少可供插件沙箱启动的 Chromium 时跳过。 | +| `plugins/profile-pause.test.mjs` 的真实页面用例(2026-11-19) | 插件静默、恢复及浏览器分区内的页面与 Node 行为 | CI workflow 未设置 `CINDY_TEST_CHROMIUM`,也没有安装这层用到的浏览器。真实页面用例只在自有机器上验证,CI 运行协议替身用例。2026-11-19 发布前最后一轮在自有 macOS 机器上两版 Node 各 6/6;浏览器自身沙箱不能套在外层隔离里,这组用例要在不加外层隔离的环境里跑。主干同步 3 之后在集成分支 `868941897a` 上再跑一次,6/6、0 跳过。 | +| `scripts/lifecycle.e2e.mjs`(全量之外) | 管理启动、附着与停止后台 Host | Windows 上最后一次 stop 的既有 ECONNREFUSED 缺口仍在,CI 只在 macOS、Ubuntu 运行该脚本。 | ## 六、M2 可接(状态已在 Host 上具备,只差通道) | 通道 | 状态来源 | 具备于 | |---|---|---| -| `maker:session-background-activity`、`maker:session-background-activity:list`、推送 `maker:session-background-activity-changed` | `claude-session-background-activity.ts`,由回环代理的请求与响应观察写入,任务关闭时清 | 24a | +| `maker:session-background-activity`、`maker:session-background-activity:list`、推送 `maker:session-background-activity-changed` | `claude-session-background-activity.ts`,由回环代理的请求与响应观察写入,回合起止由 Host 的事件流写入(第一批检查点 1),任务关闭时清 | 24a;回合起止:第一批检查点 1 | | `maker:claude-session-route:get`、推送 `maker:claude-session-route-changed` | `claude-session-route-registry.ts`,由回环代理的路由决策写入 | 24a | | `process-monitor:subscribe`、`process-monitor:unsubscribe`(现归 C 类窗口本地,窗口进程只看得到自己的子进程;接 Host 的登记时要重新归类) | `process-monitor/codex-process-registry.ts`,由三个引擎的进程登记写入,进程结束时清 | m1-cp17b | +| device-link 推送 `HISTORY_WORK_PATCH_CHANNEL`(运行中工作行的增量) | `device-link/historyViewPush.ts` 的 `buildHistoryWorkPatch`,读共用历史读取器的工作页(桌面经 `setHistoryWorkPageReader` 装,`localDb/ipc/messages.ts`);Host 不装时控制端拿到 `{ kind: refresh }`、整页重读 | 历史读取器共用(第七节第 27 项) | +| 推送 `local-db:sessions:patched` 的 `lastTurnEndedAt` | `localDb/sessionActiveTurn.ts`,回合结束写库后经 `setOnSessionTurnEndedPersisted` 通知(桌面装成 `broadcastSessionPatched`);Host 的事件流照常写回合标记,只是不推 | 回合起止:第一批检查点 1 | +| 推送 `maker:provider:upstream-error` | `maker-host/provider-upstream-error-observer.ts` 的 `reportProviderUpstreamError`,由 Codex 回环代理(`maker-host/codex-proxy-host.ts`)写入(桌面经 `setProviderUpstreamErrorBroadcaster` 广播到窗口);Host 不装时广播是空操作 | Host 的 Codex 回环代理(`agent/codex-runtime.ts`) | +| 推送 `git-context:pr-refs-changed`;读写 `git-context:pr-refs:list`、`git-context:pr-refs:list-all`、`git-context:pr-refs:manage`(乙 13) | `git-context/prRefsStore.ts`(`session_pr_refs` 表),有变化时经 `setPrRefsChangedListener` 通知(桌面装成广播给所有窗口,`git-context/ipc.ts`);Host 不装时通知是空操作。`manage` 加 PR 时要经 GitHub 核实,随 `setGithubReadRuntime`(第 22 行) | 甲 24:写消息时提取,改正、撤回、清除恢复与 MCP App 卡片更新后重算 | + +## 七、Host 重写的逻辑 + +目标是让 Host 自己写的那层越来越薄。这里列出 Host 重写了桌面已有判断的地方。只接端口、用共用主体的不算;HTTP 服务、IPC 路由、登录命令行等 Host 平台自己的部分也不算。每项的状态是三选一:已改为共用(Host 删掉自己的那份)、保留并有对照测试、平台差别。每批结束时更新,写明这批减少了几项、新增了几项。 + +第一版(第一批开始时,2026-11-15):共 18 项。已改为共用 0,保留并有对照测试 1(第 1 项),平台差别 1(第 17 项),待定 16。做法:按“照桌面”“as the desktop”“line for line”等说法检索,再逐个读候选文件确认。可能漏项,以后碰到再补,并写明是新发现的。 + +之后新发现的:第 19 项(2026-11-15,#10613 评审,平台差别);第 20 至 22 项(2026-11-16,第一批检查点 2)。现为 22 项:已改为共用 1(第 20 项),保留并有对照测试 2(第 1、22 项),平台差别 3(第 17、19、21 项),待定 16。第一批检查点 2:减少 1 项(第 20 项改为共用),新增 3 项。 + +检查点 3(2026-11-16):第 2、3 项改为共用(Host 的那份已删),第 7、8 项的改模型部分改为共用(档位、快速模式仍是 Host 的,检查点 3b);新增第 23 项。现为 23 项:已改为共用 3(第 2、3、20 项),保留并有对照测试 3(第 1、22、23 项),平台差别 3(第 17、19、21 项),待定 14。检查点 3:减少 2 项,新增 1 项。 + +28a(2026-11-17):新增第 24 项,减少 0 项。 + +session_search(2026-11-17):新增第 25 项(调用方检查,待定),减少 0 项。 + +withAccountDataAccess(2026-11-17):新增第 26 项,减少 0 项。 + +历史读取器(2026-11-17):新增第 27 项并改为共用(Host 的 anchor 已删),减少 1 项。 + +运行时调整覆盖(2026-11-17,4b):新增第 28 项,同日改为共用(Host 的照抄已删),减少 1 项。 + +28b(2026-11-17):新增第 29 项(平台差别),减少 0 项。 + +事件预处理甲 11、12、14、15、16(2026-11-18):新增第 30 至 35 项(均待定),减少 0 项。 + +事件预处理收尾(2026-11-18,审核方结论):第 30 项对齐(Host 的 `fallback` 已删),减少 1 项;第 31、32 项保留并有源码守护;第 33 至 35 项已定保留。 + +28c(2026-11-18):新增 0 项,减少 0 项。PAC 与自动发现交给 Chromium 辅助进程,不在 Host 里重写判断;第 29 项(macOS 静态读法)只在辅助进程没有答案时兜底。 + +8g B 静默停止后续跑(2026-11-18):新增第 36 项,评审后已定保留并有源码守护,减少 0 项。 + +线 A ②(2026-11-18)新增第 37、38 项,分别登记闸门放开后的复核和任务忙碌判断的差异,减少 0 项。 + +3d 用量记录(2026-11-18):新增第 39 至 41 项,减少 0 项。 + +Windows 启动重读(2026-11-18):新增第 42 项,减少 0 项。 + +主干同步后的任务延后(2026-11-19):新增第 43 项,减少 0 项。 + +| # | 位置 | 重写了桌面的什么 | 状态 | +|---|---|---|---| +| 1 | `agent/context-recovery.ts` `holdsOverflowBroadcast` | `sessionEventDelivery.ts` 压住上下文恢复错误广播的判据 | 保留并有对照测试(`sessionEventPipeline.test.ts`);第一批改为共用 | +| 2 | `agent/model-window-gate.ts` `modelSwitchGateInput` | `applySessionRuntimeSelection` 远程分支的闸门输入 | 已改为共用(检查点 3:文件已删,走共用 `handleSetModel`) | +| 3 | `main.ts` 的 `pendingAgentSwitches`、`applyPendingAgentSwitch`、`projectAgentSwitchIntent` | `sessionAgentSwitchHandler.ts` 的待切换登记与应用 | 已改为共用(检查点 3:共用 `createPendingAgentSwitchRegistry`、`applyPendingAgentSwitchIfIdle`,经发送事务的落定钩子) | +| 4 | `agent/turn-executor.mjs` `listen` 的事件处理顺序;第一批检查点 1 加入的后台活动检测回合起止(`noteBackgroundActivity`)待抽:归第一批桌面准备 D7,抽成共用后 Host 改为调用,抽之前不算减少 | `prepareSessionEvent` → 投递 → 终态的流水线 | 待定;第一批只重排终态顺序,保留并有对照测试 | +| 5 | `agent/turn-executor.mjs` `finish` 的终态结算 | `sessionEventTerminal.ts` 与 register 的 `onTurnErrorEvent` 收尾 | 待定;同上 | +| 6 | `agent/turn-executor.mjs` 的 `send`、`openTurn`、`dispatchTurn` | `register.ts` 的 `sendToAgentAccepted` | 待定;第一批检查点 2 补齐了第 32 行的发送前端口(工作目录、归档恢复、计划与目标说明、本轮模型)与协调器钩子,换引擎交接归检查点 3 | +| 7 | `agent/session-settings.mjs` 的 `applyQueuedSessionSettings`、`applyLiveSessionSettings` | 回合中改模型的延期兑现、发送时对账 | 待定;第一批改走共用核心后删掉;检查点 3:改模型走共用;检查点 3b-1:档位、快速模式、思考开关的入口走共用处理函数;甲 8:`/sessions/update` 不再经 `applyLiveSessionSettings` 改运行时,它只剩排队发送时的对账(`applyQueuedSessionSettings`)一个调用方 | +| 8 | `agent/session-update.ts` `createHostSessionUpdate`(改模型、来源走 set-model;运行时设置已改为拒绝(甲 8);任务状态的写入也在这里) | `applySessionRuntimeSelection`(改模型、来源、努力);状态写入对应桌面 `patchSessionMetaInDb`(恢复为 active 时走数据库事务 `sessions.setStatus` 并通知插件,Host 只直接改列,第一批桌面准备时新发现) | 待定;第一批改走共用核心 `applyRuntimeSetModelChange`;状态写入:恢复为 active 改用共用事务,Host 只保留三步组合(`agent/task-restore.ts`,第一批检查点 2)。与桌面 active 分支逐步对应:取 worktree 变更锁——Host 不取(Host 进程不回收 worktree,见第二节“恢复已归档任务”);`noteSessionsRestoring`——共用;数据库事务 `sessions.setStatus`——共用;灵动岛——平台差别;原生归档同步——平台差别(Host 归档也不同步);广播 `sessions:patched`——Host 发 `session_changed`。归档仍只改列(第二节“手动归档”);检查点 3:改模型、来源走共用 `handleSetModel`(`runtime-selection.ts` `setModel`);检查点 3b-1:档位另有共用入口,本函数里直接写 `effort` 的旧路径仍在;甲 5:工作目录移动走 `updateSessionInDb` 原样搬出的移动段(`sessionWorkingDirMove.ts`) | +| 9 | `agent/turn-executor.mjs` Git 基线的结算 | `sessionEventDelivery.ts` 的保存点结算 | 待定;上下文恢复重放自己开、撤基线的那几步已删,与桌面一样交给共用事务的 `beforeDispatchDirectUserTurn` / `onUndispatchedDirectUserTurn`(#10613 评审发现重复开基线) | +| 10 | `agent/start-options.ts` 启动钩子的步骤编排 | `maker-host/index.ts` 的启动钩子与 `onBeforeStart` | 待定 | +| 11 | `agent/codex-token-reader.ts` | `createCodexAuthTokenReader`(注释自述逐行相同) | 待定(第二批) | +| 12 | `agent/codex-auth-boundary.ts` | `maker-host/index.ts` 的三个鉴权边界钩子(注释自述逐步相同) | 待定(第二批) | +| 13 | `agent/codex-invalidation.ts` | `DesktopCodexAuthAdapter.invalidate` 的两个分支 | 待定(第二批) | +| 14 | `agent/codex-system-login.ts`、`agent/codex-runtime.ts` `createBridgeTokenReader` | 桌面 Codex 适配器与系统登录的对账、`getAccessToken` | 待定(第二批) | +| 15 | `agent/claude-proxy-runtime.ts`、`agent/runtime.ts` 的凭据路由 | 桌面代理的凭据路由规则 | 待定(第二批) | +| 16 | `main.ts` 的模型清单刷新、`agent/providers.mjs` | 桌面 `runModelsSync` 与目录变更点的刷新 | 待定(第二批) | +| 17 | `agent/auxiliary-model-chain.ts` | 辅助模型链(两处答案故意不同) | 平台差别(第二节) | +| 18 | `agent/send-preflight.ts` | 桌面 `prepareUserMessageForAgent` 的附件归一化;远程任务的拦截 | 待定(附件随第 12 行);拦截是平台差别。放开远程执行时要重看 `apps/host/src/desktop-module-setters.ts` 里以此为由的 not-applicable 项(现在是 `bindHostedSessionProvider`、`bindHostedAttachmentPreservation`) | +| 19 | `agent/turn-executor.mjs` `replay` 用被认领那一轮的 clientId 给重放的事件和回执打标(`agent/context-recovery.ts` `replayClientId`) | 桌面没有对应:桌面重放不带 clientId(只有 Pi 缓存兼容带 `retryUserClientId`) | 平台差别:Host 的 `/api/chat` 靠终态事件的 clientId 结束一条消息的流,桌面渲染层不靠 clientId 判断结束。只打标,不写用户行,事务仍不带 `persistUserMessage`;只在这次恢复进行中有效。新发现(2026-11-15,#10613 评审) | +| 20 | `agent/turn-executor.mjs` 原来的 `checkWorkDirExists`(只做 stat)。新发现(2026-11-16,第一批检查点 2) | `createWorkingDirectoryPreflight` 与 `createWorkingDirectoryRecovery` | 已改为共用(`agent/working-directory.ts`,Host 的那份已删)。两个端口不同,见第二节“工作目录检查” | +| 21 | `chat.mjs` 一条消息的流何时结束;`agent/turn-executor.mjs` 在“已落库但派发失败”的错误行落库后发 `interrupted` 回执(第一批检查点 2);`agent/input-queue.mjs` `inputStatus` 认出派发失败留下的恢复点 | 桌面没有这个入口 | 平台差别(Host 自己的入口)。结束条件与依据:1)账号退出、不能再进入应用;2)投影的恢复点是派发前的本条(`queue-head`),补 `interrupted` 回执后结束;3)本条的 `interrupted` 回执:停止后没有终态事件时(`finish`),以及本条已落库但派发失败、错误行落库之后(协调器的 `persistTerminalSendError`,只在这条路上发);4)本条的 `done` 或终态错误,不算后台与续接边界;5)连上时查到本条已记录或已中断,直接回执后结束(重连)。被上下文恢复认领的错误不写错误行、不发回执,流等到重放的 `done`。自动续跑:本条的终态错误被接管时(带 `autoResumePending`),流跟着续跑(`autoResumeOf`)到它结束或放弃(检查点 4b)。静默停止(8g B,审核方 2026-11-18 定“流跟到续跑结束”):决策未定的静默停止 done 带 `silentStopPending`,不结束流;结束条件是续跑的 `done`、耗尽横幅的终态错误,或没有续跑就结算时本条的 `recorded` 回执(`turn-executor.mjs` 的 `endSilentStopTurn`);调用方中途断开不影响续跑 | +| 22 | `agent/turn-executor.mjs` 的 `peekPlanReconcileNote`:读计划快照、按状态选说明的几行组合 | `register.ts` 同名端口的闭包(读 `readCodexPlanState`,已封用 `buildCompletedPlanGuardNote`,有未完成步骤或被中断用 `buildPlanReconcileNote`) | 保留并有对照测试(`input-queue.test.mjs`“interrupted Codex plan”);以后有桌面准备时可抽成共用 | +| 23 | `agent/runtime-selection.ts` 里照 `register.ts` 抄写的装配:冷启动 Pi 的绑定(读任务行、把任务行映射成启动参数的 12 个字段、准备启动参数)、待切凭据读取器的投影、`rememberThinkingIntent` 的推送内容。新发现(2026-11-16,检查点 3 复核) | `register.ts` 同名绑定 | 已改为共用(小块抄写单元:桌面 `677d0fe481` 原样搬出,Host `42293bed1d` 改绑):冷启动 Pi 绑定 `createColdPiRehydrationBinding`、待切凭据读取器 `createPendingCredentialSwitchRouteReader`、`createRememberThinkingIntent`,以及同时搬出的回合结束时落地待切凭据 `settlePendingCredentialSwitchWith`、切换分隔行重播 `rebroadcastAgentSwitchBoundaryWith`、切换选项的两个读取函数。Host 的副本已删,端口绑 Host 原副本用的函数。测试覆盖:思考意图有 Host 测试(`input-queue.test.mjs`“thinking choice”);冷启动 Pi 的续接 id、选项读取有桌面测试;读取器、回合结束落地、分隔行重播的所有者判断两边都没有测试能发现改坏,补不补见检查点交付 | +| 24 | `agent/runtime.ts` 给 Codex 的 `getOutboundPathFact`(28a,2026-11-17) | 桌面 `maker-host/index.ts` 同名端口的三行闭包,逐行对应:没有线程号返回 null;取 Codex 代理记的线程出口 origin(桌面 `getCodexThreadUpstreamOrigin`,Host `options.codexRuntime?.proxy.getCodexThreadUpstreamOrigin`,同一个共用工厂 `createCodexProxyHost` 的产物);有 origin 时取解析器对它的判定(桌面 `getOutboundPathSnapshotFor`,Host `getHostOutboundPathSnapshotFor`,同一个共用核心的实例),没有就返回 null。差别只在 Host 没有 Codex 运行时那一种情况,取不到 origin、返回 null | 保留,有 Host 测试(`agent/outbound-path-fact.test.mjs`),桌面没有对应测试;这三行没有桌面共用件,抽成共用要改桌面 `index.ts`,不在 28a | +| 25 | `agent/memory-mcp-ports.ts` `createHostSessionSearch`:session_search 调用方的检查(当前库、账号边界、调用的任务不是 restricted,检索前后各核一遍)。新发现(2026-11-17,接 session_search 时照抄) | `mcp-integrations/mcp-providers.ts:687-706` 的 `searchSessions` 闭包。它写在 `createLiziMcpProviders` 的参数里,`pluginTaskHelperScope.test.ts:46` 按源码文本从 `mcp-providers.ts` 截取它来测,不能原样搬走。检索本身已是共用(`sessionSearchCore.ts`) | 待定:要改为共用,先把桌面闭包搬成工厂并改写那条按源码截取的测试。有照抄不走样的守护:`hostDesktopSourceContracts.guard.test.ts`“keeps the cindy_memory caller checks line for line with the desktop closures”(只允许检索那一处不同) | +| 26 | `agent/memory-mcp-ports.ts` `hostAccountDataAccess`:cindy_memory 每次调用前的账号数据检查(当前库、账号边界、调用的任务不是 restricted,操作前后各核一遍)。新发现(2026-11-17,接 `withAccountDataAccess` 时照抄) | `mcp-integrations/mcp-providers.ts:409-424` 的 `withAccountDataAccess` 闭包。它写在 `createLiziMcpProviders` 之前的装配里,`pluginTaskHelperScope.test.ts:56` 按源码文本截取它来测,不能原样搬走 | 待定:和第 25 项一起,先把桌面闭包搬成工厂并改写那条按源码截取的测试。有照抄不走样的守护:`hostDesktopSourceContracts.guard.test.ts`“keeps the cindy_memory caller checks line for line with the desktop closures”。两层检查(session_search 自己的复核与 `withAccountDataAccess`)中任一层单独存在都不漏数据,精确的错误文本由外层保证(调用中途换账号的测试分层改坏所得,2026-11-17)| +| 27 | `agent/history.ts` `createHostHistoryReader` 里的 anchor:按桌面语义照抄(任务要存在,消息是本任务的、未回退、在此刻读到的清空线之后),修清空线之前的消息可作锚点(第五节“Host 历史读取器”①,`8ba57dfc03`)。新发现(2026-11-17),登记时写明“历史读取器共用后删除” | `localDb/ipc/messages.ts` 历史读取器的 anchor(现 `localHistoryViewReader.ts`) | 已改为共用(2026-11-17):桌面 `728b61ab69` 把读取器装配搬成 `createLocalHistoryViewReader`,Host 改绑后删掉自己的 anchor,list、outline、hydrate、validate、revision 一并用桌面的 | +| 28 | 任务运行时启动前的运行时调整覆盖(原 `agent/runtime-override.ts`,2026-11-17 4b 新发现) | `maker-ipc/sessionRuntimeControl.ts` `applySessionRuntimeOverrideForStart`(从 register.ts bootstrapSession 原样搬出) | 已改为共用(2026-11-17):Host 的 bootstrapSession 与 restoreSession 在启动准入之前调同一个函数(groupDecidesSource 传 false:Host 在准入时拒绝供应商组任务),Host 的照抄与对照守护已删。搬移时查出照抄漏了桌面后面两处用法:有调整时启动后**不把供应商写回任务行**(保留已保存的基线)、effort 与 Fast 按调整设;照抄版把换上去的供应商写进了任务行(9853b81568 引入的偏差),已随搬移改正。effort 与 Fast 两项 Host 从 opts 读、多一步按模型能力归一化(差别很小)。行为测试 `input-queue.test.mjs`“auto-resume route switch…”断言续跑跑在新路线上、任务行仍是原供应商 | +| 29 | `macos-system-proxy.ts`:读 macOS 静态系统代理并换成 PAC 结果串(28b,2026-11-17) | 桌面没有对应代码,桌面问 Chromium。Host 照 Chromium 148(Electron 42.11.12)写了:读哪些键(`proxy_config_service_mac.cc`);HTTPS 项仍是 HTTP 代理、SOCKS 按 v5、缺端口用默认端口、缺主机或空主机忽略该项(`proxy_chain_util_apple.cc`、`proxy_server.cc`);按 scheme 选代理、回落到 SOCKS(`proxy_config.cc`);例外规则的解析与匹配,后写的规则优先,`?` 匹配零或一个字符(`proxy_host_matching_rules.cc`、`scheme_host_port_matcher_rule.cc`、`scheme_host_port_matcher.cc`、`base/strings/pattern.cc`);隐式例外(localhost、127/8、::1、IPv4 映射的回环与链路本地、169.254/16、fe80::/10) | 平台差别,以 macOS CI 比对作对照(与 Electron 逐条比对;改到这份实现的 PR 上运行,Electron 升级经 `CHROMIUM_RULES_ELECTRON_VERSION` 的守护带到这里,见第五节“甲:28b 的 macOS CI 比对”;Chromium main 已多了 0.0.0.0 与 `[::]` 的隐式例外);单元测试按源码出处写预期。按源码定、待 CI 实测:scutil 的文本格式(SCPrint 的实现不在 configd 开源里);`*User` 键有非空的值即算带认证(空值不算);非整数的数、非字符串的主机、非数组的例外列表都按没有这个键读(Chromium 按 CF 类型取值,类型不符即为空,文本里分不出字符串形式的数字);PAC 地址不是合法 URL 时用手动设置(`has_pac_url` 看 GURL 是否合法,Host 用 Node 的 URL 判断,两者在少见写法上可能不同);代理主机规范化失败时忽略该项(`proxy_server.cc`);端口不在 1–65535 时 Host 报 unknown(Chromium 把整数收成 16 位端口的那一步没读到);代理主机里有空白、斜杠、`@`、`%` 时 Host 报 unknown(Chromium 可能只忽略该项);`169.254/16` 按 `url_canon_ip.h` 读作 169.0.0.254/16(只影响 169.0.x.x;169.254.x.x 由隐式例外兜住);不带方括号的 IPv6 主机规则从不命中。CI 不覆盖:`ExcludeSimpleHostnames`、缺端口、空主机(networksetup 设不出来) | +| 30 | `agent/interactions.mjs` 的 `fallback`:确认中转自己给卡片的默认决定。新发现(2026-11-18,甲 12) | `register.ts` 的 `defaultDecisionForPending`(现在 `maker-ipc/sessionEventPreparationSteps.ts`)。差别:Host 给权限卡片的默认决定带 `dismissed: true`,桌面不带;提问与计划两边一样。运行时自己收掉卡片这一条路(`interaction_dismissed`)甲 12 起照桌面,用共用的 `defaultDecisionForPending`;中止、换运行时、owner 变化、重复请求号等其余路径仍用 Host 的 `fallback`,没改 | 已对齐(2026-11-18 收尾,审核方结论):确认中转删掉自己的 `fallback`,中止、换运行时、owner 变化、重复请求号这几条路径都改用共用的 `defaultDecisionForPending`,权限卡片的默认决定不再带 `dismissed`。改前查证:Host、网页端与测试都不读权限决定上的 `dismissed`(maker-core 的类型里权限决定没有这个字段,渲染层与 Claude Code、Codex 适配器只对提问与计划读它)。测试:Host `agent/interactions.test.mjs`“a stopped task closes its pending cards with the desktop's default decisions” | +| 31 | `agent/generated-images.ts` 的 `readSource`:生成图读来源,Host 自己的一份。新发现(2026-11-18,甲 11) | `register.ts` `createGeneratedImageDelivery` 的 `readSource` 闭包。桌面依次:来源标为 remote-agent 的拒绝;任务在远程主机上时,经 SSH 文件服务(`materializeSshRemoteMedia`,限 `MAX_GENERATED_IMAGE_BYTES`)把图片路径取到本机缓存再读;托管地址认 `cindy-media://`(`resolveCindyMediaUrl`)和旧的 `xdt-image://`(`imageCacheStore.resolveSafe`),读失败而图片带路径时回落到路径;最后读图片给的本机路径。Host 去掉了 SSH 一支(远程主机任务直接 `REMOTE_SOURCE_REQUIRED`)和 `xdt-image://` 一支,`cindy-media://` 用 Host 媒体库的 `resolveSafe`,其余次序与回落相同。桌面那份一改(判断次序、回落、读文件的限制、新的地址形式),这边要跟着看 | 保留并有源码守护(审核方结论):桌面 `hostDesktopSourceContracts.guard.test.ts`“pins the desktop generated-image readSource that the Host copy follows”钉住桌面那段的文本指纹,桌面一改就红,并提示来这里对照 | +| 32 | `agent/generated-images.ts` 的 `deliverCodexGeneratedImage`:开始交付、失败记 warn、交出已发出的工具事件。新发现(2026-11-18,甲 11) | `register.ts` 同名函数,逐行对应 | 保留并有源码守护(审核方结论):同一守护文件“starts a live generated-image delivery with the desktop function, line for line”逐行比对两边,只容许交付实例的名字不同 | +| 33 | `agent/turn-executor.mjs` `interactionDismissedPorts` 的 `persistInteractionDecision`:只保存提问与计划的决定。新发现(2026-11-18,甲 12) | `register.ts` 同名函数(同一个判断 `agent/interactions.mjs` 的 `settle` 里原来也有) | 已定:保留(审核方结论) | +| 34 | `agent/turn-executor.mjs` `standaloneTextPorts` 的 `getActiveInputClientId`:本回合的输入(回合未结束、代次相符)。新发现(2026-11-18,甲 14) | `AgentInputCoordinator.getActiveInputClientId`。差别:输入来源给空(只用来判断伙伴私信,Host 准入时拒绝伙伴输入) | 已定:保留(审核方结论) | +| 35 | `agent/history.ts` `readMessagesList` 首页开始生成图恢复的条件(没有 `before`、`after` 游标)。新发现(2026-11-18,甲 11 补充测试) | `localDb/ipc/localHistoryViewReader.ts` `createReadMessagesList` 的同一个判断(桌面还要求没有 `beforeTs` 且不是 outline,Host 的列表没有这两个参数)。Host 的消息列表本身是 Host 自己的读取,见第五节“Host 历史读取器” | 已定:保留(审核方结论) | +| 36 | `agent/silent-stop.ts` 的 `schedule` 与 `decideLater`:静默停止终态的排期与 1.5 秒后的决策;`markTurnEndedAndCheckIdle` 端口按 Host 的回合记录回答“是不是有更新的回合”。新发现(2026-11-18,8g B) | `sessionTurnObserver.ts` 的 `onTerminal` 静默停止分支(`silentStopTurnLeaseGate.schedule` 加 `claimHostTurnContinuation`)、`sessionEventPreparation.ts` 的静默停止分支(`turnLeaseIdForEvent`、1.5 秒定时器),以及 `sessionTurnLease.ts` 的 `markTurnEndedAndCheckIdle`(按持久的回合租约) | 已定:保留(审核方 2026-11-18),有源码守护:桌面 `hostDesktopSourceContracts.guard.test.ts`“pins the desktop silent-stop terminal scheduling that the Host copy follows”与“pins the desktop silent-stop decision timing that the Host copy follows”钉住桌面两段的文本指纹,桌面一改就红,并提示来这里对照。`markTurnEndedAndCheckIdle` 端口按 Host 的回合记录回答,回合开始与结束的标记见第二节“静默停止续跑期间的回合标记” | +| 37 | 线 A ②:桌面占用期间保留待切凭据与运行时控制,重建运行时以后复核账号、登记时的路线与代次,再依次处理两种待办与输入等待者 | 桌面没有 profile 互斥闸门,回合结束直接进入结算 | 平台差别。定时器、关闭回调及已经开始的异步结算都要守住同一条写入边界 | +| 38 | `agent/runtime-selection.ts` 的 `isSessionInTurn` 使用 `Session.isTurnRunning()`,引擎尚未确认权限变更期间也算忙 | 桌面读取 `sessionTurnActivityTracker` 的前台回合状态 | 平台差别。这个窗口内,Host 更容易将路线切换登记为待生效。普通模型选择器的 `pendingUntilSend` 仍等下一次发送 | +| 39 | `agent/turn-executor.mjs` 的 `recordTurnUsage` 与 `agent/usage-recording.ts` 的 `usageTarget`:终态取用量落点的约 20 行(3d,2026-11-18) | `sessionEventTerminal.ts:186–221`:consume 本轮最后一条助手消息、失败轮交接给配对的 done、Claude 续接边界 remember/finish。这几行在桌面上和 flush、盖章交织 | 保留(与桌面同一顺序);差别:迟到事件(Host 回合结束后、上一代)只用交接的 id、不 consume。测试 `agent/usage-recording.test.mjs` | +| 40 | `agent/usage-recording.ts` 的 AsyncLocalStorage 路由、owner 比较与 `drain`,以及“在回合中”集合(`noteRunningStatus`、`noteTurnEnded`)(3d,2026-11-18) | 桌面的端口是进程级默认实现,写库取当时的库;“在回合中”是 `sessionTurnActivityTracker.isSessionInTurn` | Host 独有的写入边界:按运行时绑定的 owner 写、上下文外的写入丢弃、关库前等写完;已开始的端口调用里的嵌套写入(消息补丁、定时任务运行的花费)比较该调用取到的 owner,不取上下文,因为任务写队列暂停后的重试(`retryFailedWrites`)在上下文之外重放它们;“在回合中”照桌面重写(前台 running status 开始,最后一个 done、终止性 error、not-running status 结束)。测试同上 | +| 41 | `agent/usage-push-channels.ts` 的 `PHASE1_UNFORWARDED_USAGE_CHANNELS` 与 `device-link.ts` 的镜像接收方过滤(3d,2026-11-18) | 桌面设备互联转发全部可转发通道 | 平台差别(第二节“用量变化不推给远程设备”):第一阶段不转发 12 条用量通道,名单外照常;读取与推送那一批落地时删掉。测试同上(名单内不转、名单外照转、可转发的 `usage:` 通道全部归类) | +| 42 | Host 启动与运行中扫描桌面 PID 身份(甲) | 桌面共用扫描和单次 1,500 ms 身份查询;桌面只延后迁移 | Host 持租约同时重读登记和进程身份。仅身份不明时按 0.5、1、2 秒递增等待,最多四轮。十秒预算决定是否开始下一轮,已完成的首轮或重查轮都采用查清的结果。确认桌面存活或重查发现新桌面登记立即拒绝。进程已结束或已证明 PID 复用时沿原路径开库。运行中的定期扫描也改了:每轮先读登记取得候选,再带进程身份重读。若登记在两次读取之间消失,但进程仍存活且身份与原登记相符,本轮仍判为阻塞。 | +| 43 | `agent/session-update.ts` 里 `snoozedUntil` 的日期校验(主干同步后,2026-11-19) | 桌面 `localDb/ipc/sessions.ts` 的 `validateSnoozeTime`(未导出):必须是将来的时间、不超过 366 天,否则 INVALID_PARAMS,信息相同 | 逐句照抄,两边必须保持一致;桌面改这一段时 Host 同步改,或届时把它搬成共用。测试:`session-update.test.mjs` 的 “task snooze: the Host update saves, rejects and clears the date like the desktop” | +| 44 | 桌面占用期间 Host 整体静默插件(2026-11-19,插件基座,走白名单确认) | 内嵌桌面不传网关的静默信号,插件继续工作 | Host 先中止当前网关信号,再同步发起逻辑页、Node 进程的停止。入口仍保留启用、批准和 owner 的查询,静默期拒绝工具、拉起、唤醒及宿主请求。下载用 `abortAll`。静默打断的在途工具调用报告结果不确定,分块暂存只撤掉未提交的数据,已提交的回执继续以原 staging ID 查询。两次干净扫描及输入运行时重建后,重试失败的清理步骤。后续每次干净扫描继续尝试未完成的恢复。恢复时更新信号并补推插件清单与状态,真实熔断及浏览器分区保留。恢复中途出错(与占用无关,比如某个插件的授权核对读盘失败、`reconcile` 或安装变更补做抛错)时,运行时回到静默,下一轮干净扫描再试;这个错一直在的话,插件会一直提示桌面正在使用,日志每轮一条警告。启动时 `reconcile` 失败本来也是整体不可用,所以接受这个取向,看到这个提示时先查日志里的恢复错误。“不确定”会多报:占用前已受理、但还没送到插件(插件正在拉起)就被打断的调用,也报不确定,方向是安全的(审核方 2026-11-19)。 | diff --git a/docs/host/systemd.md b/docs/host/systemd.md index 8a7b039333c..1da20fd12fb 100644 --- a/docs/host/systemd.md +++ b/docs/host/systemd.md @@ -45,7 +45,7 @@ systemctl --user daemon-reload | --- | --- | --- | | `WorkingDirectory` | `%h/development/cindy` | 你的 checkout 绝对路径 | | `ExecStart` | `/usr/bin/env pnpm start-host` | 建议改成绝对路径,避免 systemd 的 PATH 与登录 shell 不同 | -| `Environment=CINDY_HOST_REGION` | `global` | `cn` 或 `global`;不写按 global | +| `Environment=CINDY_HOST_REGION` | 注释掉 | 从 checkout 运行(本单元的 `ExecStart`)时选择版本:`cn` 或 `global`,不写按 global。安装的 Host 发布包按区域各一个,版本在构建时定死,不需要这一行;写了而且和包的版本不同,Host 拒绝启动(`HOST_REGION_MISMATCH`)。装国内版包的,删掉这一行或写 `cn` | | `CINDY_HOST_DATA_DIR` | 注释掉 | 指定后直接使用该目录,等价于 Desktop 的 `XDT_USER_DATA_DIR` | | `CINDY_HOST_OWNER` | 注释掉 | 登录阶段完成前必须显式给出 owner id;否则 host 只提供 `/health`,不打开数据库 | diff --git a/package.json b/package.json index 66d60e3ad13..74a6b5282bc 100644 --- a/package.json +++ b/package.json @@ -98,7 +98,7 @@ "licenses:generate": "node scripts/generate-third-party-notices.mjs", "lint": "pnpm -r lint", "format": "pnpm -r format", - "test:runner": "node --test scripts/__tests__/browsermcp-env.test.mjs scripts/__tests__/check-built-in-skills.test.mjs scripts/__tests__/personal-build-recovery.test.mjs scripts/__tests__/personal-build.test.mjs scripts/__tests__/personal-build-managed.test.mjs scripts/__tests__/check-settings-search.test.mjs scripts/__tests__/repo-worktrees.test.mjs scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/remote-bundle-inputs.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/duration-shards.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/desktop-dev-node-options.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/brand-terminology-guard.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/publish-page-manual.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs scripts/__tests__/check-test-hygiene.test.mjs scripts/__tests__/check-pr-design-basis.test.mjs scripts/__tests__/host-channel-coverage.test.mjs scripts/__tests__/host-agent-deps-contract.test.mjs && node apps/desktop/scripts/check-windows-atomic-rename.mjs", + "test:runner": "node --test scripts/__tests__/browsermcp-env.test.mjs scripts/__tests__/check-built-in-skills.test.mjs scripts/__tests__/personal-build-recovery.test.mjs scripts/__tests__/personal-build.test.mjs scripts/__tests__/personal-build-managed.test.mjs scripts/__tests__/check-settings-search.test.mjs scripts/__tests__/repo-worktrees.test.mjs scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/remote-bundle-inputs.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/duration-shards.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/desktop-dev-node-options.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/brand-terminology-guard.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/publish-page-manual.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs scripts/__tests__/check-test-hygiene.test.mjs scripts/__tests__/check-pr-design-basis.test.mjs scripts/__tests__/host-channel-coverage.test.mjs scripts/__tests__/host-agent-deps-contract.test.mjs scripts/__tests__/host-skill-projection-owner.test.mjs scripts/__tests__/host-server-hold-classification.test.mjs && node apps/desktop/scripts/check-windows-atomic-rename.mjs", "test:workspaces": "node scripts/test-workspaces.mjs", "test:agent-net-native": "node scripts/check-agent-net-native.mjs", "test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit", diff --git a/scripts/__tests__/host-agent-deps-contract.test.mjs b/scripts/__tests__/host-agent-deps-contract.test.mjs index 02fb49834b2..62a46269c38 100644 --- a/scripts/__tests__/host-agent-deps-contract.test.mjs +++ b/scripts/__tests__/host-agent-deps-contract.test.mjs @@ -39,12 +39,24 @@ function interfaceMembers(rel, name) { return members; } +/** + * The bag of `new (…)`: an object literal, or one written out through `explicitPorts({...})` + * (apps/host/src/agent/explicit-ports.ts, which returns its argument as T). + */ +function constructorBag(node) { + const argument = node.arguments?.[0]; + if (argument && ts.isCallExpression(argument) && ts.isIdentifier(argument.expression) + && argument.expression.text === 'explicitPorts' && argument.arguments.length === 1) return argument.arguments[0]; + return argument; +} + /** Literal keys of `new ({...})`, following `...(cond ? {...} : {})`; other spreads are reported. */ function constructorKeys(sf, ctor) { const found = []; const visit = node => { + const bag = ts.isNewExpression(node) ? constructorBag(node) : undefined; if (ts.isNewExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === ctor - && node.arguments?.[0] && ts.isObjectLiteralExpression(node.arguments[0])) { + && bag && ts.isObjectLiteralExpression(bag)) { const keys = []; const spreads = []; const collect = (object) => { @@ -62,7 +74,7 @@ function constructorKeys(sf, ctor) { } } }; - collect(node.arguments[0]); + collect(bag); found.push({ keys, spreads }); } ts.forEachChild(node, visit); @@ -74,8 +86,12 @@ function constructorKeys(sf, ctor) { // The spread bundles are built in TypeScript as Pick/Partial, so their keys are type checked there. // The per-model resolver bundles come from engineModelResolvers.ts, typed as Required>. +// The ports another engine reads (agent-deps-engines.ts) are `satisfies { [K in keyof AgentDeps]?: undefined }`; +// codexRuntimePorts is the Codex runtime's typed deps or its unbound fallback, typed the same way in runtime.ts. const TYPED_SPREADS = new Set(['options.mcpRuntime.codexDeps', 'options.codexRuntime?.deps', 'options.mcpRuntime.piDeps', - 'claudeModelResolvers', 'codexModelResolvers', 'piModelResolvers']); + 'claudeModelResolvers', 'codexModelResolvers', 'piModelResolvers', + 'PORTS_ONLY_CODEX_READS', 'PORTS_ONLY_PI_READS', 'PORTS_ONLY_CLAUDE_READS', + 'PORTS_ONLY_CLAUDE_AND_PI_READ', 'PORTS_ONLY_CLAUDE_AND_CODEX_READ', 'codexRuntimePorts']); test('every key the Host hands an engine or Maker exists in the maker-core dependency types', () => { const runtime = parse('apps/host/src/agent/runtime.ts'); diff --git a/scripts/__tests__/host-server-hold-classification.test.mjs b/scripts/__tests__/host-server-hold-classification.test.mjs new file mode 100644 index 00000000000..4cb9e5ddc29 --- /dev/null +++ b/scripts/__tests__/host-server-hold-classification.test.mjs @@ -0,0 +1,42 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import test from 'node:test'; + +// §3.2 guard (static, kept on purpose for a permission boundary). While a desktop holds the profile, the service +// refuses writes through its allowlist (service.mjs HOST_PATHS_ALLOWED_WHILE_HELD), but server.mjs answers some +// paths itself, outside that allowlist. Twice an entry there wrote data the desktop shares while it was held +// (turning remote control on; /chat creating a task). Every path server.mjs matches must be classified here. +// Failure it catches: a new path in server.mjs that would write shared data during a hold with nobody reviewing +// it. Minimal failing input: add `if (request.method === 'POST' && url.pathname === '/control/x')` to server.mjs. +// Tier: guard (source read, no server started); a root source contract (check-test-hygiene ROOT_SOURCE_CONTRACTS), +// run by `pnpm test:runner`. +test('every path server.mjs answers itself is classified for a desktop hold', () => { + const source = fs.readFileSync(new URL('../../apps/host/src/server.mjs', import.meta.url), 'utf8'); + const found = new Set(); + for (const m of source.matchAll(/url\.pathname\s*===\s*(?:'([^']*)'|([A-Z][A-Z0-9_]+))/g)) found.add(m[1] ?? m[2]); + for (const m of source.matchAll(/url\.pathname\.(startsWith|endsWith)\(\s*(?:'([^']*)'|([A-Z][A-Z0-9_]+))\s*\)/g)) { + found.add(`${m[1]}:${m[2] ?? m[3]}`); + } + for (const m of source.matchAll(/\[\s*('[^']*'(?:\s*,\s*'[^']*')*)\s*(?:,\s*)?\]\.includes\(url\.pathname\)/g)) { + for (const literal of m[1].matchAll(/'([^']*)'/g)) found.add(literal[1]); + } + // service: the service gate decides (writes refused while held unless allowlisted). + // refused: writes refused while held. exception: may write shared data while held, registered in the release + // table (docs/host/personal-migration-release-table.md). none: writes no data the desktop shares. + const classified = { + 'startsWith:/api/': 'service', + 'startsWith:/api/auth/': 'service', + '/api/auth/logout': 'exception: sign-out updates the shared account vault under its cross-process lock', + '/logout': 'exception: same sign-out as /api/auth/logout', + 'startsWith:HOST_IPC_PATH_PREFIX': 'none: the bound IPC channels read only (ipc-bindings)', + '/chat': 'refused: a new task at the entry check before it is created; input to an existing task by the queue', + '/control/remote': 'refused for enable and Agent-Net on/off; exception for disable and revoke; status reads', + '/control/stop': 'exception: stopping finishes accepted work (queue drain, usage, error rows)', + '/control/attachment': 'none', HOST_IPC_MANIFEST_PATH: 'none', '/control/platform': 'none', + '/web/pair': 'none', '/web/session': 'none', '/events': 'none', '/health': 'none', '/me': 'none', + '/plugins': 'none', '/sessions': 'none', 'startsWith:/sessions/': 'none', 'endsWith:/messages': 'none', + '/connect': 'none', '/connect.js': 'none', '/': 'none', '/shim.js': 'none', 'startsWith:/assets/': 'none', + }; + assert.deepEqual([...found].filter(path => !(path in classified)).sort(), [], 'paths server.mjs answers that are not classified'); + assert.deepEqual(Object.keys(classified).filter(path => !found.has(path)).sort(), [], 'classified paths server.mjs no longer answers'); +}); diff --git a/scripts/__tests__/host-skill-projection-owner.test.mjs b/scripts/__tests__/host-skill-projection-owner.test.mjs new file mode 100644 index 00000000000..7da017616c5 --- /dev/null +++ b/scripts/__tests__/host-skill-projection-owner.test.mjs @@ -0,0 +1,47 @@ +/* + * 测试价值 + * - 规则依据:发布表第 25 行 25b,审核方定 (a):Host 常驻进程(serve)不发布 Skill 投影的 owner, + * 由窗口或 `cindy-host login` 发布。闸门 `configureProjectionBoundaryOwnerCommit` 默认允许(桌面不注入), + * 所以拒绝完全靠 serve 入口的那一次注入。失效后果:注入丢了,serve 能在没有窗口的情况下改写边界, + * 方案 A 被静默打破;login 不注入允许时则一样(默认允许),但改坏顺序或换文件就不再可见。 + * - 为什么是静态检查:注入发生在 main.ts 的 serve 分支顶层,加载 main.ts 就会启动整个服务;拒绝本身的 + * 行为由 apps/host/src/boundary.test.mjs“25b: serve refuses …”经生产函数覆盖。 + * - 最小失败输入:删掉 main.ts 里的 `refuseSkillProjectionOwnerCommit();`,或把它挪到监听之后;或别的 + * Host 文件直接调用 `configureProjectionBoundaryOwnerCommit(`。 + * - tier:guard(登记在 check-test-hygiene.mjs 的 ROOT_SOURCE_CONTRACTS)。 + */ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const read = (rel) => fs.readFileSync(path.join(root, rel), 'utf8').replace(/\r\n/g, '\n'); + +test('serve injects the owner-commit refusal before it listens, and only the owner module sets the gate', () => { + const main = read('apps/host/src/main.ts'); + const serve = main.indexOf("const profileDir = resolveHostDataDir();\nconfigureUserDataDir(profileDir);"); + const refusal = main.indexOf('\nrefuseSkillProjectionOwnerCommit();\n'); + assert.ok(serve > -1 && refusal > serve, 'the serve branch calls refuseSkillProjectionOwnerCommit()'); + assert.equal(main.indexOf('\nrefuseSkillProjectionOwnerCommit();\n', refusal + 1), -1); + assert.ok(refusal < main.indexOf('acquireHostServiceLease(profileDir)'), 'the refusal precedes the service lease and listening'); + + const login = read('apps/host/src/login-cli.mjs'); + assert.ok(login.indexOf('allowSkillProjectionOwnerCommit();') > login.indexOf('await assertNoDesktopOnProfile('), + 'login allows the commit only after the coexistence check'); + + const offenders = []; + const walk = (dir) => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { walk(full); continue; } + if (!/\.(ts|mts|mjs|cts)$/.test(entry.name) || /\.test\.mjs$/.test(entry.name)) continue; + if (fs.readFileSync(full, 'utf8').includes('configureProjectionBoundaryOwnerCommit(')) { + offenders.push(path.relative(root, full).split(path.sep).join('/')); + } + } + }; + walk(path.join(root, 'apps/host/src')); + assert.deepEqual(offenders, ['apps/host/src/agent/skill-projection-owner.ts']); +}); diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjs index 6c383910063..f163bdaed82 100644 --- a/scripts/check-test-hygiene.mjs +++ b/scripts/check-test-hygiene.mjs @@ -4,7 +4,7 @@ // 跑:node scripts/check-test-hygiene.mjs 检查(CI 阻断) // node scripts/check-test-hygiene.mjs --update 把基线收紧到当前计数(只降不升) // -// 三条规则都只看源码文本,结果与机器快慢无关: +// 以下三条单测规则按基线计数,结果与机器快慢无关: // reset-modules 每次 vi.resetModules() 都会让后续 import 重新求值整条模块链。 // codexProxyHost.test.ts 逐用例重置时 285 条用例耗时 105s,不重置只要 7s。 // 新增调用必须在上一行写 `// reset-modules: <被隔离的模块状态>`。 @@ -18,6 +18,7 @@ // 存量计数记在 scripts/test-hygiene-baseline.json,只允许减少:某文件的计数超过基线、 // 或基线外的文件出现未豁免的命中,都会失败。门禁对照可信 Git 基准拒绝基线上调, // 手改 JSON 与 `--update` 均不能绕过;只有确认基准提交还没有基线文件时才首次登记。 +// 另查 apps/host 下的测试、脚本和夹具:按名称或路径结束进程直接报错,不可加入基线。 import { existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; import { execFileSync } from 'node:child_process'; @@ -53,8 +54,12 @@ const ROOT_SOURCE_CONTRACTS = new Map([ ['scripts/__tests__/ensure-agent-binaries.test.mjs', 'runtime preparation startup wiring'], // Restart scripts and app bootstrap must agree on isolation/process boundaries. ['scripts/__tests__/restart-desktop-remote.test.mjs', 'restart and bootstrap isolation contracts'], + // The Host's serve entry injects the Skill projection owner-commit refusal (release table row 25, 25b). + ['scripts/__tests__/host-skill-projection-owner.test.mjs', 'Host projection owner-commit injection'], // Host hands maker-core engines only dependency keys maker-core reads (spreads escape tsc's excess-key check). ['scripts/__tests__/host-agent-deps-contract.test.mjs', 'Host engine wiring and maker-core dependency keys'], + // Every path the Host's server.mjs answers outside the service gate is classified for a desktop hold. + ['scripts/__tests__/host-server-hold-classification.test.mjs', 'Host server paths classified for a desktop hold'], // Packaged notice generation and both application entry points must stay wired. ['scripts/__tests__/third-party-notices.test.mjs', 'cross-platform bundled license contracts'], ]); @@ -1303,6 +1308,80 @@ function walk(dir, out) { } } +// Host test cleanup must target processes the fixture started. Include scripts and +// integration fixtures omitted from the unit-test ratchet, with no baseline allowance. +const PROCESS_TOOL = /(?:^|[/\\])(?:pkill|killall)(?:\.exe)?$/i; +const NAME_KILL_COMMANDS = [ + // Executable following a shell control operator or wrapper. + /(?:^|[;&|(\n]|\b(?:then|do|if|sudo|command|exec|xargs)\s+)\s*['"]?(?:[^\s'"`]+\/)?(?:pkill|killall)\b/i, + /\bkill\s+(?:-[\w-]+\s+)*["']?(?:\$\(|`)[^\n)]*\b(?:pgrep|pidof)\b/i, + /\b(?:pgrep|pidof)\b[^\n|]*\|\s*xargs\b[^\n|]*\bkill\b/i, + /\btaskkill(?:\.exe)?\b[^\n;&|]*(?:\/im\b|\/fi\s+["\x27]?(?:imagename|windowtitle|services|modules)\b)/i, + /\bstop-process\b[^\n;|]*-(?:process)?name\b|\bget-process\b(?![^\n|]*-id\b)[^\n|]*\|\s*stop-process\b/i, + /\b(?:system|Popen|check_call|check_output|run|call)\s*\(\s*\[?\s*['"](?:[^'"]*[/\\])?(?:pkill|killall)\b/i, +]; + +function terminatesByName(text) { + return NAME_KILL_COMMANDS.some(pattern => pattern.test(text)); +} + +// A file URL's pathname still contains percent escapes and may start with /C:/. +// HTTP routing uses pathname directly, so match only URL constructions rooted in a file. +function readsFileUrlPathname(ts, node) { + if (!ts.isPropertyAccessExpression(node) || node.name.text !== 'pathname') return false; + let url = node.expression; + while (ts.isParenthesizedExpression(url)) url = url.expression; + if (ts.isCallExpression(url) && url.expression.getText() === 'pathToFileURL') return true; + if (!ts.isNewExpression(url) || url.expression.getText() !== 'URL') return false; + const [value, base] = url.arguments ?? []; + if (!value) return false; + if (ts.isStringLiteralLike(value) && /^[a-z][a-z0-9+.-]*:/i.test(value.text)) return /^file:/i.test(value.text); + return value.getText() === 'import.meta.url' || base?.getText() === 'import.meta.url' + || (base && ts.isStringLiteralLike(base) && /^file:/i.test(base.text)); +} + +function hostTestAndScriptViolations() { + const files = execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', + 'apps/host/'], { cwd: ROOT, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }).split('\0'); + const violations = []; + for (const file of files) { + if (!/\.(?:[cm]?[jt]sx?|sh|bash|zsh|py|ps1|bat|cmd)$/i.test(file)) continue; + if (!/(?:^|\/)(?:scripts|__tests__|__fixtures__|fixtures?|tests?|test-support|e2e)\//.test(file) + && !/(?:\.(?:test|spec|selftest|e2e)\.|[.-]fixture\.|(?:^|\/)(?:break(?:s|-it)?|mutation)[.-])/.test(file)) continue; + const fullPath = path.join(ROOT, file); + if (!existsSync(fullPath)) continue; + const source = readFileSync(fullPath, 'utf8'); + if (!/\b(?:pathname|pkill|killall|pgrep|pidof|taskkill(?:\.exe)?|Stop-Process|Get-Process)\b/i.test(source)) continue; + const hit = (index, message = '只能结束本次启动并记录了 PID 的进程') => violations.push(file + ':' + (1 + lineOf(source, index)) + ' — ' + message); + if (!/\.[cm]?[jt]sx?$/.test(file)) { + for (const match of source.matchAll(/^.*$/gm)) { + if (!/^\s*#/.test(match[0]) && terminatesByName(match[0])) hit(match.index); + } + continue; + } + const ts = typescript ??= requireDesktop('typescript'); + const ast = parseTestSource(ts, source); + const visit = node => { + if (readsFileUrlPathname(ts, node)) hit(node.getStart(ast), '文件 URL 转为本地路径请使用 fileURLToPath'); + if (ts.isStringLiteralLike(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) { + // Reading a generated command, checking a command name in a fake, and + // naming a test do not execute commands against the machine. + const parent = node.parent; + const callee = ts.isCallExpression(parent) ? parent.expression.getText(ast) : ''; + if (/^(?:it|test|describe)(?:\.|$)|\.(?:includes|toContain|toBe|endsWith|startsWith)$/.test(callee) + || ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken) return; + const command = node.text.trim(); + const taskkillByName = /(?:^|[/\\])taskkill(?:\.exe)?$/i.test(command) && ts.isCallExpression(parent) + && parent.arguments[0] === node && /['"]\/{1,2}im['"]|['"]\/{1,2}fi['"]\s*,\s*['"](?:imagename|windowtitle|services|modules)\b/i.test(parent.arguments[1]?.getText(ast) ?? ''); + if (PROCESS_TOOL.test(command) || terminatesByName(command) || taskkillByName) hit(node.getStart(ast)); + } + ts.forEachChild(node, visit); + }; + visit(ast); + } + return violations; +} + async function loadGuardFiles(root) { const configUrl = pathToFileURL(path.join(root, 'scripts', 'test-workspaces.config.mjs')); const { default: manifest } = await import(configUrl.href); @@ -1422,6 +1501,11 @@ export async function main(args = process.argv.slice(2)) { return 1; } } + const hostViolations = hostTestAndScriptViolations(); + if (hostViolations.length) { + for (const violation of hostViolations) console.error('[test-hygiene] ' + violation); + return 1; + } const counts = await scanRepository(); const { violations, tightenable } = compareWithBaseline(counts, baseline); if (args.includes('--update')) { From efa9a32054e0ad2e34817ede169bbd950ec97a11 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:35:23 +1300 Subject: [PATCH 2/9] fix(host): declare unsupported remote Pi and ACP ports Keep SSH Pi endpoint probing and plugin engine switching unavailable on the Node Host while completing the shared port bindings. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- apps/host/src/agent/agent-deps-engines.ts | 1 + apps/host/src/agent/runtime-selection.ts | 3 +++ apps/host/src/agent/runtime.ts | 1 + 3 files changed, 5 insertions(+) diff --git a/apps/host/src/agent/agent-deps-engines.ts b/apps/host/src/agent/agent-deps-engines.ts index 5663d0f39b4..cf7c668efe8 100644 --- a/apps/host/src/agent/agent-deps-engines.ts +++ b/apps/host/src/agent/agent-deps-engines.ts @@ -61,6 +61,7 @@ export const PORTS_ONLY_PI_READS = { mutatePiManagedPackage: undefined, onPiManagedPackageMutationSettled: undefined, preparePiExtraSpawnConfig: undefined, + probeRemotePiProviderEndpoint: undefined, registerPiProxySession: undefined, remotePiSkipMcpBridge: undefined, resolvePiAgentHome: undefined, diff --git a/apps/host/src/agent/runtime-selection.ts b/apps/host/src/agent/runtime-selection.ts index 857e2e4393f..5ab75fb9456 100644 --- a/apps/host/src/agent/runtime-selection.ts +++ b/apps/host/src/agent/runtime-selection.ts @@ -374,6 +374,9 @@ export function createHostRuntimeSelection(deps: HostRuntimeSelectionDeps) { resolveProviderGroupTarget: undefined, assertAgentDeviceRouteUsable: undefined, describeAgentDevice: undefined, + // Plugin engines are only assembled on the desktop. The switch handler rejects ACP without admission. + admitPluginEngineTarget: undefined, + describePluginEngine: undefined, resolveHandoffWindow: async ({ sessionId, agent, model, providerId, agentDeviceId }) => { if (agentDeviceId) return null; const budget = await deps.readStoredSessionContextWindowBudget(sessionId); diff --git a/apps/host/src/agent/runtime.ts b/apps/host/src/agent/runtime.ts index 2183a76c7ef..e0d57767a9d 100644 --- a/apps/host/src/agent/runtime.ts +++ b/apps/host/src/agent/runtime.ts @@ -945,6 +945,7 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { getRemotePiAgentProxyEnv: undefined, getRemotePiFileOps: undefined, getRemotePiTransport: undefined, + probeRemotePiProviderEndpoint: undefined, remotePiSkipMcpBridge: undefined, resolveRemotePiBinaryPath: undefined, // Not bound on the desktop either (pi-host.ts takes it as an option, maker-host/index.ts passes none): From 8b829821a70ba673dc8ba36aa0be62368e1b05e1 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:42:13 +1300 Subject: [PATCH 3/9] fix(host): retain failed reply writes across profile release A failed disposal leaves the old executor in place. Closing fences new input but permits another disposal; a later clean scan retries the original owner-scoped history writes and only rebuilds the runtime when disposal succeeds. Reopen from the desktop-written queue snapshot without replaying the old queue. Keep writes paused while storage fails and report the existing persistence error in the queue projection and request refusal. Retry at the existing scan cadence. Account-boundary disposal still retires the old runtime and closes its storage even if draining fails, so old-owner writes never follow a new owner. Cover release failure and recovery through the real input queue, and pin the shared switch handler refusal when Host leaves ACP admission unbound. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- apps/host/src/agent/input-queue.mjs | 44 ++++++++---- apps/host/src/agent/input-queue.test.mjs | 85 ++++++++++++++++++++++++ apps/host/src/agent/turn-executor.mjs | 26 ++++++-- apps/host/src/main.ts | 8 +-- 4 files changed, 141 insertions(+), 22 deletions(-) diff --git a/apps/host/src/agent/input-queue.mjs b/apps/host/src/agent/input-queue.mjs index 2e0daaf9291..fef1f65dd3d 100644 --- a/apps/host/src/agent/input-queue.mjs +++ b/apps/host/src/agent/input-queue.mjs @@ -205,6 +205,9 @@ export function createInputQueue(deps) { } function persist(id, snapshot) { const state = stateFor(id); + // A held runtime being replaced must not publish its old queue over the + // desktop's snapshot. Writes already in flight still have to settle. + if (closing && profileHold && !ownerStopping) return state.writing; state.snapshot = snapshot; const writing = state.writing.catch(() => {}).then(() => { assertCurrent(); return deps.persistQueueSnapshot?.(id, snapshot); }); state.writing = writing; @@ -375,6 +378,7 @@ export function createInputQueue(deps) { const state = stateFor(id); const admission = state.admission; const result = state.commands.catch(() => {}).then(async () => { + if (closing && !ownerStopping) refuseWhileHeld(); if (closing || state.closed) throw new Error('session is closed'); assertCurrent(); await coordinator.ensureQueueRestored(id); @@ -515,7 +519,14 @@ export function createInputQueue(deps) { }), enqueueDurableWrite: (id, label, fn) => command(id, () => executor.enqueueDurableWrite(id, label, fn)), projection: id => project(coordinator.getProjection(id)), - getProjection: id => command(id, () => api.projection(id)), + async getProjection(id) { + // The held runtime can still show the write failure after disposal has started. + if (closing && profileHold && !ownerStopping && states.has(id)) { + assertCurrent(); + return api.projection(id); + } + return command(id, () => api.projection(id)); + }, inputStatus: (id, clientId) => command(id, async () => { const projection = api.projection(id); // Before the recovery point below: during context recovery the claimed input is the recovery @@ -673,14 +684,18 @@ export function createInputQueue(deps) { }, settleAndWake, retryTurnSettlement, canSettleTurnControls: () => !ownerStopping && !closing && profileHold === null, - async dispose() { + async dispose(canRetryPersistence) { + const retry = closing ? canRetryPersistence : undefined; closing = true; // No runtime is released while this owner's runtime drains and stops. idleRelease?.stop(); // Recoveries in flight end as failures and write their error rows first (bounded), // before their tasks are stopped; a stop would read as the user's and drop the error. await executor.drainRecoveriesForShutdown(); - const settled = await Promise.allSettled([...states.keys()].map(async id => { + const settled = await Promise.allSettled([...states].map(async ([id, state]) => { + // A failed snapshot was already reported. Wait for it, but do not replay the + // old queue over the desktop's durable snapshot when rebuilding after a hold. + if (retry) state.writing = state.writing.catch(() => {}); try { await stop(id); } finally { coordinator.onSessionClosed(id); @@ -688,7 +703,7 @@ export function createInputQueue(deps) { // runtime. Keep its temporary inputs until a confirmed close or // the next process's orphan sweep; a finally cleanup could delete // files still held by that runtime. - try { await executor.close(id); await attachments?.closeSession(id); } + try { await executor.close(id, retry); await attachments?.closeSession(id); } finally { await flushed(id); } } })); @@ -739,6 +754,7 @@ export function createInputQueue(deps) { } }; api.isHeldForDesktop = () => profileHold !== null; + api.profileHoldMessage = () => profileHold?.message ?? null; api.profileHoldGeneration = () => profileHoldGeneration; /** * The desktop is gone: open again only once no turn runs (false: still held, ask again later). The @@ -749,17 +765,19 @@ export function createInputQueue(deps) { let releasing = null; async function release() { if (ownerStopping || runtime.hasRunningTurns()) return false; - // The hold ends between the two runtimes: no read of the new one is held by mistake. When the - // old one cannot be disposed, the new one stays held and the next clean scan tries again. + // Keep the old executor and its failed history writes until the next clean scan can drain them. const released = profileHold; - let disposed = false; - try { await runtime.dispose(); disposed = true; } - // A desktop that came back meanwhile replaced the hold: that one stays. - finally { - if (disposed && !ownerStopping && profileHold === released) profileHold = null; - runtime = createRuntime(); - if (ownerStopping) runtime.beginStop(); + const sameHold = () => !ownerStopping && profileHold === released; + try { + await runtime.dispose(sameHold); + } catch (error) { + if (sameHold()) released.message = errorText(error instanceof AggregateError ? error.errors[0] ?? error : error); + throw error; } + // A desktop that came back meanwhile replaced the hold: that one stays. + if (sameHold()) profileHold = null; + runtime = createRuntime(); + if (ownerStopping) runtime.beginStop(); if (profileHold === null) { runtime.startIdleRelease(); for (const id of deps.deferredTurnSettlements?.() ?? []) { diff --git a/apps/host/src/agent/input-queue.test.mjs b/apps/host/src/agent/input-queue.test.mjs index ba81f059aab..32a3ba4a404 100644 --- a/apps/host/src/agent/input-queue.test.mjs +++ b/apps/host/src/agent/input-queue.test.mjs @@ -3782,6 +3782,20 @@ test('model change at send: the context rollover resumes a released Pi task to r 'the released runtime is resumed to read its window'); }); +// Production entry: the Host's switchAgent handler leaves the task and its pending choice unchanged. +// Basis: #11629, Host has no ACP runtime. The desktop's tests only reject with the admission port bound. +// Minimal input (unit): a local Claude task and a valid plugin engine route, using the real Host handler. +test('switching to a plugin engine is unsupported on the Host', async t => { + const r = await modelChangeRuntime(t); + await r.createTask('switch-to-acp'); + await assert.rejects(r.selection.switchAgent({ + sessionId: 'switch-to-acp', targetAgentKind: 'acp', model: 'deepseek-v4', + providerId: 'acp-plugin:_ns__local__dsh-acp:dsh', + }), { code: 'UNSUPPORTED_CAPABILITY', message: '[UNSUPPORTED_CAPABILITY] plugin engines are not available here' }); + assert.equal(r.row('switch-to-acp').agent_kind, 'cc'); + assert.equal(r.selection.projectIntent('switch-to-acp') ?? null, null); +}); + // Rule (sessionAgentSwitchHandler.ts applyPendingAgentSwitchIfIdle: a user's engine pick that fails // to land does not stop the send; only a same-engine pick, an Agent's pick or a change of computer // throws): the send goes on with the task's current engine, and the pick stays for the next send, @@ -7268,6 +7282,77 @@ test('profile hold: the desktop answered one queued input meanwhile; reopened, t assert.deepEqual(h.maker.sessions.get('held').sent, ['still waiting']); }); +// Production entry: enqueue a turn and releaseDesktopHold as the profile monitor does; +// the saved history must contain the original reply once, with no second provider send. +// Basis: #11629, a failed dispose discarded the only copy of the reply and its retry. +// Gap: the manual Resume test never disposes and rebuilds the runtime. +// Minimal input: one failed assistant write, one failed release, then storage recovers. +// Tier: unit, with the real queue and executor and an injected history writer; 4.53 s for the targeted file run. +test('profile hold: a failed release keeps the reply for the next release to save', async t => { + const id = 'held-reply'; + let diskFull = true; + const saved = []; + const h = createHarness({ persistMessage: async (_id, message) => { + if (message.role === 'assistant' && diskFull) throw new Error('disk full'); + saved.push(message); + } }); + t.after(async () => { diskFull = false; await h.queue.dispose(); }); + + await enqueue(h, id, { clientId: 'one', text: 'run once' }); + const session = h.maker.getSession(id); + session.emit({ type: 'text', data: { text: 'the original reply', isFinal: true } }); + session.emit({ type: 'done' }); + await waitFor(() => !h.queue.isTurnRunning(id)); + assert.equal(h.queue.projection(id).error, 'disk full'); + + h.queue.holdForDesktop(HELD); + await assert.rejects(h.queue.releaseDesktopHold(), /Failed to drain task persistence/); + assert.equal(h.queue.isHeldForDesktop(), true); + const service = createHostService({ profileHold: h.queue.profileHoldMessage }); + const writeRefusal = { code: 'PRECONDITION_FAILED', message: '[PRECONDITION_FAILED] disk full' }; + await assert.rejects(service('/api/input/enqueue'), writeRefusal); + await assert.rejects(h.queue.enqueue(id, { clientId: 'two', text: 'blocked until storage recovers' }), writeRefusal); + const paused = await h.queue.getProjection(id); + assert.equal(paused.queuePaused, true); + assert.equal(paused.error, 'disk full'); + await assert.rejects(h.queue.releaseDesktopHold(), /Failed to drain task persistence/, 'an unsuccessful retry keeps the queue held'); + diskFull = false; + assert.equal(await h.queue.releaseDesktopHold(), true); + assert.equal(h.queue.profileHoldMessage(), null); + assert.deepEqual(saved.filter(row => row.role === 'assistant').map(row => row.content), ['the original reply']); + assert.deepEqual(session.sent, ['run once']); +}); + +// Production entry: enqueue and releaseDesktopHold; the rebuilt queue must show the desktop's snapshot. +// Basis: the desktop can edit the shared queue while it holds the profile. The reply-replay test +// does not cover queue snapshot write failures. Minimal input (unit): one rejected enqueue write +// followed by one input durably queued by the desktop. +test('profile hold: release retry restores the durable queue after a failed snapshot write', async t => { + const id = 'held-snapshot'; + let saved = []; + let fail = true; + const h = createHarness({ + loadQueueSnapshot: async () => saved, + persistQueueSnapshot: async (_id, items) => { + if (fail) throw new Error('disk full'); + saved = items; + }, + }); + t.after(() => h.queue.dispose()); + + await assert.rejects(h.queue.enqueue(id, { clientId: 'not-saved', text: 'not saved' }), /disk full/); + h.queue.holdForDesktop(HELD); + await assert.rejects(h.queue.releaseDesktopHold(), /Failed to drain task persistence/); + fail = false; + saved = [{ clientId: 'desktop', text: 'from the desktop', persistedContent: 'from the desktop', + model: 'stored-model', workingDir: '/tmp', effort: '', permissionMode: 'ask', + chatMessage: { clientId: 'desktop', role: 'user', content: 'from the desktop' }, + createOpts: { agentKind: 'claude-code', model: 'stored-model', workingDir: '/tmp' } }]; + assert.equal(await h.queue.releaseDesktopHold(), true); + assert.deepEqual((await h.queue.getProjection(id)).pendingQueue.map(item => item.clientId), ['desktop']); + assert.deepEqual(saved.map(item => item.clientId), ['desktop']); +}); + test('profile hold: a durable queue restored while held stays unsent, and resume is refused', async t => { const h = durableHold(t); // A queue saved before this runtime read it (a restart, or another process). diff --git a/apps/host/src/agent/turn-executor.mjs b/apps/host/src/agent/turn-executor.mjs index 86048f87785..91806e7fff0 100644 --- a/apps/host/src/agent/turn-executor.mjs +++ b/apps/host/src/agent/turn-executor.mjs @@ -153,6 +153,15 @@ export function createTurnExecutor(deps) { return history; } + async function retryHistoryWrites(id, history, turn) { + await history.retryFailedWrites(); + if (turn) turn.persistenceError = null; + if (turn?.terminal && !turn.interruptedByShutdown) { + deps.assertCurrent(); + await deps.markEnded?.(id, turn.endedAt); + } + } + // The Git baseline of one turn, settled as the desktop's event delivery settles it // (sessionEventDelivery.ts: a done takes the after-edit savepoint, a terminal error cancels the // baseline), each at most once for this turn of this instance. A failed turn that reports its @@ -1459,17 +1468,24 @@ export function createTurnExecutor(deps) { if (!turn) return; const history = historyFor(id); await history.drain(); - await history.retryFailedWrites(); - turn.persistenceError = null; - if (turn.terminal && !turn.interruptedByShutdown) { deps.assertCurrent(); await deps.markEnded?.(id, turn.endedAt); } + await retryHistoryWrites(id, history, turn); }, - async close(id) { + async close(id, canRetryPersistence) { deps.interactions?.detach(id); const turn = turns.get(id); await turn?.settlement; const history = histories.get(id); await history?.drain(); - if (history?.hasFailedWrites()) throw new Error(turn?.persistenceError || 'Reply persistence is incomplete'); + if (history && (history.hasFailedWrites() || (canRetryPersistence && turn?.persistenceError))) { + if (!canRetryPersistence?.()) throw new Error(turn?.persistenceError || 'Reply persistence is incomplete'); + deps.assertCurrent(); + try { await retryHistoryWrites(id, history, turn); } + catch (error) { + if (turn) turn.persistenceError = errorText(error); + deps.onPersistenceError(id, error); + throw error; + } + } releaseBinding(id); bindings.get(id)?.unsubscribe(); bindings.delete(id); diff --git a/apps/host/src/main.ts b/apps/host/src/main.ts index 2ab4a9871ac..3b2ade42f49 100644 --- a/apps/host/src/main.ts +++ b/apps/host/src/main.ts @@ -1479,8 +1479,8 @@ const serverDeps = { // The HTTP logout's first step, before it closes the platform client and drains requests (server.mjs). beginOwnerBoundaryStop: () => ownerBoundary.begin(), // Coexistence plan A: while a desktop uses this profile, only reads, stops and answers reach the - // handlers (service.mjs HOST_PATHS_ALLOWED_WHILE_HELD); the rest get this refusal. - profileHold: () => (inputQueue.isHeldForDesktop() ? profileInUseMessage() : null), + // handlers (service.mjs HOST_PATHS_ALLOWED_WHILE_HELD). A failed release reports its write error. + profileHold: inputQueue.profileHoldMessage, browserBackend: (handler: keyof NonNullable['browserSettings'], payload: unknown) => { if (!platformTools) throw new Error('HOST_RUNTIME_NOT_READY'); return platformTools.browserSettings[handler](undefined, payload); @@ -1898,7 +1898,7 @@ const serverDeps = { }, chat: createChatHandler({ readSession: (id: string) => sessionStorage?.get(id), - profileHold: () => (inputQueue.isHeldForDesktop() ? profileInUseMessage() : null), + profileHold: inputQueue.profileHoldMessage, createSession: (body: Record) => serverDeps.createSession(body), enqueue: enqueueUserInput, inputStatus: (id: string, clientId: string) => inputQueue.inputStatus(id, clientId), @@ -2239,7 +2239,7 @@ function startDeviceLink(): void { }, // The Device Link create entry, with the runtime start admission (agent/create-runtime-session.ts). // Coexistence plan A: a new task's runtime and a plugin page's calls are refused while held (device-link.ts). - profileHold: () => (inputQueue.isHeldForDesktop() ? profileInUseMessage() : null), + profileHold: inputQueue.profileHoldMessage, createRuntimeSession: input => { return createHostRuntimeSession(explicitPorts({ serverDeps, From 43d4a1b1f052e6de41325423956616f87517e026 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:42:16 +1300 Subject: [PATCH 4/9] docs(host): record release review findings Record the remote Pi probe, the M1 limit for ACP engines, and the scope of the owned Windows reproduction. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- docs/host/personal-migration-release-table.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/host/personal-migration-release-table.md b/docs/host/personal-migration-release-table.md index 6867007eaa5..f8a268f34d7 100644 --- a/docs/host/personal-migration-release-table.md +++ b/docs/host/personal-migration-release-table.md @@ -101,6 +101,7 @@ | 项 | 桌面 | Host | 后果 | |---|---|---|---| +| 插件引擎(ACP,2026-11-20) | 2026-11-19 起,主干 `95158bc18f`、`3178ad31f3`、`5dbf2a58c3` 等支持从本机插件选引擎、新建和切换任务,并支持插件引擎上的协作 Worker | M1 不装配 ACP 引擎。新建 ACP 任务由 `agent/start-options.ts` 的 `requireBuiltinAgentKind` 拒绝;切换到 ACP 返回 `UNSUPPORTED_CAPABILITY` | 用户无法在 Cindy 后台服务上新建插件引擎任务或把已有任务切换到插件引擎。改用内置引擎,或在独立运行的桌面端使用。Host 装配留到 M1 之后,具体阶段待定。 | | 桌面占用期间的插件静默(2026-11-19) | 桌面上的插件照常运行 | Host 暂停逻辑页和插件 Node 进程,保留分区与安装批准。手机和远程端连着 Host 时插件暂不可用,插件工具与宿主请求返回服务层相同的 `PRECONDITION_FAILED`。有意关页时,待决钩子按静默失败收口且不计熔断。这是 8i「受理后失页等截止」的例外,意外失页仍等原截止。用户和助手消息钩子没有 `onFailure`,暂停时跳过询问并沿用既有放行 | 正在执行的插件工具调用会中断,调用方收到「结果不确定」,重试前需要核对。在途回合的输出不会经过消息钩子改写或拦截。已有插件终端保持运行,占用期间不新开。占用期间的旁听事件直接丢弃。占用前已缓冲的事件等下一条事件再送。Host 未使用桌面的 `preparePublish` 会话切换去重调用点。 | | 桌面占用期间的发现延迟(2026-11-19) | 桌面没有占用闸门 | 占用靠每 10 秒重扫加目录监听(去抖 250 毫秒)发现,从桌面开库到后台服务察觉最长约十秒,这期间后台服务照常读写 | 这是整个并存方案的真实边界。入口检查之后才开始的占用,可能留下一个空任务行或空对话目录,与发现延迟同类,不单独处理 | | 桌面占用期间不经 service 的入口(2026-11-19) | 桌面没有占用闸门 | `server.mjs` 自己应答的入口逐个分类,根目录源码契约 `scripts/__tests__/host-server-hold-classification.test.mjs`(`pnpm test:runner` 执行)守护,新增入口没登记就失败。**拒绝**:开启远程控制、开关 Agent-Net(入口与设置锁内各查一次);`/chat` 为不存在的任务建任务(读完任务、建任务前同步查一次;新任务在开流前被拒,返回 500 与 `chat_failed` 事件,与任务不存在时相同;已存在任务在开流后被队列拒,返回 200 与同一事件,这是原有行为)。**登记例外**:关闭远程控制、撤销控制设备,写 profile 根的 `device-link-settings.json`,与桌面同一份文件、同一把跨进程锁,正在运行的桌面每 5 秒轮询跟随:关闭会断开桌面当前所有控制链路,撤销会断开对应设备;写之前先走两端共用的分享可用性策略,有登记时向账号区域的服务停用对应分享的可用性,并从共用的 `provider-share-availability.json` 移除登记。占用期间后台服务的远程控制仍在线,已授权的控制端仍能读,撤销在这时有实际用处;只有本机持后台服务令牌的客户端能触发。登出:持账号库跨进程锁更新共用账号库与登出标记,删除登录令牌记录。`/control/stop`:关停收尾,排空队列、在途用量入库、有条件写错误行。**不写共用数据**:`/control/attachment`、`/control/platform`、`/web/pair`、`/web/session`、`/events` 与读接口、IPC 现有只读绑定。Agent-Net 设备身份是后台服务自己的记录 | 占用期间在后台服务登出:桌面不会立即登出,最迟在下次续期时(通常在令牌到期前五分钟,鉴权失败可提前)回到登录页并提示“本机的登录凭证已失效(可能是同一台设备上的其他实例退出了登录),请重新登录。”,同时停止该账号仍在跑的任务;在此之前桌面仍用内存里的令牌工作。用户 2026-11-19 定:保持允许。结构性的改法(服务器层对占用期间的写请求统一默认拒绝)登记为待办,不在第一阶段 | @@ -437,7 +438,7 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | 带界面的验证 | 用户已允许(隔离沙箱、复用 host-usage);2e 之前客户端模式只做导航与读取 | | 测试纪律:会碰到 Codex 登录的运行 | host-usage 沙箱的 codex-home/auth.json 链着本机真实的 Codex 登录,Host 在那里走到 Codex、订阅桥或作废逻辑就可能经链接改写它。凡是会让这些跑起来的运行,一律用 HOME 隔离、假登录的 profile;host-usage 只做不触发这些路径的只读检查,拿不准就不用 | | 合并 main 之后的核对 | 每次合并 main,检查这次合并改到的桌面函数里有没有 Host 重写过的对应实现(范围是 C3 盘点的丙类清单),有就在汇报里列出并跟上(审核方 m1-cp18e 定)。m1-cp18e 对本分支已有的合并补查:`d142106052` 已跟上,`b1c5d88705` 见第二节「引擎二进制的路径」,`c783b679b9` 属 M2 的供应商视图,`73270d8f06`(Codex 线程历史目录)归 m1-cp18d。2026-11-17 合并 main(落后 243 个提交,合到 fb2b13ab5d):改到 Host 重写过的桌面函数的有四个提交——`e322628568` 给共用的工作目录恢复加了端口 `canRecreateDirectory`(只在当前 owner 的命名空间里重建),Host 没绑,已跟上(`agent/working-directory.ts`,测试 `input-queue.test.mjs`“another owner's namespace”);`b276229eae`(本机代理路由就绪后再启动)提交本身已改了 Host 的 `runtime.ts`;`c743604b79`(只读开发快照复用)只改桌面 `auth-adapters.ts` 与 `codex-auth-link.ts` 内部,Host 用的 `codex-auth-link` 导出没变;`d4a65f3cd1` 只动历史读取,与 Host 重写无关 | -| 显式端口(2026-11-17,起因 main `e322628568`) | Host 传给共用工厂的端口一律经 `explicitPorts()`(`agent/explicit-ports.ts`):T 的每个可选端口都要写出来,接真或写 `undefined` 并注明为什么可以不绑;桌面以后新加可选端口,Host 在绑定处类型检查报错。已覆盖 `working-directory.ts`、`runtime-selection.ts`、`context-recovery-assembly.ts`、`context-recovery.ts`、`context-usage.ts`(32 处调用、6 个带类型的端口对象);检查点 4 新接的工厂直接这样写。这一遍查出的未绑可选端口与结论:换引擎处理器的五个换电脑端口(乙 5,Host 入口拒绝,走不到);上下文恢复的伙伴会话清单(Host 不跑伙伴)、订阅账号的原生会话交接(第 30 行,Host 未做发送前换号);上下文恢复的冷启动 Pi 窗口核实——桌面把同一个绑定给了改模型与恢复两处,Host 只给了改模型,已接真(`fc3a113f03`,测试“the context rollover resumes a released Pi task”)。memory.mjs 一批(2026-11-17):记忆管理器的端口包挪到 `agent/memory-manager-ports.ts`(第 11 行);cindy_memory 的 `memory` 依赖(`createHostMemoryMcpProviders`)也已挪到 `agent/memory-mcp-ports.ts`,经 `explicitPorts`(2026-11-17):`searchSessions` 接真(第 11 行);`searchProviders`(插件提供的记忆,第 33 行)、`beginWrite`(只记伙伴学习)、`getSessionContext`(provider 按任务自己补)写 `undefined`;`withAccountDataAccess` 接真(照抄桌面,第七节第 26 项;审核方 2026-11-17 定甲类)。其余 Host 文件尚未改写:类型扫描(scratchpad 脚本,按上下文类型找桌面或共用包里声明的可选成员)在 Host 其余文件里还有约 200 个对象字面量留着未写的可选成员,多数是每次调用的选项或数据形状,不是端口;待按“端口包”筛出后分批改写。runtime.ts 一批(2026-11-17):三个引擎的 AgentDeps 与 Maker 的 MakerDeps、生命周期钩子都经 `explicitPorts`。AgentDeps 是三个引擎共用的一个接口(87 个可选端口),按 maker-core 里哪个引擎的代码读它归类(`agent/agent-deps-engines.ts`:只有 Codex 读的 30 个、只有 Pi 读的 27 个、只有 Claude 读的 13 个、Claude 与 Pi 读的 2 个、Claude 与 Codex 读的 2 个;基类读的 13 个算三个引擎都读),每个引擎的端口包先写进别的引擎才读的那几组,再写自己读的每一个;引擎保存传入的对象原样、成员一律用 `?.` 或 `??` 读,所以显式写 `undefined` 与不写相同。条件展开改成直接写值(`getManagedSkills`、`getGhostRosterPrompt`、`makerMemory`、`resolveLocalMcpDuplicateChoices`、`registerPiProxySession`、`mcpProviders`);Codex 运行时的端口包改按字面量定型(原来是 `Partial`,会把所有键都算成已写),MCP 运行时的两包改为 `Required>`。这一遍查出、桌面绑了而 Host 没绑的端口与结论:远程执行那一组(Claude 3 个、Codex 2 个、Pi 7 个,含远端 Pi 的代理令牌派生)——send-preflight 拒绝远程任务(第七节第 18 行);伙伴的会话环境(第四节,M3);SkillHub 发现隔离(第四节,M2);Codex 的 Skill 投影(第 25 行)与 host-tools-only 工具目录(第 29 行);Pi 的项目信任输入——桌面也没绑(`pi-host.ts` 收这个选项,`maker-host/index.ts` 不传),两边一样;换电脑启动 Agent(乙 5);生命周期的 `onStartSucceeded`(桌面只做协同与伙伴的事)与 `isTransientCloseRequest`(只让瞬态重建跳过暂存附件与工作树池的清理,Host 的 onClose 没有这两样);Codex 的出站路径事实——当时 Host 的出站解析不记判定,记为第二节已知差别;28a 已接上(第 28 行)。真缺口一个,已接上:Codex 的服务端压缩选择(`getCodexServerCompactionPreference`),桌面每次启动 Codex 读用户在窗口里的选择,Host 原来不传、选择被忽略;现在读 owner 目录里同一个文件(测试 `engine-deps.test.mjs`“server-compaction”,改坏会红) | +| 显式端口(2026-11-17,起因 main `e322628568`) | Host 传给共用工厂的端口一律经 `explicitPorts()`(`agent/explicit-ports.ts`):T 的每个可选端口都要写出来,接真或写 `undefined` 并注明为什么可以不绑;桌面以后新加可选端口,Host 在绑定处类型检查报错。已覆盖 `working-directory.ts`、`runtime-selection.ts`、`context-recovery-assembly.ts`、`context-recovery.ts`、`context-usage.ts`(32 处调用、6 个带类型的端口对象);检查点 4 新接的工厂直接这样写。这一遍查出的未绑可选端口与结论:换引擎处理器的五个换电脑端口(乙 5,Host 入口拒绝,走不到);上下文恢复的伙伴会话清单(Host 不跑伙伴)、订阅账号的原生会话交接(第 30 行,Host 未做发送前换号);上下文恢复的冷启动 Pi 窗口核实——桌面把同一个绑定给了改模型与恢复两处,Host 只给了改模型,已接真(`fc3a113f03`,测试“the context rollover resumes a released Pi task”)。memory.mjs 一批(2026-11-17):记忆管理器的端口包挪到 `agent/memory-manager-ports.ts`(第 11 行);cindy_memory 的 `memory` 依赖(`createHostMemoryMcpProviders`)也已挪到 `agent/memory-mcp-ports.ts`,经 `explicitPorts`(2026-11-17):`searchSessions` 接真(第 11 行);`searchProviders`(插件提供的记忆,第 33 行)、`beginWrite`(只记伙伴学习)、`getSessionContext`(provider 按任务自己补)写 `undefined`;`withAccountDataAccess` 接真(照抄桌面,第七节第 26 项;审核方 2026-11-17 定甲类)。其余 Host 文件尚未改写:类型扫描(scratchpad 脚本,按上下文类型找桌面或共用包里声明的可选成员)在 Host 其余文件里还有约 200 个对象字面量留着未写的可选成员,多数是每次调用的选项或数据形状,不是端口;待按“端口包”筛出后分批改写。runtime.ts 一批(2026-11-17):三个引擎的 AgentDeps 与 Maker 的 MakerDeps、生命周期钩子都经 `explicitPorts`。AgentDeps 是三个引擎共用的一个接口(87 个可选端口),按 maker-core 里哪个引擎的代码读它归类(`agent/agent-deps-engines.ts`:只有 Codex 读的 30 个、只有 Pi 读的 27 个、只有 Claude 读的 13 个、Claude 与 Pi 读的 2 个、Claude 与 Codex 读的 2 个;基类读的 13 个算三个引擎都读),每个引擎的端口包先写进别的引擎才读的那几组,再写自己读的每一个;引擎保存传入的对象原样、成员一律用 `?.` 或 `??` 读,所以显式写 `undefined` 与不写相同。条件展开改成直接写值(`getManagedSkills`、`getGhostRosterPrompt`、`makerMemory`、`resolveLocalMcpDuplicateChoices`、`registerPiProxySession`、`mcpProviders`);Codex 运行时的端口包改按字面量定型(原来是 `Partial`,会把所有键都算成已写),MCP 运行时的两包改为 `Required>`。这一遍查出、桌面绑了而 Host 没绑的端口与结论:远程执行那一组(Claude 3 个、Codex 2 个、Pi 7 个,含远端 Pi 的代理令牌派生)——send-preflight 拒绝远程任务(第七节第 18 行);2026-11-20 补记:主干 `f09ceba136` 新增 Pi 专读的 `probeRemotePiProviderEndpoint`,只在 SSH 路线上探测 BYOM 地址,Host 同样显式留空;伙伴的会话环境(第四节,M3);SkillHub 发现隔离(第四节,M2);Codex 的 Skill 投影(第 25 行)与 host-tools-only 工具目录(第 29 行);Pi 的项目信任输入——桌面也没绑(`pi-host.ts` 收这个选项,`maker-host/index.ts` 不传),两边一样;换电脑启动 Agent(乙 5);生命周期的 `onStartSucceeded`(桌面只做协同与伙伴的事)与 `isTransientCloseRequest`(只让瞬态重建跳过暂存附件与工作树池的清理,Host 的 onClose 没有这两样);Codex 的出站路径事实——当时 Host 的出站解析不记判定,记为第二节已知差别;28a 已接上(第 28 行)。真缺口一个,已接上:Codex 的服务端压缩选择(`getCodexServerCompactionPreference`),桌面每次启动 Codex 读用户在窗口里的选择,Host 原来不传、选择被忽略;现在读 owner 目录里同一个文件(测试 `engine-deps.test.mjs`“server-compaction”,改坏会红) | | 验证纪律:Host 类型检查的堆 | 本机跑 `NODE_OPTIONS=--max-old-space-size=8192 pnpm --filter @cindy/host typecheck`(与 CI 相同;12288 也可);不设时默认堆会 OOM(rc 134)。CI(`.github/workflows/ci.yml`)的 Host 作业不单独设,靠工作流全局的 `NODE_OPTIONS: '--max-old-space-size=8192'`;发布 Host PR 前若工作流的全局值改了,要回头核 | | 验证纪律:改 Host 文件时连读 Host 文件的桌面测试一起跑(2026-11-17) | 桌面有 36 个测试文件读 `apps/host` 的源码(guard 层的 `hostDesktopSourceContracts.guard.test.ts` 等,清单用 `grep -rlE "apps/host\|hostAgent\|host/src" apps/desktop/src --include="*.test.ts"` 取)。显式端口那一批(`70ae7d471c`)只跑了 Host 全量,漏了其中一条 guard(`40dd1413de` 补)。以后凡改 Host 文件,交付前连这批一起跑 | | 准备分支与集成分支的桌面差异(2026-11-19) | 两个分支之间 `apps/desktop` 和 `packages` 只差三个只在集成分支的桌面测试文件:`src/main/__tests__/authColdStartRecovery.test.ts`、`hostDesktopSourceContracts.guard.test.ts` 读 Host 源码;`cindy-brain/__tests__/hostToolSlot.test.ts` 不读 Host 源码,是随第七节第 44 项新增的静默端口补桌面测试夹具一行(2026-11-19 复查更正)。它们要配集成分支上的 Host 代码,所以只留在集成分支。落地核对时以这三个文件为准,Host PR 正文写明 | @@ -465,7 +466,7 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 | 主干同步 5 之后的验证(2026-11-19) | 主干钉在 `5a92f62d24`,集成分支 `7b068f570a`、准备分支 `b9fa89f919`,锁文件与 `.nvmrc` 未变。**只在开发机上验证过**(用户 2026-11-19 定:本机验证通过就发,自有 macOS 的最小集在 PR 开出后补跑,结果补进来):集成分支 Host 全量 1057/0/0(带浏览器夹具)、两边类型检查 0 错误;审核方宽模式读者集合集成分支 996 个文件 30488/43/47、准备分支 991 个文件 30485/40/47,失败都是开发机已知的 38 条环境失败加 `pi-package-store-security` 的目录监听用例;同步清单读者集合两边只有 `deviceOp` 与 `omarchy` 的文件监听用例失败,主干同样失败;`vitest related`(45 个输入,`--maxWorkers=3`)两边各约 35 条失败,与主干同批对照同名的是 `runtime.integration` 21 条、两条数据库夹具、文件监听与并发超时,另有几条只在某一边整批出错、单独复跑通过(例如 `GhostManager.test.ts` 一条钩子超时,文件与主干相同),属并发下不稳定,不算已解决;`botCandidateRecovery` 两边 100/0;整串门禁两个分支都通过(集成分支 DCO 698/104、准备分支 99/18,`test:runner` 780/778)。开发机文件监听有故障,依赖监听的用例以上一轮自有 macOS 的结果和这次补跑的结果为准 | | 主干同步 6 之后的验证(2026-11-19) | 主干钉在 `3ef44274d6`,集成分支 `1dd89e2966`、准备分支 `d76c822a05`,`.nvmrc` 未变;锁文件只多桌面渲染进程的两个依赖,两个工作区按锁文件重装(本机缓存已有,没有下载),重装同时去掉了 138 个当前锁文件里已经没有的陈旧包,此后依赖与锁文件一致。**开发机验证**(用户 2026-11-19 定:本机验证通过就发):集成分支 Host 全量 1057/0/0(带浏览器夹具)、Host 类型检查与两边桌面类型检查 0 错误;审核方宽模式读者集合集成分支 1020 个文件 31330/43/53、准备分支 1015 个文件 31324/43/53,失败是开发机已知的 38 条环境失败加文件监听类(`pi-package-store-security` 4~5 条,集成分支另有 `botSkillService` 一条,上一轮自有 macOS 上两边都通过),重装前后那 38 条不变;`deepLink.ts`、`sessionDeepLink.ts` 的读者集合 13 个文件两边各 484/0,`vitest related` 两边各 16229 过 / 2 失败 / 37 跳过,失败都是 `deviceOp.test.ts` 的文件监听用例,主干同样失败;整串门禁两个分支都通过(集成分支 DCO 699/106、准备分支 99/19,`test:runner` 781/779)。开发机文件监听有故障,依赖监听的用例以上一轮自有 macOS 的结果和这次补跑的结果为准。**自有 macOS 补跑**(Apple Silicon arm64,Node 22.22.3):准备分支 `d76c822a05`、集成分支 `49b01543ef` 对照主干 `3ef44274d6`。集成分支 Host 全量 1042/0/0,lifecycle 通过;第 2 层两个浏览器文件(Chromium 1243)15/0/0,plugin-sandbox e2e 通过。桌面 unit 全量(进程池,未装 Electron),准备分支 74523 通过、47 失败、44 跳过,主干 74455 通过、47 失败、44 跳过,失败和跳过逐条相同。装 Electron 后补跑原先收集失败的 88 个文件,两边都是 2628/0/0。剩余 46 条失败两边相同,都是测试环境问题:forge 15 条(12 条是 macOS `/tmp` 软链接)、builtinGhostProvisioner 23 条、llamaCppDownloads 7 条(临时目录下 `ENOENT`)、foreignSourceAdapters 1 条。Electron 与 Pi 批:准备分支和集成分支的 claudeHosted 均 15/0/0,piGateway、piShared、piHosted、groupRelay、claudeGrok 全过;仅登记过的 codexHosted 风险命令审批、startupProbe 原生启动对比失败,主干同样失败。没有启动图形界面的 Electron。下载的 Electron 42.11.12 来自 GitHub Releases,已校验官方哈希。npm 包(含新增的两个)按锁文件的 SHA-512 校验。除此之外没有别的下载。用临时 HOME 隔离,第 1 层只放行回环网络。这一轮没有做凭据存在性探测。前提重验和接线清单见本节“主干同步 6 的 Host 接线”。 | | 主干同步 7 之后的验证(2026-11-20) | 主干钉在 `43fb1df105`,审阅副本合并 `915dcd9847`、Host 接线 `5feea98573`,锁文件与 `.nvmrc` 未变。开发机(Node 22.22.3,临时 HOME):Host 全量 1067 通过、0 失败、0 跳过(Chromium 1243),Host 类型检查和 Desktop、Mobile、Maker Core 三档守护通过,`test:runner` 781 通过、0 失败、2 跳过。桌面 `vitest related` 16,767 通过、2 失败、73 跳过,两条失败均为本机既有的 `deviceOp.test.ts` 文件监听用例,未验证。开发机离线复用缓存,补齐两份锁文件已有的 Solidity 依赖,下载 0,复跑桌面主进程与渲染进程类型检查通过。Pi 接线用例在合并后未补端口时因 `getProxy is not a function` 失败,补接后通过。PR 首轮 Ubuntu `test:lifecycle` 通过,CI 步骤约 41 秒,低于复评线 60 秒,Ubuntu 这一耗时项关闭。第三轮 CI 在 macOS 和 Windows 上等待源码 Host 写出 endpoint 耗时约 30 秒,本机两快照对照约 8 到 9 秒。`startup-account` 的两处源码启动等待因此统一为与 `test:lifecycle` 一样的 90 秒,并记录从启动到 endpoint 就绪的实测耗时。这些数据只衡量源码启动,发行包另计。Ubuntu 的凭据等待者测试过早读取异步派发结果(`206bc30b37`),已改为等待引擎收到输入,生产派发顺序与桌面一致。逐项日志见同步 7 审阅回执。 | -| PR 首轮 CI 与评审修复(2026-11-19) | ① Ubuntu、Windows 的 Codex 出站测试缺打包用 ripgrep,给测试的运行时装配注入临时搜索程序替身,正式运行的缺文件检查照旧(`7743e6f406`)。② Windows 用量记录测试删库遇到 `EBUSY`,先关两份 SQLite 句柄再清理(`a7fa893117`)。③ Windows 代理辅助进程验收脚本把空行交给 `JSON.parse`,改为只收协议帧。生产客户端已有非协议输出过滤(`d681f5252a`)。④ macOS 认证代理的拒绝路径由 `macos-system-proxy.test.mjs` 的“a proxy that names a user is unresolved, and the user is in no log or judgement”覆盖。托管 runner 的系统接口没有发布 `HTTPSUser`,CI 对照无法验证拒绝路径,将 17 条原先要求拒绝的结果记为 `skipped-precondition`。这 17 条的 Host 与 Electron 路由一致,其他 9 条也一致。⑤ 占用期间历史读取会重试未交付图片,改为解闸后只为同一打开的账号库补交付(`79a6e4b526`)。⑥ 模型清单请求发出后才开始占用时会写共享报价和账本币种,写入前复核占用,丢弃该回包,解闸后可重刷(`caf94959b0`)。⑦ 解闸重建输入运行时后恢复空闲回收,任务仍按期释放(`5d0cec971a`)。⑧ 取消的 done 原先可能给半截回复盖成功章,改用桌面的同一成功判据并保留 Codex 原始状态检查(`59ea890ff5`,见甲 9)。⑨ Windows 的 Skill 投影守护按本机分隔符生成路径,在收集时统一成 `/`(`49f68d81ef`)。⑩ macOS 的例外列表一项带逗号时,按 Chromium 148.0.7778.280 复制代理配置的规则,重解析已成功解析、带逗号或分号的主机名项,CI 保存的 26 条路由全部与 Electron 一致(`4f4e44ab8b`)。源码见 [macOS 读取器](https://github.com/chromium/chromium/blob/148.0.7778.280/net/proxy_resolution/proxy_config_service_mac.cc#L115-L143) 和 [规则复制与重解析](https://github.com/chromium/chromium/blob/148.0.7778.280/net/proxy_resolution/proxy_host_matching_rules.cc#L118-L132)。⑪ `host-server-hold-classification.test.mjs` 的 CodeQL 正则告警要求消除空白回溯歧义,元素之间改为必有逗号,改前改后收集的 25 项完全相同(`b4ca7a6873`)。DCO:#11536 初始的 806 个提交超出接口上限,线上评估失败;本机 `check:dco` 对 `3ef44274d6..49b01543ef` 验到 700 个普通提交全部签署、106 个合并豁免,对首轮修复后的 `b4ca7a6873` 验到 710 个普通提交全部签署、106 个合并豁免。#11536 的 Windows db 档首轮因 runner 自测先失败而未跑到,随这批修复推送后补跑。⑫ 本 PR 引入的 Chromium 代理辅助进程在 Windows 上启动即退出。Electron 把 `process.stdin` 设成一开始就 EOF,worker 将关闭输入视为退出,导致无法读到系统代理并按现有策略回退直连,启动仍有期限。Windows 改用子进程 IPC,沿用同一协议、就绪口径和回退策略(`9001d67bf8`)。⑬ 保留关通道、SIGTERM、SIGKILL 的顺序,辅助进程关闭等待最多 3 秒,到期记日志并返回(`a6d3182bf6`)。⑭ 验收从 spawn 时记录退出,各组即时输出结果,失败时收尾临时 PAC 服务和测试子进程。20 轮和各组的验收断言均保留,Windows 父进程退出场景覆盖 IPC 断开(`7b38ff47e3`)。⑮ Windows 验收的清理判据曾等待 Node 的进程聚合 `close`,父端主动断开 IPC 后,这个事件可能漏发,即使辅助进程已退出、stderr 已关闭。IPC 验收改等进程 `exit` 和已有 stderr 流自己的 `close`,强杀仍失败。生产一直按 `exit` 判断退出,协议、回退和关闭期限沿用(`411cc62dd7`)。 | +| PR 首轮 CI 与评审修复(2026-11-19) | ① Ubuntu、Windows 的 Codex 出站测试缺打包用 ripgrep,给测试的运行时装配注入临时搜索程序替身,正式运行的缺文件检查照旧(`7743e6f406`)。② Windows 用量记录测试删库遇到 `EBUSY`,先关两份 SQLite 句柄再清理(`a7fa893117`)。③ Windows 代理辅助进程验收脚本把空行交给 `JSON.parse`,改为只收协议帧。生产客户端已有非协议输出过滤(`d681f5252a`)。④ macOS 认证代理的拒绝路径由 `macos-system-proxy.test.mjs` 的“a proxy that names a user is unresolved, and the user is in no log or judgement”覆盖。托管 runner 的系统接口没有发布 `HTTPSUser`,CI 对照无法验证拒绝路径,将 17 条原先要求拒绝的结果记为 `skipped-precondition`。这 17 条的 Host 与 Electron 路由一致,其他 9 条也一致。⑤ 占用期间历史读取会重试未交付图片,改为解闸后只为同一打开的账号库补交付(`79a6e4b526`)。⑥ 模型清单请求发出后才开始占用时会写共享报价和账本币种,写入前复核占用,丢弃该回包,解闸后可重刷(`caf94959b0`)。⑦ 解闸重建输入运行时后恢复空闲回收,任务仍按期释放(`5d0cec971a`)。⑧ 取消的 done 原先可能给半截回复盖成功章,改用桌面的同一成功判据并保留 Codex 原始状态检查(`59ea890ff5`,见甲 9)。⑨ Windows 的 Skill 投影守护按本机分隔符生成路径,在收集时统一成 `/`(`49f68d81ef`)。⑩ macOS 的例外列表一项带逗号时,按 Chromium 148.0.7778.280 复制代理配置的规则,重解析已成功解析、带逗号或分号的主机名项,CI 保存的 26 条路由全部与 Electron 一致(`4f4e44ab8b`)。源码见 [macOS 读取器](https://github.com/chromium/chromium/blob/148.0.7778.280/net/proxy_resolution/proxy_config_service_mac.cc#L115-L143) 和 [规则复制与重解析](https://github.com/chromium/chromium/blob/148.0.7778.280/net/proxy_resolution/proxy_host_matching_rules.cc#L118-L132)。⑪ `host-server-hold-classification.test.mjs` 的 CodeQL 正则告警要求消除空白回溯歧义,元素之间改为必有逗号,改前改后收集的 25 项完全相同(`b4ca7a6873`)。DCO:#11536 初始的 806 个提交超出接口上限,线上评估失败;本机 `check:dco` 对 `3ef44274d6..49b01543ef` 验到 700 个普通提交全部签署、106 个合并豁免,对首轮修复后的 `b4ca7a6873` 验到 710 个普通提交全部签署、106 个合并豁免。#11536 的 Windows db 档首轮因 runner 自测先失败而未跑到,随这批修复推送后补跑。⑫ 本 PR 引入的 Chromium 代理辅助进程在 Windows 上启动即退出。Electron 把 `process.stdin` 设成一开始就 EOF,worker 将关闭输入视为退出,导致无法读到系统代理并按现有策略回退直连,启动仍有期限。Windows 改用子进程 IPC,沿用同一协议、就绪口径和回退策略(`9001d67bf8`)。⑬ 保留关通道、SIGTERM、SIGKILL 的顺序,辅助进程关闭等待最多 3 秒,到期记日志并返回(`a6d3182bf6`)。⑭ 验收从 spawn 时记录退出,各组即时输出结果,失败时收尾临时 PAC 服务和测试子进程。20 轮和各组的验收断言均保留,Windows 父进程退出场景覆盖 IPC 断开(`7b38ff47e3`)。⑮ Windows 验收的清理判据曾等待 Node 的进程聚合 `close`,父端主动断开 IPC 后,这个事件可能漏发,即使辅助进程已退出、stderr 已关闭。IPC 验收改等进程 `exit` 和已有 stderr 流自己的 `close`,强杀仍失败。生产一直按 `exit` 判断退出,协议、回退和关闭期限沿用(`411cc62dd7`)。自有 Windows(session 0、提权令牌)在修复前的快照 `8160a6ae86` 上复现了同一现象:100 轮里辅助进程在标准输入上收到 0 行,约 75 ms 后以 0 退出。该环境与用户会话不可比,不单独作为生产缺陷的证据;修复以 `8874aafb21` 上的 CI 验收为准。 | | 待办:startup-account 测试改为导入生产模块(M2 之前) | `startup-account.test.mjs` 的启动阻断、关库、跨区采用、续期排期几段从 `main.ts` 提取函数源码再执行,不经过 `serve` 装配。把这些函数移到可以直接 import 的模块,测试改为导入生产模块。不在这个 PR 做 | | 待办:占用期间 `executeTaskTags` 的行为用例 | 入站分发端口里 service-gate 一类的 `executeTaskTags`,目前只有 `device-link.test.mjs` 的分类对照,没有经真实入口、在桌面占用期间被拒的行为用例。补一条:占用期间远端执行任务标签被拒,处理函数没有被调用。不在这个 PR 做 | | 待办:界面检查补上行数上限截断的自动检测 | `ui:check` 的裁切检查看不出 line-clamp 造成的省略号截断(法语启动原因面板就是这样漏过去的)。给 `ui:check` 的通用检查或登录页测试加一条:副标题等限制行数的节点,内容高度大于可见高度就报。不在这个 PR 做 | From 21fc7c6d422b859130589e00678df1a9d29dd9c9 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:46:21 +1300 Subject: [PATCH 5/9] test(host): use the default readiness wait in lifecycle acceptance The macOS background stage took 19,885 ms on the final #11536 run, 20,117 ms on the failing first #11629 run, and 12,146 ms after the port fix. The 20-second override was a readiness wait, with no performance assertion. Use the launcher default of 60 seconds. Keep the 90-second suite deadline, the lifecycle assertions and per-stage timings. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- apps/host/scripts/lifecycle.e2e.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/scripts/lifecycle.e2e.mjs b/apps/host/scripts/lifecycle.e2e.mjs index cc4d95881c5..2f3d3d1724d 100644 --- a/apps/host/scripts/lifecycle.e2e.mjs +++ b/apps/host/scripts/lifecycle.e2e.mjs @@ -35,7 +35,7 @@ async function attachFromShortLivedLauncher() { ? path.join(releaseDir, 'bin', process.platform === 'win32' ? 'node.exe' : 'node') : process.execPath, args: releaseDir ? [path.join(releaseDir, 'bin/host.mjs'), 'serve'] : ['--import', 'tsx', '--import', './src/loaders/register-raw.mjs', 'src/main.ts', 'serve'], - cwd: releaseDir ? profile : appDir, timeoutMs: 20_000 }; + cwd: releaseDir ? profile : appDir }; // A real launcher exits completely; no parent object can keep its child alive. const child = spawn(process.execPath, ['--input-type=module', '-e', 'const {ensureBackgroundHost}=await import(process.argv[1]); console.log(JSON.stringify(await ensureBackgroundHost(JSON.parse(process.argv[2]))));', From 4f27a99814bd42dbd53b74a4277c1edee52b2111 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:46:29 +1300 Subject: [PATCH 6/9] docs(host): record macOS lifecycle timing in CI Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- docs/host/personal-migration-release-table.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/host/personal-migration-release-table.md b/docs/host/personal-migration-release-table.md index f8a268f34d7..961f701b7a7 100644 --- a/docs/host/personal-migration-release-table.md +++ b/docs/host/personal-migration-release-table.md @@ -685,7 +685,9 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 Host PR 修改主干已有的 `scripts/check-test-hygiene.mjs`,文件 URL 的 `.pathname` 规则只扫描 `apps/host/` 下的测试、夹具和脚本。文件 URL 转为本地路径须使用 `fileURLToPath`,HTTP URL 仍可读取 `.pathname`。hygiene 基线没有增加。 -**Host PR 正文**:主干已有的 `apps/host/scripts/lifecycle.e2e.mjs` 在自有 Ubuntu 上耗时 37.4 秒,集成耗时 39.0 秒,主干 CI 不跑这个脚本。五段断言保持原样,跨平台总期限从 30 秒改为 90 秒,高于最慢实测值的两倍;结束时逐段报告耗时。集成 CI 保留 Ubuntu 和 macOS 步骤,Windows 显式跳过、列为未验证。PR 首轮若 Ubuntu 超过 60 秒,提交实际分段耗时复评。匿名源码启动加载的仓库模块由 3,351 个增至 3,470 个,单次启动约多 0.7 秒;五段合计约多 1.6 秒,登记为源码模式的已知变化。 +**Host PR 正文**:主干已有的 `apps/host/scripts/lifecycle.e2e.mjs` 在自有 Ubuntu 上耗时 37.4 秒,集成耗时 39.0 秒,主干 CI 不跑这个脚本。五段断言保持原样,跨平台总期限从 30 秒改为 90 秒,高于当时自有 Ubuntu 上最慢实测值的两倍;结束时逐段报告耗时。集成 CI 保留 Ubuntu 和 macOS 步骤,Windows 显式跳过、列为未验证。PR 首轮若 Ubuntu 超过 60 秒,提交实际分段耗时复评。匿名源码启动加载的仓库模块由 3,351 个增至 3,470 个,单次启动约多 0.7 秒;五段合计约多 1.6 秒,登记为源码模式的已知变化。 + +**macOS CI 补记(2026-11-20)**:#11536 最后一轮后台启动用了 19,885 ms,#11629 首轮用了 20,117 ms 并超过脚本的 20 秒就绪等待,未执行重新接入。#11629 的 `efa9a32054` 五段分别用时 9,842、12,740、11,214、12,146、126 ms,全部通过。脚本现在沿用启动器默认的 60 秒就绪等待,保留 90 秒总期限和原有断言。合并后单独排查源码启动在自有 macOS、Ubuntu 和 macOS CI 上耗时不同的原因。 主干 `8bcdaae10b` 在 `interruptedTurnAutoResumeHooks.ts` 的备用路线选择前后新增了暂停检查。后台服务在等待桌面释放数据或写队列时会暂停执行。自动续跑恰在此时到期,回调提前返回,已被续跑接管的中断便没有写进任务历史。 From d08a44b7c5dffae548f6e5a3a75c35d968a50ea4 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:55:53 +1300 Subject: [PATCH 7/9] docs(host): record profile release failures and lifecycle timing headroom Document what callers see while failed reply writes are pending and which refusal messages still describe a desktop hold. Clarify that the original 20-second wait from 6e11d2dc35 was a launcher parameter. The first #11629 macOS run used about 82 of the 90 seconds allotted to the whole script before it could reattach. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- apps/host/src/agent/input-queue.mjs | 1 + docs/host/personal-migration-release-table.md | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/host/src/agent/input-queue.mjs b/apps/host/src/agent/input-queue.mjs index fef1f65dd3d..7747a94193a 100644 --- a/apps/host/src/agent/input-queue.mjs +++ b/apps/host/src/agent/input-queue.mjs @@ -685,6 +685,7 @@ export function createInputQueue(deps) { settleAndWake, retryTurnSettlement, canSettleTurnControls: () => !ownerStopping && !closing && profileHold === null, async dispose(canRetryPersistence) { + // Report the initial drain failure before retrying history on a later clear scan. const retry = closing ? canRetryPersistence : undefined; closing = true; // No runtime is released while this owner's runtime drains and stops. diff --git a/docs/host/personal-migration-release-table.md b/docs/host/personal-migration-release-table.md index 961f701b7a7..7553853a5b8 100644 --- a/docs/host/personal-migration-release-table.md +++ b/docs/host/personal-migration-release-table.md @@ -104,6 +104,7 @@ | 插件引擎(ACP,2026-11-20) | 2026-11-19 起,主干 `95158bc18f`、`3178ad31f3`、`5dbf2a58c3` 等支持从本机插件选引擎、新建和切换任务,并支持插件引擎上的协作 Worker | M1 不装配 ACP 引擎。新建 ACP 任务由 `agent/start-options.ts` 的 `requireBuiltinAgentKind` 拒绝;切换到 ACP 返回 `UNSUPPORTED_CAPABILITY` | 用户无法在 Cindy 后台服务上新建插件引擎任务或把已有任务切换到插件引擎。改用内置引擎,或在独立运行的桌面端使用。Host 装配留到 M1 之后,具体阶段待定。 | | 桌面占用期间的插件静默(2026-11-19) | 桌面上的插件照常运行 | Host 暂停逻辑页和插件 Node 进程,保留分区与安装批准。手机和远程端连着 Host 时插件暂不可用,插件工具与宿主请求返回服务层相同的 `PRECONDITION_FAILED`。有意关页时,待决钩子按静默失败收口且不计熔断。这是 8i「受理后失页等截止」的例外,意外失页仍等原截止。用户和助手消息钩子没有 `onFailure`,暂停时跳过询问并沿用既有放行 | 正在执行的插件工具调用会中断,调用方收到「结果不确定」,重试前需要核对。在途回合的输出不会经过消息钩子改写或拦截。已有插件终端保持运行,占用期间不新开。占用期间的旁听事件直接丢弃。占用前已缓冲的事件等下一条事件再送。Host 未使用桌面的 `preparePublish` 会话切换去重调用点。 | | 桌面占用期间的发现延迟(2026-11-19) | 桌面没有占用闸门 | 占用靠每 10 秒重扫加目录监听(去抖 250 毫秒)发现,从桌面开库到后台服务察觉最长约十秒,这期间后台服务照常读写 | 这是整个并存方案的真实边界。入口检查之后才开始的占用,可能留下一个空任务行或空对话目录,与发现延迟同类,不单独处理 | +| 解除占用时回复或队列写入失败(#11629) | 桌面没有占用闸门 | 独立桌面退出后,第一次解除只排空已有写入并报告失败。后台服务继续拒绝新输入,后续确认桌面已退出的扫描(约每 10 秒)重试未保存的回复,成功后才重建运行时。失败的旧队列快照不重放,重建后从库里恢复队列。即使存储已经恢复,第一次解除遇到之前的失败也要多等一次扫描。监视器仍显示「等待回合结束」。 | 服务、聊天和设备互联创建任务入口返回带 `PRECONDITION_FAILED` 的写入错误原文,客户端不会把它显示为「桌面正在使用」。查询旧运行时尚未加载的任务队列时,第一次请求会被拒绝;已加载且受写入失败影响的任务仍可读到暂停状态与错误。主机工具、记忆写入、任务插件、项目资料更新(`apps/host/src/main.ts:893、1031、1471、1697`)及插件暂停仍提示「桌面正在使用」。这些入口的调用方有依赖占用前缀做错误分类的代码,合并后另查提示与分类如何对齐。 | | 桌面占用期间不经 service 的入口(2026-11-19) | 桌面没有占用闸门 | `server.mjs` 自己应答的入口逐个分类,根目录源码契约 `scripts/__tests__/host-server-hold-classification.test.mjs`(`pnpm test:runner` 执行)守护,新增入口没登记就失败。**拒绝**:开启远程控制、开关 Agent-Net(入口与设置锁内各查一次);`/chat` 为不存在的任务建任务(读完任务、建任务前同步查一次;新任务在开流前被拒,返回 500 与 `chat_failed` 事件,与任务不存在时相同;已存在任务在开流后被队列拒,返回 200 与同一事件,这是原有行为)。**登记例外**:关闭远程控制、撤销控制设备,写 profile 根的 `device-link-settings.json`,与桌面同一份文件、同一把跨进程锁,正在运行的桌面每 5 秒轮询跟随:关闭会断开桌面当前所有控制链路,撤销会断开对应设备;写之前先走两端共用的分享可用性策略,有登记时向账号区域的服务停用对应分享的可用性,并从共用的 `provider-share-availability.json` 移除登记。占用期间后台服务的远程控制仍在线,已授权的控制端仍能读,撤销在这时有实际用处;只有本机持后台服务令牌的客户端能触发。登出:持账号库跨进程锁更新共用账号库与登出标记,删除登录令牌记录。`/control/stop`:关停收尾,排空队列、在途用量入库、有条件写错误行。**不写共用数据**:`/control/attachment`、`/control/platform`、`/web/pair`、`/web/session`、`/events` 与读接口、IPC 现有只读绑定。Agent-Net 设备身份是后台服务自己的记录 | 占用期间在后台服务登出:桌面不会立即登出,最迟在下次续期时(通常在令牌到期前五分钟,鉴权失败可提前)回到登录页并提示“本机的登录凭证已失效(可能是同一台设备上的其他实例退出了登录),请重新登录。”,同时停止该账号仍在跑的任务;在此之前桌面仍用内存里的令牌工作。用户 2026-11-19 定:保持允许。结构性的改法(服务器层对占用期间的写请求统一默认拒绝)登记为待办,不在第一阶段 | | 任务里遇到缺失插件(主干同步 4,2026-11-19) | 主干 `089105c276`、`d9fc65bd15` 之后,桌面任务遇到缺失插件,可以在任务内搜索、选择发行版、确认安装(`ghost_market_search`、`ghost_market_install`) | 后台服务的插件网关没有注入市场服务(`apps/host/src/plugins/gateway.ts:86–115`),任务里只得到“去这台任务电脑的插件设置里看”的提示(共用 `ghost.ts:1863,1906–1922,1939–1940`)。主干同时删掉了共用代码里原来的兜底引导(回查已安装清单或改道),所以后台服务上的引导比同步前少。客户端模式的窗口里,插件设置目前也装不上:`plugin-market:install`、`ghosts:install` 留在窗口进程,而安装确认的答复 `ghosts:install-consent:resolve` 被委托给后台服务,只认后台服务事件流登记的请求,窗口本地的确认在代理里被拒,安装不落盘(`hostChannelContract.ts:433–482`、`bootstrap-electron.ts:1360–1382,1499–1519`、`host-delegation.ts:227–231`;这条委托是主干 `a7f5289e84` 加的);网页端也没有安装入口。**所以目前连着后台服务时没有可用的安装途径。** | 要装缺失插件,先退出后台服务,在普通桌面里装好、退出普通桌面后再启动后台服务。同一 profile、同一账号的安装,后台服务下次发现或调用时重新扫描磁盘即可使用,不必重新批准;静默期间则在解除占用后的 reconcile 里重扫(`plugins/runtime.ts:126–148,466–492`、`profile-coexistence.ts:342–377`)。客户端窗口的官方市场取不到账号访问令牌,依赖账号鉴权的条目可能更早就看不到。已批准插件的正常运行不受影响。迁移前要解决,见第五节 | | 已登录后的凭据续期(乙) | 桌面与 Host 按 access token 的到期时间安排续期 | 在 macOS 上,Host 监听后,`commitRenewal` 持账号库锁重读会话,同步解密两轮实测 648 / 780 ms。正常定时续期在 `exp` 前 5 分钟;若 token 有效一小时,约每 55 分钟一次,实际以 token 为准。启动恢复会话、被服务端拒绝后刷新也可触发,临时失败按退避重试 | 两次测量中,正在运行的任务需由 Host 事件循环处理的回调、输出和 IPC 分别停顿约 0.65 / 0.78 秒。独立引擎子进程仍可运行;测量值是这次同步重读的时长。 2026-11-19 补记:Host 远控中转每次建立连接或重连取令牌一次;稳态心跳(Host 的中转客户端配置 15 秒,`device-link.ts:393`)不取;2026-11-19 复查更正,原文写 20 秒。普通重连起步约 0.7–1 秒,最高退避档约 21–30 秒。已有 Agent-Net 身份在成功读取后按节点实例、账号与服务缓存,通常每个实例每个账号只解密一次;读取失败会在下次连接再查。同步解密可能影响连线恢复与同一事件循环里的在途操作,纳入本乙项。0.65–0.78 秒是续期路径的实测,Agent-Net 走同一通道,未另测时延。 | @@ -687,7 +688,7 @@ Host PR 修改主干已有的 `scripts/check-test-hygiene.mjs`,文件 URL 的 **Host PR 正文**:主干已有的 `apps/host/scripts/lifecycle.e2e.mjs` 在自有 Ubuntu 上耗时 37.4 秒,集成耗时 39.0 秒,主干 CI 不跑这个脚本。五段断言保持原样,跨平台总期限从 30 秒改为 90 秒,高于当时自有 Ubuntu 上最慢实测值的两倍;结束时逐段报告耗时。集成 CI 保留 Ubuntu 和 macOS 步骤,Windows 显式跳过、列为未验证。PR 首轮若 Ubuntu 超过 60 秒,提交实际分段耗时复评。匿名源码启动加载的仓库模块由 3,351 个增至 3,470 个,单次启动约多 0.7 秒;五段合计约多 1.6 秒,登记为源码模式的已知变化。 -**macOS CI 补记(2026-11-20)**:#11536 最后一轮后台启动用了 19,885 ms,#11629 首轮用了 20,117 ms 并超过脚本的 20 秒就绪等待,未执行重新接入。#11629 的 `efa9a32054` 五段分别用时 9,842、12,740、11,214、12,146、126 ms,全部通过。脚本现在沿用启动器默认的 60 秒就绪等待,保留 90 秒总期限和原有断言。合并后单独排查源码启动在自有 macOS、Ubuntu 和 macOS CI 上耗时不同的原因。 +**macOS CI 补记(2026-11-20)**。#11536 最后一轮后台启动用了 19,885 ms,#11629 首轮用了 20,117 ms 并超过脚本的 20 秒就绪等待,未执行重新接入。该等待自 `6e11d2dc35` 起是启动器的就绪参数,脚本没有相应的性能断言。#11629 的 `efa9a32054` 五段分别用时 9,842、12,740、11,214、12,146、126 ms,全部通过。脚本现在沿用启动器默认的 60 秒就绪等待,保留 90 秒总期限和原有断言。首轮失败前四个阶段已用约 82 秒,留给全脚本的余量约 8 秒。合并后单独排查源码启动在自有 macOS、Ubuntu 和 macOS CI 上耗时不同的原因。 主干 `8bcdaae10b` 在 `interruptedTurnAutoResumeHooks.ts` 的备用路线选择前后新增了暂停检查。后台服务在等待桌面释放数据或写队列时会暂停执行。自动续跑恰在此时到期,回调提前返回,已被续跑接管的中断便没有写进任务历史。 From 823f2c7ce1a4da72dc4861a883915cf1e3705b70 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:02:05 +1300 Subject: [PATCH 8/9] test(host): leave room for slow lifecycle acceptance runs The final #11536 macOS run took about 76.7 seconds across all stages. The first #11629 macOS run took 81.6 seconds across four stages before reattachment, leaving about eight seconds under the 90-second suite deadline. Keep the whole-script hang limit above twice the slowest observed run by raising it to 180 seconds. The 60-second readiness wait and Ubuntu performance review threshold are unchanged. The CI job allows 20 minutes. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- apps/host/scripts/lifecycle.e2e.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/scripts/lifecycle.e2e.mjs b/apps/host/scripts/lifecycle.e2e.mjs index 2f3d3d1724d..cba7e778ad1 100644 --- a/apps/host/scripts/lifecycle.e2e.mjs +++ b/apps/host/scripts/lifecycle.e2e.mjs @@ -68,7 +68,7 @@ function launch() { listening.catch(() => undefined); return { child, exit, listening }; } -const LIFECYCLE_TIMEOUT_MS = 90_000; +const LIFECYCLE_TIMEOUT_MS = 180_000; const timings = new Map(); let stageStarted; function beginStage(name) { From 5f71023567c65cb19fc2e5195806d3e14c2cd774 Mon Sep 17 00:00:00 2001 From: Dash <125997726+dashhuang@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:02:06 +1300 Subject: [PATCH 9/9] docs(host): record the lifecycle acceptance deadline and review threshold Record the slow macOS CI runs and distinguish the 180-second hang limit for the whole script from the 60-second readiness wait and performance review threshold. Assisted-by: Cindy (https://cindy.app) Signed-off-by: Dash <125997726+dashhuang@users.noreply.github.com> --- docs/host/personal-migration-release-table.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/host/personal-migration-release-table.md b/docs/host/personal-migration-release-table.md index 7553853a5b8..bbc93d9b932 100644 --- a/docs/host/personal-migration-release-table.md +++ b/docs/host/personal-migration-release-table.md @@ -686,9 +686,9 @@ rc9 在发布提交 `ce58e49a47` 上的 27 项 CI 全部通过。Windows 的独 Host PR 修改主干已有的 `scripts/check-test-hygiene.mjs`,文件 URL 的 `.pathname` 规则只扫描 `apps/host/` 下的测试、夹具和脚本。文件 URL 转为本地路径须使用 `fileURLToPath`,HTTP URL 仍可读取 `.pathname`。hygiene 基线没有增加。 -**Host PR 正文**:主干已有的 `apps/host/scripts/lifecycle.e2e.mjs` 在自有 Ubuntu 上耗时 37.4 秒,集成耗时 39.0 秒,主干 CI 不跑这个脚本。五段断言保持原样,跨平台总期限从 30 秒改为 90 秒,高于当时自有 Ubuntu 上最慢实测值的两倍;结束时逐段报告耗时。集成 CI 保留 Ubuntu 和 macOS 步骤,Windows 显式跳过、列为未验证。PR 首轮若 Ubuntu 超过 60 秒,提交实际分段耗时复评。匿名源码启动加载的仓库模块由 3,351 个增至 3,470 个,单次启动约多 0.7 秒;五段合计约多 1.6 秒,登记为源码模式的已知变化。 +**Host PR 正文**:主干已有的 `apps/host/scripts/lifecycle.e2e.mjs` 在自有 Ubuntu 上耗时 37.4 秒,集成耗时 39.0 秒,主干 CI 不跑这个脚本。五段断言保持原样,跨平台总期限最初从 30 秒改为 90 秒,高于当时自有 Ubuntu 上最慢实测值的两倍。结束时逐段报告耗时。集成 CI 保留 Ubuntu 和 macOS 步骤,Windows 显式跳过、列为未验证。PR 首轮若 Ubuntu 超过 60 秒,提交实际分段耗时复评。匿名源码启动加载的仓库模块由 3,351 个增至 3,470 个,单次启动约多 0.7 秒;五段合计约多 1.6 秒,登记为源码模式的已知变化。 -**macOS CI 补记(2026-11-20)**。#11536 最后一轮后台启动用了 19,885 ms,#11629 首轮用了 20,117 ms 并超过脚本的 20 秒就绪等待,未执行重新接入。该等待自 `6e11d2dc35` 起是启动器的就绪参数,脚本没有相应的性能断言。#11629 的 `efa9a32054` 五段分别用时 9,842、12,740、11,214、12,146、126 ms,全部通过。脚本现在沿用启动器默认的 60 秒就绪等待,保留 90 秒总期限和原有断言。首轮失败前四个阶段已用约 82 秒,留给全脚本的余量约 8 秒。合并后单独排查源码启动在自有 macOS、Ubuntu 和 macOS CI 上耗时不同的原因。 +**macOS CI 补记(2026-11-20)**。#11536 最后一轮后台启动用了 19,885 ms,#11629 首轮用了 20,117 ms 并超过脚本的 20 秒就绪等待,未执行重新接入。该等待自 `6e11d2dc35` 起是启动器的就绪参数,脚本没有相应的性能断言。#11629 的 `efa9a32054` 五段分别用时 9,842、12,740、11,214、12,146、126 ms,全部通过。脚本沿用启动器默认的 60 秒就绪等待和原有断言。#11536 最后一轮五个阶段合计约 76.7 秒,#11629 首轮失败前四个阶段合计 81.6 秒,原来 90 秒的整套测试只剩约 8 秒余量。以 macOS CI 实测约 82 秒为参照,按原有「高于最慢实测值的两倍」的规则将全脚本防挂死期限调到 180 秒。CI 作业的上限是 20 分钟,Ubuntu 的 60 秒耗时复评线仍适用。合并后单独排查源码启动在自有 macOS、Ubuntu 和 macOS CI 上耗时不同的原因。 主干 `8bcdaae10b` 在 `interruptedTurnAutoResumeHooks.ts` 的备用路线选择前后新增了暂停检查。后台服务在等待桌面释放数据或写队列时会暂停执行。自动续跑恰在此时到期,回调提前返回,已被续跑接管的中断便没有写进任务历史。