diff --git a/.github/workflows/orca-server-artifact.yml b/.github/workflows/orca-server-artifact.yml new file mode 100644 index 00000000000..2840ad7caa7 --- /dev/null +++ b/.github/workflows/orca-server-artifact.yml @@ -0,0 +1,133 @@ +name: Server-only Linux artifact + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: + - 'config/scripts/orcad-distribution/server-artifact/**' + - '.github/workflows/orca-server-artifact.yml' + # The launcher relies on how the CLI picks and starts its serve runtime. + - 'src/cli/runtime/launch.ts' + - 'src/cli/runtime/orca-app-executable.ts' + - 'src/cli/runtime/serve-orcad-launch.ts' + - 'src/shared/orcad-local-serve-selection.ts' + - 'src/shared/orcad-artifacts.ts' + # Catch serve regressions on main between releases. + schedule: + - cron: '45 11 * * *' + workflow_dispatch: + # Releases pass the qualified template this run already built, so the tarball ships its exact bytes. + workflow_call: + inputs: + ref: + description: Git ref to check out, e.g. the release tag + type: string + required: true + template_artifact: + description: Name of this run's qualified orcad-template artifact; blank builds the host slot + type: string + default: '' + outputs: + packed: + description: "'true' when both tarballs were packed and passed the smoke" + value: ${{ jobs.package.outputs.packed }} + +permissions: + contents: read + +concurrency: + group: orca-server-artifact-${{ inputs.ref && format('run-{0}', github.run_id) || github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ !inputs.ref }} + +jobs: + package: + if: github.event_name != 'pull_request' || github.event.pull_request.draft != true + strategy: + fail-fast: false + matrix: + include: + - arch: x64 + runner: ubuntu-24.04 + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + permissions: + contents: read + actions: read + env: + ORCA_BACKGROUND_LAUNCH: '1' + TARGET: linux-${{ matrix.arch }}-glibc + outputs: + packed: ${{ steps.smoke.outcome == 'success' }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ inputs.ref }} + persist-credentials: false + # A release cut from a ref older than this workflow has nothing to pack; skip instead of failing. + - name: Check the ref can pack the tarball + id: supported + run: | + if [ -f config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs ]; then + echo 'supported=true' >> "$GITHUB_OUTPUT" + else + echo '::notice::This ref predates the server-only tarball; skipping it.' + fi + - uses: ./.github/actions/install-node-dependencies + if: steps.supported.outputs.supported == 'true' + with: + cache-pnpm-store: ${{ !inputs.ref }} + - name: Use the qualified release template + if: steps.supported.outputs.supported == 'true' && inputs.template_artifact != '' + uses: actions/download-artifact@v8 + with: + name: ${{ inputs.template_artifact }} + path: out/orcad-template + # Without a release template, build this runner's slot the way the desktop template does. + - uses: ./.github/actions/build-mobile-web-bundle + if: steps.supported.outputs.supported == 'true' && inputs.template_artifact == '' + - name: Build this runner's template slot + if: steps.supported.outputs.supported == 'true' && inputs.template_artifact == '' + run: pnpm build:orcad-template --targets "$TARGET" + - name: Pack the tarball + if: steps.supported.outputs.supported == 'true' + run: | + pnpm build:packages + SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)" node config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs --template out/orcad-template --target "$TARGET" --out-dir out/orca-server + { + echo "### orca-server-linux-${{ matrix.arch }}" + echo '```' + ls -l out/orca-server + cat out/orca-server/*.sha256 + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + - name: Start and pair on the runner + if: steps.supported.outputs.supported == 'true' + run: node config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs --archive "out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz" + # Bare images with no Node, display, GTK or X11: the tarball's own Node runs the smoke. + - name: Start and pair on minimal images + id: smoke + if: steps.supported.outputs.supported == 'true' + run: | + for image in ubuntu:24.04 debian:12-slim; do + echo "::group::$image" + docker run --rm --init \ + -v "$PWD/out/orca-server:/artifacts:ro" \ + -v "$PWD/config/scripts/orcad-distribution/server-artifact:/smoke:ro" \ + "$image" sh -ec ' + mkdir -p /tmp/runtime + tar -xzf /artifacts/orca-server-linux-${{ matrix.arch }}.tar.gz -C /tmp/runtime --strip-components=1 + /tmp/runtime/runtimes/node-*/bin/node /smoke/smoke-orcad-server-artifact.mjs --archive /artifacts/orca-server-linux-${{ matrix.arch }}.tar.gz + ' + echo '::endgroup::' + done + - uses: actions/upload-artifact@v7 + if: steps.supported.outputs.supported == 'true' + with: + name: orca-server-linux-${{ matrix.arch }} + path: | + out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz + out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz.sha256 + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index 2af8bb94c6f..c2c330ea00f 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -33,7 +33,6 @@ on: - 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts' - 'src/main/claude-usage/scanner-incremental-append.test.ts' - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' - - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx' permissions: contents: read diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 578dcdd68d9..13bed76ed0c 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -1111,7 +1111,6 @@ jobs: src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts - src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index ffc61def51f..01ed0b8ffe1 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -1039,6 +1039,21 @@ jobs: ref: refs/tags/${{ needs.cut.outputs.tag }} fast_runners: false + # Server-only Linux tarballs from the same qualified template. Nothing depends on this job, so a + # failure here never holds the desktop release. + orca-server-artifact: + needs: + - cut + - orcad-template + if: ${{ !cancelled() && needs.cut.outputs.should_release == 'true' && needs.orcad-template.result == 'success' }} + permissions: + contents: read + actions: read + uses: ./.github/workflows/orca-server-artifact.yml + with: + ref: refs/tags/${{ needs.cut.outputs.tag }} + template_artifact: orcad-template + # Gate SignPath artifact requests behind blocking tests to avoid approvals for unpublishable builds. release-preflight: needs: @@ -2241,6 +2256,39 @@ jobs: --prerelease="$prerelease" \ --repo "$GITHUB_REPOSITORY" + # After publish: the draft's asset checks and undraft never see these, and a failure here only + # leaves the server tarballs missing from an already published release. + publish-orca-server-artifact: + needs: + - cut + - publish-release + - orca-server-artifact + if: ${{ !cancelled() && needs.publish-release.result == 'success' && needs.orca-server-artifact.result == 'success' && needs.orca-server-artifact.outputs.packed == 'true' && needs.cut.outputs.tag != '' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + steps: + - uses: actions/download-artifact@v8 + with: + pattern: orca-server-linux-* + path: orca-server + merge-multiple: true + - name: Write the checksum manifest and upload + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ needs.cut.outputs.tag }} + working-directory: orca-server + run: | + set -euo pipefail + cat orca-server-linux-x64.tar.gz.sha256 orca-server-linux-arm64.tar.gz.sha256 > orca-server-sha256sums.txt + sha256sum -c orca-server-sha256sums.txt + gh release upload "$TAG" \ + orca-server-linux-x64.tar.gz \ + orca-server-linux-arm64.tar.gz \ + orca-server-sha256sums.txt \ + --clobber --repo "$GITHUB_REPOSITORY" + post-release-e2e: needs: - cut diff --git a/config/build-plugins/main-build-entry-points.ts b/config/build-plugins/main-build-entry-points.ts index 1521adc3dc3..819c08e1680 100644 --- a/config/build-plugins/main-build-entry-points.ts +++ b/config/build-plugins/main-build-entry-points.ts @@ -5,7 +5,6 @@ import { CLI_MAIN_ENTRY_NAMES } from './cli-main-entry-names' /** Main-build Rollup inputs: output file name (without .js) to its source entry. */ export const MAIN_BUILD_ENTRY_POINTS: Record = { index: resolve('src/main/index.ts'), - 'browser-extension-preload': resolve('src/preload/browser-extension-preload.ts'), 'browser-extension-native-host-supervisor-entry': resolve( 'src/main/browser/extensions/native-messaging/browser-extension-native-host-supervisor-entry.ts' ), diff --git a/config/build-plugins/sandboxed-script-bundles.ts b/config/build-plugins/sandboxed-script-bundles.ts index 9b1bd0e1f21..3bef5c5c96e 100644 --- a/config/build-plugins/sandboxed-script-bundles.ts +++ b/config/build-plugins/sandboxed-script-bundles.ts @@ -8,7 +8,14 @@ import { type BundledScript = { code: string; moduleIds: string[] } +// Unminified preload keeps dependency JSDoc whose em dashes would force two-byte storage in every renderer. +export const ONE_BYTE_UNMINIFIED_OUTPUT = { + charset: 'ascii', + comments: { legal: true, annotation: true, jsdoc: false } +} as const + const GUEST_PRELOADS = [ + { entry: 'src/preload/browser-extension-preload.ts', fileName: 'browser-extension-preload.js' }, { entry: 'src/preload/browser-guest.ts', fileName: 'browser-guest-preload.js' }, { entry: 'src/preload/doc-preview-link.ts', fileName: 'doc-preview-link-preload.js' }, { entry: 'src/preload/plugin-frame-guest.ts', fileName: 'plugin-frame-guest-preload.js' } @@ -46,7 +53,7 @@ async function bundleScript( name: 'orcaBrowserExtensionScript', fileName: () => fileName }, - rollupOptions: { external: ['electron'] } + rollupOptions: { external: ['electron'], output: ONE_BYTE_UNMINIFIED_OUTPUT } } }) for (const output of Array.isArray(result) ? result : [result]) { diff --git a/config/electron-builder.config.cjs b/config/electron-builder.config.cjs index 1be4f4201c4..b4655ee824e 100644 --- a/config/electron-builder.config.cjs +++ b/config/electron-builder.config.cjs @@ -20,9 +20,12 @@ const { assertPackagedNativeVariantsInstalled, assertProcessHostOutputBuilt, createPackagedRuntimeNodeModuleResources, + normalizeElectronArchitecture, prunePackagedRuntimeNodeModules, + readPackage, verifyPackagedMainRuntimeDeps } = require('./packaged-runtime-node-modules.cjs') +const { copyPackagedTranscribeCpp } = require('./packaged-transcribe-cpp.cjs') const { assertNoWindowsExecutablesInRuntimeNodeModules } = require('./packaged-windows-only-runtime-files.cjs') @@ -171,19 +174,6 @@ const commonExtraResources = [ nativeChatVisualsResource, emojiShortcodeDatasetResource ] -// Native speech addons need real disk paths; copy only the artifact target’s variant. -const macSpeechNativeResource = { - from: 'node_modules/sherpa-onnx-darwin-${arch}', - to: 'node_modules/sherpa-onnx-darwin-${arch}' -} -const linuxSpeechNativeResource = { - from: 'node_modules/sherpa-onnx-linux-${arch}', - to: 'node_modules/sherpa-onnx-linux-${arch}' -} -const winSpeechNativeResource = { - from: 'node_modules/sherpa-onnx-win-x64', - to: 'node_modules/sherpa-onnx-win-x64' -} // electron-builder replaces these defaults when `depends` is configured; retain // Electron's loader requirements alongside Orca's headless-host dependencies. const debElectronRuntimeDependencies = [ @@ -329,8 +319,8 @@ module.exports = { '!resources/native-chat-visuals/**', // extraResources already ships plugin bytes; exclude source duplicates. '!resources/plugins/launch/**', - // Platform extraResources selects speech natives; asar would duplicate it and ship other variants. - '!node_modules/sherpa-onnx*{,/**/*}', + // afterPack copies the target's speech engine to resources/node_modules; asar would duplicate it and ship other variants. + '!node_modules/{transcribe-cpp,@transcribe-cpp,koffi,@koromix}{,/**/*}', // CLI shim belongs beside resources/bin/orca.exe; unpacking source creates a second .cmd without its executable (#7351). '!resources/win32{,/**/*}' ], @@ -450,6 +440,13 @@ module.exports = { writeMacBuildCompatibility(resourcesDir, { version, commit, architecture }) } stampPackagedCliVersion(resourcesDir, context.packager.appInfo.version) + // Before the prune, which drops the copied packages' type declarations too. + copyPackagedTranscribeCpp( + readPackage, + resourcesDir, + context.electronPlatformName, + normalizeElectronArchitecture(context.arch) + ) prunePackagedRuntimeNodeModules(resourcesDir, context.electronPlatformName, context.arch) assertNoWindowsExecutablesInRuntimeNodeModules(resourcesDir, context.electronPlatformName) // Gate native glibc floor after pruning foreign CPU variants; GLIBC_2.34 once broke Ubuntu 20.04 startup (#9902). @@ -553,7 +550,6 @@ module.exports = { extraResources: [ ...commonExtraResources, ...windowsRuntimeResources, - winSpeechNativeResource, { from: 'resources/win32/bin/orca.cmd', to: 'bin/orca.cmd' @@ -610,7 +606,8 @@ module.exports = { rank: 'Alternate' })) ], - // Bundled ONNX Runtime (speech) needs macOS 13.4 (#22690); the update-manifest gate reads this from Info.plist. + // Set for ONNX Runtime (#22690, #39135), now gone; transcribe-cpp needs 11.0, Electron 12.0. Kept until + // Kelvin decides. The update-manifest gate reads this from Info.plist. minimumSystemVersion: '13.4', icon: 'resources/build/icon.icns', entitlements: 'resources/build/entitlements.mac.plist', @@ -633,7 +630,6 @@ module.exports = { extraResources: [ ...commonExtraResources, ...createPackagedRuntimeNodeModuleResources('darwin'), - macSpeechNativeResource, { from: 'resources/darwin/bin/orca', to: 'bin/orca' @@ -698,7 +694,6 @@ module.exports = { extraResources: [ ...commonExtraResources, ...createPackagedRuntimeNodeModuleResources('linux'), - linuxSpeechNativeResource, { from: 'native/wayland-clipboard/.build/${arch}/orca-wayland-clipboard', to: 'bin/orca-wayland-clipboard' diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 67ce4cfb757..5b3a0aab500 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -147,7 +147,6 @@ 2 test-no-real-time-wait:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts 1 test-no-real-time-wait:src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts 1 test-no-real-time-wait:src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts -5 test-no-real-time-wait:src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts 1 test-no-real-time-wait:src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process.test.ts 2 test-no-real-time-wait:src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-scan-scope.test.ts 1 test-no-real-time-wait:src/main/antigravity/windows-hook-json-post.test.ts @@ -265,7 +264,6 @@ 4 test-no-real-time-wait:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/editor/DiagramViewerModal.test.tsx 1 test-no-real-time-wait:src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx -1 test-no-real-time-wait:src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-lifecycle.test.tsx 4 test-no-real-time-wait:src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-store.test.ts 1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts 2 test-no-real-time-wait:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts @@ -458,7 +456,6 @@ 1 test-no-wall-clock:src/cli/runtime/status-caller.test.ts 2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts 2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts -1 test-no-wall-clock:src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts 1 test-no-wall-clock:src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts 3 test-no-wall-clock:src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts 4 test-no-wall-clock:src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts @@ -636,12 +633,11 @@ 2 test-no-wall-clock:src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts 1 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx 1 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx -3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx +2 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx 3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx 1 test-no-wall-clock:src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx 3 test-no-wall-clock:src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx 2 test-no-wall-clock:src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx -1 test-no-wall-clock:src/renderer/src/components/settings/accounts/providers/GrokAccountsSection.test.tsx 3 test-no-wall-clock:src/renderer/src/components/sidebar/workspace-card/review/use-workspace-reference-details.test.tsx 1 test-no-wall-clock:src/renderer/src/components/sidebar/worktree-list/listing/WorktreeList.lineage-agent-expansion-coupling.test.tsx 2 test-no-wall-clock:src/renderer/src/components/task-page/jira/task-page-jira-cache-selectors.test.ts @@ -656,10 +652,9 @@ 1 test-no-wall-clock:src/renderer/src/lib/paired-runtime-closed-tab-resume.test.ts 2 test-no-wall-clock:src/renderer/src/lib/use-tab-agent-observed-signal-dispatch.test.tsx 2 test-no-wall-clock:src/renderer/src/lib/wake-sleeping-agents-live-unmounted-pane.test.ts -1 test-no-wall-clock:src/renderer/src/lib/workspace-terminal-host-authority.test.ts +1 test-no-wall-clock:src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts 1 test-no-wall-clock:src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts 2 test-no-wall-clock:src/renderer/src/runtime/native-chat/tab-retirement/structured-agent-session-tab-retirement.test.ts -1 test-no-wall-clock:src/renderer/src/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab.test.ts 2 test-no-wall-clock:src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts 6 test-no-wall-clock:src/renderer/src/store/slices/jira/jira.test.ts 5 test-no-wall-clock:src/renderer/src/store/slices/worktrees/metadata/worktree-meta-hosted-review.test.ts @@ -693,7 +688,6 @@ 2 test-timeout-needs-reason:src/main/acp/journal/acp-structured-broken-stream.test.ts 4 test-timeout-needs-reason:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts 1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts -1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts 1 test-timeout-needs-reason:src/main/ai-vault/parse-cache/session-parse-cache-large-scan.test.ts 1 test-timeout-needs-reason:src/main/antigravity/native-macos-credentials.real.test.ts 1 test-timeout-needs-reason:src/main/antigravity/posix-hook-invocation.test.ts @@ -708,7 +702,7 @@ 1 test-timeout-needs-reason:src/main/browser/cookies/browser-cookie-import-validated-partition.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/guest-lifecycle/find/browser-find-frame-traversal.electron.test.ts 1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts -2 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts +1 test-timeout-needs-reason:src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts 3 test-timeout-needs-reason:src/main/claude-usage/scanner-incremental-reader.test.ts 1 test-timeout-needs-reason:src/main/claude/claude-agent-sdk-exit-proof.test.ts 1 test-timeout-needs-reason:src/main/claude/claude-background-run-isolation-real-cli.test.ts diff --git a/config/focus-setting-read-baseline.txt b/config/focus-setting-read-baseline.txt index 9e6d01f833d..4b3f4c25346 100644 --- a/config/focus-setting-read-baseline.txt +++ b/config/focus-setting-read-baseline.txt @@ -222,14 +222,14 @@ 2 src/renderer/src/lib/browser/workspace/workspace-browser-tab-open.ts 1 src/renderer/src/lib/client-creation-action-error.ts 2 src/renderer/src/lib/client-creation-action-policy.ts -1 src/renderer/src/lib/default-creation-host.ts # the sanctioned reader of the default host +1 src/renderer/src/runtime/hosts/selection/default-creation-host.ts # the sanctioned reader of the default host 1 src/renderer/src/lib/launch-ai-vault-session.ts 1 src/renderer/src/lib/local-preflight-context.ts 2 src/renderer/src/runtime/hosts/observations/provider-runtime-context.ts -2 src/renderer/src/lib/repo-runtime-owner.ts -1 src/renderer/src/lib/runtime-session-mirror-owners.ts +2 src/renderer/src/lib/workspace/ownership/repo-runtime-owner.ts +1 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts 1 src/renderer/src/lib/runtime-session-mirror-targets.ts -1 src/renderer/src/lib/single-runtime-legacy-owner.ts +1 src/renderer/src/lib/workspace/ownership/single-runtime-legacy-owner.ts 1 src/renderer/src/lib/skill-runtime-command.ts 1 src/renderer/src/lib/terminal-close-route.ts 4 src/renderer/src/lib/terminal-worktree-route.ts # resolveTerminalPtyOwner: teardown, close and PTY identity read spawn's attribution (round 3 F8), which retired the deprecated resolver's readers @@ -239,7 +239,7 @@ 1 src/renderer/src/lib/work-items/linear/linear-issue-write.ts 1 src/renderer/src/lib/workspace/activation/worktree-activation.ts 1 src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.ts # a setup terminal with no row spawns on the focused runtime -1 src/renderer/src/lib/worktree-jump-navigation.ts +1 src/renderer/src/lib/workspace/activation/worktree-jump-navigation.ts 17 src/renderer/src/runtime/jira/runtime-jira-client.ts 2 src/renderer/src/runtime/jira/runtime-jira-summary-client.ts 5 src/renderer/src/runtime/jira/runtime-jira-user-fields-client.ts diff --git a/config/legacy-relay-compat-tags-baseline.txt b/config/legacy-relay-compat-tags-baseline.txt index c168b52ead7..3ed5dc0a23e 100644 --- a/config/legacy-relay-compat-tags-baseline.txt +++ b/config/legacy-relay-compat-tags-baseline.txt @@ -15,7 +15,6 @@ src/main/managed-server/migration/cutover/orcad-migration-delta-move.ts src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts src/main/ssh/migration-source/orcad-migration-terminal-gate.ts -src/main/ssh/host-server/ssh-host-server-on-connect.test.ts src/main/ssh/host-server/ssh-host-server-on-connect.ts src/main/ssh/targets/ssh-target-orcad-preflight.ts src/preload/api-types.ts diff --git a/config/legacy-relay-importers-baseline.txt b/config/legacy-relay-importers-baseline.txt index ef18c667b27..c48864aa1ed 100644 --- a/config/legacy-relay-importers-baseline.txt +++ b/config/legacy-relay-importers-baseline.txt @@ -14,4 +14,3 @@ tests/e2e/cross-version-wire/legacy-relay-bridge.unit.test.ts tests/e2e/helpers/legacy-relay-docker-host.ts src/main/managed-server/install/remote-install-model.ts src/main/ssh/system-transport/ssh-system-transport.integration.test.ts -src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts diff --git a/config/main-layout-writer-baseline.txt b/config/main-layout-writer-baseline.txt index 096973f7717..00c1afab41e 100644 --- a/config/main-layout-writer-baseline.txt +++ b/config/main-layout-writer-baseline.txt @@ -32,6 +32,7 @@ 2 src/main/persistence/migrating-orcad-catalog/orcad-destination-client-state.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-destination-workspace-session.ts 3 src/main/persistence/migrating-orcad-catalog/orcad-dormant-state-records.ts +1 src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts 2 src/main/persistence/migrating-orcad-catalog/orcad-source-client-subtraction.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-source-dormant-state.ts 1 src/main/persistence/migrating-orcad-catalog/orcad-source-scrollback-state.ts @@ -53,11 +54,11 @@ 2 src/main/pty/scrollback/terminal-scrollback-snapshots.ts 1 src/main/runtime/browser/client-pages/client-hosted-browser-page-persistence.ts 1 src/main/runtime/client/runtime-client-state.ts -1 src/main/runtime/session-tabs/headless-editor-tabs.ts 4 src/main/runtime/orchestration/terminal-authority/runtime-legacy-worker-terminal-recovery-persistence.ts 2 src/main/runtime/session-graph/session-graph-promotion.ts 2 src/main/runtime/session-lifecycle/projection/apply-mobile-session-tab-navigation.ts 2 src/main/runtime/session-lifecycle/projection/build-headless-mobile-session-browser-tabs.ts +1 src/main/runtime/session-tabs/headless-editor-tabs.ts 2 src/main/runtime/session-tabs/headless-tab-group-moves.ts 6 src/main/runtime/session-tabs/headless-tab-properties.ts 2 src/main/runtime/session-tabs/headless-terminal-tab-titles.ts @@ -72,5 +73,4 @@ 3 src/main/runtime/terminal/surface/mobile-session-layout-projection.ts 1 src/main/runtime/workspaces/session-hosts/get-runtime-id.ts 1 src/main/runtime/workspaces/session-hosts/runtime-workspace-session-controller.ts -1 src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.ts 1 src/main/ssh/targets/ssh-target-id-migration.ts diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index 45c12030430..a4efe1beedc 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -496,9 +496,10 @@ 10 src/main/speech/openai-api-key-store.ts 2 src/main/speech/speech-model-download-cleanup.ts 1 src/main/speech/speech-model-download-transport.ts +1 src/main/speech/speech-model-files.ts 2 src/main/speech/speech-model-http-download.ts -1 src/main/speech/stt-worker-model-config.ts -2 src/main/speech/stt-worker-paths.ts +1 src/main/speech/speech-vad-model.ts +2 src/main/speech/stt-gpu-failure-marker.ts 2 src/main/sqlite/harden-database-files.ts 1 src/main/sqlite/row-cache/keyed-json-row-cache.ts 2 src/main/sqlite/row-cache/legacy-json-source.ts @@ -609,6 +610,7 @@ 7 src/shared/serve-bundle-park.ts 1 src/shared/serve-user-data-path.ts 3 src/shared/source-scan/source-tree-scan.ts +2 src/shared/speech-recognizer-package.ts 5 src/shared/startup-command-staging.ts 1 src/shared/terminal/pty/native-process/pty-process-ceiling-state.ts 8 src/shared/windows-breakaway-launcher.ts diff --git a/config/mobile-localization-coverage-allowlist.json b/config/mobile-localization-coverage-allowlist.json index 50d8243f0f7..265dd13cf28 100644 --- a/config/mobile-localization-coverage-allowlist.json +++ b/config/mobile-localization-coverage-allowlist.json @@ -307,6 +307,27 @@ "dynamic": false, "count": 1 }, + { + "filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx", + "kind": "object-property:label", + "text": "Shift", + "dynamic": false, + "count": 1 + }, + { + "filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx", + "kind": "object-property:label", + "text": "Ctrl", + "dynamic": false, + "count": 1 + }, + { + "filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx", + "kind": "object-property:label", + "text": "Alt", + "dynamic": false, + "count": 1 + }, { "filePath": "mobile/src/tasks/mobile-smart-source-modes.ts", "kind": "object-property:label", diff --git a/config/packaged-runtime-node-modules.cjs b/config/packaged-runtime-node-modules.cjs index a5a9ed3bb33..5a3893af9e5 100644 --- a/config/packaged-runtime-node-modules.cjs +++ b/config/packaged-runtime-node-modules.cjs @@ -15,6 +15,7 @@ const { } = require('./scripts/native-build/windows/windows-pe-machine.cjs') const { adoptPackagedNativeBuildEntries } = require('./packaged-native-build-entries.cjs') const { runtimePackageExcludeFilter } = require('./packaged-windows-only-runtime-files.cjs') +const { missingTranscribeCppPackages } = require('./packaged-transcribe-cpp.cjs') const { NATIVE_BUILD_PACKAGES, TRANSIENT_NATIVE_BUILD_ENTRY_FILTER @@ -81,7 +82,6 @@ const PACKAGED_MAIN_REQUIRED_FILES = [ const PACKAGED_MAIN_SOURCE_RE = /^out\/main\/.+\.js$/ const TYPE_DECLARATION_ARTIFACT_RE = /\.d\.(?:c|m)?ts(?:\.map)?$/ const JS_SOURCE_MAP_ARTIFACT_RE = /\.(?:c|m)?js\.map$/ -const VERSIONED_ONNXRUNTIME_DYLIB_RE = /^libonnxruntime\.\d[\d.]*\.dylib$/ const NODE_BUILTINS = new Set([ ...builtinModules, @@ -518,31 +518,6 @@ function prunePackagedRuntimeTypeAndSourceMapArtifacts(resourcesDir) { pruneMatchingFiles(nodeModulesDir, isPrunableTypeOrSourceMapArtifact) } -function prunePackagedSherpaOnnx(resourcesDir, electronPlatformName) { - if (electronPlatformName !== 'darwin') { - return - } - const nodeModulesDir = join(resourcesDir, 'node_modules') - if (!existsSync(nodeModulesDir)) { - return - } - for (const entry of readdirSync(nodeModulesDir, { withFileTypes: true })) { - if (!entry.isDirectory() || !entry.name.startsWith('sherpa-onnx-darwin-')) { - continue - } - const packageDir = join(nodeModulesDir, entry.name) - const packageEntries = readdirSync(packageDir) - const hasVersionedOnnxRuntime = packageEntries.some((filename) => - VERSIONED_ONNXRUNTIME_DYLIB_RE.test(filename) - ) - if (hasVersionedOnnxRuntime) { - // Why: darwin sherpa-onnx binaries link to the versioned ONNX Runtime - // install name; the unversioned dylib is a duplicate fallback copy. - rmSync(join(packageDir, 'libonnxruntime.dylib'), { force: true }) - } - } -} - function prunePackagedZodSources(resourcesDir) { // Why: Zod's src tree is TypeScript source only selected by the @zod/source // condition; packaged runtime import/require paths resolve to built JS. @@ -556,17 +531,7 @@ function assertPackagedNativeVariantsInstalled(electronPlatformName, electronArc const isInstalled = (name) => existsSync(join(nodeModulesDir, name, 'package.json')) const missing = [] - const rootOptionalDependencies = - JSON.parse(readFileSync(join(projectDir, 'package.json'), 'utf8')).optionalDependencies ?? {} - // Why win32 is always x64: winSpeechNativeResource packages sherpa-onnx-win-x64 for every - // Windows target (there is no sherpa-onnx-win-arm64; it runs under emulation). - const sherpaName = - electronPlatformName === 'win32' - ? 'sherpa-onnx-win-x64' - : `sherpa-onnx-${electronPlatformName}-${architecture}` - if (sherpaName in rootOptionalDependencies && !isInstalled(sherpaName)) { - missing.push(sherpaName) - } + missing.push(...missingTranscribeCppPackages(readPackage, electronPlatformName, architecture)) // Why prefix, not equality: linux variants carry a libc suffix (watcher-linux-x64-glibc), // mirroring what prunePackagedParcelWatcher keeps. @@ -634,7 +599,6 @@ function prunePackagedRuntimeNodeModules(resourcesDir, electronPlatformName, ele // Why before the filename walk: zod/src is deleted wholesale, so walking it first is wasted work. prunePackagedZodSources(resourcesDir) prunePackagedRuntimeTypeAndSourceMapArtifacts(resourcesDir) - prunePackagedSherpaOnnx(resourcesDir, electronPlatformName) } function pruneMatchingFiles(directory, shouldPrune) { @@ -656,13 +620,14 @@ module.exports = { createPackagedRuntimeNodeModuleResources, findAsarEntry, isPackagedExternalSpecifier, + normalizeElectronArchitecture, normalizeNodePtyWindowsArch, packageNameFromSpecifier, prunePackagedNodePty, prunePackagedParcelWatcher, prunePackagedRuntimeNodeModules, prunePackagedRuntimeTypeAndSourceMapArtifacts, - prunePackagedSherpaOnnx, prunePackagedZodSources, + readPackage, verifyPackagedMainRuntimeDeps } diff --git a/config/packaged-transcribe-cpp.cjs b/config/packaged-transcribe-cpp.cjs new file mode 100644 index 00000000000..2fe3334a712 --- /dev/null +++ b/config/packaged-transcribe-cpp.cjs @@ -0,0 +1,97 @@ +const { cpSync, existsSync } = require('node:fs') +const { execFileSync } = require('node:child_process') +const { join } = require('node:path') + +const TRANSCRIBE_CPP_PACKAGES = require('../src/shared/transcribe-cpp-packages.json') +// transcribe.dll needs MSVC runtime >= 14.40 (older ones crash in std::mutex); the system copy may be older. +const WINDOWS_CRT_DLLS = ['msvcp140.dll', 'vcruntime140.dll', 'vcruntime140_1.dll'] +const MIN_WINDOWS_CRT_VERSION = [14, 40] + +/** + * The packages the speech host loads transcribe-cpp from, in load order: the ESM binding, koffi + * (its FFI), koffi's prebuilt addon, and the target's native libraries. Each resolves from the + * previous one's directory, as Node does at runtime. Null where the target ships no transcribe-cpp. + */ +function transcribeCppRuntimePackages(readPackage, electronPlatformName, architecture) { + const native = TRANSCRIBE_CPP_PACKAGES[`${electronPlatformName}-${architecture}`] + if (!native) { + return null + } + const binding = readPackage('transcribe-cpp') + const koffi = readPackage('koffi', binding.packageDir) + const koffiAddon = readPackage( + `@koromix/koffi-${electronPlatformName}-${architecture}`, + koffi.packageDir + ) + const nativeLibraries = readPackage(native, binding.packageDir) + return [binding, koffi, koffiAddon, nativeLibraries] +} + +function readFileVersion(dll) { + const version = execFileSync( + 'powershell.exe', + ['-NoProfile', '-Command', `(Get-Item -LiteralPath '${dll}').VersionInfo.FileVersion`], + { encoding: 'utf8' } + ).trim() + return version.split(/[.,\s]+/).map((part) => Number.parseInt(part, 10)) +} + +function copyWindowsCrt(nativeDir) { + const systemDir = join(process.env.SystemRoot || 'C:\\Windows', 'System32') + for (const name of WINDOWS_CRT_DLLS) { + const source = join(systemDir, name) + if (!existsSync(source)) { + throw new Error( + `Packaging transcribe-cpp needs ${source} (Visual C++ 2015-2022 x64 runtime).` + ) + } + const [major, minor] = readFileVersion(source) + if (!Number.isFinite(major) || !Number.isFinite(minor)) { + throw new Error(`Cannot read the file version of ${source}.`) + } + const [minMajor, minMinor] = MIN_WINDOWS_CRT_VERSION + if (major < minMajor || (major === minMajor && minor < minMinor)) { + throw new Error( + `${source} is ${major}.${minor}; transcribe-cpp needs ${MIN_WINDOWS_CRT_VERSION.join('.')}+. ` + + 'Install the latest Visual C++ 2015-2022 x64 redistributable on the build host.' + ) + } + // App-local beside transcribe.dll, which loads its dependencies from its own directory. + cpSync(source, join(nativeDir, name)) + } +} + +/** Copy transcribe-cpp into the slice's resources/node_modules, outside asar where koffi can dlopen it. */ +function copyPackagedTranscribeCpp(readPackage, resourcesDir, electronPlatformName, architecture) { + // beforePack's assertPackagedNativeVariantsInstalled already failed any real build missing these; + // only an afterPack driven without it (packaging tests) gets here without them. + if (missingTranscribeCppPackages(readPackage, electronPlatformName, architecture).length > 0) { + return + } + const packages = transcribeCppRuntimePackages(readPackage, electronPlatformName, architecture) + if (!packages) { + return + } + for (const { name, packageDir } of packages) { + const target = join(resourcesDir, 'node_modules', ...name.split('/')) + cpSync(packageDir, target, { recursive: true, dereference: true }) + } + if (electronPlatformName === 'win32') { + copyWindowsCrt(join(resourcesDir, 'node_modules', ...packages[3].name.split('/'))) + } +} + +/** The transcribe-cpp packages a target needs that this install lacks (install:release adds other CPUs). */ +function missingTranscribeCppPackages(readPackage, electronPlatformName, architecture) { + try { + transcribeCppRuntimePackages(readPackage, electronPlatformName, architecture) + return [] + } catch (error) { + return [String(error.message ?? error)] + } +} + +module.exports = { + copyPackagedTranscribeCpp, + missingTranscribeCppPackages +} diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 00b3edcbd75..28b0a2371fb 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -459,10 +459,10 @@ "invariant": "A prompt occurrence leaves the input region only when an accepted reply answers it (a current host's provider acknowledgment, or an older host's whole-write acceptance as before) or the user collapses it to a strip above the composer, which writes nothing and keeps the card mounted with its partial answer; status-backed occurrences are told apart by the host wait's start, so view toggles and remounts preserve them while real clear/replacement supersedes them, and a transcript-only one is dropped when the view stops observing it; obsolete results cannot change replacements; selector groups wait for complete writes before pacing; refusal or unknown handoff never causes replay; a card retires an unsubmitted composer send without writing under it or losing its text, and the hidden composer cannot send or interrupt; Collapse or Escape folds a card without writing, never during an in-flight answer, and a new occurrence shows expanded again; the phone blocks only Send while a card is expanded and shows one card per occurrence; cancellation stops unsent groups and active dictation can stop.", "oracle": "Audit2251 narrows agent-paste-draft.test.ts from 25 authored cases (26 literal cases) to four. Retained cases cover buffered readiness on PTY binding, separate spawn/composer lifetimes, real per-PTY paste/Enter serialization against a competing paste, and frame closure/no Enter after a rejected content chunk. Intentionally lost alarms include agent marker and fallback examples, direct-write failure/rejection, missing-PTY and Codex process-only timeout paths, exact nonprimary-PTY routing, full large-body chunk reconstruction, escaping/CRLF samples, internal laziness/yield work assertions, oversized preflight refusal, and exact configured delay/budget counts. No equivalent replacement, new execution, real PTY/provider delivery, rendered/native UI, deployment, measured performance or cross-platform result is claimed. Historical prior account (preserved verbatim): Mobile owner-layout policy retires whole tests and mixed registrations without equivalent replacement coverage. Retained callbacks and reduced selectors need fresh execution at their stated scope; prior measurements do not validate them. Historical oracle: Audit2003: Remove agent-prompt absence routing, throwing/live/missing-probe and cached-probe-count examples from the stale-leaf source. Controller-proven absence, unknown-liveness admission, obsolete-absence clearing and same-ID respawn fences remain at a supplied provider/row seam. Preserve the independent wire-codec receipt only in its original scope. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove partial-runtime terminal-send guard/status/floor/query projection and argument-inventory samples. Retained RPC viewport admission, authenticated-client spoof refusal, text admission and stale-binding fences remain bounded mock-boundary behavior. The unchanged wire-codec receipt remains valid only for its original command; it does not validate this reduced RPC selector. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1908 removes the complete prompt-presentation hook and literal interactive-protocol mapping suites and narrows the interactive card and prompt-card input suites. Lost alarms include replacement approval A settling after answered B; collapse/expand composer ownership and partial-answer presentation; identical new waits after an unmounted view; collapsed transcript re-reads; answered/dismissed status-backed persistence and retirement; and literal answer-to-PTY byte arrays. The retained stale-PTY acknowledgment, cancellation/answer retry, and answered-approval remount/rebind assertions remain meaningful but are not equivalent replacement coverage. No fresh reduced-selector result, physical provider, rendered/native-focus, mixed-version deployment, soak, or measured-budget validation is claimed. The unchanged wire-codec receipt remains valid only for its exact command. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): After acknowledged phone replies with stale host status, the exact card disappears and Send is enabled; unknown, refused or unverifiable-settlement replies retain enabled choices, while an older host's accepted reply dismisses like an acknowledged one; a same-occurrence view toggle retains pending acknowledgment and real replacements discard it. A slow 32 KiB SSH answer completes all chunks before Enter; cancellation preserves issued bytes but omits remaining groups. Paired settlement invokes the actual provider and lost callbacks remain unknown; older hosts deliver ordinary messages, launch and selector groups once and their accepted answers dismiss as before. An answered card stays hidden across a view remount; a collapsed card is a strip that frees the composer and expands back; an identical question in a new wait shows again; a composer send caught by a new card keeps its bubble without submitting or clearing the line under it. Audit2450 removes the MobileNativeChatView failure-banner callback-only example whose old banner is supplied unchanged by its props. Retain fatal-read gating and the ordering test that preserves a new delivery notice. The removed false-send/old-banner combination has no equivalent replacement; prior raw receipts and budgets retain their original source scope. No new soak, platform, performance or red/green claim.", "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-paste-draft.test.ts src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts src/main/runtime/terminal/input/runtime-terminal-writer.test.ts src/main/runtime/rpc/terminal-send.test.ts src/main/runtime/terminal/input/terminal-send-stale-leaf-liveness.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts mobile/src/session/mobile-prompt-controller.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts --maxWorkers=1", - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-paste-draft.test.ts src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx src/renderer/src/components/native-chat/prompts/NativeChatResolvedView.prompt-card-input.test.tsx src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts src/main/ipc/pty/ipc/write-input-user-input.test.ts src/main/ipc/pty/pty-write-ipc-validation.test.ts --maxWorkers=2", "ORCA_BACKGROUND_LAUNCH=1 mobile/node_modules/.bin/vitest run --config mobile/vitest.config.ts mobile/src/session/native-chat/MobileNativeChatView.prompt-presentation.test.ts mobile/src/session/native-chat/MobileNativeChatView.failure-banner.test.ts --maxWorkers=2" ], "testFiles": [ @@ -471,8 +471,8 @@ "src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.prompt-card-composer.test.tsx", "src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx", "src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts", - "src/renderer/src/lib/agent-paste-draft.test.ts", - "src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts", + "src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts", + "src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts", "src/main/ipc/pty/ipc/write-input-user-input.test.ts", "src/main/ipc/pty/pty-write-ipc-validation.test.ts", "src/main/runtime/terminal/input/runtime-terminal-writer.test.ts", @@ -2389,13 +2389,13 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator-tab-palette-activation.test.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts src/renderer/src/lib/open-mobile-emulator-tab.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/cmd-j/worktree-checks-review-index.test.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts src/shared/workspace-session/workspace-session-schema.test.ts", "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], @@ -2404,11 +2404,11 @@ "src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx", "src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts", "src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts", - "src/renderer/src/lib/simulator-palette-search.test.ts", + "src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts", "src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts", - "src/renderer/src/lib/simulator-tab-palette-activation.test.ts", - "src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts", - "src/renderer/src/lib/open-mobile-emulator-tab.test.ts", + "src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts", + "src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts", + "src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts", "src/renderer/src/runtime/web-session-tabs-sync/identity/web-session-tabs-sync-mirror-identity.test.ts", "tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts", "src/shared/workspace-session/workspace-session-schema.test.ts" @@ -2426,7 +2426,7 @@ ] }, { - "file": "src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts", + "file": "src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts", "assertions": [ "same-id folder simulator reuse selects the active owning host", "inactive local simulator creation remains host-stamped amid a collision", @@ -2486,7 +2486,7 @@ "result": "failed", "durationSeconds": 0.8, "summary": "The final-review oracle failed 4/16 before the follow-up: same-id folder simulator reuse selected no owning tab, inactive local simulator creation was unstamped, the paired SSH/runtime alias resolved local metadata, and an explicit unknown owner fell back locally. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts" + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts" }, { "date": "2026-08-20", @@ -2496,7 +2496,7 @@ "result": "failed", "durationSeconds": 0.1, "summary": "The final reviewer repo-label oracle failed 1/6 before the follow-up: a paired SSH worktree resolved the local bare-id repository instead of its runtime-owned repository. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts" + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts" }, { "date": "2026-08-20", @@ -2506,7 +2506,7 @@ "result": "failed", "durationSeconds": 0.1, "summary": "The final clean-round fail-closed oracle failed 1/7 before the follow-up: an unavailable explicit runtime owner borrowed physical SSH repository metadata. Historical command preserved after the test-value audit removed the palette repo resolver suite. currentCommand is an administrative link to a remaining gate command; this historical run has not validated that command or equivalent coverage.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts" + "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts" }, { @@ -4451,7 +4451,7 @@ "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-tabs-sync-browser-tabs.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-grant-registry.test.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/main/browser/document-preview/doc-preview-failure-notice.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts", @@ -4490,7 +4490,7 @@ "src/renderer/src/components/browser-pane/workspace-doc/use-doc-preview-guest-tools.test.ts", "src/renderer/src/components/browser-pane/workspace-doc/HtmlDocPreview.toolbar.test.tsx", "src/shared/document-preview/doc-preview-scheme.test.ts", - "src/renderer/src/lib/doc-preview-grants.test.ts", + "src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts", "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", "src/renderer/src/components/link-actions/LinkActionPopover.test.tsx", "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-editor-diff-tabs.test.ts", @@ -6086,6 +6086,7 @@ "Keep missing-proof mixed-version behavior identical to the incumbent client path." ], "knownGaps": [ + "Audit3037 removes seven supplied-input baseline cases from the terminal-input-gating registrar. Input-and-repaint wrapper selectors and unrelated assertions remain; historical receipts do not validate the reduced source bytes. Pane authority, acknowledgment refusal and quarantine recovery cases remain, without native or RPC execution claims.", "Audit2145 accepts removal of canned runtime metadata/guard/forwarding, fake in-memory persistence, private work-count and wrapper-duplication tests from the construction/orca-runtime.test.ts aggregate, plus the two automation run-context guards from runtime-workspace-launch-contracts.test.ts. Retained race, framing, physical completion and ownership callbacks remain byte-identical. Existing commands remain valid selectors; historical receipts stay unchanged and provide no fresh validation or replacement coverage for the reduced suites.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts: structural support changed only; no new authored removal credit. src/main/runtime/construction/orca-runtime.test.ts: remove only literal registration import/call pairs await import('../orca-runtime-tests/worktree-setup-and-startup.spec'), await import('../orca-runtime-tests/gitlab-and-pr-bases.spec'); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionFreshNativeFollowResetTests } from '../output/pty-connection-fresh-native-follow-reset.spec', registerPtyConnectionFreshNativeFollowResetTests(); no additional authored credit. src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts: routes tab switch and capture start by explicit page id; accepts focus on tab switch without altering bridge args (focus is main-side concern); keeps terminal cwd resolution fail-soft when the provider is unavailable. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts: drops the bounded scan cache when orphan-cleanup removal completes; clears optimistic reconcile tokens when a CLI worktree removal succeeds; emits drift without mutating when the fetched base fast-forwards created HEAD; emits base_changed without mutation when the fetched base rewrote history; skips stale-token reconciles without mutating or emitting stale status; emits unknown without mutation when fetch fails or the base ref is missing. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts: routes runtime preserved-branch force-delete through the selected WSL project runtime; replies to a waiting client with the error of a delete that fails after acceptance; treats forced runtime deletion of an already-missing unregistered worktree as cleanup; treats normal runtime deletion of an already-missing unregistered worktree as cleanup. src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts: warns that a missing-repo removal only forgot the workspace; restores runtime watchers when CLI worktree deletion fails after teardown; does not re-spend the drain budget on a removal after a wedged install was abandoned; routes runtime worktree removal through the selected WSL project runtime; force-deletes a branch that was preserved by runtime worktree removal. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts: records GitLab pasted-project recents only after successful runtime lookup; threads explicit origin preference through runtime WSL PR base resolution; resolves local GitLab fork MR bases from the target project MR head ref; captures the fork MR head from a dedicated ref, not the shared FETCH_HEAD; keeps the durable MR head when the head fetch fails but the local ref resolves; routes runtime GitLab fork MR base git calls through the selected WSL project runtime. src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts: passes SSH connection ids through GitLab task operations; routes runtime GitLab issue, MR, work-item, and todo actions through the selected WSL project runtime; routes runtime GitLab MR details, review-management, job, and pasted URL actions through the selected WSL project runtime; normalizes runtime GitLab issue list arguments like the desktop IPC path. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts: does not warn when setup is explicitly skipped for CLI-created worktrees; puts the agent a create starts in the first default tab, as the window does; keeps the 8s main-runtime startup readiness budget for agents without an override; gives OpenCode the 20s main-runtime startup readiness budget; launches explicit startup agents with prompts for CLI-created worktrees. src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts: returns a setup launch payload for CLI-created worktrees when hooks are explicitly enabled; does not hand the window a setup main never tried to start; passes the selected Windows setup shell into runtime runner generation; follows normal setup policy for CLI-created worktrees without activating them; uses returned WSL setup shell metadata when runtime spawns setup; uses the shell-aware setup runner for windowless creates without a startup command; reports the in-process setup hook as running when nothing can launch the runner. src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts: coalesces two clients sleeping the same host worktree; stops exactly the expected live PTYs for a worktree; explains a refused workspace close instead of throwing the raw refusal enum. src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts: marks the desktop-active worktree as isActive; includes SSH-backed worktrees in the mobile worktree summary; caches repeated malformed path misses before normalizing them again. src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts: keeps title-only foreground work ahead of monitoring in another pane; keeps a local hook row while a connected PTY still backs its pane; keeps an OSC row via its connected PTY after the pane binding is cleared. src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts: resolves files through a source-visible linked-checkout worktree; marks saved session tabs with live PTYs as host sidebar activity; attributes live legacy PTYs from saved layout bindings when their panes are hidden; marks saved browser tabs as host sidebar activity like desktop; falls back to the path-keyed GitHub cache entry; includes folder workspaces in compact worktree summaries for mobile; attaches inline agent rows from the latest OSC 9999 status; projects monitoring over a title-derived working status. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts: pushes to an idle pane when the only live waiter filters out the message type; resolves a registered waiter without PTY-injecting when the leaf is already idle; keeps already-idle status after tui-idle wait for immediate message delivery; resolves message waiters when notifyMessageArrived is called; does not resolve type-filtered message waiters for unrelated message types; removes message waiter abort listeners after message arrival; resolves message waiters on timeout when no message arrives. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts: delivers pending mail via notifyMessageArrived when the recipient is already idle; does not keep retrying when every pending row was already pointed; repoints pending rows restored with a live-idle coordinator. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts: rolls back a half-created terminal whose surface never publishes. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts: rejects startup prompts for agents that require post-ready stdin; uses portable Unix quoting for mobile agent launch commands in WSL project runtimes; keeps PowerShell quoting for mobile agent launch commands in Windows host runtimes; uses cmd.exe quoting for mobile agent launch commands in local Windows host runtimes; publishes headless mobile session agent identity with synthesized PTY status; rejects disabled mobile session agent launches before spawning; validates mobile terminal insertion anchors before resolving agent launch commands. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts: coalesces a reconnect close burst onto one authoritative PTY inventory; keeps an explicit user close destructive while the PTY is live; builds mobile session agent launch commands on the runtime host; injects mobile quick-command prompts into the host-built agent startup command. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts: closes persisted headless terminal parents before any prior list call; tears down a serve-owned headless tab on close while a renderer is attached so it cannot resurrect; defers a renderer-published pending tab to the renderer instead of tearing it down; returns a delegated close outcome with no selection tombstone when the renderer owns the outcome; tears down a runtime pending shell the renderer never adopted on close. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts: materializes a plain shell when the pending tab has no launch agent; hydrates legacy persisted terminal tabs without layout entries; reads and indexes the full agent-status snapshot once per mobile projection; kills persisted SSH PTYs when closing hydrated headless tabs before pane metadata is restored; materializes hydrated pending headless terminals with the persisted session identity. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts: hydrates a persisted SSH-owned pane before an attached renderer publishes its graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts: publishes the desktop's tab name over the live agent title, and the live title without one; uses fresh neutral PTY titles over stale mobile snapshot and OSC titles; operates PTY-backed mobile session terminals without a renderer graph; reuses pane close for live PTYs that do not own a renderer tab; lists PTY-backed mobile session terminals without a renderer graph; shows and resolves active PTY-backed mobile session terminals without a renderer graph. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts: creates mobile session terminals for folder workspaces in a headless runtime server; spawns fresh headless SSH mobile session terminals instead of reattaching synthetic local ids; hydrates headless mobile session terminals from the host workspace session; keeps live headless mobile session terminals when a desktop renderer publishes without them; publishes laptop-created remote runtime split terminals to phone session tabs. src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts: does not report headless wake degradation without sleeping records; does not wake slept agents for non-mobile session-only activation; does not rewrite unread metadata when a mobile activation finds the worktree already read; returns unread:false from worktree.ps after a mobile activation clears the flag; materializes pending mobile session terminals without focusing desktop clients; closes browser mobile session tabs when addressed by browser workspace id. src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts: resolves mobile terminal surfaces by exact split leaf; closes the matching mobile terminal UUID leaf without closing the whole tab; closes the whole mobile terminal tab when addressed by parent tab id; activates the active split leaf when addressed by parent tab id; clears unread metadata on mobile worktree activation without focusing desktop clients; wakes slept agents on the host renderer when a phone activates a worktree. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts: publishes the hook provider session on a headless mobile tab so native chat can address the transcript; recovers the agent type from the hook row when the pane was launched without an agent hint; reads one agent-status snapshot per projection, not one per terminal tab; waits for unknown-launch foreground owner before publishing Pi-compatible mobile status; keeps Pi-compatible mobile session status as Pi for an unknown-launch foreground pi PTY; keeps renderer-vetted mobile agent status for custom-titled terminals. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts: publishes terminal surface agent status for paired web clients; preserves authoritative OMP identity for Pi-compatible remote terminal snapshots; normalizes a remote OMP title without republishing omitted launch identity; skips the foreground-process probe when the PTY launch agent is already known; probes the foreground process only on a status transition for unknown launch agents; passes the client signal and the slept-worktree refusal to the spawn. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts: does not use stale runtime-created PTY status when a neutral PTY title exists; recognizes runtime-created Codex PTY handles from the ready prompt; recognizes runtime-created Antigravity PTY handles from the ready prompt; recognizes live leaf Antigravity terminals from the ready prompt; recognizes a later Antigravity header with a prompt but no model line; keeps mobile terminal surfaces visible while their leaf handle is pending. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts: lets Claude agents management titles clear stale runtime-created title status; does not recognize live Claude agents panes from a Claude foreground process; does not let stale tab-level agent titles override current neutral pane titles; lists live terminals with fresh pane titles over stale tab titles; lets adopted neutral pane titles use non-shell foreground fallback; lets adopted neutral pane titles retry wrapper foregrounds until recognized; authorizes settled CLI prompts only after positive %s foreground identity; does not recognize arbitrary foreground TUIs as running agents; lets live neutral pane titles retry wrapper foregrounds until recognized; lets current Claude agents PTY titles override stale runtime-created OSC titles; does not let stale Claude agents OSC titles suppress current PTY title activity. src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts: keeps preallocated terminal handles valid across renderer reloads; preserves runtime-created PTY process identity after graph unavailable; keeps prompt bindings fenced across runtime restarts without provider incarnation; recognizes runtime-created PTY handles with agent launch titles; does not treat a bare Cursor Agent native title as a running agent session; uses stale runtime-created PTY status when there is no title or foreground evidence. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts: keeps orphaned list and show writability aligned with the send gate. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts: cancels a coalesced SSH worker recovery retry when its provider disconnects. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts: retries renderer reveal before clearing an adopted legacy worker sleeping record. src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts: recovers exported ORCA_TERMINAL_HANDLE from discovered live PTY sessions. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts: applies ANSI erase-from-start line controls in retained previews; applies ANSI stripping for private or intermediate CSI line controls; applies ANSI stripping for unsupported erase-line modes; reveals an agent terminal under the pane the caller reserved; keeps a fresh %s pane host-owned when a desktop window is available; keeps desktop publication %s separate from the reserved host spawn; mints its own pane when the reserved leaf is malformed, and reports the one it used; starts an agent terminal with the model the caller picked; starts an agent terminal without a model flag when no pick was made; attributes a startup-agent launch named %s as %s; attributes a fresh agent session the host builds as unknown; leaves a bare agent command the user typed out of launch attribution. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts: trims oversized terminal output bursts without per-line array shifts; builds terminal previews without mapping the full retained tail; keeps recent PTY replay output capped without needing previous data for large chunks; applies terminal redraw controls before retaining previews; applies ANSI terminal redraw controls before retaining previews; retains multi-line ANSI footer redraws instead of appending old frames; keeps the cursor column when erasing full lines in multi-line redraws; applies ANSI split redraw controls without leaking raw params. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts: returns renderer visible screen lines through terminal.read RPC JSON result; separates composer drafts from provider-owned terminal screens. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts: reports an in-flight PTY focus as not navigated when its notifier disappears; reports graph-leaf focus as not navigated without a host notifier; grounds the provider mode tracker before a later chunk, in the emulator order; grounds an in-flight provider snapshot capture so it cannot publish the pre-reset screen; waits for terminal exit and resolves with the exit status; keeps terminal read payloads bounded while retained output remains pageable; trims terminal read preview character budget without per-line array shifts. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts: submits a silent Claude composer once after the bounded render fallback; chunks large terminal.send text before provider writes; yields chunked terminal input through immediates between writes; yields while validating accepted large terminal.send text before provider writes; reveals a background terminal session when focusing its handle; replays captured launch config when focusing a background agent session; reveals background terminal sessions with the freshest PTY title; renames background terminal handles without requiring a visible tab; keeps a background terminal handle stable while reveal adoption is racing. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts: resolves tui-idle when a stale Codex prompt is followed by Antigravity readiness; returns an agent-neutral blocked wait result for update prompts; returns an agent-neutral blocked wait result for workspace trust prompts; returns an agent-neutral blocked wait result for cwd selection prompts; returns a blocked wait result for Codex model migration prompts; returns a blocked wait result for Codex startup hook review prompts; returns an agent-neutral blocked wait result for generic interactive prompts; splits text and enter writes for background terminal handles; types the lead line for %s: %s; submits through the agent-specific PTY timing policy for %s. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts: waits for exit on background terminal handles; keeps retained PTY transcript memory when controller refresh fails; resolves tui-idle from an Antigravity ready prompt preview; resolves Antigravity ready prompts with newline-heavy pasted tails without splitting; resolves live-leaf tui-idle from an Antigravity ready prompt preview. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts: spawns the available Qoder command for a captured same-session resume: %s; does not use the local Windows shell setting for remote Windows bare agent creates; matches canonical bare agent commands when a command override is configured; keeps non-bare agent command terminal creates unchanged; keeps disabled bare agent command terminal creates unchanged; injects runtime hook receiver env into terminal sessions; creates background terminal sessions for a $label; creates background terminal sessions for a $label; enables Claude Agent Teams only for direct Claude launches when configured in-process; reveals Claude Agent Teams launches with the rewritten launch config; preserves Claude Agent Teams for sequenced Claude launches. src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts: creates visible terminal sessions without asking the renderer to focus a tab; asks the pty controller for the requested shell instead of a startup command; knows the agent a flagged launch command names before any process read; retires a flagged command pane identity when the command exits; retires only receipted restored PTY authority on command completion and exit; forgets synthetic handles when disconnected PTY records are pruned. src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts: returns OSC titles from headless main terminal snapshots; adopts renderer-seeded titles into headless main terminal snapshots; returns cwd metadata from seeded headless main terminal snapshots; adopts OSC7 host metadata from seeded headless terminal scrollback; falls back to the renderer snapshot for hidden-output recovery without headless state; keeps an empty headless snapshot authoritative for hidden-output recovery; advances the absolute output sequence across a daemon stream gap; emits explicit OSC 9999 agent status from runtime PTY data. src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts: falls back to the provider snapshot for a restored PTY with no mounted renderer; falls back to the available mirror when authoritative provider history is unavailable; keeps an empty renderer snapshot when the provider has no retained content; keeps restored provider history authoritative after later live output; uses provider alternate-screen state while a partial model is unsafe; prefers the tracked title over the headless emulator lastTitle; keeps the cursor-agent literal in record-fallback snapshots only without a tracker title; touches mobile snapshots once for decorative spinner ticks, again on idle. src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts: creates a same-repo PR branch override from a resolved head SHA and matching push target; skips broad remote fetch for an existing full-SHA PR base; creates a selected Bitbucket PR branch override from a matching remote branch; suffixes an existing PR when a matching push target lacks selected PR metadata; suffixes a matching push target branch when selected PR metadata has no PR number; suffixes a matching push target branch when the existing PR is different; suffixes a selected PR remote conflict when the PR lookup fails; checks out an unused runtime PR branch only when it is at the resolved head SHA; suffixes only the runtime worktree path when an exact PR branch checkout path exists. src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts: returns runtime local base update suggestions from addWorktree; creates a runtime local worktree from a usable persisted local branch base; does not create a runtime local worktree when the refresh fails and no local base ref exists; creates a branchNameOverride worktree from the selected matching remote base ref. src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts: repaints from the main-owned snapshot when main drops pending output at the cap. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts: records a mode 2031 subscribe from the raw chunk boundary without answering. src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts: retries a fresh-spawn native follow reset when renderer dimensions return. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/construction/orca-runtime.test.ts, src/main/runtime/orca-runtime-tests/targeting-and-resilience.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-04.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-removal-and-reconciliation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases-part-02.spec.ts, src/main/runtime/orca-runtime-tests/gitlab-and-pr-bases.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup-part-03.spec.ts, src/main/runtime/orca-runtime-tests/worktree-setup-and-startup.spec.ts, src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-13.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-12.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-11.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-10.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-08.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-07.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-05.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-04.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs-part-02.spec.ts, src/main/runtime/orca-runtime-tests/mobile-session-tabs.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-05.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-12.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-11.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-10.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-09.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-08.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-07.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-06.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-03.spec.ts, src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness.spec.ts, src/main/runtime/orca-runtime-tests/headless-snapshots.spec.ts, src/main/runtime/orca-runtime-tests/terminal-side-effect-facts-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation-part-02.spec.ts, src/main/runtime/orca-runtime-tests/local-worktree-creation.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2095 current-parent preparation2126 (approved2092/2093 removals; source refresh2109/independent2112): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts: rejects exact terminal stop for multiple expected PTYs before stopping anything; omits stale renderer leaves when fresh PTY liveness is required; omits unbound renderer placeholders when fresh PTY liveness is required; captures the event method before the nested sleep receipt changes it; returns the close receipt without requiring a PTY stop; uses the same stop result as an empty explicit stop. src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts: builds a compact worktree summary from persisted and live runtime state; reads the linked-PR state from the renderer repoId-keyed GitHub cache; carries persisted worktree host ownership in mobile summaries; emits only instance- and boundary-validated lineage parents in mobile summaries; resolves WSL platforms only for repos represented in mobile summaries; omits worktrees hidden by the host visibility policy from mobile summaries; applies linked-checkout source visibility to mobile summaries. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts: routes runtime GitHub PR details and actions through the selected WSL project runtime; passes SSH connection context through hosted review creation flows; routes local WSL project hosted review flows through runtime git options; treats SSH worktree drift as unknown without local git probes. src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts: emits one mobile session terminal tab per live PTY even if two tabs resolve to it; resolves projected split authority from the parent layout PTY binding; keeps explicit-id terminal lists from resolving all worktrees; keeps explicit-id cold-cache terminal lists from classifying unrelated same-repo worktrees; keeps unknown bare terminal-list ids on the no-scan exact-id path; matches explicit-id cwd PTYs for folder workspace instance IDs; routes PTY output through the PTY leaf index in large terminal graphs. src/main/runtime/orca-runtime-tests/window-authority.spec.ts: claims the first window as authoritative and ignores later windows; transfers authority from the headless sentinel to the first real window; relays terminal browser launches only while headless owns the graph; marks live headless PTYs for renderer reattach before desktop promotion; reports the activation gate state while no desktop window is available; bumps the epoch and enters reloading when the authoritative window reloads; can mark the graph ready for the authoritative window; drops back to unavailable and clears authority when the window disappears; hands the graph back to headless when a promoted serve window closes (#27292); keeps a crashed promoted serve renderer on its own window while the window is open; stays unavailable during initial loads before a graph is published. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/main/runtime/orca-runtime-tests/terminal-sleep-and-teardown-part-03.spec.ts, src/main/runtime/orca-runtime-tests/mobile-creation-and-orchestration-part-04.spec.ts, src/main/runtime/orca-runtime-tests/hooks-and-hosted-review-part-02.spec.ts, src/main/runtime/orca-runtime-tests/terminal-listing.spec.ts, src/main/runtime/orca-runtime-tests/window-authority.spec.ts. Unresolved local/computed edges remain explicit debt.", @@ -6817,8 +6818,7 @@ "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts", "assertions": [ "fresh local IPC worktree spawns are marked with cwdFallback worktree", - "startup cwd fallback metadata prints a generic in-terminal notice", - "remote-runtime worktree spawns are not marked with cwdFallback" + "startup cwd fallback metadata prints a generic in-terminal notice" ] } ], @@ -6856,6 +6856,7 @@ "Add WSL/mobile/API spawn provider-contract coverage or explicitly narrow their risk scope." ], "knownGaps": [ + "Audit3037 retires the runtime-owner spawn-routing suite and its remote cwdFallback-absence assertion claim. Actual routing-composition alarms are intentionally lost; no replacement or renewed execution credit. Other historical claims and receipts retain their original scope.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec', registerPtyConnectionTerminalBellAttentionTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts: forwards onBell to pane attention and notification policy; hands the bell to the attention module with its pane even when pane attention is off. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts, src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts. Unresolved local/computed edges remain explicit debt.", "Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", @@ -10887,7 +10888,7 @@ "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coverageNotes": "Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/11107#discussion_r3663321387", "https://github.com/stablyai/orca/issues/13858", @@ -10897,11 +10898,11 @@ "https://linear.app/stably/issue/STA-4022" ], "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. A worker_done caller may report success only after the owning runtime returns an explicit lifecycle verdict or authoritative reads prove that the exact Task, Dispatch, and worker report receipt settled the expected outcome. Federated terminal settlement must remain replay-eligible until the worker durably acknowledges it, and identical same-outcome retries must converge idempotently. Independently updated clients and worker servers must preserve the negotiated protocol: current peers use Run-home lifecycle settlement, while protocol v1/v2 peers retain their legacy completion path without receiving newer-only fields. A federated worker may accept only the authority defined by its negotiated protocol. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata. A nested worker's creator edge requires the current creator pane, process incarnation, and owning Run generation; reminting and rebinding that pane to another Run must remove the stale edge. Explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "oracle": "Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", "commands": [ "ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts src/cli/handlers/orchestration-migration.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation-lifecycle-settlement.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts --reporter=dot", @@ -10915,7 +10916,6 @@ "src/cli/handlers/orchestration.test.ts", "src/cli/handlers/orchestration-lifecycle-rejection.test.ts", "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", - "src/cli/handlers/orchestration-migration.test.ts", "src/cli/handlers/orchestration-check-identity.test.ts", "src/cli/handlers/orchestration-worker-cli.test.ts", "src/main/runtime/rpc/methods/orchestration/worker/composed-workers.test.ts", @@ -10950,12 +10950,6 @@ "file": "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts", "assertions": ["a rejected lifecycle verdict is emitted as a JSON ok=false envelope"] }, - { - "file": "src/cli/handlers/orchestration-migration.test.ts", - "assertions": [ - "first and replayed legacy worker_done settlements are accepted from their authoritative runtime verdict" - ] - }, { "file": "src/cli/handlers/orchestration-check-identity.test.ts", "assertions": [ @@ -11038,15 +11032,6 @@ "result": "passed", "durationSeconds": 20, "summary": "The combined candidate passed one real Electron and compiled-CLI journey: wrong worker identity exited nonzero with ok=false while Dispatch stayed dispatched, the exact worker received an explicit completed verdict, and runtime state independently reached completed." - }, - { - "date": "2026-08-11", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts src/cli/handlers/orchestration-migration.test.ts", - "result": "passed", - "durationSeconds": 0.4, - "summary": "Three focused files passed 12 deterministic tests covering explicit current and Run-home verdicts, JSON failure output, exact report and terminal-state verification for stripped responses, stale/stopped rejection, idempotent retry, and first/replayed attested legacy settlements." } ], "runtimeBudget": { @@ -11072,6 +11057,8 @@ "Attach saved intentional-break artifacts for hidden local presentation and dropped stable-pane delivery." ], "knownGaps": [ + "Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit.", + "Audit2923 retires this entire mixed three-file receipt from current evidenceRuns because its selector included the removed migration suite. Preserved verbatim original JSON object (historical only; no reduced-selector validation):\n{\n \"date\": \"2026-08-11\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration-lifecycle-rejection.test.ts src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts src/cli/handlers/orchestration-migration.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 0.4,\n \"summary\": \"Three focused files passed 12 deterministic tests covering explicit current and Run-home verdicts, JSON failure output, exact report and terminal-state verification for stripped responses, stale/stopped rejection, idempotent retry, and first/replayed attested legacy settlements.\"\n }", "Audit2086 (sources2082/2083): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-06.spec.ts: suppresses saved mobile agent status when live evidence is the Claude agents screen; suppresses saved mobile agent status when the current terminal title is neutral; suppresses saved mobile agent status when fresh live OSC title is Claude agents; keeps saved PTY bindings pending until the runtime knows the PTY is connected; refreshes daemon PTY liveness before publishing mobile session tabs; does not invalidate a newly spawned SSH pane from an overlapping stale process list. src/main/runtime/orca-runtime-tests/pty-title-status.spec.ts: associates controller PTYs with mixed-case Windows and UNC cwd paths; uses OSC titles rather than controller process names for rendererless PTYs; ignores the bare cursor-agent native title so synthesized spinner state survives; only records the bare Cursor native title via the stale-working clear; refuses a bare Cursor title while the foreground read is unavailable; does not treat a bare Cursor title as an agent once the shell owns the foreground; accepts a bare Cursor title when the foreground read confirms cursor-agent; refuses a bare Cursor title on a runtime pty with no controller attached; clears a stale working title after 3s of title-less output; cancels the stale-title timer when the PTY exits; keeps stale-title timers isolated per PTY. src/main/runtime/orca-runtime-tests/paired-settings.spec.ts: projects runtime-backed settings to paired clients; updates quick commands without widening general paired settings payloads; applies native-chat option deltas atomically on the runtime host; keeps a future-launch default when an older client asks to prune from inventory; preserves concurrent additions after forty quick commands; accepts runtime-backed setting updates from paired clients; broadcasts visibility default changes to paired clients; reconciles hooks only when paired-client hook settings change; rejects relative paths for runtime nested repo scan/import. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", "Audit2070 (sources2068/2069): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime.test.ts: ordinary registration cleanup removes only await import('./orca-runtime-tests/hooks-and-hosted-review.spec'). src/main/runtime/orca-runtime-tests/worktree-removal-archive-hook-gate.spec.ts: removes and records the waiver when the failure is explicitly overridden; removes without an override record when the hook succeeds; removes when the hook is configured but not requested; removes when no archive hook is configured; holds a desktop removal in the same repo until this one is accepted; joins a desktop removal of the same worktree accepted while this one waited. src/main/runtime/orca-runtime-tests/worktree-ps-agent-row-dismissal.spec.ts: drops the row as soon as the user dismisses it, without waiting for the PTY to exit; tells paired clients to republish on the transition and on the dismissal; rejoins a row through its %s handle after pane ownership clears. src/main/runtime/orca-runtime-tests/hooks-and-hosted-review.spec.ts: reports an error when the SSH filesystem provider is unavailable; reports an SSH orca.yaml as an error without reading any filesystem; reports ok for a local repo hook check; reads SSH issue commands as absent and drops writes without touching any filesystem; allows host integration slug helpers for SSH repos through provider-aware GitHub clients; routes runtime GitHub repo identity helpers through the selected WSL project runtime; routes runtime GitHub issue and work-item actions through the selected WSL project runtime; pins explicit origin preference on runtime open-by-number work item lookups; forwards check-details cancellation without local Git overrides. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence.", @@ -12415,6 +12402,7 @@ "Add Linux and Windows WebGL visibility evidence before claiming cross-platform visual coverage." ], "knownGaps": [ + "Audit3037 removes seven supplied-input baseline cases from the terminal-input-gating registrar. Input-and-repaint wrapper selectors and unrelated assertions remain; historical receipts do not validate the reduced source bytes. No renewed atlas, renderer, native or performance evidence is claimed.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts: refreshes after each scheduled atlas reset; falls back to a timeout when animation frames are unavailable; continues recovery when a manager throws after scheduling. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts: structural support changed only; no new authored removal credit. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionFreshNativeFollowResetTests } from '../output/pty-connection-fresh-native-follow-reset.spec', registerPtyConnectionFreshNativeFollowResetTests(); no additional authored credit. src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts: repaints from the main-owned snapshot when main drops pending output at the cap. src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts: records a mode 2031 subscribe from the raw chunk boundary without answering. src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts: retries a fresh-spawn native follow reset when renderer dimensions return. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-dropped-output-snapshot-healing.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/emulation/pty-connection-mode2031-raw-subscription.spec.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output/pty-connection-fresh-native-follow-reset.spec.ts, src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts. Unresolved local/computed edges remain explicit debt. Retired active assertionRefs (raw original objects retained as historical only): {\n \"file\": \"src/renderer/src/components/terminal-pane/render-health/terminal-webgl-atlas-recovery.test.ts\",\n \"assertions\": [\"limits atlas recovery to explicit renderer lifecycle events\"]\n }", "The Electron harness used a deterministic visibility-event fallback because BrowserWindow.hide did not change document.visibilityState.", "No isolated live paired-server candidate run is recorded; remote-runtime coverage is a provider-agnostic renderer contract plus production incident evidence.", diff --git a/config/renderer-layout-writer-baseline.txt b/config/renderer-layout-writer-baseline.txt index 96f667bb196..1c132f4e79c 100644 --- a/config/renderer-layout-writer-baseline.txt +++ b/config/renderer-layout-writer-baseline.txt @@ -27,6 +27,7 @@ 3 src/renderer/src/lib/workspace/persistence/workspace-session-staged-browser-tabs.ts 1 src/renderer/src/lib/workspace/persistence/workspace-session-unified-tabs.ts 17 src/renderer/src/lib/workspace/persistence/workspace-session.ts +13 src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts 3 src/renderer/src/runtime/hosted-terminals/recovery/adoption/web-session-terminal-recovery-snapshot-validation.ts 1 src/renderer/src/runtime/hosted-terminals/recovery/surfaces/web-session-terminal-orphan-recovery-surface.ts 2 src/renderer/src/runtime/hosted-terminals/recovery/surfaces/web-session-terminal-orphan-topology.ts @@ -35,15 +36,14 @@ 10 src/renderer/src/runtime/sync-runtime-graph/mobile-session-group-projection.ts 2 src/renderer/src/runtime/sync-runtime-graph/mobile-session-snapshots.ts 2 src/renderer/src/runtime/sync-runtime-graph/sync-key.ts -13 src/renderer/src/runtime/browser/creation/testing/web-runtime-browser-creation-placement-test-rig.ts -1 src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot.ts -3 src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-client-owned-tab-placement.ts 1 src/renderer/src/runtime/web-session-tabs-sync/agent-status-primitives.ts 8 src/renderer/src/runtime/web-session-tabs-sync/apply-active-state.ts 18 src/renderer/src/runtime/web-session-tabs-sync/apply-final-patch.ts 2 src/renderer/src/runtime/web-session-tabs-sync/apply-preparation-groups.ts 5 src/renderer/src/runtime/web-session-tabs-sync/apply-terminal-records.ts 4 src/renderer/src/runtime/web-session-tabs-sync/apply-worktree-records.ts +1 src/renderer/src/runtime/web-session-tabs-sync/inventory/web-runtime-session-snapshot.ts +3 src/renderer/src/runtime/web-session-tabs-sync/placement/web-session-client-owned-tab-placement.ts 2 src/renderer/src/runtime/web-session-tabs-sync/session-tabs-inventory-absence.ts 10 src/renderer/src/store/slices/browser/cleanup/browser-close-actions.ts 2 src/renderer/src/store/slices/browser/create-browser-slice.ts @@ -57,7 +57,7 @@ 9 src/renderer/src/store/slices/editor/checks/check-run-details-actions.ts 6 src/renderer/src/store/slices/editor/closing/close-file-action.ts 10 src/renderer/src/store/slices/editor/closing/recently-closed-editor-tabs.ts -3 src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts +1 src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts 2 src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-selection.ts 1 src/renderer/src/store/slices/editor/file-ids/open-file-path-rekey.ts 2 src/renderer/src/store/slices/editor/file-ids/rekey-open-files-action.ts @@ -82,7 +82,7 @@ 4 src/renderer/src/store/slices/tabs/tab-group-state.ts 9 src/renderer/src/store/slices/tabs/tabs-close-actions.ts 14 src/renderer/src/store/slices/tabs/tabs-create-actions.ts -23 src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts +22 src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts 11 src/renderer/src/store/slices/tabs/tabs-drop-actions.ts 8 src/renderer/src/store/slices/tabs/tabs-empty-workspace.ts 4 src/renderer/src/store/slices/tabs/tabs-focus-actions.ts @@ -91,11 +91,13 @@ 1 src/renderer/src/store/slices/tabs/tabs-hydration.ts 8 src/renderer/src/store/slices/tabs/tabs-label-actions.ts 10 src/renderer/src/store/slices/tabs/tabs-move-actions.ts -9 src/renderer/src/store/slices/tabs/tabs-reconciliation.ts +4 src/renderer/src/store/slices/tabs/tabs-reconciliation-batch.ts # split from tabs-reconciliation.ts (9 -> 2 + 4) +2 src/renderer/src/store/slices/tabs/tabs-reconciliation.ts 4 src/renderer/src/store/slices/tabs/tabs-session-actions.ts 1 src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts 5 src/renderer/src/store/slices/tabs/tabs-surface.ts -24 src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts +19 src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts +3 src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts # moved unchanged out of worktree-layout-lifecycle.ts (24 -> 19 + 3) 5 src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts 2 src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts 6 src/renderer/src/store/terminals/create-terminal-slice.ts @@ -112,7 +114,7 @@ 10 src/renderer/src/store/terminals/terminal-tab-creation.ts 7 src/renderer/src/store/terminals/terminal-tab-navigation.ts 3 src/renderer/src/store/terminals/terminal-tab-presentation.ts -4 src/renderer/src/store/terminals/terminal-tab-title-batch.ts +2 src/renderer/src/store/terminals/terminal-tab-title-batch.ts 5 src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts 2 src/renderer/src/store/terminals/workspace-terminal-hydration.ts 2 src/renderer/src/store/terminals/workspace-terminal-reconnect.ts diff --git a/config/scripts/build/mobile-web-app/mobile-web-page-routes.mjs b/config/scripts/build/mobile-web-app/mobile-web-page-routes.mjs index 1e391c41ccc..79d0482fb59 100644 --- a/config/scripts/build/mobile-web-app/mobile-web-page-routes.mjs +++ b/config/scripts/build/mobile-web-app/mobile-web-page-routes.mjs @@ -102,13 +102,14 @@ export const MOBILE_WEB_PAGE_ROUTES = [ 'native.audio.read', 'native.audio.stop' ], - // Optional media.name falls back to the file type; terminalKeyRail falls back to the page's row; the image viewer drops its actions without native.image.act; dictation uses the computer without native.speech.act. + // Optional media.name falls back to the file type; terminalKeyRail falls back to the page's row; the image viewer drops its actions without native.image.act; dictation uses the computer without native.speech.act; without native.a11y.announce only the page's live region speaks. optionalGrants: [ 'externalNavigation', 'native.media.name', 'native.pdf.view', 'native.image.act', 'native.speech.act', + 'native.a11y.announce', 'terminalKeyRail', DEVICE_STORE_GRANT ] diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 27d7cc7420f..50cf3747f19 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -102,9 +102,7 @@ "config/scripts/locale-catalog/locale-repair-catalog-missing-leaves.test.mjs": 159, "config/scripts/locale-catalog/locale-translation-policy-ko-round5.test.mjs": 154, "config/scripts/locale-catalog/locale-translation-policy.es-pr.test.mjs": 91, - "config/scripts/locale-catalog/locale-translation-policy.es-round5.test.mjs": 153, "config/scripts/locale-catalog/locale-translation-policy.ja-relocalization.test.mjs": 116, - "config/scripts/locale-catalog/locale-translation-policy.ja-round5.test.mjs": 209, "config/scripts/locale-catalog/locale-translation-policy.test.mjs": 189, "config/scripts/localization/source-extraction/localization-extraction-call-syntax.test.mjs": 317, "config/scripts/localization/extraction-policy/localization-extraction-change-scope.test.mjs": 732, @@ -313,7 +311,6 @@ "src/cli/automation-owner-conflict-recovery.test.ts": 448, "src/cli/automation-runs-paging.test.ts": 569, "src/cli/browser/browser-empty-values.test.ts": 313, - "src/cli/browser/browser.test.ts": 431, "src/cli/codex-command-classification.test.ts": 65, "src/cli/command-suggestion-budget.test.ts": 132, "src/cli/command-suggestion-destructive-families.test.ts": 226, @@ -331,7 +328,6 @@ "src/cli/handlers/automation-owner-fencing.test.ts": 529, "src/cli/handlers/computer-action-validation.test.ts": 317, "src/cli/handlers/computer-state-formatting.test.ts": 337, - "src/cli/handlers/connector.test.ts": 781, "src/cli/handlers/core.test.ts": 194, "src/cli/handlers/data-account-commands.test.ts": 431, "src/cli/handlers/emulator.test.ts": 303, @@ -348,21 +344,13 @@ "src/cli/handlers/orchestration-legacy-read-only.test.ts": 526, "src/cli/handlers/orchestration-lifecycle-json-rejection.test.ts": 555, "src/cli/handlers/orchestration-lifecycle-rejection.test.ts": 781, - "src/cli/handlers/orchestration-migration.test.ts": 536, - "src/cli/handlers/orchestration-request-show-cli.test.ts": 581, - "src/cli/handlers/orchestration-send-receipt-warnings.test.ts": 565, - "src/cli/handlers/orchestration-task-create-cli.test.ts": 652, "src/cli/handlers/orchestration-task-list-brief.test.ts": 494, - "src/cli/handlers/orchestration-windows-ask-cli.test.ts": 801, "src/cli/handlers/orchestration-worker-cli.test.ts": 706, - "src/cli/handlers/orchestration-worker-show-wait-cli.test.ts": 748, "src/cli/handlers/orchestration.test.ts": 543, "src/cli/handlers/orchestration/agent-view.test.ts": 511, "src/cli/handlers/orchestration/concise-list-row-size.test.ts": 492, "src/cli/handlers/orchestration/mutation-request.test.ts": 4146, "src/cli/handlers/orchestration/older-runtime-run-binding.test.ts": 547, - "src/cli/handlers/orchestration/terminal-identity-codex-filtered.test.ts": 409, - "src/cli/handlers/orchestration/worker-list-run-scope.test.ts": 495, "src/cli/handlers/orchestration/worker-output.test.ts": 79, "src/cli/handlers/orchestration/worker-start-implicit-coordinator.test.ts": 522, "src/cli/handlers/plugin-dev-watch.test.ts": 942, @@ -374,13 +362,10 @@ "src/cli/handlers/profile-state-recovery-admission.test.ts": 2149, "src/cli/handlers/profile-state.test.ts": 1045, "src/cli/handlers/repo-visibility.test.ts": 419, - "src/cli/handlers/search.test.ts": 578, - "src/cli/handlers/serve-restore.test.ts": 120, "src/cli/handlers/serve-service.test.ts": 200, "src/cli/handlers/skill-guide-host-gate.test.ts": 596, "src/cli/handlers/skill-sharing.test.ts": 423, "src/cli/handlers/speech.test.ts": 454, - "src/cli/handlers/terminal-daemon.test.ts": 426, "src/cli/handlers/terminal-set-pane-title.test.ts": 623, "src/cli/handlers/terminal-split.test.ts": 452, "src/cli/handlers/terminal-switch-paired-reveal.test.ts": 487, @@ -394,7 +379,6 @@ "src/cli/index-omitted-host-scope-selectors.test.ts": 6719, "src/cli/index-orchestration.test.ts": 659, "src/cli/index-terminal-commands.test.ts": 466, - "src/cli/index-vm-recipe-doctor.test.ts": 459, "src/cli/index-workspace-owner-choice-scaling.test.ts": 10154, "src/cli/index-workspace-owner-choice.test.ts": 1072, "src/cli/index-worktree-create-agent.test.ts": 582, @@ -417,7 +401,6 @@ "src/cli/plugin-authoring/plugin-test-node.test.ts": 110, "src/cli/plugin-authoring/plugin-test-runner.test.ts": 6256, "src/cli/plugin-authoring/plugin-type-files-symlink.test.ts": 743, - "src/cli/plugin-authoring/plugin-type-files.test.ts": 372, "src/cli/plugin-authoring/plugin-worker-panel-template.test.ts": 1469, "src/cli/plugin-dev-watch/plugin-dev-watch-approval.test.ts": 544, "src/cli/plugin-dev-watch/plugin-dev-watch-check.test.ts": 427, @@ -456,7 +439,6 @@ "src/cli/runtime/serve-update-supervisor-gate.test.ts": 73, "src/cli/runtime/status-caller.test.ts": 488, "src/cli/runtime/status.test.ts": 1406, - "src/cli/runtime/terminal-prompt-mutation-recovery-plugin-denied.test.ts": 125, "src/cli/runtime/transport-framing.test.ts": 194, "src/cli/runtime/transport.test.ts": 462, "src/cli/runtime/types.test.ts": 62, @@ -468,17 +450,14 @@ "src/cli/skills-reference-selector.test.ts": 528, "src/cli/skills.test.ts": 386, "src/cli/specs/account.test.ts": 95, - "src/cli/specs/bundled-guide-flags.test.ts": 246, "src/cli/specs/cli-command-names-parity.test.ts": 205, "src/cli/specs/profile-state.test.ts": 102, "src/cli/terminal-format.test.ts": 84, - "src/cli/terminal-list-host-scope-format.test.ts": 127, "src/cli/terminal-read-screen.test.ts": 660, "src/cli/worktree-ps-program-status.test.ts": 65, "src/cli/worktree-ps-terminal-verdict.test.ts": 60, "src/cli/worktree-selector-caller-host.test.ts": 107, "src/cli/worktree-selector-wsl-posix-path.test.ts": 134, - "src/cli/wsl-distro-cli-refusal.test.ts": 74, "src/main/acp/process/acp-agent-connection.test.ts": 407, "src/main/acp/discovery/acp-at-rest-commands.test.ts": 1400, "src/main/acp/transport/acp-json-rpc-peer.test.ts": 195, @@ -551,55 +530,39 @@ "src/main/agent-hooks/installation/configuration/managed-toml-ownership.test.ts": 52, "src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts": 3479, "src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts": 1257, - "src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts": 717, "src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts": 643, - "src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts": 607, "src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts": 820, - "src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts": 681, "src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts": 681, - "src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts": 696, "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts": 10279, "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts": 34523, - "src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts": 683, "src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts": 877, - "src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts": 674, - "src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts": 765, "src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts": 675, "src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts": 679, "src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts": 5451, "src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts": 802, "src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts": 895, - "src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts": 671, "src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts": 679, "src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts": 741, "src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts": 860, "src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts": 847, "src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts": 706, - "src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts": 716, "src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts": 1125, "src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts": 729, - "src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts": 645, "src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts": 801, "src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts": 723, - "src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts": 692, "src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts": 723, "src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts": 941, "src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts": 719, "src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts": 2674, "src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts": 1088, "src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts": 1014, - "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts": 656, "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts": 647, - "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts": 653, "src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts": 723, "src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts": 697, "src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts": 673, "src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts": 685, "src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts": 759, "src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts": 937, - "src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts": 713, - "src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts": 737, - "src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts": 768, "src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts": 813, "src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts": 818, "src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts": 745, @@ -607,13 +570,10 @@ "src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts": 1716, "src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts": 2772, "src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts": 657, - "src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts": 660, "src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts": 665, "src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts": 708, - "src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts": 672, "src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts": 641, "src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts": 676, - "src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts": 843, "src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts": 681, "src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts": 762, "src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts": 852, @@ -624,7 +584,6 @@ "src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts": 764, "src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts": 687, "src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts": 643, - "src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts": 694, "src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts": 666, "src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts": 718, "src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts": 697, @@ -637,7 +596,6 @@ "src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts": 1814, "src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts": 990, "src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts": 898, - "src/main/agent-hooks/server/program-status/hook-precedence.test.ts": 45, "src/main/agent-hooks/server/testing/replay/spool.test.ts": 999, "src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts": 669, "src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts": 108, @@ -645,15 +603,12 @@ "src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts": 345, "src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts": 262, "src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts": 44, - "src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts": 64, "src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.test.ts": 1235, "src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts": 2231, "src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts": 3176, "src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.test.ts": 1280, - "src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts": 1529, "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts": 62, "src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts": 1951, - "src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts": 1364, "src/main/agent-launch/agent-launch-account-env.test.ts": 958, "src/main/agent-launch/agent-launch-executor-cancel.test.ts": 1455, "src/main/agent-launch/agent-launch-mode-settings.test.ts": 4041, @@ -941,8 +896,6 @@ "src/main/browser/cookies/browser-google-cookie-clear-target.test.ts": 6235, "src/main/browser/element-grab/browser-grab-payload.test.ts": 55, "src/main/browser/guest-lifecycle/devtools/browser-guest-devtools-dock.test.ts": 57, - "src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-plugin-frame.test.ts": 280, - "src/main/browser/guest-lifecycle/input/shortcuts/browser-guest-shortcut-precedence.test.ts": 411, "src/main/browser/guest-lifecycle/input/browser-guest-target-url.test.ts": 50, "src/main/browser/guest-lifecycle/input/browser-guest-wheel-zoom-scroll.test.ts": 45, "src/main/browser/client-hosts/leases/browser-host-client-identity.test.ts": 97, @@ -950,24 +903,18 @@ "src/main/browser/identity/mode/browser-identity-mode-store.test.ts": 95, "src/main/browser/guest-lifecycle/prompts/browser-javascript-dialogs.test.ts": 54, "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts": 603, - "src/main/browser/guest-lifecycle/manager/navigation/browser-manager-auth-user-agent.test.ts": 555, "src/main/browser/guest-lifecycle/manager/downloads/browser-manager-client-hosted-downloads.test.ts": 670, - "src/main/browser/guest-lifecycle/manager/downloads/browser-manager-destroyed-guest-downloads.test.ts": 589, "src/main/browser/guest-lifecycle/manager/registration/browser-manager-destroyed-guest.test.ts": 633, "src/main/browser/guest-lifecycle/manager/devtools/browser-manager-devtools-retirement.test.ts": 551, "src/main/browser/guest-lifecycle/manager/downloads/browser-manager-downloads.test.ts": 592, - "src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-capture.test.ts": 516, "src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-mode.test.ts": 567, "src/main/browser/guest-lifecycle/manager/grab/browser-manager-grab-selection.test.ts": 584, - "src/main/browser/guest-lifecycle/manager/registration/browser-manager-guest-unload.test.ts": 534, "src/main/browser/guest-lifecycle/manager/browser-manager-guest-visibility.test.ts": 543, "src/main/browser/guest-lifecycle/manager/navigation/browser-manager-load-failure-replay.test.ts": 549, "src/main/browser/guest-lifecycle/manager/registration/browser-manager-page-prompt-routing.test.ts": 560, "src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-child.test.ts": 503, "src/main/browser/guest-lifecycle/manager/popups/browser-manager-popup-routing.test.ts": 575, "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-tab-identity.test.ts": 619, - "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-override.test.ts": 597, - "src/main/browser/guest-lifecycle/manager/viewport/browser-manager-viewport-ownership.test.ts": 550, "src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts": 101, "src/main/browser/network/execution-routes/browser-network-execution-route.test.ts": 272, "src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts": 127, @@ -1007,8 +954,6 @@ "src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts": 979, "src/main/browser/sessions/partition-policies/browser-session-partition-proxy-install.test.ts": 477, "src/main/browser/sessions/proxy/browser-session-proxy.test.ts": 857, - "src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts": 603, - "src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts": 478, "src/main/browser/sessions/profiles/browser-session-registry.test.ts": 883, "src/main/browser/identity/wire-probes/browser-session-ua-wire-identity-cross-context.electron.test.ts": 7167, "src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts": 8280, @@ -4173,7 +4118,6 @@ "src/main/ssh/connection/ssh-connection-reconnect-ladder.test.ts": 570, "src/main/ssh/connection/ssh-connection-sftp-namespace.test.ts": 1290, "src/main/ssh/connection/ssh-connection-sftp-wire.test.ts": 481, - "src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts": 324, "src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts": 350, "src/main/ssh/targets/ssh-connection-store.test.ts": 377, "src/main/ssh/connection/ssh-connection-system-transport.test.ts": 458, @@ -4191,7 +4135,6 @@ "src/main/ssh/legacy-relay/bridge/legacy-relay-client.test.ts": 109, "src/main/ssh/legacy-relay/bridge/legacy-relay-hidden-output.test.ts": 179, "src/main/ssh/legacy-relay/bridge/legacy-relay-target-bridge.test.ts": 167, - "src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts": 322, "src/main/ssh/legacy-relay/endpoints/ssh-host-relay-census-for-target.test.ts": 53, "src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts": 232, "src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-inventory.test.ts": 178, @@ -4221,7 +4164,6 @@ "src/main/managed-server/migration/transfers/orcad-migration-snapshot-coordinator.test.ts": 309, "src/main/ssh/migration-source/orcad-migration-source-fence.test.ts": 2000, "src/main/persistence/migrating-orcad-catalog/orcad-migration-source-retention.test.ts": 2297, - "src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts": 1903, "src/main/managed-server/migration/cutover/orcad-migration-stuck-host-profiles.test.ts": 2402, "src/main/ssh/migration-source/orcad-migration-terminal-gate.test.ts": 63, "src/main/managed-server/install/orcad-remote-deploy.test.ts": 537, @@ -4647,7 +4589,6 @@ "src/packages/process-host/src/run-process-windows-tree-kill.test.ts": 81, "src/packages/process-host/src/run-process.test.ts": 9406, "src/packages/process-host/src/spawn-observer.test.ts": 357, - "src/packages/process-host/src/spawn-process-stdio.test.ts": 311, "src/packages/process-host/src/windows-command-line.test.ts": 73, "src/packages/process-host/src/windows-tree-kill.test.ts": 81, "src/packages/process-host/src/wsl-distro-allowlist.test.ts": 55, @@ -4705,7 +4646,6 @@ "src/renderer/src/components/NativeChatResumeOnRestartGroups.test.tsx": 3472, "src/renderer/src/components/NewWorkspaceComposerCard.quick-file-drop.test.tsx": 4557, "src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx": 1301, - "src/renderer/src/components/NotificationCardStack.test.tsx": 272, "src/renderer/src/components/QuickOpen.selection.test.tsx": 1046, "src/renderer/src/components/SelectedTextCopyMenu.test.tsx": 329, "src/renderer/src/components/TerminalSearch.test.tsx": 458, @@ -4723,15 +4663,12 @@ "src/renderer/src/components/activity/activity-scope-filter.test.ts": 734, "src/renderer/src/components/activity/activity-search-query.test.tsx": 2286, "src/renderer/src/components/activity/activity-terminal-portal-publication-loop.react185.test.tsx": 222, - "src/renderer/src/components/activity/activity-thread-grouping.status-order.test.ts": 759, - "src/renderer/src/components/activity/activity-thread-list-pane-collapsible.test.tsx": 3688, "src/renderer/src/components/activity/activity-thread-list-pane.multi-select.test.tsx": 4699, "src/renderer/src/components/activity/activity-thread-list-pane.virtualization.test.tsx": 4863, "src/renderer/src/components/activity/useActivityUnreadCount.freshness.test.tsx": 1990, "src/renderer/src/components/activity/useActivityUnreadCount.test.ts": 1633, "src/renderer/src/components/agent-session-continuation/agent-session-continuation-selection.test.ts": 56, "src/renderer/src/components/agent-tab-shortcut-launch.test.ts": 369, - "src/renderer/src/components/agent/AgentLaunchPickerMenu.language.test.tsx": 2115, "src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx": 2090, "src/renderer/src/components/artifacts/ArtifactCollection.test.tsx": 1833, "src/renderer/src/components/artifacts/ArtifactPreview.test.tsx": 474, @@ -4743,14 +4680,12 @@ "src/renderer/src/components/automations/AutomationRunsTable.test.tsx": 668, "src/renderer/src/components/automations/AutomationSchedulePicker.test.ts": 431, "src/renderer/src/components/automations/AutomationTimeField.test.tsx": 654, - "src/renderer/src/components/automations/AutomationsListPanel.test.tsx": 2441, "src/renderer/src/components/automations/AutomationsPage.behavior.test.tsx": 3389, "src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx": 2932, "src/renderer/src/components/automations/AutomationsPage.run-navigation.test.tsx": 3056, "src/renderer/src/components/automations/ExternalAutomationManagers.test.tsx": 852, "src/renderer/src/components/automations/automation-captured-owner.test.ts": 379, "src/renderer/src/components/automations/automation-create-projects.test.ts": 42, - "src/renderer/src/components/automations/automation-detail-tab-navigation.test.ts": 201, "src/renderer/src/components/automations/automation-host-cache-controller.test.ts": 411, "src/renderer/src/components/automations/automation-host-cache-error.test.ts": 391, "src/renderer/src/components/automations/automation-host-cache-health.test.ts": 52, @@ -4766,14 +4701,11 @@ "src/renderer/src/components/automations/automation-host-recovery.test.ts": 51, "src/renderer/src/components/automations/automation-host-scale-gates.test.ts": 638, "src/renderer/src/components/automations/automation-host-scheduler.test.ts": 439, - "src/renderer/src/components/automations/automation-host-status-descriptors.test.ts": 231, "src/renderer/src/components/automations/automation-legacy-schedule-editing.test.ts": 449, "src/renderer/src/components/automations/automation-list-focus-recovery.test.ts": 48, - "src/renderer/src/components/automations/automation-list-keyboard-navigation.test.ts": 61, "src/renderer/src/components/automations/automation-list-row-identity.test.ts": 626, "src/renderer/src/components/automations/automation-list-search.test.ts": 75, "src/renderer/src/components/automations/automation-list-view.test.ts": 257, - "src/renderer/src/components/automations/automation-project-groups.test.ts": 54, "src/renderer/src/components/automations/automation-run-context.test.ts": 58, "src/renderer/src/components/automations/automation-run-history-keyboard-navigation.test.ts": 434, "src/renderer/src/components/automations/automation-run-open-target.test.ts": 442, @@ -4797,7 +4729,6 @@ "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.failure-remount.test.tsx": 3085, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.markup.test.tsx": 4575, "src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.test.tsx": 6541, - "src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx": 497, "src/renderer/src/components/browser-pane/annotate/MarkupOverlay.test.tsx": 1124, "src/renderer/src/components/browser-pane/annotate/browser-annotation-output.test.ts": 74, "src/renderer/src/components/browser-pane/annotate/browser-grab-toast-owner-cleanup.test.tsx": 1007, @@ -4815,7 +4746,6 @@ "src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.retention-props.test.tsx": 3808, "src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx": 307, "src/renderer/src/components/browser-pane/assemble-chrome/use-browser-page-find-shortcuts.test.tsx": 1874, - "src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx": 1020, "src/renderer/src/components/browser-pane/browser-client-page-attachment-scan-budget.test.ts": 464, "src/renderer/src/components/browser-pane/browser-client-page-metadata-publisher.test.ts": 315, "src/renderer/src/components/browser-pane/browser-client-page-profile-staging.test.ts": 434, @@ -4831,9 +4761,7 @@ "src/renderer/src/components/browser-pane/history/use-browser-history-shortcut.test.tsx": 1990, "src/renderer/src/components/browser-pane/host-guest/agent-input-focus-guard.test.ts": 228, "src/renderer/src/components/browser-pane/host-guest/browser-automation-visibility.test.ts": 45, - "src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts": 180, "src/renderer/src/components/browser-pane/host-guest/browser-guest-eviction-veto.test.ts": 1724, - "src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts": 2035, "src/renderer/src/components/browser-pane/host-guest/browser-page-evicted-guest-recovery.test.ts": 1839, "src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts": 515, "src/renderer/src/components/browser-pane/host-guest/browser-page-registration-ownership.test.ts": 2197, @@ -5001,13 +4929,10 @@ "src/renderer/src/components/editor/save/queue/editor-save-lossless-baseline.test.ts": 1990, "src/renderer/src/components/editor/save/transforms/editor-save-plugin-hook.test.ts": 2122, "src/renderer/src/components/editor/save/queue/editor-save-queue-bytes-owner.test.ts": 1667, - "src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts": 2137, "src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts": 2075, - "src/renderer/src/components/editor/save/queue/editor-save-queue-records.test.ts": 2036, "src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts": 2043, "src/renderer/src/components/editor/save/queue/editor-save-queue.test.ts": 1814, "src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts": 1250, - "src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts": 1239, "src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts": 1998, "src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts": 1485, "src/renderer/src/components/editor/image-png-export.chromium.test.ts": 212, @@ -5247,7 +5172,6 @@ "src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx": 4252, "src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx": 4070, "src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx": 3527, - "src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-status.test.tsx": 3370, "src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx": 3069, "src/renderer/src/components/native-chat/viewport/scroll/NativeChatMessageList.visual-scroll.test.tsx": 6691, "src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.test.tsx": 20958, @@ -5275,9 +5199,7 @@ "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.host-outage.test.tsx": 3552, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx": 2911, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx": 3014, - "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.retained-draft.test.tsx": 3736, "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx": 4459, - "src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.wsl-host-stopped.test.tsx": 3657, "src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx": 583, "src/renderer/src/components/native-chat/tools/lines/NativeChatToolLine.test.tsx": 3544, "src/renderer/src/components/native-chat/tools/lines/NativeChatToolOutput.test.tsx": 410, @@ -5342,7 +5264,6 @@ "src/renderer/src/components/native-chat/queue/editing/native-chat-queued-edit-draft.test.ts": 649, "src/renderer/src/components/native-chat/viewport/rail/native-chat-rail-outline-parity.test.ts": 497, "src/renderer/src/components/native-chat/viewport/scroll/native-chat-reader-scroll-input.test.tsx": 311, - "src/renderer/src/components/native-chat/paste/native-chat-remote-image-paste.test.tsx": 1834, "src/renderer/src/components/native-chat/attachments/uploads/native-chat-resolved-path-ownership.test.ts": 1749, "src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.test.ts": 293, "src/renderer/src/components/native-chat/drafts/native-chat-sent-prompt-history.test.ts": 217, @@ -5352,7 +5273,6 @@ "src/renderer/src/components/native-chat/pane/routing/native-chat-split-flow.test.ts": 1916, "src/renderer/src/components/native-chat/composer/submit/native-chat-structured-send-composition-clear.test.tsx": 2098, "src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts": 362, - "src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-work-runs.test.ts": 278, "src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.test.ts": 304, "src/renderer/src/components/native-chat/native-chat-task-list-state.test.ts": 62, "src/renderer/src/components/native-chat/native-chat-thread-goal-rows.test.ts": 50, @@ -5591,7 +5511,6 @@ "src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx": 2718, "src/renderer/src/lib/skill-runtime-command.test.ts": 1670, "src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.test.tsx": 1025, - "src/renderer/src/components/settings/accounts/providers/GrokAccountsSection.test.tsx": 623, "src/renderer/src/components/settings/accounts/sign-in/HostAccountSignInPrompt.test.tsx": 309, "src/renderer/src/components/settings/agents/launch/HostAgentLaunchSettings.test.tsx": 7498, "src/renderer/src/components/settings/developer-permissions/LocalNetworkConnectionTest.test.tsx": 592, @@ -5612,7 +5531,6 @@ "src/renderer/src/components/settings/ssh/SshPane.test.tsx": 1699, "src/renderer/src/components/settings/ssh/targets/SshTargetForm.test.tsx": 1014, "src/renderer/src/components/settings/ssh/targets/SshTargetList.test.tsx": 2093, - "src/renderer/src/components/settings/tasks/TaskSourceProviderCard.test.tsx": 467, "src/renderer/src/components/settings/tasks/TaskSourceSimpleSetup.test.tsx": 527, "src/renderer/src/components/settings/TerminalAppearanceSection.ghostty.test.ts": 549, "src/renderer/src/components/settings/terminal/appearance/TerminalContrastSetting.test.tsx": 798, @@ -5765,7 +5683,6 @@ "src/renderer/src/components/sidebar/worktree-list/rows/repo-header-ssh-isolation.test.tsx": 2945, "src/renderer/src/components/sidebar/worktree-list/rows/section-header-create-host.test.tsx": 2393, "src/renderer/src/components/sidebar/worktree-list/viewport/hard-scroll-up.test.ts": 66, - "src/renderer/src/components/sidebar/worktree-list/viewport/header-folder-composition.test.tsx": 3725, "src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.ts": 293, "src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.tsx": 269, "src/renderer/src/components/sidebar/worktree-list/drag/worktree-manual-order-store-write.test.ts": 2144, @@ -5857,7 +5774,6 @@ "src/renderer/src/components/task-page/gitlab/use-task-page-gitlab-loading.test.tsx": 1504, "src/renderer/src/components/task-page/jira/Content.board-owner.test.tsx": 2582, "src/renderer/src/components/task-page/jira/IssueAssigneeField.test.tsx": 1122, - "src/renderer/src/components/task-page/jira/TaskPageJiraStatusFilters.test.tsx": 923, "src/renderer/src/components/task-page/jira/task-page-jira-board-detail-integration.test.tsx": 2192, "src/renderer/src/components/task-page/jira/task-page-jira-board-transitions.test.ts": 69, "src/renderer/src/components/task-page/jira/task-page-jira-board-view.test.tsx": 2287, @@ -5927,7 +5843,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/startup/launch-parity-window-tab.test.ts": 17426, "src/renderer/src/components/terminal-pane/layout-serialization.test.ts": 109, "src/renderer/src/components/terminal-pane/pty-transport/legacy-relay/legacy-relay-bridge-transport.test.ts": 358, - "src/renderer/src/components/terminal-pane/session-restore/newer-daemon/newer-daemon-hold-banner.test.tsx": 477, "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts": 1040, "src/renderer/src/components/terminal-pane/pty-connection/agent-identity/foreground-process/pane-delayed-agent-startup.test.ts": 285, "src/renderer/src/components/terminal-pane/pty-connection/agent-identity/foreground-process/pane-foreground-agent-tracker.test.ts": 486, @@ -6014,7 +5929,6 @@ "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-reattach-admission.test.ts": 1636, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-recycled-pty-incarnation.test.ts": 787, "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-errors.test.ts": 1218, - "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-user-input.test.ts": 953, "src/renderer/src/components/terminal-pane/input/focus/regular-terminal-focus-ownership.test.ts": 208, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/remote-hidden-output-restore-outcomes.test.ts": 2794, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/remote-hidden-output-restore-unavailable-banner.repro.test.ts": 2355, @@ -6376,9 +6290,9 @@ "src/renderer/src/i18n/ui-intl-formatters.test.ts": 208, "src/renderer/src/lib/activate-ai-vault-structured-session-host.test.ts": 589, "src/renderer/src/lib/activate-ai-vault-structured-session-reveal.test.ts": 2099, - "src/renderer/src/lib/activate-tab-and-focus-pane.test.ts": 54, - "src/renderer/src/lib/active-agent-note-send-explicit-target.test.ts": 980, - "src/renderer/src/lib/active-agent-note-send-focused-session.test.ts": 536, + "src/renderer/src/lib/workspace/tabs/activate-tab-and-focus-pane.test.ts": 54, + "src/renderer/src/lib/agent-session/messaging/terminal/active-agent-note-send-explicit-target.test.ts": 980, + "src/renderer/src/lib/agent-session/messaging/terminal/active-agent-note-send-focused-session.test.ts": 536, "src/renderer/src/lib/activity-thread-display.test.ts": 134, "src/renderer/src/lib/agent-account-restart-startup.test.ts": 1780, "src/renderer/src/lib/agent-session/launch/background/agent-background-session-launch-host.test.ts": 1910, @@ -6395,10 +6309,10 @@ "src/renderer/src/lib/agent-session/launch/pane/agent-launch-tab-main-written.test.ts": 2084, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-tab-publication.test.ts": 1855, "src/renderer/src/lib/agent-session/launch/pane/agent-launch-through-host.test.ts": 1975, - "src/renderer/src/lib/agent-message-send.test.ts": 182, - "src/renderer/src/lib/agent-paste-draft-submit-retry.test.ts": 315, - "src/renderer/src/lib/agent-paste-draft.test.ts": 445, - "src/renderer/src/lib/agent-resume-launch-target.test.ts": 3911, + "src/renderer/src/lib/agent-session/messaging/agent-message-send.test.ts": 182, + "src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft-submit-retry.test.ts": 315, + "src/renderer/src/lib/agent-session/messaging/paste/agent-paste-draft.test.ts": 445, + "src/renderer/src/lib/agent-session/resume/agent-resume-launch-target.test.ts": 3911, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-after-failure.test.ts": 870, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-close-race.test.ts": 983, "src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-create-message.test.ts": 2521, @@ -6417,10 +6331,9 @@ "src/renderer/src/lib/agent-session/structured-agent-session-draft-position-lifetime.test.tsx": 3166, "src/renderer/src/lib/agent-session/structured-agent-session-ordinary-draft.test.tsx": 9907, "src/renderer/src/lib/agent-session/structured-agent-session-provisional-tab.test.ts": 3672, - "src/renderer/src/lib/agent-skill-cli-prerequisite.test.ts": 219, - "src/renderer/src/lib/agent-startup-delayed-delivery-perf.test.ts": 1708, - "src/renderer/src/lib/agent-status-evidence-clock.test.ts": 88, - "src/renderer/src/lib/agent-status.test.ts": 172, + "src/renderer/src/lib/agent-session/launch/startup/agent-startup-delayed-delivery-perf.test.ts": 1708, + "src/shared/agent-status/contracts/agent-status-evidence-clock.test.ts": 88, + "src/shared/agent-status/title/agent-title-tracker.test.ts": 172, "src/renderer/src/lib/agent-session/resume/history/ai-vault-antigravity-reference-host.test.ts": 678, "src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.drop-repin.test.ts": 541, "src/renderer/src/lib/agent-session/resume/history/ai-vault-resume-command.test.ts": 665, @@ -6451,7 +6364,6 @@ "src/renderer/src/lib/clipboard-image-copy.test.ts": 243, "src/renderer/src/lib/cmd-j-host-qualified-candidate-ownership.test.ts": 526, "src/renderer/src/lib/cmd-j-linear-issue-intent.test.ts": 42, - "src/renderer/src/lib/code-editor-theme.test.ts": 101, "src/renderer/src/lib/code-host-error-copy.test.ts": 297, "src/renderer/src/lib/codex-pane-selection-lane.test.ts": 543, "src/renderer/src/lib/agent-session/accounts/codex/codex-session-restart-shell-flap.test.ts": 1745, @@ -6461,24 +6373,22 @@ "src/renderer/src/lib/comment-body-line-count.test.ts": 84, "src/renderer/src/lib/comment-body-submit-state.test.ts": 55, "src/renderer/src/lib/composer-submit-cancellation.test.ts": 41, - "src/renderer/src/lib/connection-context.test.ts": 1817, + "src/renderer/src/lib/workspace/ownership/connection-context.test.ts": 1817, "src/renderer/src/lib/crash-diagnostics.test.ts": 176, "src/renderer/src/lib/create-untitled-markdown.test.ts": 566, "src/renderer/src/lib/desktop-created-server-tabs.test.ts": 1933, - "src/renderer/src/lib/direct-ssh-target-scope.test.ts": 48, + "src/renderer/src/lib/workspace/ownership/direct-ssh-target-scope.test.ts": 48, "src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup-callers.test.tsx": 2436, "src/renderer/src/lib/workspace/creation/work-item/direct-work-item-setup.test.ts": 2072, - "src/renderer/src/lib/doc-preview-grants.test.ts": 2094, - "src/renderer/src/lib/editor-file-operation-owner.test.ts": 2848, - "src/renderer/src/lib/workspace/activation/initial-surface/empty-workspace-default-agent-chat.test.ts": 1895, + "src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts": 2094, + "src/renderer/src/lib/editor/file-operations/editor-file-operation-owner.test.ts": 2848, "src/renderer/src/lib/emulator-error-copy.test.ts": 415, "src/renderer/src/lib/ensure-hooks-confirmed.test.ts": 799, - "src/renderer/src/lib/ensure-simulator-tab-behavior.test.ts": 3601, - "src/renderer/src/lib/execute-open-editor-path-move.test.ts": 2458, - "src/renderer/src/lib/execution-host-facts.test.ts": 1796, + "src/renderer/src/lib/simulator/tabs/ensure-simulator-tab-behavior.test.ts": 3601, + "src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts": 1796, "src/renderer/src/lib/feature-education-telemetry.test.ts": 52, "src/renderer/src/lib/feedback-image-attachments.test.ts": 557, - "src/renderer/src/lib/file-preview-link-open.test.ts": 2311, + "src/renderer/src/lib/browser/documents/file-preview-link-open.test.ts": 2311, "src/renderer/src/lib/file-search-selection.test.ts": 51, "src/renderer/src/lib/find-query-bounds.test.ts": 45, "src/renderer/src/lib/finished-agent-resume-resurrection.test.ts": 1872, @@ -6517,11 +6427,10 @@ "src/renderer/src/lib/lazy-with-retry.test.ts": 282, "src/renderer/src/lib/linear-board-drag-payload.test.ts": 58, "src/renderer/src/lib/work-items/linear/linear-issue-context-snapshot.test.ts": 55, - "src/renderer/src/lib/work-items/linear/linear-issue-url-lookup.test.ts": 374, "src/renderer/src/lib/work-items/linear/linear-issue-workspace-attachment.test.ts": 99, "src/renderer/src/lib/link-source-local-open-owner.test.ts": 433, "src/renderer/src/lib/linked-work-item-context.test.ts": 64, - "src/renderer/src/lib/monaco-editor-gutter-disposal.test.ts": 295, + "src/renderer/src/lib/editor/monaco/monaco-editor-gutter-disposal.test.ts": 295, "src/renderer/src/lib/monaco-languages/markdown-heading-outline.test.ts": 70, "src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts": 697, "src/renderer/src/lib/monaco-languages/plugin-grammar-tokenization.test.ts": 282, @@ -6540,7 +6449,7 @@ "src/renderer/src/lib/non-secure-context-crypto.repro.test.ts": 1691, "src/renderer/src/lib/onboarding-folder-cancellation.test.ts": 2486, "src/renderer/src/lib/open-agent-message-sender.test.ts": 1497, - "src/renderer/src/lib/open-mobile-emulator-tab.test.ts": 545, + "src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts": 545, "src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts": 884, "src/renderer/src/lib/order-empty-query-worktrees.test.ts": 62, "src/renderer/src/lib/os-file-drop-cancellation-guard.test.ts": 204, @@ -6620,7 +6529,7 @@ "src/renderer/src/lib/react-commit-cascade-observer.test.ts": 189, "src/renderer/src/lib/react-commit-cascade-telemetry.test.ts": 159, "src/renderer/src/lib/react-error-boundary-reporting.test.ts": 55, - "src/renderer/src/lib/remap-open-editor-tabs-for-path-change.test.ts": 2178, + "src/renderer/src/lib/editor/file-operations/remap-open-editor-tabs-for-path-change.test.ts": 2178, "src/renderer/src/lib/rename-user-named-tab-access.test.ts": 2804, "src/renderer/src/lib/renderer-agent-status-observation-ingress.test.ts": 81, "src/renderer/src/lib/renderer-app-platform.test.ts": 197, @@ -6651,11 +6560,11 @@ "src/renderer/src/lib/sidebar-ended-creations.test.ts": 1889, "src/renderer/src/lib/sidebar-pending-layer.test.ts": 338, "src/renderer/src/lib/sidebar-shadow/workspace-activity-shadow.test.ts": 1728, - "src/renderer/src/lib/simulator-launch-coordination.test.ts": 43, - "src/renderer/src/lib/simulator-palette-search.test.ts": 515, - "src/renderer/src/lib/simulator-pane-shutdown-scheduler.test.ts": 1679, - "src/renderer/src/lib/simulator-tab-layout-owner.test.ts": 2398, - "src/renderer/src/lib/simulator-tab-palette-activation.test.ts": 1903, + "src/renderer/src/lib/simulator/launch/simulator-launch-coordination.test.ts": 43, + "src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts": 515, + "src/renderer/src/lib/simulator/tabs/simulator-pane-shutdown-scheduler.test.ts": 1679, + "src/renderer/src/lib/simulator/tabs/simulator-tab-layout-owner.test.ts": 2398, + "src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts": 1903, "src/renderer/src/lib/sleeping-agent-session-launch-windows-quoting.test.ts": 547, "src/renderer/src/lib/source-control/remote/source-control-remote-error.test.ts": 340, "src/renderer/src/lib/ssh-config-passive-sync.test.ts": 1513, @@ -6690,7 +6599,7 @@ "src/renderer/src/lib/windows-terminal-capabilities-race.test.ts": 450, "src/renderer/src/lib/windows-terminal-capabilities.test.ts": 585, "src/renderer/src/lib/windows-terminal-capability-reprobe.test.ts": 198, - "src/renderer/src/lib/workspace-activation-path-gate.test.ts": 2107, + "src/renderer/src/lib/workspace/activation/workspace-activation-path-gate.test.ts": 2107, "src/renderer/src/lib/browser/workspace/workspace-browser-tab-open-placement.test.ts": 1996, "src/renderer/src/lib/workspace-doc-address-input.test.ts": 470, "src/renderer/src/lib/workspace-file-drag.test.ts": 70, @@ -6701,7 +6610,7 @@ "src/renderer/src/lib/workspace/persistence/workspace-session-ssh-partition-ownership.test.ts": 309, "src/renderer/src/lib/workspace/persistence/workspace-session-ssh-partition-round-trip.test.ts": 1775, "src/renderer/src/lib/workspace/search/tabs/workspace-tab-palette-activation.store.test.ts": 1994, - "src/renderer/src/lib/workspace-terminal-host-authority.test.ts": 2066, + "src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts": 2066, "src/renderer/src/lib/workspace/activation/worktree-activation-automation-filter.test.ts": 2431, "src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts": 2295, "src/renderer/src/lib/workspace/activation/worktree-activation-emptied-workspace-reseed.test.ts": 3630, @@ -6709,26 +6618,24 @@ "src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts": 2043, "src/renderer/src/lib/workspace/activation/worktree-activation-web-runtime.test.ts": 2768, "src/renderer/src/lib/workspace/activation/worktree-agent-activation-seam.test.ts": 3440, - "src/renderer/src/lib/workspace/activation/worktree-agent-live-surface-adoption-layout-owner.test.ts": 1898, "src/renderer/src/lib/workspace/creation/worktree-creation-backend-startup-focus.test.ts": 2267, "src/renderer/src/lib/workspace/creation/worktree-creation-initial-surface.test.ts": 5258, "src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-lifecycle.test.ts": 2633, "src/renderer/src/lib/workspace/creation/worktree-creation-structured-session-prompts.test.tsx": 4554, - "src/renderer/src/lib/worktree-live-terminal-surface-owners.test.ts": 266, - "src/renderer/src/lib/worktree-operation-route-index.test.ts": 262, - "src/renderer/src/lib/worktree-operation-route.test.ts": 342, + "src/renderer/src/lib/workspace/ownership/worktree-live-terminal-surface-owners.test.ts": 266, + "src/renderer/src/lib/workspace/ownership/worktree-operation-route-index.test.ts": 262, + "src/renderer/src/lib/workspace/ownership/worktree-operation-route.test.ts": 342, "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-comment-snippet.test.ts": 53, "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-titleless-review.test.ts": 198, - "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-runtime-owner-identity.test.ts": 425, "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-search.test.ts": 206, "src/renderer/src/lib/workspace/search/worktrees/worktree-palette-task-url-match.test.ts": 165, - "src/renderer/src/lib/worktree-reactivation-preserved-pane-replacement.test.ts": 2268, - "src/renderer/src/lib/worktree-reactivation-tab-forkbomb.test.ts": 4131, + "src/renderer/src/lib/workspace/activation/worktree-reactivation-preserved-pane-replacement.test.ts": 2268, + "src/renderer/src/lib/workspace/activation/worktree-reactivation-tab-forkbomb.test.ts": 4131, "src/renderer/src/lib/workspace/ownership/worktree-runtime-owner-index.detected.test.ts": 121, "src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.test.ts": 380, "src/renderer/src/lib/worktree-status-spinner-launch-agent.test.ts": 271, "src/renderer/src/lib/worktree-status.test.ts": 306, - "src/renderer/src/lib/wsl-move-renderer-store-rewrites.test.ts": 1072, + "src/renderer/src/lib/workspace/persistence/wsl-move-renderer-store-rewrites.test.ts": 1072, "src/renderer/src/runtime/rpc/calls/abortable-runtime-environment-call.test.ts": 189, "src/renderer/src/runtime/provider-accounts/observations/claude-agent-view-observations.test.ts": 105, "src/renderer/src/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab.test.ts": 397, @@ -6744,7 +6651,6 @@ "src/renderer/src/runtime/native-chat/naming/legacy-chat-rename-migration.test.tsx": 3834, "src/renderer/src/runtime/local-structured-session-tabs-sync/local-structured-session-tabs-sync.test.ts": 2643, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/mirrored-agent-status-clock-skew.test.ts": 1839, - "src/renderer/src/runtime/hosted-terminals/mounted-surfaces/mounted-terminal-tab-registry.test.ts": 634, "src/renderer/src/runtime/web-session-tabs-sync/agent-status/paired-reconnect-sidebar-agent-count.test.ts": 1905, "src/renderer/src/runtime/web-session-tabs-sync/closing/paired-terminal-tab-close-environment-removal.test.ts": 1897, "src/renderer/src/runtime/web-session-tabs-sync/closing/paired-terminal-tab-close-reload.test.ts": 1943, @@ -6758,8 +6664,6 @@ "src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stale-stream-frames.test.ts": 234, "src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts": 826, "src/renderer/src/runtime/hosts/updates/remote-server-restart-wait.test.ts": 49, - "src/renderer/src/runtime/browser/client-hosting/restored-client-hosted-browser-host-attach.test.ts": 43, - "src/renderer/src/runtime/browser/client-hosting/restored-client-hosted-browser-host-restart-attach.test.ts": 474, "src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts": 64, "src/renderer/src/runtime/files/reads/runtime-directory-page-client.test.ts": 268, "src/renderer/src/runtime/rpc/environment-revisions/runtime-environment-pairing-refresh.test.ts": 109, @@ -6770,7 +6674,6 @@ "src/renderer/src/runtime/files/reads/runtime-file-range-client.test.ts": 444, "src/renderer/src/runtime/files/mutations/runtime-file-write-disk-precondition.test.ts": 478, "src/renderer/src/runtime/source-control/git/runtime-git-client.test.ts": 513, - "src/renderer/src/runtime/provider-accounts/sign-in/runtime-host-account-sign-in-client.test.ts": 487, "src/renderer/src/runtime/hosts/connections/runtime-host-contact-regained.test.ts": 413, "src/renderer/src/runtime/jira/runtime-jira-image-client.test.ts": 214, "src/renderer/src/runtime/jira/runtime-jira-payload-stream.test.ts": 192, @@ -6945,7 +6848,6 @@ "src/renderer/src/store/slices/editor/git/editor-remote-branch-actions.test.ts": 935, "src/renderer/src/store/slices/editor/hydration/editor-session-duplicate-restore.test.ts": 1931, "src/renderer/src/store/slices/editor/focus/editor-set-active-file-guard.test.ts": 895, - "src/renderer/src/store/slices/editor/tabs/editor-state-worktree-purge-leak.test.ts": 1740, "src/renderer/src/store/slices/editor/tabs/editor-tab-layout-owner.test.ts": 1883, "src/renderer/src/store/slices/editor/tabs/editor-tab-placement.test.ts": 1837, "src/renderer/src/store/slices/editor/tabs/editor-tab-shared-project-owner.test.ts": 954, @@ -6964,7 +6866,6 @@ "src/renderer/src/store/github/pull-requests/github-pr-branch-direct-refresh-scope.test.ts": 667, "src/renderer/src/store/github/pull-requests/github-pr-branch-fallback-results.test.ts": 658, "src/renderer/src/store/github/pull-requests/github-pr-branch-linked-pr-divergence.test.ts": 662, - "src/renderer/src/store/github/checks/github-pr-checks-fetch.test.ts": 766, "src/renderer/src/store/github/comments/github-pr-comment-read-order.test.ts": 570, "src/renderer/src/store/github/comments/github-pr-comments.test.ts": 746, "src/renderer/src/store/github/pull-requests/github-pr-host-scope.test.ts": 1030, @@ -6973,7 +6874,6 @@ "src/renderer/src/store/github/pull-requests/github-pr-request-lifetime.test.ts": 1458, "src/renderer/src/store/github/projects/github-project-view-tables.test.ts": 656, "src/renderer/src/store/github/repositories/github-repo-lookup-index.test.ts": 51, - "src/renderer/src/store/github/review-threads/github-review-thread-actions.test.ts": 574, "src/renderer/src/store/github/review-threads/github-review-thread-rollback.test.ts": 663, "src/renderer/src/store/github/task-records/github-task-record-retries.test.ts": 758, "src/renderer/src/store/github/task-records/github-task-records.test.ts": 807, @@ -6983,7 +6883,6 @@ "src/renderer/src/store/github/work-items/github-work-items-twin-cache-host.test.ts": 672, "src/renderer/src/store/slices/hosted-review/hosted-review-request-lifetime.test.ts": 110, "src/renderer/src/store/slices/hosted-review/hosted-review.test.ts": 320, - "src/renderer/src/store/repos/issue-source-preference-twin.test.ts": 1858, "src/renderer/src/store/slices/jira/jira-status-filter-cache.test.ts": 1770, "src/renderer/src/store/slices/jira/jira-web-client-status.test.ts": 1901, "src/renderer/src/store/slices/jira/jira.test.ts": 312, @@ -7034,7 +6933,7 @@ "src/renderer/src/store/slices/settings/settings.test.ts": 1938, "src/renderer/src/store/slices/worktrees/create/sparse-presets.test.ts": 217, "src/renderer/src/store/slices/ssh/ssh.test.ts": 1843, - "src/renderer/src/lib/active-worktree-removal-successor.test.ts": 1867, + "src/renderer/src/lib/workspace/activation/active-worktree-removal-successor.test.ts": 1867, "src/renderer/src/store/slices/worktrees/session/store-active-worktree-selection.test.ts": 2039, "src/renderer/src/store/terminals/store-create-tab-start-in-main.test.ts": 1801, "src/renderer/src/store/slices/tabs/store-open-to-side-layout-owner.test.ts": 1919, @@ -7061,7 +6960,6 @@ "src/renderer/src/store/slices/tabs/tabs-unread-and-focus.test.ts": 1801, "src/renderer/src/store/slices/tabs/structured-chat-close-owner.test.ts": 1866, "src/renderer/src/store/slices/tabs/tabs-reconciliation-empty-groups.test.ts": 1703, - "src/renderer/src/store/terminals/terminal-input-activity-store-write.test.ts": 1726, "src/renderer/src/store/terminals/terminal-layout-pty-ownership.test.ts": 1734, "src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts": 1627, "src/renderer/src/store/terminals/terminal-pane-detach-agent-retention.test.ts": 2846, @@ -7074,7 +6972,6 @@ "src/renderer/src/store/terminals/terminals-hydration-canonical-pty-overlap.test.ts": 1946, "src/renderer/src/store/terminals/terminals-hydration-canonical-rows.test.ts": 1680, "src/renderer/src/store/slices/ui/ui-agent-send-target.test.ts": 760, - "src/renderer/src/store/slices/ui/ui-feature-interactions.test.ts": 648, "src/renderer/src/store/slices/ui/ui-host-filter-sync.test.ts": 597, "src/renderer/src/store/slices/ui/ui-host-workspace-statuses.test.ts": 1695, "src/renderer/src/store/slices/ui/ui-modal-slot-dismissal.test.ts": 662, @@ -7098,7 +6995,6 @@ "src/renderer/src/store/slices/settings/worktree-visibility-settings-write.test.ts": 307, "src/renderer/src/store/slices/worktrees/teardown/worktrees-always-force-delete.test.ts": 1611, "src/renderer/src/store/slices/worktrees/teardown/worktrees-background-removal.test.ts": 2011, - "src/renderer/src/store/slices/worktrees/create/worktrees-create-base-status.test.ts": 1252, "src/renderer/src/store/slices/worktrees/create/worktrees-create-captured-host.test.ts": 1148, "src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-listing-merge.test.ts": 1311, "src/renderer/src/store/slices/worktrees/listing/worktrees-fetch-owner-routing.test.ts": 2038, @@ -7127,7 +7023,6 @@ "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-reference-origins.test.ts": 1218, "src/renderer/src/store/slices/worktrees/session/worktrees-terminal-reference-source-race.test.ts": 1063, "src/renderer/src/store/slices/workspace-attention/worktrees-unread-state.test.ts": 1704, - "src/renderer/src/store/slices/worktrees/session/worktrees-workspace-selection-state.test.ts": 1170, "src/renderer/src/store/slices/worktrees/host-scoped-row-merges.test.ts": 1805, "src/renderer/src/store/slices/worktrees/listing/detected-worktree-meta.test.ts": 318, "src/renderer/src/store/slices/worktrees/listing/stale-listing-purges-created-worktree.test.ts": 1828, @@ -7196,7 +7091,6 @@ "src/shared/agent-cli-install-dir-fallback.test.ts": 130, "src/shared/agent-launch/startup/agent-command-line-intent.test.ts": 95, "src/shared/agent-status/title/agent-detection.test.ts": 188, - "src/shared/agent-hook-listener/transport/agent-hook-endpoint-file.test.ts": 58, "src/shared/agent-hook-listener/transport/agent-hook-endpoint-temp-cleanup.test.ts": 55, "src/shared/agent-hook-listener/normalization/agent-hook-listener-claude-elicitation.test.ts": 229, "src/shared/agent-hook-listener/normalization/agent-hook-listener-codex-approval-ownership.test.ts": 258, @@ -7302,7 +7196,6 @@ "src/shared/agent-status/transport/agent-status-osc-pending-retention.test.ts": 154, "src/shared/agent-status/transport/agent-status-osc.test.ts": 104, "src/shared/agent-status/store/agent-status-store-reopen.test.ts": 199, - "src/shared/agent-status/contracts/agent-status-subject.test.ts": 171, "src/shared/agent-status/title/agent-status-tracker-program-activity.test.ts": 77, "src/shared/agent-launch/startup/agent-tui-input-clear.test.ts": 57, "src/shared/ai-vault/resume/ai-vault-resume-command.test.ts": 70, @@ -8357,7 +8250,6 @@ "tests/e2e/git-history-tooltip-wrap.spec.ts": 22900, "tests/e2e/git-no-upstream-polling-churn.spec.ts": 22600, "tests/e2e/github-cli-stall-repro.spec.ts": 18200, - "tests/e2e/github-created-issue-start-prefill.spec.ts": 43100, "tests/e2e/github-url-smart-input-transition.spec.ts": 58200, "tests/e2e/golden-agent-tui-launch.spec.ts": 27300, "tests/e2e/golden-core-flows.spec.ts": 91100, diff --git a/config/scripts/ci/unit-selection/check-test-file-runners.mjs b/config/scripts/ci/unit-selection/check-test-file-runners.mjs index 24993494bd6..09f620398b7 100644 --- a/config/scripts/ci/unit-selection/check-test-file-runners.mjs +++ b/config/scripts/ci/unit-selection/check-test-file-runners.mjs @@ -34,13 +34,6 @@ const NON_UNIT_TEST_RUNNERS = [ sources: ['tests/e2e/vitest.config.ts'], mirrors: ["'tests/e2e/computer-*.e2e.ts'"] }, - { - name: 'agent-status benchmark', - manual: true, - include: ['config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts'], - sources: ['config/vitest.agent-status-benchmark.config.ts'], - mirrors: ["'config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts'"] - }, { name: 'mobile', include: ['mobile/src/**/*.test.ts', 'mobile/src/**/*.test.tsx', 'mobile/scripts/**/*.test.ts'], diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs index 567d2c83bf9..0f946b7faba 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs @@ -53,7 +53,6 @@ export const UNIT_EXCLUDE = [ 'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts', 'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts', 'src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts', diff --git a/config/scripts/locale-catalog/locale-translation-policy-ko-round5.test.mjs b/config/scripts/locale-catalog/locale-translation-policy-ko-round5.test.mjs index e03157e0bc6..6d8561bcdcc 100644 --- a/config/scripts/locale-catalog/locale-translation-policy-ko-round5.test.mjs +++ b/config/scripts/locale-catalog/locale-translation-policy-ko-round5.test.mjs @@ -3,147 +3,6 @@ import { describe, expect, it } from 'vitest' import { repairTranslatedValue } from './locale-translation-policy.mjs' describe('locale-translation-policy ko round 5', () => { - it('fixes Korean round 5 review, integration, and search keyword regressions', () => { - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.workspace.status.409528031f', - enValue: 'Review', - localeValue: '검토', - locale: 'ko' - }) - ).toBe('리뷰') - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.workspace.status.6c1efa2cf8', - enValue: 'In review', - localeValue: '검토 중', - locale: 'ko' - }) - ).toBe('리뷰 중') - expect( - repairTranslatedValue({ - key: 'auto.components.TaskPage.524f095d55', - enValue: 'Needs review', - localeValue: '검토 필요', - locale: 'ko' - }) - ).toBe('리뷰 필요') - expect( - repairTranslatedValue({ - key: 'auto.components.onboarding.IntegrationsStep.277f30eb34', - enValue: - 'Linear, GitLab, Bitbucket, Azure DevOps, Gitea, and Jira live in Settings > Integrations.', - localeValue: - 'Linear, GitLab, Bitbucket, Azure DevOps, Gitea 및 Jira는 설정 > 통합에 있습니다.', - locale: 'ko' - }) - ).toBe('Linear, GitLab, Bitbucket, Azure DevOps, Gitea 및 Jira는 설정 > 연동에 있습니다.') - expect( - repairTranslatedValue({ - key: 'auto.components.settings.general.search.244e3fb4c8', - enValue: 'Install the Orca skill so agents know to use the Orca CLI.', - localeValue: '에이전트가 Orca CLI 사용 방법을 알 수 있도록 Orca 기술을 설치합니다.', - locale: 'ko' - }) - ).toBe('에이전트가 Orca CLI를 사용하도록 Orca 스킬을 설치하세요.') - expect( - repairTranslatedValue({ - key: 'auto.components.editor.MarkdownPreview.322afab6ff', - enValue: 'Review notes', - localeValue: '메모 검토', - locale: 'ko' - }) - ).toBe('리뷰 노트') - expect( - repairTranslatedValue({ - key: 'auto.components.right.sidebar.source.control.repo.icon.ecf63ec3ef', - enValue: 'Launch', - localeValue: '시작하다', - locale: 'ko' - }) - ).toBe('실행') - expect( - repairTranslatedValue({ - key: 'auto.components.GitHubItemDialog.485609c4f2', - enValue: 'check #', - localeValue: '확인하다 #', - locale: 'ko' - }) - ).toBe('체크 #') - expect( - repairTranslatedValue({ - key: 'auto.lib.automation.templates.maintenance.prompt', - enValue: - 'Check for stuck work, stale generated files, failing validation, and anything that needs human attention. Report only actionable issues.', - localeValue: - '작업 중단, 오래 생성된 파일, 유효성 검사 실패 및 사람의 주의가 필요한 모든 사항을 확인하세요. 실행 가능한 문제만 보고하세요.', - locale: 'ko' - }) - ).toBe( - '작업 중단, 오래 생성된 파일, 유효성 검사 실패 및 사람의 주의가 필요한 모든 사항을 확인하세요. 실행 가능한 이슈만 보고하세요.' - ) - expect( - repairTranslatedValue({ - key: 'auto.components.GitLabItemDialog.02cbe2de44', - enValue: 'Pipeline', - localeValue: '파이프라인', - locale: 'ko' - }) - ).toBe('파이프라인') - }) - - // Why: #12113 — brand names stay Latin, but generic workflow nouns keep their Korean. - it('keeps brand names English and generic workflow terms translated', () => { - expect( - repairTranslatedValue({ - key: 'auto.components.feature.wall.BrowserAnimatedVisual.04096318ab', - enValue: 'Terminal 1', - localeValue: '터미널 1', - locale: 'ko' - }) - ).toBe('터미널 1') - expect( - repairTranslatedValue({ - key: 'auto.components.skills.SkillsPage.38e0951c3a', - enValue: 'Agent Skills', - localeValue: '에이전트 스킬', - locale: 'ko' - }) - ).toBe('에이전트 스킬') - expect( - repairTranslatedValue({ - key: 'auto.components.LinearIssueMarkdownDescriptionEditor.d9c47069ef', - enValue: 'Markdown', - localeValue: '가격 인하', - locale: 'ko' - }) - ).toBe('Markdown') - expect( - repairTranslatedValue({ - key: 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.9623a5107d', - enValue: 'Unpushed commits', - localeValue: '푸시되지 않은 커밋', - locale: 'ko' - }) - ).toBe('푸시되지 않은 커밋') - expect( - repairTranslatedValue({ - key: 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.0b1766738a', - enValue: 'Repo', - localeValue: '레포', - locale: 'ko' - }) - ).toBe('레포') - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.add.repo.local.start.actions.fb4fc5380e', - enValue: 'Local project, Git repo, or folder with many repos', - localeValue: '로컬 프로젝트, Git 저장소 또는 저장소가 많은 폴더', - locale: 'ko' - }) - ).toBe('로컬 프로젝트, Git 저장소 또는 저장소가 많은 폴더') - }) - it('re-glues Korean particles after Latin terms without gluing content words', () => { // A wrong space before the 에 particle is re-glued onto the Latin term. expect( diff --git a/config/scripts/locale-catalog/locale-translation-policy.es-round5.test.mjs b/config/scripts/locale-catalog/locale-translation-policy.es-round5.test.mjs deleted file mode 100644 index 3bf5a77fb3a..00000000000 --- a/config/scripts/locale-catalog/locale-translation-policy.es-round5.test.mjs +++ /dev/null @@ -1,65 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { repairTranslatedValue } from './locale-translation-policy.mjs' - -describe('locale-translation-policy es round 5', () => { - // Why: #12113 — brand names stay Latin, but generic workflow nouns keep their Spanish. - it('keeps brand names English and generic workflow terms translated', () => { - expect( - repairTranslatedValue({ - key: 'auto.components.LinearIssueMarkdownDescriptionEditor.d9c47069ef', - enValue: 'Markdown', - localeValue: 'Reducción', - locale: 'es' - }) - ).toBe('Markdown') - expect( - repairTranslatedValue({ - key: 'auto.components.TaskPage.7f3f7b4c18', - enValue: 'Description (optional, markdown)', - localeValue: 'Descripción (opcional, rebaja)', - locale: 'es' - }) - ).toBe('Descripción (opcional, markdown)') - expect( - repairTranslatedValue({ - key: 'auto.components.right.sidebar.source.control.primary.action.ed93b4f14f', - enValue: 'Commit', - localeValue: 'Comprometerse', - locale: 'es' - }) - ).toBe('Commit') - expect( - repairTranslatedValue({ - key: 'auto.components.right.sidebar.GitHistoryPanel.cf7cad58d2', - enValue: 'No commits yet', - localeValue: 'Aún no hay compromisos', - locale: 'es' - }) - ).toBe('Aún no hay commits') - expect( - repairTranslatedValue({ - key: 'auto.components.right.sidebar.SourceControl.b94112eb9e', - enValue: 'Commit message', - localeValue: 'mensaje de confirmación', - locale: 'es' - }) - ).toBe('mensaje de confirmación') - expect( - repairTranslatedValue({ - key: 'auto.components.workspace.cleanup.WorkspaceCleanupDialog.0b1766738a', - enValue: 'Repo', - localeValue: 'repositorio', - locale: 'es' - }) - ).toBe('repositorio') - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.add.repo.local.start.actions.fb4fc5380e', - enValue: 'Local project, Git repo, or folder with many repos', - localeValue: 'Proyecto local, repositorio de Git o carpeta con muchos repositorios', - locale: 'es' - }) - ).toBe('Proyecto local, repositorio de Git o carpeta con muchos repositorios') - }) -}) diff --git a/config/scripts/locale-catalog/locale-translation-policy.ja-relocalization.test.mjs b/config/scripts/locale-catalog/locale-translation-policy.ja-relocalization.test.mjs index 433a3e4b537..0ab813ce684 100644 --- a/config/scripts/locale-catalog/locale-translation-policy.ja-relocalization.test.mjs +++ b/config/scripts/locale-catalog/locale-translation-policy.ja-relocalization.test.mjs @@ -6,16 +6,6 @@ const ja = (enValue, localeValue, key = 'auto.test.relocalization') => repairTranslatedValue({ key, enValue, localeValue, locale: 'ja' }) describe('locale-translation-policy ja relocalization', () => { - it('heals generic terms the brand revert left in Latin mid-sentence', () => { - expect(ja('Close terminal?', 'この terminal を閉じますか?')).toBe('このターミナルを閉じますか?') - expect(ja('New Terminal', '新規 Terminal')).toBe('新規ターミナル') - expect(ja('Stop the agent?', 'この agent を停止しますか?')).toBe('この Agent を停止しますか?') - expect(ja('Nothing to commit.', 'commit するものはありません。')).toBe( - 'コミットするものはありません。' - ) - expect(ja('Open the repo', 'repo を開く')).toBe('リポジトリを開く') - }) - it('leaves the second word of a two-word command in Latin', () => { expect(ja('a commit hook or git commit fails', 'コミットフックまたは git commit が失敗')).toBe( 'コミットフックまたは git commit が失敗' @@ -36,21 +26,6 @@ describe('locale-translation-policy ja relocalization', () => { expect(ja('Run git commit -m', 'git commit -m を実行')).toBe('git commit -m を実行') }) - it('keeps commands and identifiers in English so they still run', () => { - expect(shouldPreserveEnglishValue('pnpm install')).toBe(true) - expect(shouldPreserveEnglishValue('glab auth login')).toBe(true) - expect(shouldPreserveEnglishValue("gh pr list --json number -q '.[0].number'")).toBe(true) - expect(shouldPreserveEnglishValue('--model sonnet')).toBe(true) - expect(shouldPreserveEnglishValue('localhost, 127.0.0.1, *.internal')).toBe(true) - expect(shouldPreserveEnglishValue('stale-agent-row-{{value0}}')).toBe(true) - expect(shouldPreserveEnglishValue('text-foreground')).toBe(true) - expect(shouldPreserveEnglishValue('{basePrompt}')).toBe(true) - expect(shouldPreserveEnglishValue('{firstPrompt}')).toBe(true) - expect(shouldPreserveEnglishValue('{assistantMessage}')).toBe(true) - expect(shouldPreserveEnglishValue('/pricing')).toBe(true) - expect(shouldPreserveEnglishValue('/signup')).toBe(true) - }) - it('repairs translated code examples back to executable values', () => { expect(ja('--model sonnet', '--モデルソネット')).toBe('--model sonnet') expect( @@ -68,78 +43,10 @@ describe('locale-translation-policy ja relocalization', () => { expect(shouldPreserveEnglishValue('e.g. {{value0}}')).toBe(false) }) - it('normalizes Japanese typography and settled terminology', () => { - expect(ja('Loading…', '読み込み中...')).toBe('読み込み中…') - expect(ja('Merge conflict', 'マージ紛争')).toBe('マージ競合') - // Why: MT inserts a Microsoft-style separator space that Japanese compounds do not use. - expect(ja('Status bar', 'ステータス バー')).toBe('ステータスバー') - expect(ja('Missing credentials', '資格情報がありません')).toBe('認証情報がありません') - expect(ja('Unknown', '未知')).toBe('不明') - expect(ja('Restart the server', 'サーバを再起動')).toBe('サーバーを再起動') - expect(ja('Open the browser', 'ブラウザーを開く')).toBe('ブラウザを開く') - }) - - it('preserves translated Japanese Skills labels', () => { - expect( - ja( - 'Filter by agent', - 'エージェントで絞り込み', - 'auto.components.skills.SkillsPage.filterProvider' - ) - ).toBe('エージェントで絞り込み') - }) - - it('preserves the native chat subagent label', () => { - expect(ja('Subagent', 'サブエージェント', 'components.native-chat.tool.row.subagent')).toBe( - 'サブエージェント' - ) - }) - it('leaves ranges and token samples out of the ellipsis rule', () => { expect(ja('Compare main...HEAD', 'main...HEAD を比較')).toBe('main...HEAD を比較') }) - it('spaces the Latin terms the phrase fixes write back in', () => { - expect(ja('Clear cookies', 'クッキーを消去')).toBe('Cookie を消去') - expect(ja('Safely fast-forward the branch', 'ブランチを安全に早送りします')).toBe( - 'ブランチを安全に fast-forward します' - ) - }) - - it('uses ホスト for host, and leaves サーバー alone when English says server', () => { - expect(ja('Host path', 'サーバーパス')).toBe('ホストパス') - expect(ja('Enter a path that exists on the selected host.', 'ランタイムサーバー上のパス')).toBe( - 'ホスト上のパス' - ) - // Why: host and server are deliberately distinct wherever the English uses both. - expect(ja('Save the server host', 'サーバーを保存')).toBe('サーバーを保存') - }) - - it('restores Git vocabulary and brand names the MT localized', () => { - expect(ja('Branch upstream', 'ブランチの上流')).toBe('ブランチの upstream') - expect(ja('origin has commits', '起源にコミットがあります')).toBe('origin にコミットがあります') - expect(ja('Discard all staged changes?', '段階的な変更を破棄しますか?')).toBe( - 'ステージ済みの変更を破棄しますか?' - ) - expect(ja('Create Hermes automation', 'エルメスオートメーションを作成')).toBe( - 'Hermes オートメーションを作成' - ) - expect(ja('Delete the worktree', 'worktree を削除')).toBe('ワークツリーを削除') - }) - - it('keeps class strings, refs, and fixture filenames in English', () => { - for (const value of [ - 'size-4 text-muted-foreground', - 'text-amber-700 dark:text-amber-300', - 'origin/main', - 'upstream/main', - 'login.spec.ts', - 'bastion.example.com' - ]) { - expect(shouldPreserveEnglishValue(value)).toBe(true) - } - }) - it('preserves a selector that has no declaration block', () => { for (const value of [ 'div.pricing-grid > div.card.starter:nth-of-type(1) > a.cta', diff --git a/config/scripts/locale-catalog/locale-translation-policy.ja-round5.test.mjs b/config/scripts/locale-catalog/locale-translation-policy.ja-round5.test.mjs deleted file mode 100644 index 1955a9eef24..00000000000 --- a/config/scripts/locale-catalog/locale-translation-policy.ja-round5.test.mjs +++ /dev/null @@ -1,157 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { repairTranslatedValue } from './locale-translation-policy.mjs' - -describe('locale-translation-policy ja round 5', () => { - it('fixes inline, launch, action, MR, and status chip regressions', () => { - expect( - repairTranslatedValue({ - key: 'auto.components.GitHubItemDialog.6e43a16435', - enValue: 'Inline', - localeValue: '列をなして', - locale: 'ja' - }) - ).toBe('インライン') - expect( - repairTranslatedValue({ - key: 'auto.components.repo.repo.icon.ecf63ec3ef', - enValue: 'Launch', - localeValue: '打ち上げ', - locale: 'ja' - }) - ).toBe('起動') - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.workspace.status.2c19d1db33', - enValue: 'Play', - localeValue: '遊ぶ', - locale: 'ja' - }) - ).toBe('再生') - expect( - repairTranslatedValue({ - key: 'auto.components.TaskPage.8396825a14', - enValue: 'Action', - localeValue: 'アクション', - locale: 'ja' - }) - ).toBe('操作') - expect( - repairTranslatedValue({ - key: 'auto.components.TaskPage.456b8512da', - enValue: 'MergeRequest', - localeValue: 'マージリクエスト', - locale: 'ja' - }) - ).toBe('MR') - expect( - repairTranslatedValue({ - key: 'auto.components.github.PRFilterDropdowns.7f1ba66c3e', - enValue: 'Reviewed by', - localeValue: 'レビュー者', - locale: 'ja' - }) - ).toBe('レビュアー') - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.workspace.status.caebe3c10f', - enValue: 'Conductor Review', - localeValue: '指揮者のレビュー', - locale: 'ja' - }) - ).toBe('Conductor レビュー') - expect( - repairTranslatedValue({ - key: 'auto.components.github.pr.merge.state.bf5e4c6c92', - enValue: 'Blocked', - localeValue: 'ブロック', - locale: 'ja' - }) - ).toBe('ブロック中') - expect( - repairTranslatedValue({ - key: 'auto.components.settings.IntegrationsPane.027440e1cb', - enValue: 'Merge requests, issues, todos, and pipelines via the', - localeValue: 'リクエスト、イシュー、ToDo、パイプラインをマージします。', - locale: 'ja' - }) - ).toBe('MR、Issue、ToDo、パイプラインは') - expect( - repairTranslatedValue({ - key: 'auto.components.GitLabItemDialog.98718490e4', - enValue: 'MR title is required.', - localeValue: 'MRの肩書きは必須です。', - locale: 'ja' - }) - ).toBe('MR タイトルは必須です。') - expect( - repairTranslatedValue({ - key: 'auto.components.settings.terminal.search.d5e6c7fab1', - enValue: 'font features', - localeValue: 'フォントの特徴', - locale: 'ja' - }) - ).toBe('フォント特性') - expect( - repairTranslatedValue({ - key: 'auto.components.GitHubItemDialog.f05d237049', - enValue: 'Add a project first', - localeValue: 'まずプロジェクトを追加してください', - locale: 'ja' - }) - ).toBe('まずプロジェクトを追加') - }) - - // Why: #12113 — brand names stay Latin, but generic workflow nouns keep their Japanese. - it('keeps brand names English and generic workflow terms translated', () => { - expect( - repairTranslatedValue({ - key: 'auto.components.status.bar.WorkspaceSpaceManagerPanel.e9528a89b3', - enValue: 'Terminals', - localeValue: '端末', - locale: 'ja' - }) - ).toBe('ターミナル') - expect( - repairTranslatedValue({ - key: 'auto.components.skills.SkillsPage.38e0951c3a', - enValue: 'Agent Skills', - localeValue: 'Agent のスキル', - locale: 'ja' - }) - ).toBe('Agent のスキル') - expect( - repairTranslatedValue({ - key: 'auto.components.tab.bar.TabBar.3d5d6c960d', - enValue: 'New Markdown', - localeValue: '新規マークダウン', - locale: 'ja' - }) - ).toBe('新規 Markdown') - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.local.base.ref.suggestion.toast.commits', - enValue: 'commits', - localeValue: 'コミット', - locale: 'ja' - }) - ).toBe('コミット') - expect( - repairTranslatedValue({ - key: 'auto.components.mobile.slides.WorktreeListSlide.22971156df', - enValue: 'Repo', - localeValue: 'リポ', - locale: 'ja' - }) - ).toBe('リポ') - expect( - repairTranslatedValue({ - key: 'auto.components.sidebar.add.repo.local.start.actions.fb4fc5380e', - enValue: 'Local project, Git repo, or folder with many repos', - localeValue: - 'ローカル プロジェクト、Git リポジトリ、または多数のリポジトリを含むフォルダー', - locale: 'ja' - }) - ).toBe('ローカルプロジェクト、Git リポジトリ、または多数のリポジトリを含むフォルダー') - }) -}) diff --git a/config/scripts/native-build/linux/verify-linux-glibc-floor.cjs b/config/scripts/native-build/linux/verify-linux-glibc-floor.cjs index a82ff3b1f3e..ab288f7ea91 100644 --- a/config/scripts/native-build/linux/verify-linux-glibc-floor.cjs +++ b/config/scripts/native-build/linux/verify-linux-glibc-floor.cjs @@ -43,9 +43,6 @@ const COMPAT_SLOT_GLIBC_FLOOR = glibcFloorProfile( [1, 3, 7] ) -// Lazy speech-worker sherpa prebuilt requires GCC11 GLIBCXX_3.4.29; exempt C++ floor only, retain glibc gate because it is not launch-critical. -const LIBSTDCXX_FLOOR_EXEMPT = /(?:^|[/\\])sherpa-onnx/ - // VER_FLG_WEAK needs may resolve null and use fallback; they must not raise required floor. const VER_FLG_WEAK = 0x2 @@ -118,15 +115,9 @@ function isLibstdcxxNode(name) { return name.startsWith('GLIBCXX_') || name.startsWith('CXXABI_') } -// Gate load-time requirements; exempt sherpa C++ needs only, never its glibc needs. -function findFloorViolations(needs, filePath = '', glibcFloor = DESKTOP_GLIBC_FLOOR) { - const exemptLibstdcxx = LIBSTDCXX_FLOOR_EXEMPT.test(filePath) - return needs.filter( - (need) => - !need.weak && - isVersionNodeAboveFloor(need.name, glibcFloor) && - !(exemptLibstdcxx && isLibstdcxxNode(need.name)) - ) +// Gate load-time requirements; weak needs can resolve to null and fall back. +function findFloorViolations(needs, glibcFloor = DESKTOP_GLIBC_FLOOR) { + return needs.filter((need) => !need.weak && isVersionNodeAboveFloor(need.name, glibcFloor)) } // Ubuntu20.04 keeps openpty/forkpty in libutil until glibc2.34 merge: require DT_NEEDED even when newer libc compat aliases satisfy link-time floor. @@ -402,7 +393,7 @@ function verifyLinuxGlibcFloor(rootDir, options = {}) { const { versionNeeds, neededLibraries, isStatic } = readDynamicInfo(filePath, objdumpPath) const isMuslTarget = isMuslTemplatePayload(filePath, neededLibraries, versionNeeds) // Remote musl payloads use their host's C++ runtime, not Ubuntu's libstdc++ or libutil. - const floorViolations = findFloorViolations(versionNeeds, filePath, glibcFloor).filter( + const floorViolations = findFloorViolations(versionNeeds, glibcFloor).filter( (need) => !isMuslTarget || !isLibstdcxxNode(need.name) ) // Inspect dynamic symbols only if relocated provider is absent from DT_NEEDED; healthy case avoids extra objdump. diff --git a/config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs b/config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs new file mode 100644 index 00000000000..7dd14db6070 --- /dev/null +++ b/config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs @@ -0,0 +1,273 @@ +#!/usr/bin/env node +// Packs one target's qualified template slot, its pinned Node and a launcher into the server-only +// tarball `orca serve` runs from on hosts without the desktop app. +// node pack-orcad-server-artifact.mjs --template out/orcad-template --target linux-x64-glibc [--out-dir out/orca-server] +import { createHash } from 'node:crypto' +import { + chmodSync, + copyFileSync, + mkdirSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync +} from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' +import { c as createTar } from 'tar' +import { + ORCAD_NODE_RUNTIME_DIR_PREFIX, + ORCAD_RUNTIMES_DIRNAME, + ORCAD_SERVER_ENTRY_FILENAME, + ORCAD_TEMPLATE_MANIFEST_FILENAME, + ORCAD_TEMPLATE_TARGETS_DIR, + ORCAD_VERSION_FILENAME, + ORCAD_CLI_ENTRY_FILENAME, + orcadNodeRuntimeExecutable, + orcadTemplateCommonFilenames, + orcadTemplateTargetFilenames +} from '../../../../src/shared/orcad-artifacts.ts' +import { ORCAD_LOCAL_SERVE_SELECTION_ENTRY } from '../../../../src/shared/orcad-local-serve-selection.ts' +import { + NODE_RUNTIME_PIN, + nodeRuntimeExecutablePath, + nodeRuntimeReleaseUrl, + pinnedNodeRuntimeAsset +} from '../../../../src/shared/node-runtime-pin.ts' +import { + ensurePinnedNodeExecutable, + fetchPinnedFile, + pinnedNodeCacheDir +} from '../prebuilds/pinned-node-downloads.mjs' +import { extract } from '../../node-runtime/archive-identity/update-node-runtime-pin.mjs' +import { computeOrcadFullVersion } from '../server-bundle/orcad-artifact-version.mjs' +import { assertNotDarkBuild } from '../../../dark-build-switches.cjs' +import { isDirectInvocation } from '../../tool-invocation/script-entry-detection.mjs' + +const root = resolve(import.meta.dirname, '../../../..') +const SLOT_DIR = 'orcad' +const LAUNCHER = 'bin/orca-ide' + +/** Published name without the libc suffix: only glibc slots are published. */ +export function orcaServerArtifactName(target) { + const match = /^(linux|darwin)-(x64|arm64)(?:-glibc)?$/.exec(target) + if (!match) { + throw new Error( + `No server-only artifact for ${target}; use linux-x64-glibc or linux-arm64-glibc` + ) + } + return `orca-server-${match[1]}-${match[2]}` +} + +function sha256(path) { + return createHash('sha256').update(readFileSync(path)).digest('hex') +} + +function isExecutable(filename) { + return /(?:^|\/)(?:rg|spawn-helper)$/.test(filename) +} + +function copyVerified(source, destination, expectedSha256, executable) { + mkdirSync(dirname(destination), { recursive: true }) + copyFileSync(source, destination) + const actual = sha256(destination) + if (actual !== expectedSha256) { + throw new Error(`${source} hashed ${actual}; the template manifest expects ${expectedSha256}`) + } + if (executable) { + chmodSync(destination, 0o755) + } +} + +/** Copies exactly the slot files the desktop deploys over SSH, each checked against the manifest. */ +function stageSlot(templateDir, target, slotDir) { + const manifest = JSON.parse( + readFileSync(join(templateDir, ORCAD_TEMPLATE_MANIFEST_FILENAME), 'utf8') + ) + const targetManifest = manifest.targets?.[target] + if (!targetManifest) { + throw new Error(`${templateDir} has no ${target} slot`) + } + const mobileWebAssets = Object.keys(manifest.commonSha256).filter((name) => + name.startsWith('out/mobile-web/') + ) + const common = orcadTemplateCommonFilenames([]) + const commonFiles = [...new Set([...common, ...mobileWebAssets])] + for (const filename of commonFiles) { + const expected = manifest.commonSha256[filename] + if (!expected) { + throw new Error(`Template manifest omits ${filename}`) + } + copyVerified( + join(templateDir, ...filename.split('/')), + join(slotDir, ...filename.split('/')), + expected, + isExecutable(filename) + ) + } + for (const filename of orcadTemplateTargetFilenames(target)) { + const expected = targetManifest.files?.[filename] + if (!expected) { + throw new Error(`Template manifest omits ${target} ${filename}`) + } + copyVerified( + join(templateDir, ORCAD_TEMPLATE_TARGETS_DIR, target, ...filename.split('/')), + join(slotDir, ...filename.split('/')), + expected, + isExecutable(filename) + ) + } + // Hashed like a desktop slot without the optional browser, which this tarball omits. + const version = computeOrcadFullVersion(slotDir, { target, agentBrowserFilename: null }) + writeFileSync(join(slotDir, ORCAD_VERSION_FILENAME), `${version}\n`) + return version +} + +// Why sh: it must run before any Node exists on the host. ELECTRON_RUN_AS_NODE=1 is how the packaged +// app's CLI runs, and the CLI strips it from the server's environment; the other two would point +// `serve` at a desktop app this install does not have. +function launcherScript(nodeRelativePath) { + return `#!/bin/sh +# Orca server-only launcher: runs the bundled Orca CLI under the bundled Node. +set -e +self=$0 +if command -v readlink >/dev/null 2>&1 && resolved=$(readlink -f -- "$self" 2>/dev/null); then + self=$resolved +fi +root=$(CDPATH= cd -- "$(dirname -- "$self")/.." && pwd -P) +node="$root/${nodeRelativePath}" +unset ORCA_APP_EXECUTABLE ORCA_SERVE_RUNTIME +ELECTRON_RUN_AS_NODE=1 +export ELECTRON_RUN_AS_NODE +exec "$node" "$root/${SLOT_DIR}/${ORCAD_CLI_ENTRY_FILENAME}" "$@" +` +} + +// The CLI asks `/out/main/.js` which server to run; here the answer is fixed. +function selectionEntryScript() { + return `'use strict' +// Answers \`orca serve\`'s runtime question for the server-only artifact (src/shared/orcad-local-serve-selection.ts). +const { readFileSync } = require('node:fs') +const { join } = require('node:path') +const flag = process.argv.indexOf('--app-root') +const root = flag === -1 ? join(__dirname, '..', '..', '..') : process.argv[flag + 1] +const slot = join(root, ${JSON.stringify(SLOT_DIR)}) +let selection +try { + const version = readFileSync(join(slot, ${JSON.stringify(ORCAD_VERSION_FILENAME)}), 'utf8').trim() + selection = { kind: 'orcad', runtime: process.execPath, entry: join(slot, ${JSON.stringify(ORCAD_SERVER_ENTRY_FILENAME)}), version } +} catch (error) { + process.stderr.write('This Orca server install is incomplete; extract the release archive again.\\n') + process.exit(1) +} +process.stdout.write('ORCA_SERVE_RUNTIME ' + JSON.stringify(selection) + '\\n') +` +} + +/** Node's notice ships with its binary; it comes from the same hash-checked archive. */ +async function copyNodeLicense(target, destination) { + const asset = pinnedNodeRuntimeAsset(target) + const cacheDir = pinnedNodeCacheDir() + const archive = await fetchPinnedFile({ + url: nodeRuntimeReleaseUrl(asset.source, asset.archive), + destination: join(cacheDir, asset.archive), + sha256: asset.archiveSha256 + }) + const topLevel = nodeRuntimeExecutablePath(target, asset.archive).replace(/\/bin\/node$/, '') + const extractDir = join(cacheDir, `license-${asset.archiveSha256.slice(0, 12)}`) + extract(archive, extractDir, `${topLevel}/LICENSE`) + copyFileSync(join(extractDir, topLevel, 'LICENSE'), destination) +} + +function listEntries(dir, base = dir) { + const entries = [] + for (const name of readdirSync(dir, { withFileTypes: true }).sort((a, b) => + a.name < b.name ? -1 : a.name > b.name ? 1 : 0 + )) { + const path = join(dir, name.name) + entries.push(relative(base, path)) + if (name.isDirectory()) { + entries.push(...listEntries(path, base)) + } + } + return entries +} + +export async function packOrcaServerArtifact({ templateDir, target, outDir }) { + // A dark build's template must never ship as a server either. + assertNotDarkBuild([templateDir]) + const name = orcaServerArtifactName(target) + const { version: appVersion } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) + const topDir = `orca-server-${appVersion}-${name.slice('orca-server-'.length)}` + const stagingRoot = join(outDir, '.staging') + const staging = join(stagingRoot, topDir) + rmSync(stagingRoot, { recursive: true, force: true }) + mkdirSync(staging, { recursive: true }) + + const orcadVersion = stageSlot(templateDir, target, join(staging, SLOT_DIR)) + const runtimeAsset = pinnedNodeRuntimeAsset(target) + const nodeRelativePath = [ + ORCAD_RUNTIMES_DIRNAME, + `${ORCAD_NODE_RUNTIME_DIR_PREFIX}${runtimeAsset.executableSha256}`, + orcadNodeRuntimeExecutable(target) + ].join('/') + copyVerified( + await ensurePinnedNodeExecutable({ target }), + join(staging, ...nodeRelativePath.split('/')), + runtimeAsset.executableSha256, + true + ) + const launcher = join(staging, ...LAUNCHER.split('/')) + mkdirSync(dirname(launcher), { recursive: true }) + writeFileSync(launcher, launcherScript(nodeRelativePath), { mode: 0o755 }) + chmodSync(launcher, 0o755) + const selectionEntry = join(staging, 'out', 'main', `${ORCAD_LOCAL_SERVE_SELECTION_ENTRY}.js`) + mkdirSync(dirname(selectionEntry), { recursive: true }) + writeFileSync(selectionEntry, selectionEntryScript()) + writeFileSync( + join(staging, 'VERSION'), + `orca ${appVersion}\norcad ${orcadVersion}\nnode ${NODE_RUNTIME_PIN.version}\ntarget ${target}\n` + ) + copyFileSync(join(root, 'LICENSE'), join(staging, 'LICENSE')) + await copyNodeLicense(target, join(staging, ORCAD_RUNTIMES_DIRNAME, 'NODE-LICENSE')) + + const archive = join(outDir, `${name}.tar.gz`) + rmSync(archive, { force: true }) + createTar( + { + file: archive, + sync: true, + cwd: stagingRoot, + gzip: { level: 9 }, + portable: true, + noDirRecurse: true, + // Fixed mtime: rebuilding the same tag yields the same bytes. + mtime: new Date(Number(process.env.SOURCE_DATE_EPOCH ?? 0) * 1000) + }, + [topDir, ...listEntries(staging).map((entry) => `${topDir}/${entry}`)] + ) + rmSync(stagingRoot, { recursive: true, force: true }) + const digest = sha256(archive) + writeFileSync(`${archive}.sha256`, `${digest} ${name}.tar.gz\n`) + return { archive, sha256: digest, topDir, orcadVersion } +} + +function argument(argv, name) { + const index = argv.indexOf(name) + return index === -1 ? null : (argv[index + 1] ?? null) +} + +if (isDirectInvocation(import.meta.url, process.argv[1])) { + const templateDir = argument(process.argv, '--template') + const target = argument(process.argv, '--target') + if (!templateDir || !target) { + throw new Error( + 'Usage: pack-orcad-server-artifact.mjs --template --target [--out-dir ]' + ) + } + const result = await packOrcaServerArtifact({ + templateDir: resolve(templateDir), + target, + outDir: resolve(argument(process.argv, '--out-dir') ?? join(root, 'out', 'orca-server')) + }) + process.stdout.write(`${JSON.stringify(result)}\n`) +} diff --git a/config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs b/config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs new file mode 100644 index 00000000000..c4c96330aac --- /dev/null +++ b/config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +// Installs a server-only tarball the documented way, starts `orca serve --recipe-json`, then pairs a +// second CLI profile with the printed code. Uses only node: builtins so the archive's own Node can run it +// on an image that has nothing else. +// node smoke-orcad-server-artifact.mjs --archive out/orca-server/orca-server-linux-x64.tar.gz +import { execFileSync, spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { + closeSync, + existsSync, + mkdirSync, + mkdtempSync, + openSync, + readFileSync, + rmSync +} from 'node:fs' +import { tmpdir } from 'node:os' +import { basename, join, resolve } from 'node:path' + +const argv = process.argv.slice(2) +const archiveArg = argv[argv.indexOf('--archive') + 1] +if (!argv.includes('--archive') || !archiveArg) { + fail('Usage: smoke-orcad-server-artifact.mjs --archive ') +} +const archive = resolve(archiveArg) +const work = mkdtempSync(join(tmpdir(), 'orca-server-smoke-')) +const install = join(work, 'install') +const projectRoot = join(work, 'project') +const serverProfile = join(work, 'server-profile') +const clientProfile = join(work, 'client-profile') +// Linux names the CLI orca-ide, like the desktop package. +const orca = join(install, 'bin', 'orca-ide') + +try { + verifyChecksum() + for (const dir of [install, projectRoot, serverProfile, clientProfile]) { + mkdirSync(dir, { recursive: true }) + } + execFileSync('tar', ['-xzf', archive, '-C', install, '--strip-components=1'], { + stdio: 'inherit' + }) + const version = run([orca, '--version'], serverProfile) + assert(version.status === 0, `orca --version failed:\n${version.stderr}`) + console.log(`installed ${version.stdout.trim()}`) + + const started = Date.now() + const serve = run( + [orca, 'serve', '--recipe-json', '--project-root', projectRoot, '--port', '0'], + serverProfile, + { timeout: 120_000 } + ) + assert(serve.status === 0, `serve --recipe-json exited ${serve.status}:\n${serve.stderr}`) + const recipe = JSON.parse(serve.stdout.trim().split('\n').at(-1)) + const pairingCode = recipe.pairingCode ?? recipe.connection?.pairingCode + assert( + typeof pairingCode === 'string' && pairingCode.length > 0, + `no pairing code: ${serve.stdout}` + ) + assert( + (recipe.projectRoot ?? recipe.connection?.projectRoot) === projectRoot, + `recipe JSON names another project root: ${serve.stdout}` + ) + console.log(`PASS serve --recipe-json printed a pairing code in ${Date.now() - started} ms`) + + const status = run([orca, '--pairing-code', pairingCode, 'status', '--json'], clientProfile, { + timeout: 60_000 + }) + assert(status.status === 0, `paired status failed:\n${status.stderr}\n${status.stdout}`) + const result = JSON.parse(status.stdout).result ?? {} + assert( + result.runtime?.state === 'ready' && result.runtime?.reachable !== false, + `paired client did not reach a ready server: ${status.stdout}` + ) + console.log( + `PASS a second profile paired and saw runtime ${result.runtime.runtimeId ?? ''} ready` + ) +} finally { + stopServersFrom(install) + rmSync(work, { recursive: true, force: true }) +} + +function verifyChecksum() { + const sums = `${archive}.sha256` + if (!existsSync(sums)) { + return + } + const [expected, name] = readFileSync(sums, 'utf8').trim().split(/\s+/) + const actual = createHash('sha256').update(readFileSync(archive)).digest('hex') + assert(name === basename(archive) && actual === expected, `${archive} does not match ${sums}`) + console.log('PASS checksum') +} + +// stderr goes to a file: the detached server keeps it open, and a pipe would hold spawnSync until timeout. +function run(command, profile, { timeout = 30_000 } = {}) { + const [program, ...args] = command + const log = join(work, `${basename(profile)}.stderr.log`) + const fd = openSync(log, 'a') + try { + const result = spawnSync(program, args, { + cwd: projectRoot, + encoding: 'utf8', + timeout, + stdio: ['ignore', 'pipe', fd], + env: { ...process.env, ORCA_USER_DATA_PATH: profile, ORCA_BACKGROUND_LAUNCH: '1' } + }) + return { ...result, stderr: readFileSync(log, 'utf8').slice(-4000) } + } finally { + closeSync(fd) + } +} + +// --recipe-json leaves the server running on purpose; this smoke must not. +function stopServersFrom(dir) { + const listing = spawnSync('ps', ['-eo', 'pid=,args='], { encoding: 'utf8' }) + for (const line of (listing.stdout ?? '').split('\n')) { + const match = /^\s*(\d+)\s+(.*)$/.exec(line) + if (match && match[2].includes(dir) && Number(match[1]) !== process.pid) { + try { + process.kill(Number(match[1]), 'SIGKILL') + } catch {} + } + } +} + +function assert(condition, message) { + if (!condition) { + fail(message) + } +} + +function fail(message) { + console.error(`FAIL ${message}`) + process.exitCode = 1 + throw new Error(message) +} diff --git a/config/scripts/performance/agent-lineage/agent-inspection-cadence-batching-benchmark.mjs b/config/scripts/performance/agent-lineage/agent-inspection-cadence-batching-benchmark.mjs deleted file mode 100644 index ac0f0ec31af..00000000000 --- a/config/scripts/performance/agent-lineage/agent-inspection-cadence-batching-benchmark.mjs +++ /dev/null @@ -1,141 +0,0 @@ -#!/usr/bin/env node -// Measure real cadence picker against independent ±10% jitter over simulated time. -// TTL-deduped same-tick work shares one capture, so count distinct wake instants rather than pane wakes. -import { spawnSync } from 'node:child_process' -import fs from 'node:fs' -import nodeModule from 'node:module' -import path from 'node:path' -import process from 'node:process' -import { fileURLToPath, pathToFileURL } from 'node:url' - -if (!process.execArgv.includes('--experimental-transform-types')) { - const result = spawnSync( - process.execPath, - ['--experimental-transform-types', '--no-warnings', import.meta.filename], - { stdio: 'inherit' } - ) - process.exit(result.status ?? 1) -} - -nodeModule.registerHooks({ - resolve(specifier, context, nextResolve) { - if (specifier.startsWith('.') && !/\.[cm]?[jt]s$/.test(specifier) && context.parentURL) { - const candidate = new URL(`${specifier}.ts`, context.parentURL) - if (fs.existsSync(fileURLToPath(candidate))) { - return { url: candidate.href, shortCircuit: true } - } - } - return nextResolve(specifier, context) - } -}) - -const ROOT = path.resolve(import.meta.dirname, '../../../..') -const WINDOW_MS = Number(process.env.ORCA_INSPECTION_BENCH_WINDOW_MS ?? '60000') -const PANE_COUNTS = (process.env.ORCA_INSPECTION_BENCH_PANES ?? '1,2,4,8') - .split(',') - .map((value) => Number(value.trim())) - -if (!Number.isSafeInteger(WINDOW_MS) || WINDOW_MS <= 0) { - throw new Error(`ORCA_INSPECTION_BENCH_WINDOW_MS must be a positive integer, got ${WINDOW_MS}`) -} -for (const paneCount of PANE_COUNTS) { - if (!Number.isSafeInteger(paneCount) || paneCount <= 0) { - throw new Error(`ORCA_INSPECTION_BENCH_PANES entries must be positive, got ${paneCount}`) - } -} - -const { nextCadenceInspectionDelayMs } = await import( - pathToFileURL( - path.join( - ROOT, - 'src/renderer/src/components/terminal-pane/agent-completion/agent-completion-poll-interval.ts' - ) - ).href -) -const { POLL_TIER_INTERVAL_MS } = await import( - pathToFileURL( - path.join( - ROOT, - 'src/renderer/src/components/terminal-pane/agent-completion/agent-completion-poll-cadence.ts' - ) - ).href -) -const { PROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MS } = await import( - pathToFileURL(path.join(ROOT, 'src/shared/process-table-snapshot-reader.ts')).href -) - -// Pre-change: independent ±10% jitter per pane, re-rolled on every reschedule. -function baselineDelayMs(baseMs) { - return Math.round(baseMs * (1 + (Math.random() * 0.2 - 0.1))) -} - -function simulate(paneCount, baseMs, pickDelay) { - const startedAt = 1_700_000_000_000 - const wakes = [] - for (let pane = 0; pane < paneCount; pane += 1) { - // Panes mount at arbitrary moments, which is what spreads them apart in the first place. - let clock = startedAt + Math.floor(Math.random() * baseMs) - while ((clock += pickDelay(baseMs, clock)) < startedAt + WINDOW_MS) { - wakes.push(clock) - } - } - // Snapshot TTL starts at actual capture, not epoch grid; nearby wakes reuse it. - let captures = 0 - let snapshotExpiresAt = -Infinity - for (const wakeAt of wakes.sort((left, right) => left - right)) { - if (wakeAt >= snapshotExpiresAt) { - captures += 1 - snapshotExpiresAt = wakeAt + PROCESS_TABLE_SNAPSHOT_MAX_STALENESS_MS - } - } - return captures -} - -function medianOf(rounds, run) { - const samples = Array.from({ length: rounds }, run).sort((left, right) => left - right) - return samples[Math.floor(samples.length / 2)] -} - -const baseMs = POLL_TIER_INTERVAL_MS.idle -console.log( - `Agent-completion cadence — whole-host \`ps\` captures over ${WINDOW_MS / 1000}s at the idle tier (${baseMs}ms)\n` -) -console.log('| visible panes | before | after | reduction |') -console.log('| --- | --- | --- | --- |') -for (const paneCount of PANE_COUNTS) { - const before = medianOf(21, () => simulate(paneCount, baseMs, baselineDelayMs)) - const after = medianOf(21, () => - simulate(paneCount, baseMs, (base, now) => - nextCadenceInspectionDelayMs({ - baseMs: base, - hasConsecutiveErrors: false, - alignToSharedGrid: true, - now - }) - ) - ) - // Short windows may yield no baseline captures; avoid meaningless division by zero. - const reduction = before > 0 ? `${(((before - after) / before) * 100).toFixed(0)}%` : 'n/a' - console.log(`| ${paneCount} | ${before} | ${after} | ${reduction} |`) -} - -// Detection latency must not regress: the grid deadline is always within one interval. -let worstDelay = 0 -for (let sample = 0; sample < 100_000; sample += 1) { - const now = 1_700_000_000_000 + sample * 7 - worstDelay = Math.max( - worstDelay, - nextCadenceInspectionDelayMs({ - baseMs, - hasConsecutiveErrors: false, - alignToSharedGrid: true, - now - }) - ) -} -if (worstDelay > baseMs) { - throw new Error(`grid alignment delayed a poll to ${worstDelay}ms, above the ${baseMs}ms tier`) -} -console.log( - `\nWorst observed wait: ${worstDelay}ms (tier interval ${baseMs}ms) — no inspection is ever delayed.` -) diff --git a/config/scripts/performance/agent-lineage/agent-lineage-cycle-cleanup-benchmark.mjs b/config/scripts/performance/agent-lineage/agent-lineage-cycle-cleanup-benchmark.mjs deleted file mode 100644 index 0693bc025a0..00000000000 --- a/config/scripts/performance/agent-lineage/agent-lineage-cycle-cleanup-benchmark.mjs +++ /dev/null @@ -1,90 +0,0 @@ -// Run: node --expose-gc config/scripts/agent-lineage-cycle-cleanup-benchmark.mjs [baseline-ref] -import assert from 'node:assert/strict' -import { execFileSync } from 'node:child_process' -import { readFile } from 'node:fs/promises' -import { performance } from 'node:perf_hooks' -import { transform } from 'esbuild' -import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' - -const sourcePath = 'src/renderer/src/components/dashboard/agent-row-lineage-model.ts' -const baseline = process.argv[2] ?? '20ab9950654' -const beforeSource = execFileSync('git', ['show', `${baseline}:${sourcePath}`], { - encoding: 'utf8', - windowsHide: true -}) -async function load(source) { - const { code } = await transform(source, { loader: 'ts', format: 'esm' }) - return (await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`)) - .buildAgentRowLineageTree -} -const before = await load(beforeSource) -const after = await load(await readFile(sourcePath, 'utf8')) - -function row(index, parent) { - return { - paneKey: `pane-${index}`, - entry: { - terminalHandle: `term-${index}`, - orchestration: parent === undefined ? undefined : { parentPaneKey: `pane-${parent}` } - } - } -} - -// Exercise duplicate keys, disconnected cycles, missing parents, and handle fallback. -let seed = 7391 -function random(max) { - seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0 - return seed % max -} -for (let sample = 0; sample < 500; sample++) { - const rows = Array.from({ length: 40 }, () => { - const value = row(random(30), random(40)) - value.entry.orchestration.parentTerminalHandle = `term-${random(40)}` - value.entry.orchestration.coordinatorHandle = `term-${random(40)}` - return value - }) - if (sample % 2 === 0) { - rows.unshift(row('root', undefined)) - } - assert.deepEqual(after(rows), before(rows)) -} - -const results = [] -for (const [topology, count] of [ - ['flat', 1000], - ['all-cycles', 1000], - ['mixed-cycles', 100], - ['mixed-cycles', 500], - ['mixed-cycles', 1000] -]) { - const rows = Array.from({ length: count }, (_, index) => - row(index, topology === 'flat' ? undefined : index ^ 1) - ) - if (topology === 'mixed-cycles') { - rows.unshift(row('root', undefined)) - } - assert.deepEqual(after(rows), before(rows)) - for (let warmup = 0; warmup < 30; warmup++) { - before(rows) - after(rows) - } - const samples = { before: [], after: [] } - for (const pair of buildCounterbalancedSchedule(8, 'before', 'after')) { - for (const arm of pair) { - global.gc?.() - const run = arm === 'before' ? before : after - const cpu = process.cpuUsage() - const start = performance.now() - for (let iteration = 0; iteration < 30; iteration++) { - run(rows) - } - const wallMs = (performance.now() - start) / 30 - const used = process.cpuUsage(cpu) - samples[arm].push({ wallMs, cpuMs: (used.user + used.system) / 30_000 }) - } - } - results.push({ topology, count, samples }) -} -console.log( - JSON.stringify({ baseline, node: process.version, parityGraphs: 500, results }, null, 2) -) diff --git a/config/scripts/performance/agent-lineage/agent-lineage-reachability-benchmark.mjs b/config/scripts/performance/agent-lineage/agent-lineage-reachability-benchmark.mjs deleted file mode 100644 index bf881a2be79..00000000000 --- a/config/scripts/performance/agent-lineage/agent-lineage-reachability-benchmark.mjs +++ /dev/null @@ -1,118 +0,0 @@ -import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' -import { performance } from 'node:perf_hooks' -import { transform } from 'esbuild' -import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' -import { summarizeBenchmarkSamples } from '../measurement/benchmark-sample-summary.mjs' - -// git show :src/renderer/src/components/dashboard/agent-row-lineage-model.ts | node config/scripts/agent-lineage-reachability-benchmark.mjs -async function load(source) { - const { code } = await transform(source, { loader: 'ts', format: 'esm' }) - return (await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`)) - .buildAgentRowLineageTree -} -const implementations = { - before: await load(readFileSync(0, 'utf8')), - after: await load( - readFileSync('src/renderer/src/components/dashboard/agent-row-lineage-model.ts', 'utf8') - ) -} -function orderedTree(tree) { - return { - roots: tree.rootRows, - children: [...tree.childrenByParentPaneKey], - childKeys: [...tree.childPaneKeys] - } -} - -let seed = 42 -const random = (max) => { - seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0 - return Math.floor((seed / 2 ** 32) * max) -} -let differentialCases = 0 -for (let trial = 0; trial < 5000; trial += 1) { - const count = random(100) - const rows = Object.freeze( - Array.from({ length: count }, (_, index) => - Object.freeze({ - paneKey: `pane-${random(count + 4)}`, - index, - entry: Object.freeze({ - terminalHandle: random(2) ? `term-${random(count)}` : undefined, - orchestration: Object.freeze({ - parentPaneKey: random(3) ? `pane-${random(count + 4)}` : undefined, - parentTerminalHandle: random(2) ? `term-${random(count)}` : undefined, - coordinatorHandle: random(2) ? `term-${random(count)}` : undefined - }) - }) - }) - ) - ) - assert.deepEqual( - orderedTree(implementations.after(rows)), - orderedTree(implementations.before(rows)) - ) - differentialCases += 1 -} - -const results = [] -for (const count of [8, 32, 128, 512, 1024]) { - for (const topology of ['flat', 'fanout', 'balanced', 'chain']) { - const rows = Array.from({ length: count }, (_, index) => { - const parent = - topology === 'fanout' - ? 0 - : topology === 'balanced' - ? Math.floor((index - 1) / 4) - : index - 1 - return { - paneKey: `pane-${index}`, - entry: { - orchestration: - index > 0 && topology !== 'flat' ? { parentPaneKey: `pane-${parent}` } : undefined - } - } - }) - const expected = orderedTree(implementations.before(rows)) - assert.deepEqual(orderedTree(implementations.after(rows)), expected) - const iterations = Math.max(5, Math.floor(10_000 / count)) - for (let warmup = 0; warmup < 20; warmup += 1) { - implementations.before(rows) - implementations.after(rows) - } - /** @type {{ before: number[], after: number[] }} */ - const samples = { before: [], after: [] } - for (const pair of buildCounterbalancedSchedule(8, 'before', 'after')) { - for (const arm of pair) { - let result - const started = performance.now() - for (let repeat = 0; repeat < iterations; repeat += 1) { - result = implementations[arm](rows) - } - samples[arm].push(performance.now() - started) - assert.deepEqual(orderedTree(result), expected) - } - } - results.push({ - count, - topology, - iterations, - meanMicrosecondsPerTree: Object.fromEntries( - Object.entries(samples).map(([arm, values]) => [ - arm, - (values.reduce((sum, ms) => sum + ms, 0) * 1000) / values.length / iterations - ]) - ), - before: summarizeBenchmarkSamples(samples.before), - after: summarizeBenchmarkSamples(samples.after) - }) - } -} -console.log( - JSON.stringify( - { node: process.version, platform: process.platform, differentialCases, results }, - null, - 2 - ) -) diff --git a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts b/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts deleted file mode 100644 index 774c2411787..00000000000 --- a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts +++ /dev/null @@ -1,255 +0,0 @@ -// Compare identical benchmark APIs on baseline/candidate; separate instrumented allocation counts from clean timing to avoid patch-induced deoptimization. -// Run: ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.agent-status-benchmark.config.ts -// Reported-user scale: 423 worktrees/634 tabs, rather than the 100-worktree fixture. -import { writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import type { AppState } from '@/store/types' -import type { AgentStatusBatchUpdate } from '@/store/slices/agent-status/agent-status-contract' -import '@/store/slices/agent-status/agent-status' -import { MAX_LIVE_AGENT_STATUSES } from '@/store/slices/agent-status/agent-status-capacity-eviction' -import type { createTestStore } from '@/store/testing/app-store-test-fixture' -import { - createAgentStatusPaneRoutingIndex, - resolvePaneKeyFromRoutingIndex -} from '@/hooks/ipc-events/agent-status-pane-routing-index' -import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' -import { resolvePaneKey } from '@/hooks/ipc-events/agent-status-routing' - -const WORKTREES = 423 -const EVENTS = 1_000 -const BATCH_SIZE = 8 -const BASE_TIME = 2_000_000_000 - -const counters = { maps: 0, sets: 0, tabComparisons: 0 } - -const NativeMap = globalThis.Map -const NativeSet = globalThis.Set - -function withAllocationCounting(run: () => T): T { - class CountingMap extends NativeMap { - constructor(entries?: Iterable | null) { - super(entries) - counters.maps += 1 - } - } - class CountingSet extends NativeSet { - constructor(values?: Iterable | null) { - super(values) - counters.sets += 1 - } - } - counters.maps = 0 - counters.sets = 0 - globalThis.Map = CountingMap - globalThis.Set = CountingSet - try { - return run() - } finally { - globalThis.Map = NativeMap - globalThis.Set = NativeSet - } -} - -function buildFixture(countTabIteration: boolean) { - const fixture = buildAgentStatusScaleFixture( - countTabIteration - ? () => { - counters.tabComparisons += 1 - } - : undefined - ) - fixture.store.setState({ setGeneratedTabTitlesFromAgentPrompts: () => {} }) - return fixture -} - -function measure(run: () => void): number { - const start = performance.now() - run() - return performance.now() - start -} - -function per1k(value: number): number { - return Math.round((value / EVENTS) * 1000) -} - -/** One burst-shaped pass: a fresh index per batch, one pane resolution per event. */ -function runIndexedRouting(store: ReturnType, paneKeys: string[]): void { - for (let event = 0; event < EVENTS; event += 1) { - if (event % BATCH_SIZE === 0) { - store.setState({ agentStatusEpoch: event }) - } - const index = createAgentStatusPaneRoutingIndex(store.getState()) - resolvePaneKeyFromRoutingIndex(index, paneKeys[event % paneKeys.length]) - } -} - -function runStandaloneRouting(state: AppState, paneKeys: string[]): void { - for (let event = 0; event < EVENTS; event += 1) { - resolvePaneKey(state, paneKeys[event % paneKeys.length]) - } -} - -function buildBatches( - owners: { tabId: string; worktreeId: string }[], - paneKeys: string[] -): AgentStatusBatchUpdate[][] { - const batches: AgentStatusBatchUpdate[][] = [] - for (let event = 0; event < EVENTS; event += 1) { - const batchIndex = Math.floor(event / BATCH_SIZE) - const owner = owners[event % owners.length] - batches[batchIndex] ??= [] - batches[batchIndex].push({ - paneKey: paneKeys[event % paneKeys.length], - payload: { state: 'working', prompt: `turn ${event}`, agentType: 'claude' }, - timing: { updatedAt: BASE_TIME + event, stateStartedAt: BASE_TIME + event }, - routing: { tabId: owner.tabId, worktreeId: owner.worktreeId } - }) - } - return batches -} - -const nextTick = (): Promise => - new Promise((resolve) => { - queueMicrotask(resolve) - }) - -async function runCommitPass( - store: ReturnType, - batches: AgentStatusBatchUpdate[][], - onBatch?: (elapsed: number) => void -): Promise { - for (const batch of batches) { - const elapsed = measure(() => { - store.getState().setAgentStatuses(batch) - }) - onBatch?.(elapsed) - // Each 33 ms burst is its own tick in production; let the deferred freshness scan run. - await nextTick() - } -} - -describe('agent-status hot path benchmark', () => { - it('reports routing, resolution and commit cost at 423 worktrees', async () => { - const report: Record = {} - const fixture = buildFixture(false) - const index = createAgentStatusPaneRoutingIndex(fixture.store.getState()) - for (const [position, paneKey] of fixture.paneKeys.entries()) { - const resolved = resolvePaneKeyFromRoutingIndex(index, paneKey) - expect(resolved).toMatchObject({ - exists: true, - owningWorktreeId: fixture.owners[position].worktreeId - }) - expect(resolved).toEqual(resolvePaneKey(fixture.store.getState(), paneKey)) - } - - { - const alloc = buildFixture(false) - withAllocationCounting(() => runIndexedRouting(alloc.store, alloc.paneKeys)) - report['routing.indexed.mapAllocationsPer1kEvents'] = per1k(counters.maps) - report['routing.indexed.setAllocationsPer1kEvents'] = per1k(counters.sets) - - const warm = buildFixture(false) - runIndexedRouting(warm.store, warm.paneKeys) - const clean = buildFixture(false) - report['routing.indexed.ms'] = Number( - measure(() => runIndexedRouting(clean.store, clean.paneKeys)).toFixed(2) - ) - } - - { - const alloc = buildFixture(true) - counters.tabComparisons = 0 - withAllocationCounting(() => runStandaloneRouting(alloc.store.getState(), alloc.paneKeys)) - report['routing.standalone.tabComparisonsPer1kEvents'] = per1k(counters.tabComparisons) - report['routing.standalone.mapAllocationsPer1kEvents'] = per1k(counters.maps) - - const warm = buildFixture(false) - runStandaloneRouting(warm.store.getState(), warm.paneKeys) - const clean = buildFixture(false) - report['routing.standalone.ms'] = Number( - measure(() => runStandaloneRouting(clean.store.getState(), clean.paneKeys)).toFixed(2) - ) - } - - { - const alloc = buildFixture(true) - counters.tabComparisons = 0 - runIndexedRouting(alloc.store, alloc.paneKeys) - report['routing.indexed.tabComparisonsPer1kEvents'] = per1k(counters.tabComparisons) - } - - // Store commits: 1,000 updates folded in 125 transactions, one microtask tick per transaction. - { - const counted = buildFixture(false) - const nativeObjectAssign = Object.assign - const nativeObjectValues = Object.values - let objectAssignCalls = 0 - let objectAssignPropertyCopies = 0 - let freshnessEntryVisits = 0 - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: `Object.assign` is an overload set no single arrow can satisfy; this wrapper only counts calls and forwards every argument to the captured native implementation. - Object.assign = (( - target: Record, - ...sources: readonly Record[] - ) => { - objectAssignCalls += 1 - for (const source of sources) { - if (source && typeof source === 'object') { - objectAssignPropertyCopies += Object.keys(source).length - } - } - return nativeObjectAssign(target, ...sources) - }) as typeof Object.assign - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: same overload-set limit as the `Object.assign` wrapper above; this one counts visited entries and returns the native result unchanged. - Object.values = ((value: Record) => { - const result = nativeObjectValues(value) - freshnessEntryVisits += result.length - return result - }) as typeof Object.values - const countedBatches = buildBatches(counted.owners, counted.paneKeys) - try { - await runCommitPass(counted.store, countedBatches) - } finally { - Object.assign = nativeObjectAssign - Object.values = nativeObjectValues - } - report['commit.objectAssignCallsPer1kUpdates'] = per1k(objectAssignCalls) - report['commit.stagedPropertyCopiesPer1kUpdates'] = per1k(objectAssignPropertyCopies) - report['commit.freshnessEntryVisitsPer1kUpdates'] = per1k(freshnessEntryVisits) - report['commit.transactions'] = countedBatches.length - const committed = counted.store.getState().agentStatusByPaneKey - const expected = new Map( - countedBatches - .flat() - .slice(-MAX_LIVE_AGENT_STATUSES) - .map((update) => [update.paneKey, update]) - ) - expect(Object.keys(committed).sort()).toEqual([...expected.keys()].sort()) - for (const [paneKey, update] of expected) { - expect(committed[paneKey]).toMatchObject({ - ...update.payload, - ...update.timing, - ...update.routing - }) - } - - const warm = buildFixture(false) - await runCommitPass(warm.store, buildBatches(warm.owners, warm.paneKeys)) - const clean = buildFixture(false) - let elapsed = 0 - await runCommitPass(clean.store, buildBatches(clean.owners, clean.paneKeys), (batchMs) => { - elapsed += batchMs - }) - report['commit.ms'] = Number(elapsed.toFixed(2)) - } - - const outputPath = - process.env.ORCA_AGENT_STATUS_BENCH_OUTPUT ?? - join(tmpdir(), 'agent-status-hot-path-benchmark.json') - writeFileSync( - outputPath, - `${JSON.stringify({ worktrees: WORKTREES, events: EVENTS, report }, null, 2)}\n` - ) - }) -}) diff --git a/config/scripts/performance/claude-usage/claude-usage-cache-representation-check.mjs b/config/scripts/performance/claude-usage/claude-usage-cache-representation-check.mjs deleted file mode 100644 index 212ec5a974b..00000000000 --- a/config/scripts/performance/claude-usage/claude-usage-cache-representation-check.mjs +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env node -import assert from 'node:assert/strict' -import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { createHash } from 'node:crypto' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { parseArgs } from 'node:util' -import { runProcessSync } from '@orca/process-host' -import { - loadClaudeUsageBenchmarkScanner, - readClaudeUsageBenchmarkBaselineSources -} from './claude-usage-benchmark-scanner.mjs' - -const ROOT = fileURLToPath(new URL('../../../..', import.meta.url)) -const STORE_PATH = 'src/main/claude-usage/store.ts' -const { values } = parseArgs({ - options: { - 'baseline-ref': { type: 'string', default: '51e7181850b022bae2d41091fe1229accef4bd50' }, - 'usage-keys': { type: 'string', default: '16384' }, - output: { type: 'string' } - } -}) -const usageKeys = Number(values['usage-keys']) -assert( - Number.isSafeInteger(usageKeys) && usageKeys > 7, - 'usage-keys must be an integer above seven' -) -process.env.ORCA_CLAUDE_USAGE_APPEND_BENCH_BASELINE = values['baseline-ref'] - -function serializationIndent(source) { - const indent = /jsonIndent:\s*(\d+)/.exec(source) - return indent ? Number(indent[1]) : undefined -} - -function sourceHash(source) { - return createHash('sha256').update(source).digest('hex') -} - -function persistedState(result) { - return { - schemaVersion: 6, - worktreeFingerprint: '[]', - processedFiles: result.processedFiles, - sessions: result.sessions, - dailyAggregates: result.dailyAggregates, - scanState: { - enabled: true, - lastScanStartedAt: 1, - lastScanCompletedAt: 2, - lastScanError: null - } - } -} - -function usageRecord(cwd, index, inputTokens = 100) { - return `${JSON.stringify({ - type: 'assistant', - sessionId: 'active-session', - timestamp: new Date(Date.UTC(2026, 9, 9, 12, 0, index)).toISOString(), - requestId: `request-${index}`, - cwd, - gitBranch: 'benchmark', - message: { - id: `message-${index}`, - model: 'claude-sonnet-4-6', - usage: { - input_tokens: inputTokens, - output_tokens: 10, - cache_read_input_tokens: 0, - cache_creation_input_tokens: 20, - cache_creation: { ephemeral_1h_input_tokens: 5 } - } - } - })}\n` -} - -const home = await mkdtemp(join(tmpdir(), 'orca-claude-cache-representation-')) -try { - const project = join(home, '.claude', 'projects', 'benchmark') - const cwd = join(home, 'repo') - await mkdir(project, { recursive: true }) - await mkdir(cwd) - const transcriptPath = join(project, 'active-session.jsonl') - const history = Array.from({ length: usageKeys }, (_, index) => usageRecord(cwd, index)).join('') - const baseline = await readClaudeUsageBenchmarkBaselineSources() - const storeRead = runProcessSync({ - program: 'git', - args: ['show', `${baseline.baselineCommit}:${STORE_PATH}`], - cwd: ROOT, - timeoutMs: 10_000, - maxOutputBytes: 1024 * 1024, - env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' } - }) - assert.equal(storeRead.code, 0, storeRead.stderr) - const currentStore = await readFile(join(ROOT, ...STORE_PATH.split('/')), 'utf8') - const stores = { baseline: storeRead.stdout, current: currentStore } - const loaded = await Promise.all([ - loadClaudeUsageBenchmarkScanner(home, baseline.sources, new Map(), baseline.baselineCommit), - loadClaudeUsageBenchmarkScanner(home) - ]) - const arms = {} - const results = [] - for (const [index, arm] of ['baseline', 'current'].entries()) { - const { scanner, bundleSha256, sourceFingerprints } = loaded[index] - await writeFile(transcriptPath, history) - const cold = await scanner.scanClaudeUsageFiles([], [], undefined, []) - await appendFile(transcriptPath, usageRecord(cwd, 7, 2_000)) - const result = await scanner.scanClaudeUsageFiles( - [], - JSON.parse(JSON.stringify(cold.processedFiles)), - undefined, - [] - ) - const fresh = await scanner.scanClaudeUsageFiles([], [], undefined, []) - assert.deepEqual(result, fresh, `${arm} resume differs from a fresh scan`) - assert.equal(result.processedFiles[0].ownedDedupeKeys.length, usageKeys) - assert.equal(result.sessions[0].totalInputTokens, usageKeys * 100 + 1_900) - const state = persistedState(result) - const compact = JSON.stringify(state) - const indented = JSON.stringify(state, null, 2) - const indent = serializationIndent(stores[arm]) - assert.deepEqual(JSON.parse(compact), JSON.parse(indented)) - assert.deepEqual(structuredClone(state), state) - arms[arm] = { - compactFullStateBytes: Buffer.byteLength(compact), - indentedFullStateBytes: Buffer.byteLength(indented), - productionFullStateBytes: Buffer.byteLength(JSON.stringify(state, null, indent)), - productionIndent: indent ?? null, - storeSha256: sourceHash(stores[arm]), - ownedKeys: result.processedFiles[0].ownedDedupeKeys.length, - bundleSha256, - sourceFingerprints - } - results.push(result) - } - assert.deepEqual(results[0].sessions, results[1].sessions) - assert.deepEqual(results[0].dailyAggregates, results[1].dailyAggregates) - const report = { - purpose: 'Actual scanner cache representation byte counts; no timing or peak-memory claim.', - node: process.version, - platform: process.platform, - arch: process.arch, - baselineRef: baseline.baselineRef, - baselineCommit: baseline.baselineCommit, - usageKeys, - historyBytes: Buffer.byteLength(history), - stateFields: 'schema v6; source cache, session/daily projections and fixed scan-state metadata', - exactColdParity: true, - crossArmProjectionParity: true, - serializationParity: true, - structuredCloneParity: true, - toolingSha256: sourceHash(await readFile(import.meta.filename)), - arms - } - if (values.output) { - await writeFile(values.output, `${JSON.stringify(report, null, 2)}\n`) - } - console.log(JSON.stringify(report)) -} finally { - await rm(home, { recursive: true, force: true }) -} diff --git a/config/scripts/performance/native-chat/native-chat-live-session-benchmark.ts b/config/scripts/performance/native-chat/native-chat-live-session-benchmark.ts deleted file mode 100644 index bb1db7cef21..00000000000 --- a/config/scripts/performance/native-chat/native-chat-live-session-benchmark.ts +++ /dev/null @@ -1,291 +0,0 @@ -// Run pnpm exec tsx config/scripts/native-chat-live-session-benchmark.ts. Synthetic 2KB messages stress fallback-key normalization. -// Excludes parsing, IPC/remote latency, React/DOM; results are not average production size or end-to-end frame latency. - -import { deepStrictEqual, strictEqual } from 'node:assert' -import { performance } from 'node:perf_hooks' -import type { - NativeChatMessage, - NativeChatSession -} from '../../../../src/shared/native-chat/native-chat-types' -import { getVerifiedNativeChatCommands } from '../../../../src/shared/native-chat/native-chat-agent-profiles' -import { surfaceSkillInvocationUserTurns } from '../../../../src/shared/native-chat/native-chat-command-envelope' -import { prepareNativeChatLiveMessages } from '../../../../src/renderer/src/components/native-chat/session/terminal/assembly/native-chat-live-message-preparation' -import { mergeNativeChatLiveSession } from '../../../../src/shared/native-chat/native-chat-live-status' -import { assembleNativeChatSession } from '../../../../src/renderer/src/components/native-chat/session/terminal/assembly/native-chat-session-assembler' - -type Operation = (index: number) => number -type ExpectedChecksum = (iterations: number) => number -type Calibration = { iterations: number; elapsedMs: number; capped: boolean } - -const TARGET_SAMPLE_MS = 50 -const MAX_ITERATIONS = 16_777_216 -const ROUNDS = 10 -let checksum = 0 -let expectedChecksum = 0 -let validatedCases = 0 -let cappedCalibrations = 0 -const sessionSink: { value: NativeChatSession | null } = { value: null } -let messageArraySink: NativeChatMessage[] | null = null -let contentSink = '' -const benchmarkStartedAt = performance.now() - -function proseFixture(count: number, bytes: number, withTurnId: boolean): NativeChatMessage[] { - const payload = 'Ab Cd '.repeat(Math.ceil(bytes / 7)).slice(0, bytes) - return Array.from({ length: count }, (_, index) => ({ - id: `message-${index}`, - role: index % 2 === 0 ? ('user' as const) : ('assistant' as const), - blocks: [{ type: 'text' as const, text: `${payload}-${index}` }], - timestamp: index, - source: 'transcript' as const, - ...(withTurnId ? { turnId: `turn-${index}` } : {}) - })) -} - -function toolFixture(count: number): NativeChatMessage[] { - return Array.from({ length: count }, (_, index) => ({ - id: `tool-${index}`, - role: index % 2 === 0 ? ('assistant' as const) : ('tool' as const), - blocks: - index % 2 === 0 - ? [ - { - type: 'tool-call' as const, - name: 'read', - input: { path: `${index}.txt`, context: 'x'.repeat(512) } - } - ] - : [{ type: 'tool-result' as const, output: `result-${index}-${'x'.repeat(512)}` }], - timestamp: index, - source: 'transcript' as const - })) -} - -function legacySession(messages: NativeChatMessage[]): NativeChatSession { - return assembleNativeChatSession({ - sources: { transcript: messages }, - sessionId: 'benchmark', - agent: 'claude' - }) -} - -function legacyMessageUpdateSession(messages: NativeChatMessage[]): NativeChatSession { - const commandNames = new Set( - getVerifiedNativeChatCommands('claude').map((command) => command.name) - ) - return legacySession(surfaceSkillInvocationUserTurns(messages, commandNames)) -} - -function directMessageUpdateSession(messages: NativeChatMessage[]): NativeChatSession { - return mergeNativeChatLiveSession({ - messages: prepareNativeChatLiveMessages(messages, 'claude'), - sessionId: 'benchmark', - agent: 'claude', - hookState: null - }) -} - -function blockContent(message: NativeChatMessage): string { - const block = message.blocks[0] - if (!block) { - return '' - } - if (block.type === 'text') { - return block.text - } - if (block.type === 'tool-call') { - return block.name - } - if (block.type === 'tool-result') { - return block.output - } - if (block.type === 'image-ref') { - return block.path ?? block.url ?? block.alt ?? '' - } - return block.type === 'background-task' ? block.taskId : block.groupId -} - -function messageWeight(message: NativeChatMessage, content: string): number { - const idTail = message.id.length > 0 ? message.id.charCodeAt(message.id.length - 1) : 0 - const contentTail = content.length > 0 ? content.charCodeAt(content.length - 1) : 0 - return message.id.length + idTail + message.role.charCodeAt(0) + content.length + contentTail -} - -function consumeSession(session: NativeChatSession, index: number): number { - sessionSink.value = session - messageArraySink = session.messages - const message = session.messages[index % session.messages.length] - if (!message) { - contentSink = '' - return session.status.charCodeAt(0) - } - contentSink = blockContent(message) - return session.status.charCodeAt(0) + messageWeight(message, contentSink) -} - -function cyclicChecksum(values: readonly number[], iterations: number): number { - if (values.length === 0) { - return 0 - } - const cycle = values.reduce((sum, value) => sum + value, 0) - const fullCycles = Math.floor(iterations / values.length) - let total = cycle * fullCycles - for (let index = 0; index < iterations % values.length; index += 1) { - total += values[index]! - } - return total -} - -function sessionExpectedChecksum(session: NativeChatSession): ExpectedChecksum { - const statusWeight = session.status.charCodeAt(0) - const weights = session.messages.map((message) => { - const content = blockContent(message) - return messageWeight(message, content) - }) - return (iterations) => statusWeight * iterations + cyclicChecksum(weights, iterations) -} - -function runSample(operation: Operation, expected: ExpectedChecksum, iterations: number): number { - let sampleChecksum = 0 - const startedAt = performance.now() - for (let index = 0; index < iterations; index += 1) { - sampleChecksum += operation(index) - } - const elapsedMs = performance.now() - startedAt - checksum += sampleChecksum - expectedChecksum += expected(iterations) - return elapsedMs -} - -function median(samples: number[]): number { - return [...samples].sort((left, right) => left - right)[Math.floor(samples.length / 2)]! -} - -function calibrate(operation: Operation, expected: ExpectedChecksum): Calibration { - let iterations = 1 - let reachedTarget = false - while (true) { - const elapsedMs = runSample(operation, expected, iterations) - if (elapsedMs >= TARGET_SAMPLE_MS) { - if (reachedTarget) { - return { iterations, elapsedMs, capped: false } - } - reachedTarget = true - continue - } - if (iterations >= MAX_ITERATIONS) { - return { iterations, elapsedMs, capped: true } - } - reachedTarget = false - iterations = Math.min(iterations * 2, MAX_ITERATIONS) - } -} - -function benchmark( - name: string, - baseline: Operation, - optimized: Operation, - expected: ExpectedChecksum -): void { - const baselineValue = baseline(0) - const optimizedValue = optimized(0) - strictEqual(optimizedValue, baselineValue, `${name}: timed arms returned different checksums`) - validatedCases += 1 - const baselineCalibration = calibrate(baseline, expected) - const optimizedCalibration = calibrate(optimized, expected) - cappedCalibrations += Number(baselineCalibration.capped) + Number(optimizedCalibration.capped) - const baselineSamples: number[] = [] - const optimizedSamples: number[] = [] - for (let round = 0; round < ROUNDS; round += 1) { - if (round % 2 === 0) { - baselineSamples.push( - runSample(baseline, expected, baselineCalibration.iterations) / - baselineCalibration.iterations - ) - optimizedSamples.push( - runSample(optimized, expected, optimizedCalibration.iterations) / - optimizedCalibration.iterations - ) - } else { - optimizedSamples.push( - runSample(optimized, expected, optimizedCalibration.iterations) / - optimizedCalibration.iterations - ) - baselineSamples.push( - runSample(baseline, expected, baselineCalibration.iterations) / - baselineCalibration.iterations - ) - } - } - const baselineMs = median(baselineSamples) - const optimizedMs = median(optimizedSamples) - const speedup = baselineMs / Math.max(optimizedMs, Number.EPSILON) - console.log( - `${name}\t${baselineCalibration.iterations}\t${optimizedCalibration.iterations}\t${baselineCalibration.elapsedMs.toFixed(1)}\t${optimizedCalibration.elapsedMs.toFixed(1)}\t${baselineMs.toFixed(6)}\t${optimizedMs.toFixed(6)}\t${speedup.toFixed(1)}x` - ) -} - -function benchmarkSessionArms( - name: string, - baselineSession: () => NativeChatSession, - optimizedSession: () => NativeChatSession -): void { - const expectedSession = baselineSession() - deepStrictEqual(optimizedSession(), expectedSession, `${name}: session mismatch`) - const expected = sessionExpectedChecksum(expectedSession) - benchmark( - name, - (index) => consumeSession(baselineSession(), index), - (index) => consumeSession(optimizedSession(), index), - expected - ) -} - -function benchmarkMessageUpdate(name: string, messages: NativeChatMessage[]): void { - benchmarkSessionArms( - name, - () => legacyMessageUpdateSession(messages), - () => directMessageUpdateSession(messages) - ) -} - -const prose300 = proseFixture(300, 2_048, false) -const fixtures = [ - ['300 x 2KB prose, no turnId', prose300], - ['300 x 2KB prose, with turnId', proseFixture(300, 2_048, true)], - ['300 tool-heavy, no turnId', toolFixture(300)], - ['100 x 2KB prose, no turnId', proseFixture(100, 2_048, false)], - ['500 x 2KB prose, no turnId', proseFixture(500, 2_048, false)] -] as const - -console.log( - `Node ${process.version}; ${ROUNDS} alternating interleaved median rounds; ${TARGET_SAMPLE_MS} ms calibration target; ${MAX_ITERATIONS} iteration cap` -) -console.log( - 'case\tbaseline iters\toptimized iters\tbaseline cal ms\toptimized cal ms\tbaseline ms/op\toptimized ms/op\tspeedup' -) - -for (const [name, messages] of fixtures) { - benchmarkMessageUpdate(name, messages) -} - -benchmarkSessionArms( - '300 x 2KB status-only frame', - () => legacySession(prose300), - () => - mergeNativeChatLiveSession({ - messages: prose300, - sessionId: 'benchmark', - agent: 'claude', - hookState: null - }) -) - -strictEqual(checksum, expectedChecksum, 'benchmark checksum accounting drifted') -strictEqual(sessionSink.value?.sessionId, 'benchmark', 'session outputs did not escape') -strictEqual(Array.isArray(messageArraySink), true, 'message arrays did not escape') -strictEqual(contentSink.length > 0, true, 'message content did not escape') -console.log( - `validated=${validatedCases} cases, checksum=${checksum}, capped calibrations=${cappedCalibrations}, runtime=${( - performance.now() - benchmarkStartedAt - ).toFixed(0)} ms` -) diff --git a/config/scripts/performance/session-search/session-search-pass-benchmark.ts b/config/scripts/performance/session-search/session-search-pass-benchmark.ts deleted file mode 100644 index 143ab0b6eda..00000000000 --- a/config/scripts/performance/session-search/session-search-pass-benchmark.ts +++ /dev/null @@ -1,87 +0,0 @@ -import assert from 'node:assert/strict' -import { mkdir, mkdtemp, rename, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { basename, join } from 'node:path' -import { isolatedScanRoots } from '../../../../src/main/ai-vault/session-scanner-test-fixtures' -import { resetSessionParseCacheForTests } from '../../../../src/main/ai-vault/parse-cache/session-parse-cache-store' -import { resetTranscriptConsumersForTests } from '../../../../src/main/ai-vault/transcripts/session-transcript-consumers' -import { SessionSearchIndexer } from '../../../../src/main/ai-vault-search/session-search-indexer' -import { writeSyntheticTranscriptCorpus } from '../../../../src/main/ai-vault-search/session-search-synthetic-corpus' - -// Bundle with esbuild --bundle --platform=node and run on target host over synthetic corpus only; never use real transcripts. -// Price warm stat-only cycle/sweep used to choose reconcile interval, without setting it or reading already-current content. - -const SESSIONS = 5_000 -const TURNS_PER_SESSION = 4 -const PROJECTS = 40 - -const corpus = await writeSyntheticTranscriptCorpus({ - sessions: SESSIONS, - turnsPerSession: TURNS_PER_SESSION -}) -const root = await mkdtemp(join(tmpdir(), 'orca-search-pass-')) -const roots = isolatedScanRoots(root) -const databasePath = join(root, 'index', 'session-search.sqlite') - -try { - // Spread synthetic corpus over project dirs to model discovery’s readdir cost instead of one flat listing. - for (let index = 0; index < PROJECTS; index++) { - await mkdir(join(roots.claudeProjectsDir, `project-${index}`), { recursive: true }) - } - await Promise.all( - corpus.files.map((path, index) => - rename(path, join(roots.claudeProjectsDir, `project-${index % PROJECTS}`, basename(path))) - ) - ) - - resetSessionParseCacheForTests() - resetTranscriptConsumersForTests() - const errors: unknown[] = [] - const indexer = new SessionSearchIndexer({ - databasePath, - roots, - historyDays: null, - // Finish cold indexing before warm measurement; deadline would contaminate timings with backlog. - passDeadlineMs: Number.MAX_SAFE_INTEGER, - onError: (error) => errors.push(error) - }) - try { - const coldStarted = performance.now() - await indexer.start() - const coldMs = performance.now() - coldStarted - assert.deepEqual(errors, []) - assert.equal(indexer.status().filesIndexed, SESSIONS, 'indexed file count') - - const sweepStarted = performance.now() - await indexer.reconcile({ full: true }) - const sweepMs = performance.now() - sweepStarted - - const cycleStarted = performance.now() - await indexer.reconcile({ full: false }) - const cycleMs = performance.now() - cycleStarted - - assert.deepEqual(errors, []) - assert.equal(indexer.status().filesDue, 0, 'nothing owed after a warm sweep') - console.log( - JSON.stringify( - { - transcripts: SESSIONS, - projectDirectories: PROJECTS, - transcriptMb: Math.round((corpus.transcriptBytes / (1024 * 1024)) * 100) / 100, - coldBuildMs: Math.round(coldMs), - warmSweepMs: Math.round(sweepMs), - warmCycleMs: Math.round(cycleMs) - }, - null, - 2 - ) - ) - } finally { - indexer.close() - resetTranscriptConsumersForTests() - resetSessionParseCacheForTests() - } -} finally { - await rm(corpus.root, { recursive: true, force: true }) - await rm(root, { recursive: true, force: true }) -} diff --git a/config/scripts/performance/session-search/session-search-retention-benchmark.ts b/config/scripts/performance/session-search/session-search-retention-benchmark.ts deleted file mode 100644 index 7ad77f618ae..00000000000 --- a/config/scripts/performance/session-search/session-search-retention-benchmark.ts +++ /dev/null @@ -1,143 +0,0 @@ -import assert from 'node:assert/strict' -import { mkdtemp, rm, stat } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { setImmediate as yieldToEventLoop } from 'node:timers/promises' -import { - syntheticCandidate, - syntheticSession, - userMessages -} from '../../../../src/main/ai-vault-search/session-search-index-test-fixture' -import { SessionSearchStore } from '../../../../src/main/ai-vault-search/session-search-store' -import SyncDatabase from '../../../../src/main/sqlite/sync-database' - -// Bundle with esbuild --bundle --platform=node and run on target host. All arms seed through store; only whole-file baseline bypasses shipped purge. - -const ROWS = 60_000 - -/** The purge yields with `setImmediate` between chunks, so a peer chain samples each gap. */ -async function sampleLoopStalls(running: () => boolean, intervals: number[]): Promise { - let previous = performance.now() - while (running()) { - await yieldToEventLoop() - const now = performance.now() - intervals.push(now - previous) - previous = now - } -} - -/** What a search would still return: rows whose session row is still there. */ -function visibleRows(db: SyncDatabase): number { - return ( - db - .prepare(`SELECT count(*) AS n FROM messages m JOIN sessions s ON s.id = m.session_row_id`) - .get() as { n: number } - ).n -} - -const root = await mkdtemp(join(tmpdir(), 'orca-search-retention-bench-')) -try { - for (const mode of ['whole-file', 'batched', 'batched-pinned-reader']) { - const path = join(root, `${mode}.sqlite`) - const errors: unknown[] = [] - const store = new SessionSearchStore(path, (error) => errors.push(error)) - let reader: SyncDatabase | null = null - try { - const write = store.beginWrite(syntheticCandidate(), 'replace', 0)! - for (const message of userMessages( - 'synthetic benchmark needle repeated context for a representative coding conversation with commands and paths src/example.ts', - ROWS - )) { - write.add(message) - } - assert.equal( - write.commit({ - session: syntheticSession(), - byteOffset: 4096, - incomplete: false - }), - true - ) - assert.deepEqual(errors, []) - // Truncating first is what makes walBytes below the purge's own growth. - const checkpoint = new SyncDatabase(path) - checkpoint.pragma('wal_checkpoint(TRUNCATE)') - checkpoint.close() - if (mode === 'batched-pinned-reader') { - reader = new SyncDatabase(path, { readonly: true }) - reader.exec('BEGIN') - reader.prepare('SELECT count(*) FROM messages').get() - } - const probe = new SyncDatabase(path, { readonly: true }) - const intervals: number[] = [] - const started = performance.now() - if (mode === 'whole-file') { - const raw = new SyncDatabase(path) - try { - raw.exec('BEGIN IMMEDIATE') - const ids = raw.prepare('SELECT id FROM messages').all() as { - id: number - }[] - for (const { id } of ids) { - raw.prepare('DELETE FROM messages_fts WHERE rowid=?').run(id) - } - raw.exec('DELETE FROM messages; DELETE FROM sessions; DELETE FROM files; COMMIT') - } finally { - raw.close() - } - intervals.push(performance.now() - started) - } else { - let purging = true - const purge = store.purgeOlderThan(Date.now() + 60_000) - // First transaction cuts session from file, hiding search results immediately before chunked deletion finishes. - const hiddenEarly = yieldToEventLoop().then(() => visibleRows(probe)) - const sampler = sampleLoopStalls(() => purging, intervals) - await purge - purging = false - await sampler - assert.equal(await hiddenEarly, 0) - assert.deepEqual(errors, []) - } - const wallMs = performance.now() - started - probe.close() - reader?.exec('COMMIT') - reader?.close() - reader = null - const after = new SyncDatabase(path, { readonly: true }) - try { - for (const table of ['messages_fts']) { - assert.equal( - ( - after.prepare(`SELECT count(*) AS n FROM ${table}`).get() as { - n: number - } - ).n, - 0 - ) - } - } finally { - after.close() - } - const walBytes = (await stat(`${path}-wal`)).size - intervals.sort((a, b) => a - b) - console.log( - JSON.stringify({ - mode, - platform: process.platform, - node: process.version, - rows: ROWS, - wallMs: Math.round(wallMs), - samples: intervals.length, - maxStepMs: Math.round(intervals.at(-1) ?? 0), - p95StepMs: Math.round(intervals[Math.floor(intervals.length * 0.95)] ?? 0), - walBytes - }) - ) - } finally { - reader?.close() - store.close() - } - } -} finally { - await rm(root, { recursive: true, force: true }) -} diff --git a/config/scripts/performance/session-transcripts/markdown-note-line-scan-benchmark.mjs b/config/scripts/performance/session-transcripts/markdown-note-line-scan-benchmark.mjs index 1cbb8c3b037..811fa997a3b 100644 --- a/config/scripts/performance/session-transcripts/markdown-note-line-scan-benchmark.mjs +++ b/config/scripts/performance/session-transcripts/markdown-note-line-scan-benchmark.mjs @@ -6,11 +6,12 @@ import { performance } from 'node:perf_hooks' import { build } from 'esbuild' import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs' -const sourcePath = 'src/renderer/src/lib/markdown-review-notes.ts' +const sourcePath = 'src/renderer/src/lib/editor/markdown/review-notes/markdown-review-notes.ts' +const baselineSourcePath = 'src/renderer/src/lib/markdown-review-notes.ts' const baseline = process.argv[2] ?? '20ab9950654' -async function load(contents) { +async function load(contents, inputPath) { const result = await build({ - stdin: { contents, loader: 'ts', resolveDir: dirname(resolve(sourcePath)) }, + stdin: { contents, loader: 'ts', resolveDir: dirname(resolve(inputPath)) }, bundle: true, platform: 'node', format: 'esm', @@ -21,9 +22,10 @@ async function load(contents) { ) } const before = await load( - execFileSync('git', ['show', `${baseline}:${sourcePath}`], { encoding: 'utf8' }) + execFileSync('git', ['show', `${baseline}:${baselineSourcePath}`], { encoding: 'utf8' }), + baselineSourcePath ) -const after = await load(readFileSync(sourcePath, 'utf8')) +const after = await load(readFileSync(sourcePath, 'utf8'), sourcePath) const results = [] for (const [name, lineCount, width, count, iterations] of [ ['small', 20, 40, 1, 1000], diff --git a/config/scripts/performance/terminal-stream/codex-capacity-status-benchmark.ts b/config/scripts/performance/terminal-stream/codex-capacity-status-benchmark.ts deleted file mode 100644 index 006dcc785a1..00000000000 --- a/config/scripts/performance/terminal-stream/codex-capacity-status-benchmark.ts +++ /dev/null @@ -1,137 +0,0 @@ -// Run: ORCA_BACKGROUND_LAUNCH=1 node --import tsx config/scripts/codex-capacity-status-benchmark.ts -import { readFileSync } from 'node:fs' -import { performance } from 'node:perf_hooks' -import { createCodexCapacityNoticeTracker } from '../../../../src/shared/codex-native-notice' -import { HeadlessEmulator } from '../../../../src/main/daemon/emulation/headless-emulator' -import { observeCodexCapacityTerminalStatus } from '../../../../src/main/runtime/terminal/output/codex-notice-terminal-status' - -const fixture = readFileSync( - new URL( - '../../../../src/main/runtime/__fixtures__/codex-model-capacity-fullscreen.txt', - import.meta.url - ), - 'utf8' -) -const notice = fixture.indexOf('■ Selected model') -if (notice === -1) { - throw new Error('Capacity notice missing from benchmark fixture') -} -const redraw = fixture.slice(0, fixture.lastIndexOf('\x1b[?2026h', notice)) -const scenarios = [ - { name: 'plain-4K', data: 'x'.repeat(4096), iterations: 30_000 }, - { name: 'captured-TUI', data: redraw, iterations: 30_000 }, - { - name: 'warning-footer', - data: '\x1b[?2026h\x1b[21;1H⚠ 1 warning · f2 to view\x1b[?2026l', - iterations: 30_000 - }, - { name: 'tiny-typing', data: 'a', iterations: 30_000 }, - { name: 'marker-flood', data: '■'.repeat(4096), iterations: 1000 }, - { - name: 'large-after-warning', - data: `⚠ unrelated\n${'x'.repeat(1024 * 1024)}`, - iterations: 128 - } -] - -function measure(iterations: number, observe: () => void): number { - const start = performance.now() - for (let index = 0; index < iterations; index++) { - observe() - } - return performance.now() - start -} - -for (const scenario of scenarios) { - const run = () => { - const tracker = createCodexCapacityNoticeTracker() - let screenReads = 0 - const readScreen = () => { - screenReads++ - return [] - } - const elapsedMs = measure(scenario.iterations, () => tracker.observe(scenario.data, readScreen)) - if (screenReads !== 0) { - throw new Error(`${scenario.name} read the screen ${screenReads} times`) - } - return elapsedMs - } - run() - const samples = Array.from({ length: 5 }, run).sort((left, right) => left - right) - const elapsedMs = samples[2] - textResult(scenario.name, elapsedMs, scenario.iterations, scenario.data.length) -} - -for (const launchAgent of [undefined, 'codex'] as const) { - const emulator = new HeadlessEmulator({ cols: 80, rows: 24 }) - const data = 'x'.repeat(4096) - const iterations = 30_000 - let statusReads = 0 - const readStatus = () => { - statusReads++ - return undefined - } - try { - const observe = () => - observeCodexCapacityTerminalStatus( - emulator, - data, - 'node /some/wrapper.cjs', - launchAgent, - readStatus, - 1 - ) - measure(iterations, observe) - const samples = Array.from({ length: 5 }, () => measure(iterations, observe)).sort( - (left, right) => left - right - ) - if (statusReads !== 0) { - throw new Error(`Ordinary output read status ${statusReads} times`) - } - textResult(launchAgent ?? 'unrelated-terminal', samples[2], iterations, data.length) - } finally { - emulator.dispose() - } -} - -async function measureScreenRead(): Promise { - const emulator = new HeadlessEmulator({ cols: 40, rows: 24 }) - try { - await emulator.write(fixture) - for (const name of ['screen-only', 'capacity-parse-and-screen']) { - const observe = () => { - if (name === 'screen-only') { - emulator.getVisibleLines() - } else if ( - !createCodexCapacityNoticeTracker().observe(fixture, () => emulator.getVisibleLines()) - ) { - throw new Error('Captured capacity notice was not detected') - } - } - measure(1000, observe) - const samples = Array.from({ length: 5 }, () => measure(1000, observe)).sort( - (left, right) => left - right - ) - textResult(name, samples[2], 1000, fixture.length) - } - } finally { - emulator.dispose() - } -} - -void measureScreenRead().catch((error: unknown) => { - console.error(error) - process.exitCode = 1 -}) - -function textResult(name: string, elapsedMs: number, iterations: number, chars: number): void { - console.log( - JSON.stringify({ - name, - chars, - iterations, - microsecondsPerChunk: Number(((elapsedMs * 1000) / iterations).toFixed(3)), - millisecondsPerMiB: Number((elapsedMs / ((chars * iterations) / 1048576)).toFixed(3)) - }) - ) -} diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index 99d3c46bff0..f8f576a27a5 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -47,6 +47,7 @@ const RATCHET_INPUTS = { 'check-render-path-translate-ratchet.mjs': ['src/renderer/src/'], 'check-repo-host-read-ratchet.mjs': ['src/cli/', 'src/main/', 'src/shared/'], 'check-runtime-electron-ratchet.mjs': ['src/main/', 'src/cli/', 'src/shared/'], + 'check-tab-map-seam-ratchet.mjs': ['src/renderer/src/'], 'check-unproven-pty-retirement-ratchet.mjs': ['src/main/'], 'check-workspace-record-read-ratchet.mjs': ['src/renderer/src/'], 'check-worktree-id-composer-ratchet.mjs': ['src/', 'mobile/src/'] diff --git a/config/scripts/preflight/changed-checks/run-lint.mjs b/config/scripts/preflight/changed-checks/run-lint.mjs index 0a2bbe3c723..e882fcb03d2 100644 --- a/config/scripts/preflight/changed-checks/run-lint.mjs +++ b/config/scripts/preflight/changed-checks/run-lint.mjs @@ -39,6 +39,7 @@ export const LINT_STEPS = [ 'check:mobile-shared-dependency-versions', 'check:ts-nocheck-ratchet', 'check:workspace-record-read-ratchet', + 'check:tab-map-seam-ratchet', 'check:unproven-pty-retirement-ratchet', 'check:daemon-blocking-call-ratchet', 'check:main-sync-fs-ratchet', diff --git a/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs b/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs index f0c1e76f622..4c8e6a3ecbb 100644 --- a/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs +++ b/config/scripts/runtime-verification/desktop-transport/verify-computer-native.mjs @@ -13,20 +13,6 @@ const checks = [ args: ['test', '--package-path', 'native/computer-use-macos'], enabled: process.platform === 'darwin' }, - { - name: 'Linux provider Python syntax', - command: 'python3', - args: [ - '-c', - [ - 'import ast, pathlib', - 'source=pathlib.Path("native/computer-use-linux/runtime.py").read_text(encoding="utf-8")', - 'ast.parse(source)', - 'print("syntax-ok")' - ].join(';') - ], - enabled: true - }, { name: 'Linux snapshot renderer tests', command: 'python3', diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs index 29b0247827e..009f48c981c 100644 --- a/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs @@ -320,6 +320,24 @@ function isSameNameCopy(property, name) { return ts.isPropertyAccessExpression(value) && value.name.text === name } +// The transition seam names the fields it tracks in `const SEAM_*_FIELDS = [...] as const` lists; names, not writes. +function isSeamFieldNameConstant(literal) { + let list = literal.parent + if (!ts.isArrayLiteralExpression(list)) { + return false + } + let declaration = list.parent + while (ts.isAsExpression(declaration) || ts.isSatisfiesExpression(declaration)) { + declaration = declaration.parent + } + return ( + ts.isVariableDeclaration(declaration) && + ts.isIdentifier(declaration.name) && + /^SEAM_[A-Z_]+_FIELDS$/.test(declaration.name.text) && + (declaration.parent.flags & ts.NodeFlags.Const) !== 0 + ) +} + /** Layout writes in one file under one ratchet's rules. */ export function countLayoutWrites(sourceText, ratchet, fileName = 'file.tsx') { const names = [...ratchet.writerNames, ...ratchet.assignedFields] @@ -392,7 +410,8 @@ export function countLayoutWrites(sourceText, ratchet, fileName = 'file.tsx') { node.parent.expression.expression.text === 'Object' && node.parent.expression.name.text === 'hasOwn' ) && - !ts.isLiteralTypeNode(node.parent) + !ts.isLiteralTypeNode(node.parent) && + !isSeamFieldNameConstant(node) ) { count += 1 } diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs new file mode 100644 index 00000000000..c6743a1ae76 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.mjs @@ -0,0 +1,380 @@ +import fs from 'node:fs' +import path from 'node:path' +import process from 'node:process' +import { pathToFileURL } from 'node:url' +import ts from 'typescript-api' + +// The tab-map transition seam (store/keyed-record-transitions.ts) only works if its writers annotate and its +// consumers enumerate whole maps only on named cold paths; this pins both for the repaired modules, nothing wider. + +const R = 'src/renderer/src/' +const STATUS = `${R}components/native-chat/session/status/` + +/** + * Repaired consumers: the only functions allowed to walk a whole map (`coldPaths`), which callers + * may reach a cold helper (`helpers`), and the only values they may import, so a new walking helper + * can't arrive through an import unreviewed. + */ +export const CONSUMERS = new Map([ + [ + `${STATUS}structured-agent-session-tabs.ts`, + { + coldPaths: new Set(['rebuildFromSnapshot']), + helpers: { rebuildFromSnapshot: ['advance'] }, + imports: new Set(['structuredAgentSessionPaneKey', 'isStructuredTab', 'readTabMapChanges']) + } + ], + [ + `${STATUS}StructuredAgentSessionStatusBridge.tsx`, + { + coldPaths: new Set(['reconcileFromSnapshot']), + helpers: { + getStructuredAgentSessionTabs: ['reconcileFromSnapshot'], + reconcileFromSnapshot: ['reconcile'] + }, + imports: new Set([ + 'useEffect', + 'projectStatus', + 'getStructuredAgentSessionLaunchLifecycle', + 'subscribeStructuredAgentLaunchStatus', + 'getStructuredAgentSessionLaunchFailedAt', + 'useAppStore', + 'structuredAgentSessionTargetForHost', + 'getStructuredAgentSessionStatusFeed', + 'structuredAgentSessionStatusFeedKey', + 'getStructuredAgentSessionTabs', + 'getStructuredAgentSessionTabsInWorkspace', + 'readTabMapChanges', + 'createTabOwnerCache', + 'ownerInputChanged', + 'ownerInputs', + 'createStructuredSessionMembership', + 'sameSemanticTab' + ]) + } + ], + [ + `${STATUS}structured-agent-session-status-membership.ts`, + { + coldPaths: new Set(), + helpers: { getStructuredAgentSessionTabs: [] }, + imports: new Set(['structuredAgentSessionPaneKey']) + } + ] +]) +const ENUMERATING_CALLS = new Set(['keys', 'values', 'entries']) + +/** Shared tab-map writers wired to the seam: a raw record literal for these fields bypasses provenance. */ +export const WRITERS = [ + 'src/renderer/src/runtime/web-session-tabs-sync/scoped-patch-annotation.ts', + 'src/renderer/src/runtime/web-session-tabs-sync/store-patch.ts', + 'src/renderer/src/runtime/workspace-layout/frames/workspace-layout-frame-sync.ts', + 'src/renderer/src/store/slices/browser/pages/browser-page-state-actions.ts', + 'src/renderer/src/store/slices/editor/file-ids/hydrated-editor-file-ids.ts', + 'src/renderer/src/store/slices/editor/hydration/restored-editor-owner-in-place.ts', + 'src/renderer/src/store/slices/editor/hydration/restored-editor-owner-transition.ts', + 'src/renderer/src/store/slices/editor/markdown/markdown-preview-actions.ts', + 'src/renderer/src/store/slices/editor/opening/open-file-mutations.ts', + 'src/renderer/src/store/slices/ssh/ssh-target-cleanup.ts', + 'src/renderer/src/store/slices/tabs/rename-worktree-layout.ts', + 'src/renderer/src/store/slices/tabs/tab-group-state.ts', + 'src/renderer/src/store/slices/tabs/tabs-close-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-create-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-drag-preview-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-drop-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-focus-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-group-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-host-mirroring.ts', + 'src/renderer/src/store/slices/tabs/tabs-label-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-move-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-reconciliation.ts', + 'src/renderer/src/store/slices/tabs/tabs-session-actions.ts', + 'src/renderer/src/store/slices/tabs/tabs-split-ratio-actions.ts', + 'src/renderer/src/store/slices/tabs/worktree-layout-lifecycle.ts', + 'src/renderer/src/store/slices/tabs/worktree-terminal-tab-respawn.ts', + 'src/renderer/src/store/slices/worktrees/session/set-active-worktree.ts', + 'src/renderer/src/store/slices/worktrees/session/worktree-identity-rename-state.ts', + 'src/renderer/src/store/slices/worktrees/session/worktree-slice-lookups.ts', + 'src/renderer/src/store/slices/worktrees/teardown/record-key-omission.ts', + 'src/renderer/src/store/terminals/terminal-tab-close.ts', + 'src/renderer/src/store/terminals/terminal-tab-creation.ts', + 'src/renderer/src/store/terminals/terminal-tab-navigation.ts', + 'src/renderer/src/store/terminals/terminal-tab-title-batch.ts', + 'src/renderer/src/store/terminals/workspace-terminal-hydration-patch.ts', + 'src/renderer/src/store/terminals/workspace-terminal-hydration.ts', + 'src/renderer/src/store/terminals/workspace-terminal-reconnect.ts', + 'src/renderer/src/store/workspace-layout/frames/workspace-layout-frame-store-patch.ts' +] +export const SEAM_FIELDS = new Set([ + 'tabsByWorktree', + 'unifiedTabsByWorktree', + 'terminalLayoutsByTabId', + 'ptyIdsByTabId', + 'lastKnownRelayPtyIdByTabId', + 'runtimePaneTitlesByTabId', + 'pendingStartupByTabId', + 'pendingReconnectPtyIdByTabId', + 'sleepingAgentSessionsByPaneKey', + 'layoutByWorktree', + 'groupsByWorktree', + 'activeGroupIdByWorktree' +]) + +function parse(file, text) { + return ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX) +} + +function line(source, node) { + return source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1 +} + +function enclosingFunctionNames(node) { + const names = [] + for (let current = node.parent; current; current = current.parent) { + if (ts.isFunctionDeclaration(current) && current.name) { + names.push(current.name.text) + } else if ( + (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) && + ts.isVariableDeclaration(current.parent) && + ts.isIdentifier(current.parent.name) + ) { + names.push(current.parent.name.text) + } + } + return names +} + +function valueImports(source) { + const imported = [] + for (const statement of source.statements) { + const clause = ts.isImportDeclaration(statement) ? statement.importClause : null + if (!clause || clause.isTypeOnly) { + continue + } + if (clause.name) { + imported.push(clause.name) + } + const bindings = clause.namedBindings + if (bindings && ts.isNamespaceImport(bindings)) { + imported.push(bindings.name) + } else if (bindings) { + imported.push( + ...bindings.elements.filter((element) => !element.isTypeOnly).map((e) => e.name) + ) + } + } + return imported +} + +function isHelperReference(node, helpers) { + if (!ts.isIdentifier(node) || !Object.hasOwn(helpers, node.text)) { + return false + } + const parent = node.parent + const declares = + ((ts.isVariableDeclaration(parent) || ts.isFunctionDeclaration(parent)) && + parent.name === node) || + (ts.isPropertyAccessExpression(parent) && parent.name === node) || + (ts.isPropertyAssignment(parent) && parent.name === node) || + ts.isImportSpecifier(parent) + return !declares +} + +export function consumerViolations(file, text, { coldPaths, helpers, imports }) { + const source = parse(file, text) + const violations = [] + for (const name of valueImports(source)) { + if (!imports.has(name.text)) { + violations.push( + `${file}:${line(source, name)} imports ${name.text}; repaired consumers import only reviewed helpers` + ) + } + } + const visit = (node) => { + let what = null + let allowed = coldPaths + if ( + ts.isPropertyAccessExpression(node) && + ts.isIdentifier(node.expression) && + node.expression.text === 'Object' && + ENUMERATING_CALLS.has(node.name.text) + ) { + // Any reference, called or aliased (`const keys = Object.keys`). + what = `Object.${node.name.text}` + } else if (isHelperReference(node, helpers)) { + // Calls, aliases (`const resync = reconcileFromSnapshot`) and callbacks alike. + what = `${node.text}()` + allowed = new Set(helpers[node.text]) + } else if (ts.isForInStatement(node)) { + what = 'for…in' + } + if (what && !enclosingFunctionNames(node).some((name) => allowed.has(name))) { + violations.push(`${file}:${line(source, node)} ${what} outside a named cold path`) + } + if ( + ts.isFunctionDeclaration(node) && + node.name?.text === 'rebuildFromSnapshot' && + node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) { + violations.push(`${file}:${line(source, node)} rebuildFromSnapshot must stay module-private`) + } + ts.forEachChild(node, visit) + } + visit(source) + return violations +} + +function isRawRecord(expression) { + if (ts.isObjectLiteralExpression(expression)) { + return expression.properties.some((property) => ts.isSpreadAssignment(property)) + } + return ( + ts.isCallExpression(expression) && + ts.isPropertyAccessExpression(expression.expression) && + ts.isIdentifier(expression.expression.expression) && + expression.expression.expression.text === 'Object' && + ['fromEntries', 'assign'].includes(expression.expression.name.text) + ) +} + +// Only an explicit cold-path mark certifies a record built outside a construction helper or draft. +const ANNOTATED_ARGUMENT = { + markFullResync: 0 +} + +function enclosingScope(node) { + let current = node.parent + while (current && !ts.isFunctionLike(current) && !ts.isSourceFile(current)) { + current = current.parent + } + return current +} + +/** The value a local name holds at `use`: its declaration's initializer, followed through aliases. */ +function bindingSource(name, scope, use, seen = new Set()) { + if (seen.has(name)) { + return null + } + seen.add(name) + let found = null + const visit = (node) => { + if (node.pos >= use.pos) { + return + } + if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === name) { + found = node.initializer ?? null + } else if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind === ts.SyntaxKind.EqualsToken && + ts.isIdentifier(node.left) && + node.left.text === name + ) { + found = node.right + } + ts.forEachChild(node, visit) + } + visit(scope) + if (found && ts.isIdentifier(found)) { + const aliased = bindingSource(found.text, scope, use, seen) + return aliased && { ...aliased, names: [name, ...aliased.names] } + } + return found && { value: found, names: [name] } +} + +/** Whether a seam helper annotates one of `names` in place before `use` publishes it. */ +function annotatedBefore(names, scope, use) { + let annotated = false + const visit = (node) => { + if (node.pos >= use.pos) { + return + } + if ( + node.end <= use.pos && + ts.isCallExpression(node) && + ts.isIdentifier(node.expression) && + Object.hasOwn(ANNOTATED_ARGUMENT, node.expression.text) + ) { + const argument = node.arguments[ANNOTATED_ARGUMENT[node.expression.text]] + annotated ||= + argument !== undefined && ts.isIdentifier(argument) && names.includes(argument.text) + } + ts.forEachChild(node, visit) + } + visit(scope) + return annotated +} + +function rawValue(node) { + const initializer = ts.isShorthandPropertyAssignment(node) ? node.name : node.initializer + if (isRawRecord(initializer)) { + return true + } + if (!ts.isIdentifier(initializer)) { + return false + } + // Follow the local binding and its aliases; the record must be annotated before it is published. + for (let scope = enclosingScope(node); scope; scope = scope.parent && enclosingScope(scope)) { + const binding = bindingSource(initializer.text, scope, node) + if (binding) { + return isRawRecord(binding.value) && !annotatedBefore(binding.names, scope, node) + } + if (ts.isSourceFile(scope)) { + break + } + } + return false +} + +export function writerViolations(file, text) { + const source = parse(file, text) + const violations = [] + const visit = (node) => { + if ( + (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) && + (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) && + SEAM_FIELDS.has(node.name.text) && + rawValue(node) + ) { + violations.push( + `${file}:${line(source, node)} raw ${node.name.text} record; build it with a replace helper or draft, or mark it full resync` + ) + } + ts.forEachChild(node, visit) + } + visit(source) + return violations +} + +export function collect(root = process.cwd()) { + const violations = [] + for (const [file, rules] of CONSUMERS) { + violations.push( + ...consumerViolations(file, fs.readFileSync(path.join(root, file), 'utf8'), rules) + ) + } + for (const file of WRITERS) { + violations.push(...writerViolations(file, fs.readFileSync(path.join(root, file), 'utf8'))) + } + return violations +} + +export function main(root = process.cwd()) { + const violations = collect(root) + if (violations.length) { + for (const violation of violations) { + console.error(violation) + } + console.error( + 'Tab-map seam: ordinary handlers use addressed deltas (readTabMapChanges); whole-map walks belong only in the named cold paths.' + ) + return 1 + } + console.log( + `tab-map-seam ratchet OK — ${CONSUMERS.size} consumer and ${WRITERS.length} writer modules pinned.` + ) + return 0 +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit(main(process.cwd())) +} diff --git a/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs new file mode 100644 index 00000000000..7f4a6dfb6b1 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/renderer-state/check-tab-map-seam-ratchet.test.mjs @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { CONSUMERS, consumerViolations, writerViolations } from './check-tab-map-seam-ratchet.mjs' + +const BRIDGE = + 'src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx' +const rules = CONSUMERS.get(BRIDGE) + +describe('tab-map seam guard', () => { + it('rejects an ordinary handler reaching the cold path or walking a map', () => { + const text = [ + 'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)', + 'const reconcile = () => reconcileFromSnapshot()', + 'const ordinary = () => { reconcileFromSnapshot(); Object.keys(source) }' + ].join('\n') + expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ + 'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path', + 'bridge.tsx:3 Object.keys outside a named cold path' + ]) + }) + + it('rejects an unreviewed value import, not type imports', () => { + const text = [ + "import { wholeMap } from './new-walk'", + "import type { Walk } from './new-walk'" + ].join('\n') + expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ + 'bridge.tsx:1 imports wholeMap; repaired consumers import only reviewed helpers' + ]) + }) + + it('follows a raw record through a local binding unless it is marked full resync', () => { + const text = [ + 'function raw(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' set({ unifiedTabsByWorktree: next })', + '}', + 'function annotated(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' markFullResync(next, "hydration")', + ' set({ unifiedTabsByWorktree: next })', + '}' + ].join('\n') + expect(writerViolations('writer.ts', text)).toEqual([ + 'writer.ts:3 raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync' + ]) + }) + + it('follows aliases of cold helpers and enumerators', () => { + const text = [ + 'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)', + 'const reconcile = () => reconcileFromSnapshot()', + 'const resync = reconcileFromSnapshot', + 'const keys = Object.keys' + ].join('\n') + expect(consumerViolations('bridge.tsx', text, rules)).toEqual([ + 'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path', + 'bridge.tsx:4 Object.keys outside a named cold path' + ]) + }) + + it('follows aliased raw records and requires annotation before publication', () => { + const raw = + 'raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync' + const text = [ + 'function aliased(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' const unifiedTabsByWorktree = next', + ' set({ unifiedTabsByWorktree })', + '}', + 'function late(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' set({ unifiedTabsByWorktree: next })', + ' markFullResync(next, "hydration")', + '}', + 'function early(state) {', + ' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }', + ' const alias = next', + ' markFullResync(alias, "hydration")', + ' set({ unifiedTabsByWorktree: alias })', + '}' + ].join('\n') + expect(writerViolations('writer.ts', text)).toEqual([ + `writer.ts:4 ${raw}`, + `writer.ts:8 ${raw}` + ]) + }) +}) diff --git a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs index d8942881e55..7f9ba3b8138 100644 --- a/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs +++ b/config/scripts/test-runtime/sqlite-admission/vitest-node-runtime-files.mjs @@ -118,7 +118,6 @@ const NODE_RUNTIME_INCLUDE = [ 'src/main/browser/cookies/sources/browser-cookie-import-undecryptable.test.ts', 'src/main/browser/cookies/sources/browser-cookie-source-partition.test.ts', // Playwright's CDP transport needs Node's WebSocket implementation. - 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts', 'src/main/browser/guest-lifecycle/navigation/browser-link-materialization.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts', diff --git a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs index 509507aa49f..7da6a6823ae 100644 --- a/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs +++ b/config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs @@ -259,7 +259,7 @@ export const PR_E2E_SOURCE_ROUTES = [ MANAGED_SSH_HARNESS.test(file) || /^tests\/e2e\/helpers\/browser-split-(?:guest-probes|page-server)\.ts$/.test(file) || (isProductSource(file) && - /^src\/renderer\/src\/(?:lib\/(?:file-preview|workspace-file-drag|worktree-runtime-owner|connection-context)\.ts|components\/(?:right-sidebar\/file-explorer\/panel\/FileExplorer(?:Row|VirtualRows)\.tsx|browser-pane\/(?:navigate\/use-browser-page-navigation-downloads\.ts|host-guest\/attach-browser-page-webview\.ts)))$/.test( + /^src\/renderer\/src\/(?:lib\/(?:browser\/documents\/file-preview|workspace-file-drag|worktree-runtime-owner)\.ts|lib\/workspace\/ownership\/connection-context\.ts|components\/(?:right-sidebar\/file-explorer\/panel\/FileExplorer(?:Row|VirtualRows)\.tsx|browser-pane\/(?:navigate\/use-browser-page-navigation-downloads\.ts|host-guest\/attach-browser-page-webview\.ts)))$/.test( file )) }, @@ -280,7 +280,7 @@ export const PR_E2E_SOURCE_ROUTES = [ MANAGED_SSH_HARNESS.test(file) || file === 'tests/e2e/helpers/terminal-workspace-root-link.ts' || (isProductSource(file) && - /^src\/renderer\/src\/(?:components\/terminal-pane\/terminal-(?:worktree-path-link|file-link-actions|file-link-hit-testing|file-open-routing|link-handlers)\.ts|lib\/(?:workspace-file-host-routing|worktree-owner-route|worktree-operation-route|worktree-operation-catalog-route)\.ts)$/.test( + /^src\/renderer\/src\/(?:components\/terminal-pane\/terminal-(?:worktree-path-link|file-link-actions|file-link-hit-testing|file-open-routing|link-handlers)\.ts|(?:runtime\/files\/workspace-file-host-routing|lib\/workspace\/ownership\/(?:worktree-owner-route|worktree-operation-route|worktree-operation-catalog-route))\.ts)$/.test( file )) }, diff --git a/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs b/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs index 20e97e8d2f9..22ff77e7998 100644 --- a/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs +++ b/config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs @@ -25,8 +25,8 @@ export const PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES = [ (file.startsWith('src/renderer/src/components/editor/model-lifetime/identity/') || [ 'src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts', - 'src/renderer/src/lib/editor-file-operation-owner.ts', - 'src/renderer/src/lib/editor-file-operation-provenance.ts' + 'src/renderer/src/lib/editor/file-operations/editor-file-operation-owner.ts', + 'src/renderer/src/lib/editor/file-operations/editor-file-operation-provenance.ts' ].includes(file)) }, { diff --git a/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs b/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs index 0b31fb8b6f5..ac16f8b4df8 100644 --- a/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs +++ b/config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs @@ -29,7 +29,7 @@ const LAYOUT_ORACLE_PREFIXES = [ 'src/renderer/src/attention/orca-window-foreground-focus.ts', 'src/renderer/src/attention/notification-workspace-labels.ts', 'src/renderer/src/lib/agent-session/identity/pane-agent-session-id.ts', - 'src/renderer/src/lib/wsl-host-availability.ts', + 'src/renderer/src/runtime/hosts/wsl/wsl-host-availability.ts', 'src/renderer/src/lib/workspace/ownership/workspace-runtime-environment.ts', 'src/renderer/src/components/tab-group/tab-drag-drop-commit.ts', 'src/renderer/src/app-shell/use-runtime-graph-sync.ts', diff --git a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs index 9cbdc894b22..2bae139d3bb 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -131,7 +131,6 @@ export const LINUX_PACKAGE_TESTS = [ 'src/main/browser/client-pages/renderer/browser-client-page-renderer-lifecycle.electron.test.ts', 'src/main/persistence/profile-state/profile-state-writer-stall.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility.electron.test.ts', - 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-adapter-compatibility.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-native-compatibility.electron.test.ts', 'src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-background-compatibility.electron.test.ts', 'src/main/browser/extensions/api-runtime/browser-extension-api.electron.test.ts', @@ -171,6 +170,7 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts', 'src/shared/agent-launch/startup/omp-fresh-launch-cmd.win32.test.ts', 'src/shared/windows-batch-spawn.win32.test.ts', + 'src/main/claude/structured/launch/claude-structured-child-env.test.ts', 'src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts', 'src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts', 'src/main/jcode/hook-gate-script.test.ts', diff --git a/config/vitest.agent-status-benchmark.config.ts b/config/vitest.agent-status-benchmark.config.ts deleted file mode 100644 index 32b047405bb..00000000000 --- a/config/vitest.agent-status-benchmark.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from 'vitest/config' -import baseConfig from './vitest.config' - -export default defineConfig({ - ...baseConfig, - test: { - ...baseConfig.test, - // Project-level includes otherwise override this benchmark-only selection. - projects: undefined, - include: ['config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts'], - fileParallelism: false, - retry: 0 - } -}) diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index a29424675e5..f05c41e95f5 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -22,8 +22,7 @@ const contracts = [ 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', 'src/main/claude-usage/scanner-incremental-append.test.ts', - 'src/main/claude-usage/store-checkpoint-persistence.test.ts', - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx' + 'src/main/claude-usage/store-checkpoint-persistence.test.ts' ] for (const contract of contracts) { if (!existsSync(resolve(contract))) { diff --git a/config/workspace-record-read-baseline.txt b/config/workspace-record-read-baseline.txt index 46a6fdd2dbd..ca14f9bf2ad 100644 --- a/config/workspace-record-read-baseline.txt +++ b/config/workspace-record-read-baseline.txt @@ -29,24 +29,24 @@ 2 src/renderer/src/hooks/composer-state/composer-target-state.ts # P5b-2 must clear: composer store snapshot 3 src/renderer/src/lib/agent-session/resume/sleeping-record-execution-host-scope.ts # P5b-2 must clear: loosely typed state param 1 src/renderer/src/lib/browser/navigation/http-link-localhost-route.ts # P5b-2 must clear: optional state field defaults to empty; extracted from http-link-routing.ts -1 src/renderer/src/lib/connection-owner-resolution.ts # P5b-2 must clear: optional-chain compare of a previous slice -2 src/renderer/src/lib/direct-ssh-target-scope.ts # P5b-2 must clear: optional input fields default to empty +1 src/renderer/src/lib/workspace/ownership/connection-owner-resolution.ts # P5b-2 must clear: optional-chain compare of a previous slice +2 src/renderer/src/lib/workspace/ownership/direct-ssh-target-scope.ts # P5b-2 must clear: optional input fields default to empty 3 src/renderer/src/lib/duplicate-paired-servers.ts # P5b-2 must clear: optional state fields default to empty -1 src/renderer/src/lib/folder-workspace-runtime-owner.ts # P5b-2 must clear: loosely typed state param -1 src/renderer/src/lib/local-project-runtime-workspace.ts # P5b-2 must clear: optional state field defaults to empty +1 src/renderer/src/lib/workspace/ownership/folder-workspace-runtime-owner.ts # P5b-2 must clear: loosely typed state param +1 src/renderer/src/runtime/hosts/wsl/local-project-runtime-workspace.ts # P5b-2 must clear: optional state field defaults to empty 1 src/renderer/src/lib/resolved-worktree-execution-host.ts # P5b-2 must clear: loosely typed state param -2 src/renderer/src/lib/runtime-session-mirror-owners.ts # P5b-2 must clear: optional state fields default to empty +2 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts # P5b-2 must clear: optional state fields default to empty 2 src/renderer/src/lib/terminal-worktree-route.ts # P5b-2 must clear: the unattributed-twin check reads both catalogs directly 3 src/renderer/src/lib/typing-latency/diagnostic-summary.ts # P5b-2 must clear: optional state field 2 src/renderer/src/lib/unread-badge-count.ts # reads a passed-in copy 1 src/renderer/src/lib/workspace-directory.ts # P5b-2 must clear: optional state field defaults to empty -2 src/renderer/src/lib/workspace-terminal-host-authority.ts # P5b-2 must clear: optional state fields +2 src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.ts # P5b-2 must clear: optional state fields 1 src/renderer/src/lib/workspace/activation/initial-surface/worktree-initial-terminal-seeding.ts # P5b-2 must clear: treats an undefined field as a narrow adapter 1 src/renderer/src/lib/workspace/activation/worktree-activation-pty-inventory.ts # P5b-2 must clear: loosely typed state param 2 src/renderer/src/lib/workspace/ownership/worktree-runtime-owner.ts # P5b-2 must clear: loosely typed state param 3 src/renderer/src/lib/workspace/persistence/workspace-session-host-persistence.ts # P5b-2 must clear: loosely typed state param 1 src/renderer/src/lib/workspace/persistence/workspace-session.ts # P5b-2 must clear: store snapshot read; file at the max-lines limit -6 src/renderer/src/lib/worktree-operation-route.ts # P5b-2 must clear: optional state fields default to empty +6 src/renderer/src/lib/workspace/ownership/worktree-operation-route.ts # P5b-2 must clear: optional state fields default to empty 3 src/renderer/src/runtime/native-chat/local-sessions/local-structured-session-tab-retirement.ts # P5b-2 must clear: optional state fields default to empty 2 src/renderer/src/runtime/sync-runtime-graph/sync-key.ts # reads a passed-in copy 3 src/renderer/src/store/folder-workspaces/folder-workspace-catalog-actions.ts # store writer diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index 844b8971f54..968f6560164 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 160m + + downloads: 162m @@ -15,7 +15,7 @@ downloads downloads - 160m - 160m + 162m + 162m diff --git a/docs/site/content/docs/remote-servers.mdx b/docs/site/content/docs/remote-servers.mdx index 866722a7fc5..0b85c58e10a 100644 --- a/docs/site/content/docs/remote-servers.mdx +++ b/docs/site/content/docs/remote-servers.mdx @@ -189,6 +189,24 @@ Use only one host mode at a time. If the Orca desktop app is already sharing tha `orca serve` runs on Orca's own Node server (orcad) by default. If orcad can't serve on this computer, it uses the desktop app's server instead and prints one line saying why. On a packaged macOS app it uses the desktop app's server, so paired clients can still update it, unless you set `ORCA_SERVE_RUNTIME=orcad` (see [A Mac reached only over SSH](#a-mac-reached-only-over-ssh)). To always use the desktop app's server, set `ORCA_SERVE_RUNTIME=electron`. +### Install only the server on Linux + +Each release also publishes the server alone for Linux x64 and arm64: orcad, the Node runtime it runs on, and the `orca-ide` CLI. It needs no desktop packages (GTK, X11, Xvfb), so it suits your own headless Linux servers, VMs and containers. It is about 60 MB to download, against 190 MB for the `.deb`. Download it, check it, and unpack it: + +```bash +arch=$(uname -m | sed 's/x86_64/x64/; s/aarch64/arm64/') +base=https://github.com/stablyai/orca/releases/latest/download +curl -fsSLO "$base/orca-server-linux-$arch.tar.gz" -O "$base/orca-server-sha256sums.txt" +sha256sum --check --ignore-missing orca-server-sha256sums.txt +sudo mkdir -p /opt/orca-server +sudo tar -xzf "orca-server-linux-$arch.tar.gz" -C /opt/orca-server --strip-components=1 +/opt/orca-server/bin/orca-ide serve --pairing-address +``` + +To pin a release, replace `latest/download` with `download/v`, and keep that release's checksum in your script rather than downloading it next to the archive. The server needs glibc 2.28 or newer (Ubuntu 20.04, Debian 10, RHEL 8 and later). + +`orca-ide serve` takes the same flags as above, including `--supervise` under a service manager and `--recipe-json`. To update, stop the server, replace `/opt/orca-server` with a newer release, and start it again; paired clients cannot update it for you. For `orca-ide serve service install`, pass `--command /opt/orca-server/bin/orca-ide` or put `/opt/orca-server/bin` on `PATH`. A server-only install has no browser panes, dictation or paired web client, because those come with the desktop app. + ### Limit terminal memory on a Linux server By default, nothing caps how much memory a terminal's processes use, so one runaway job can push the whole server into the kernel's out-of-memory killer. On Linux you can cap each terminal by setting these variables in the environment that starts `orca serve` (or in its service unit): diff --git a/docs/styleguide/native-chat.md b/docs/styleguide/native-chat.md index 69600d8d006..4d367ca879e 100644 --- a/docs/styleguide/native-chat.md +++ b/docs/styleguide/native-chat.md @@ -27,4 +27,4 @@ The chat root (`.native-chat-appearance`) redefines these steps as ratios of the - **Focus rings:** full-width transcript rows use the inset ring (`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`) so it isn't clipped by the scroll container; standalone controls use `focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`. Inside the chat `--ring` is `--chat-focus-ring`, which clears 3:1 on the canvas; don't lower its opacity. - **Theme overrides:** plugin themes can set `--chat-bold-foreground`, `--chat-muted-foreground`, `--chat-inline-code`, `--chat-inline-code-foreground`, `--chat-code-block`, `--chat-selection` and `--chat-selection-foreground`. They feed `text-chat-foreground-faint`, `bg-chat-inline-code-surface`, `bg-chat-code-surface` and the chat root's `::selection`, so use those rather than reading the theme tokens directly. - **Selection** inside the chat is the link hue mixed into the canvas (close to the system highlight), with selected text in the full foreground so every role stays 4.5:1. Don't add per-component `selection:` colors in transcript text. -- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row. +- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`; what the reader has not seen yet uses `text-chat-unread`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row. diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 0a2e110aca1..6f3700a4962 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -6,7 +6,10 @@ import type { Plugin, Rollup } from 'vite' import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { createBootstrapFatalExitBanner } from './config/build-plugins/bootstrap-fatal-exit-banner' -import { createSandboxedScriptBundlesPlugin } from './config/build-plugins/sandboxed-script-bundles' +import { + createSandboxedScriptBundlesPlugin, + ONE_BYTE_UNMINIFIED_OUTPUT +} from './config/build-plugins/sandboxed-script-bundles' import { createMainLocaleSubsetPlugin } from './config/build-plugins/main-locale-subset' import { createSucraseUnusedTransformersPlugin } from './config/build-plugins/sucrase-unused-transformers' import { createPdfjsViewerAssetsPlugin } from './config/build-plugins/pdfjs-viewer-assets' @@ -264,10 +267,7 @@ export const electronViteConfig: UserConfig = { preload: { build: { externalizeDeps: false, - rollupOptions: { - // Unminified preload keeps dependency JSDoc whose em dashes would force two-byte storage in every renderer. - output: { charset: 'ascii', comments: { legal: true, annotation: true, jsdoc: false } } - } + rollupOptions: { output: ONE_BYTE_UNMINIFIED_OUTPUT } } }, renderer: { diff --git a/mobile/app/h/[hostId]/edit.tsx b/mobile/app/h/[hostId]/edit.tsx index a8b15a72f52..38dc364e575 100644 --- a/mobile/app/h/[hostId]/edit.tsx +++ b/mobile/app/h/[hostId]/edit.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { useQueryClient } from '@tanstack/react-query' import { Alert, View, @@ -45,6 +46,7 @@ export default function EditHostScreen() { const primeHosts = usePrimeHosts() const refreshHostClient = useRefreshHostClient() const forgetHostClient = useForgetHostClient() + const queryClient = useQueryClient() const [host, setHost] = useState(null) const [loadError, setLoadError] = useState(null) @@ -189,7 +191,7 @@ export default function EditHostScreen() { return } try { - await removeHostAndCloseClient(host.id, forgetHostClient) + await removeHostAndCloseClient(host.id, forgetHostClient, queryClient) } catch { setConfirmRemove(true) Alert.alert( diff --git a/mobile/app/h/_layout.tsx b/mobile/app/h/_layout.tsx index 85791eb3eb3..5b70ff90b8e 100644 --- a/mobile/app/h/_layout.tsx +++ b/mobile/app/h/_layout.tsx @@ -20,6 +20,8 @@ import { HostSidebarRevealContext } from '../../src/layout/host-sidebar-reveal' import { HostAreaServingContext } from '../../src/mobile-web-shell/host-area-serving' import { usePageOwnsHostArea } from '../../src/mobile-web-shell/page-owns-host-area' import { isOverlayPageRoute } from '../../src/new-workspace/overlay-page-route' +import { MobileDictationHostProvider } from '../../src/dictation/mobile-dictation-host' +import { MobileDictationPillLayer } from '../../src/dictation/MobileDictationPill' // Keep at least this much room for the detail pane when resizing the sidebar. const MIN_DETAIL_WIDTH = 320 @@ -121,33 +123,37 @@ export default function HostGroupLayout() { // Keep detail Stack at a stable tree position so fold/rotation cannot remount navigation. return ( - - {showSidebar && (sidebarOpen || foldSidebarWidth !== null) ? ( - - - {/* Edge drag handle captures Android gestures above the list. */} - {foldSidebarWidth === null ? ( - - ) : null} + {/* One dictation per host document, outliving the session screen that started it. */} + + + {showSidebar && (sidebarOpen || foldSidebarWidth !== null) ? ( + + + {/* Edge drag handle captures Android gestures above the list. */} + {foldSidebarWidth === null ? ( + + ) : null} + + ) : null} + {foldGap > 0 ? : null} + + + + + + - ) : null} - {foldGap > 0 ? : null} - - - - - - - + + ) } diff --git a/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/StrictUtf8Test.kt b/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/StrictUtf8Test.kt index f6c1162898d..b9a381729e5 100644 --- a/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/StrictUtf8Test.kt +++ b/mobile/modules/orca-gzip-utf8-codec/android/src/test/java/expo/modules/orcagziputf8codec/StrictUtf8Test.kt @@ -1,17 +1,9 @@ package expo.modules.orcagziputf8codec -import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test class StrictUtf8Test { - @Test - fun `decodes well-formed UTF-8 of every sequence length`() { - val text = "{\"a\":\"xé✓🙂\"}" - assertEquals(text, decodeStrictUtf8(text.toByteArray(Charsets.UTF_8))) - assertEquals("", decodeStrictUtf8(ByteArray(0))) - } - @Test fun `hands back to JS what TextDecoder would repair or strip`() { val refused = listOf( diff --git a/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift b/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift index 53263b7f34c..0d827b818c8 100644 --- a/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift +++ b/mobile/modules/orca-gzip-utf8-codec/tests/GzipUtf8CodecChecks.swift @@ -37,9 +37,6 @@ import Foundation check(actual == expected, "gunzip: \(name)") } - let text = "{\"a\":\"x\u{e9}\u{2713}\u{1F642}\"}" - check(decodeStrictUtf8(Data(text.utf8)) == text, "utf8: every sequence length") - check(decodeStrictUtf8(Data()) == "", "utf8: empty") let refused: [[UInt8]] = [ [0xef, 0xbb, 0xbf, 0x41], [0xc0, 0x80], [0xed, 0xa0, 0x80], [0x41, 0xe2, 0x82], [0x80], [0xf5, 0x80, 0x80, 0x80], diff --git a/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellBridgeTest.kt b/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellBridgeTest.kt index 3e7d0937dcb..c841d7d6276 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellBridgeTest.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellBridgeTest.kt @@ -1,21 +1,10 @@ package expo.modules.orcamobilewebshell -import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class MobileWebShellBridgeTest { - @Test - fun `caps a message at 640 KiB of raw bytes`() { - val cap = MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES - assertEquals(640 * 1024, cap) - assertTrue(acceptsMobileWebShellBridgeByteCount(0)) - assertTrue(acceptsMobileWebShellBridgeByteCount(cap - 1)) - assertTrue(acceptsMobileWebShellBridgeByteCount(cap)) - assertFalse(acceptsMobileWebShellBridgeByteCount(cap + 1)) - } - @Test fun `hears only a string message from the main frame of a committed document`() { assertTrue(frame()) diff --git a/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellOriginTest.kt b/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellOriginTest.kt index 080d36b7415..2f4371b7d15 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellOriginTest.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/test/java/expo/modules/orcamobilewebshell/MobileWebShellOriginTest.kt @@ -62,14 +62,6 @@ class MobileWebShellOriginTest { assertNull(mobileWebShellOrigin("bad host")) } - @Test - fun `derives a different label for every session and the same one for a repeat`() { - assertEquals(mobileWebShellOriginHost(SESSION), mobileWebShellOriginHost(SESSION)) - assertTrue(mobileWebShellOriginHost(SESSION) != mobileWebShellOriginHost("${SESSION}a")) - // Case matters to the derivation even though the host comparison ignores it. - assertTrue(mobileWebShellOriginHost(SESSION) != mobileWebShellOriginHost(SESSION.uppercase())) - } - @Test fun `serves the document and a declared asset path`() { assertEquals("/", resolve(parts("/"))) diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift index 92e9ff89ffc..79fbb8c9b10 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift @@ -7,6 +7,9 @@ private let minimumPhysicalMemory: UInt64 = 3 << 30 /// A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts. private let claimExpirySeconds: TimeInterval = 10 +/// iOS has no "memory is low" to ask before booting (Android's `lowMemory`), and pressure outlasts its warning. +private let memoryWarningBackoffSeconds: TimeInterval = 180 + /// A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for /// the view that adopts it: a parked page stops asking for init, so its ready is answered from here. final class MobileWebShellSpare: MobileWebShellDocumentSink { @@ -56,11 +59,14 @@ final class MobileWebShellSparePool { private var parked: MobileWebShellSpare? private var claimed: MobileWebShellSpare? private let shown = NSHashTable.weakObjects() + private var memoryWarningUptime: TimeInterval? - /// Whether a spare for `directory` is parked after the call; never on a small phone, inactive app or shown page. + /// Whether a spare for `directory` is parked after the call; never on a small phone, inactive app or shown + /// page, nor soon after a memory warning. func prepare(directory: String, sessionId: String) -> Bool { guard ProcessInfo.processInfo.physicalMemory > minimumPhysicalMemory, + !recentlyWarnedAboutMemory(), UIApplication.shared.applicationState == .active, shown.allObjects.isEmpty, let window = keyWindow() @@ -121,7 +127,13 @@ final class MobileWebShellSparePool { return document } - /// Memory pressure, the app leaving the foreground, files going away, or Home without a claim. + /// A spare is the first thing to give back: nothing is shown by it. + func didReceiveMemoryWarning() { + memoryWarningUptime = ProcessInfo.processInfo.systemUptime + discardAll() + } + + /// The app leaving the foreground, files going away, Home without a claim, or memory pressure. func discardAll() { for spare in [parked, claimed].compactMap({ $0 }) { spare.document.destroy() @@ -141,6 +153,11 @@ final class MobileWebShellSparePool { spare.document.destroy() } + private func recentlyWarnedAboutMemory() -> Bool { + guard let memoryWarningUptime else { return false } + return ProcessInfo.processInfo.systemUptime - memoryWarningUptime < memoryWarningBackoffSeconds + } + private func keyWindow() -> UIWindow? { UIApplication.shared.connectedScenes .compactMap { $0 as? UIWindowScene } diff --git a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift index ed5e81770d1..ba18966b711 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift @@ -9,14 +9,13 @@ public class OrcaMobileWebShellModule: Module { public func definition() -> ModuleDefinition { Name("OrcaMobileWebShell") - // A spare is the first thing to give back: nothing is shown by it. OnCreate { memoryWarningObserver = NotificationCenter.default.addObserver( forName: UIApplication.didReceiveMemoryWarningNotification, object: nil, queue: .main ) { _ in - MobileWebShellSparePool.shared.discardAll() + MobileWebShellSparePool.shared.didReceiveMemoryWarning() } } diff --git a/mobile/modules/orca-mobile-web-shell/src/spare-document.ts b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts index ca9ba5c1f85..2106c89423f 100644 --- a/mobile/modules/orca-mobile-web-shell/src/spare-document.ts +++ b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts @@ -11,7 +11,8 @@ const spareModule = (): SpareDocumentModule | null => requireOptionalNativeModule('OrcaMobileWebShell') // Boot a page from `directory` under `sessionId` and park it, invisible, until a screen claims it. -// False when native declined: a phone under 4 GB, the app not active, or a page document shown. +// False when native declined: a phone under 4 GB, the app not active, a page document shown, or an iOS +// memory warning in the last few minutes. export async function prepareSpareDocument(directory: string, sessionId: string): Promise { return (await spareModule()?.prepareSpareDocument?.(directory, sessionId)) ?? false } diff --git a/mobile/modules/orca-mobile-web-shell/tests/MobileWebShellChecks.swift b/mobile/modules/orca-mobile-web-shell/tests/MobileWebShellChecks.swift index 761c1e2a3f0..4b7eba42367 100644 --- a/mobile/modules/orca-mobile-web-shell/tests/MobileWebShellChecks.swift +++ b/mobile/modules/orca-mobile-web-shell/tests/MobileWebShellChecks.swift @@ -151,17 +151,6 @@ import Foundation static func checkLoadStateMachine() { - let failures: [(MobileWebShellFailureReason, String)] = [ - (.generationUnreadable, "generation-unreadable"), - (.isolationUnavailable, "isolation-unavailable"), - (.documentLoadFailed, "document-load-failed"), - (.renderProcessGone, "render-process-gone") - ] - for (reason, expected) in failures { - let machine = MobileWebShellLoadStateMachine() - precondition(machine.failed(reason) == MobileWebShellLoadEmission(state: "failed", reason: expected)) - } - // Only the view’s own load raises the flag; commit, failure, renderer death and failed prop application clear it. let ownLoad = MobileWebShellLoadStateMachine() precondition(!ownLoad.isShellLoad) @@ -320,23 +309,6 @@ import Foundation } - static func checkBridgeByteCap() { - let cap = MobileWebShellBridge.maxMessageByteCount - precondition(cap == 640 * 1024) - precondition(MobileWebShellBridge.acceptsByteCount(0)) - precondition(MobileWebShellBridge.acceptsByteCount(cap - 1)) - precondition(MobileWebShellBridge.acceptsByteCount(cap)) - precondition(!MobileWebShellBridge.acceptsByteCount(cap + 1)) - - let gate = MobileWebShellBridgeGate() - precondition(gate.refusedCount == 0) - precondition(gate.accepts(byteCount: cap)) - precondition(gate.refusedCount == 0) - precondition(!gate.accepts(byteCount: cap + 1)) - precondition(!gate.accepts(byteCount: cap * 2)) - precondition(gate.refusedCount == 2) - } - // One allow/opener decision; TypeScript’s readBridgeExternalLinkUrl owns scheme filtering. static func checkNavigationVerdict() { let foreign = "https://example.com/artifact-link" @@ -400,41 +372,13 @@ import Foundation precondition(verdict("javascript:alert(1)") == .cancelAndOffer("javascript:alert(1)")) } - // Check flag/policy together: only one main-frame action may spend the shell’s own-load allowance. - static func checkOwnLoadIsSpentOnce() { - let document = "orca-mobile-web://\(session)/" - func decide(_ machine: MobileWebShellLoadStateMachine) -> MobileWebShellNavigationVerdict { - MobileWebShellNavigationPolicy.verdict( - url: document, - isMainFrame: true, - isDocumentUrl: true, - isShellLoad: machine.isShellLoad, - hasGesture: false, - isDownload: false - ) - } - let machine = MobileWebShellLoadStateMachine() - machine.shellLoadStarted() - let first = decide(machine) - precondition(first == .allow) - // Spend at decision, before commit: WebKit may decide a second action first. - machine.shellLoadConsumed() - precondition(decide(machine) == .cancel) - // And the endings still drop it, for a load that is allowed and then never commits. - machine.shellLoadStarted() - machine.documentEnded() - precondition(decide(machine) == .cancel) - } - static func main() { checkRequestResolution() checkGenerationMap() checkLoadStateMachine() checkNavigationVerdict() - checkOwnLoadIsSpentOnce() checkBridgeAcceptance() checkBridgePostTarget() - checkBridgeByteCap() print("mobile web shell checks OK") } } diff --git a/mobile/rpc-foundation/goldens/event-router-failed-read-floor.json b/mobile/rpc-foundation/goldens/event-router-failed-read-floor.json new file mode 100644 index 00000000000..9dd33a238a3 --- /dev/null +++ b/mobile/rpc-foundation/goldens/event-router-failed-read-floor.json @@ -0,0 +1,215 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "a839711b15b8": { + "status": "pending" + }, + "ac14275e5e23": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + }, + "id": "frame-2", + "ok": false + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c7fbd9501e80": { + "status": "error" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + } + }, + "recording": { + "scenario": "event-router-failed-read-floor", + "checkpoints": [ + { + "id": "listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-1.json b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-1.json new file mode 100644 index 00000000000..f26f1fbaa5c --- /dev/null +++ b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-1.json @@ -0,0 +1,815 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "1eef7ff9a9b9": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 3000, + "settledAt": 3750, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "a839711b15b8": { + "status": "pending" + }, + "ac14275e5e23": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + }, + "id": "frame-2", + "ok": false + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c7fbd9501e80": { + "status": "error" + }, + "e1883df1f8f5": { + "name": "streams-registered-at-teardown", + "ordinal": 6, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + } + }, + "recording": { + "scenario": "matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-1", + "checkpoints": [ + { + "id": "event-router-failed-read-floor.normal:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:cleanup", + "observation": { + "sender": ["ac14275e5e23", "1eef7ff9a9b9"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["e1883df1f8f5"] + } + }, + { + "id": "event-router-failed-read-floor.result-null:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:cleanup", + "observation": { + "sender": ["ac14275e5e23", "1eef7ff9a9b9"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["e1883df1f8f5"] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:cleanup", + "observation": { + "sender": ["ac14275e5e23", "1eef7ff9a9b9"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["e1883df1f8f5"] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:cleanup", + "observation": { + "sender": ["ac14275e5e23", "1eef7ff9a9b9"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["e1883df1f8f5"] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:cleanup", + "observation": { + "sender": ["ac14275e5e23", "1eef7ff9a9b9"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["e1883df1f8f5"] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:floor-passed", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:unmounted", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:floor-passed", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:unmounted", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:floor-passed", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:unmounted", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": [] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-2.json b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-2.json new file mode 100644 index 00000000000..acdc360fc11 --- /dev/null +++ b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-2.json @@ -0,0 +1,566 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "a328c933a31f": { + "name": "streams-registered-at-teardown", + "ordinal": 5, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#2" + } + ] + }, + "a839711b15b8": { + "status": "pending" + }, + "ac14275e5e23": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + }, + "id": "frame-2", + "ok": false + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c686e7f77d44": { + "name": "runtime.clientEvents.subscribe#2", + "ordinal": 4, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "c7fbd9501e80": { + "status": "error" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + } + }, + "recording": { + "scenario": "matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-2", + "checkpoints": [ + { + "id": "event-router-failed-read-floor.prelude:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.prelude:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:floor-passed", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:unmounted", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:cleanup", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": ["a328c933a31f"] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:floor-passed", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:unmounted", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:cleanup", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": ["a328c933a31f"] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:floor-passed", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:unmounted", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:cleanup", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "c7fbd9501e80", + "effects": ["a328c933a31f"] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-3.json b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-3.json new file mode 100644 index 00000000000..a9e315b074f --- /dev/null +++ b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-3.json @@ -0,0 +1,637 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "0769c2565e2f": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "1fcd3f3dee98": { + "name": "streams-registered-at-teardown", + "ordinal": 7, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#2" + } + ] + }, + "4e87a83926ae": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 3000, + "settledAt": 3750, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "8b854beb872a": { + "name": "worktree.ps#2", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "a839711b15b8": { + "status": "pending" + }, + "ac14275e5e23": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + }, + "id": "frame-2", + "ok": false + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c686e7f77d44": { + "name": "runtime.clientEvents.subscribe#2", + "ordinal": 4, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "c7fbd9501e80": { + "status": "error" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + } + }, + "recording": { + "scenario": "matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-3", + "checkpoints": [ + { + "id": "event-router-failed-read-floor.prelude:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.prelude:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-4.json b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-4.json new file mode 100644 index 00000000000..dd61b787a40 --- /dev/null +++ b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-4.json @@ -0,0 +1,637 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "0769c2565e2f": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "1fcd3f3dee98": { + "name": "streams-registered-at-teardown", + "ordinal": 7, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#2" + } + ] + }, + "4e87a83926ae": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 3000, + "settledAt": 3750, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "8b854beb872a": { + "name": "worktree.ps#2", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "a839711b15b8": { + "status": "pending" + }, + "ac14275e5e23": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + }, + "id": "frame-2", + "ok": false + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c686e7f77d44": { + "name": "runtime.clientEvents.subscribe#2", + "ordinal": 4, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "c7fbd9501e80": { + "status": "error" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + } + }, + "recording": { + "scenario": "matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-4", + "checkpoints": [ + { + "id": "event-router-failed-read-floor.prelude:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.prelude:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-5.json b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-5.json new file mode 100644 index 00000000000..7edecb5933b --- /dev/null +++ b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-5.json @@ -0,0 +1,637 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "0769c2565e2f": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "1fcd3f3dee98": { + "name": "streams-registered-at-teardown", + "ordinal": 7, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#2" + } + ] + }, + "4e87a83926ae": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 3000, + "settledAt": 3750, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "8b854beb872a": { + "name": "worktree.ps#2", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "a839711b15b8": { + "status": "pending" + }, + "ac14275e5e23": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + }, + "id": "frame-2", + "ok": false + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c686e7f77d44": { + "name": "runtime.clientEvents.subscribe#2", + "ordinal": 4, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "c7fbd9501e80": { + "status": "error" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + } + }, + "recording": { + "scenario": "matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-5", + "checkpoints": [ + { + "id": "event-router-failed-read-floor.prelude:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.prelude:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-6.json b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-6.json new file mode 100644 index 00000000000..fcad6692de2 --- /dev/null +++ b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-6.json @@ -0,0 +1,637 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "0769c2565e2f": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "1fcd3f3dee98": { + "name": "streams-registered-at-teardown", + "ordinal": 7, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#2" + } + ] + }, + "4e87a83926ae": { + "name": "worktree.ps#2", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 3000, + "settledAt": 3750, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "8b854beb872a": { + "name": "worktree.ps#2", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "a839711b15b8": { + "status": "pending" + }, + "ac14275e5e23": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + }, + "id": "frame-2", + "ok": false + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c686e7f77d44": { + "name": "runtime.clientEvents.subscribe#2", + "ordinal": 4, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "c7fbd9501e80": { + "status": "error" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + } + }, + "recording": { + "scenario": "matrix-query.event-router-catalog-runtime.clientevents.subscribe-1-6", + "checkpoints": [ + { + "id": "event-router-failed-read-floor.prelude:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.prelude:read-refused", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:unmounted", + "observation": { + "sender": ["ac14275e5e23", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:five-notices-inside-the-floor", + "observation": { + "sender": ["ac14275e5e23"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:floor-passed", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:unmounted", + "observation": { + "sender": ["ac14275e5e23", "0769c2565e2f"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:cleanup", + "observation": { + "sender": ["ac14275e5e23", "4e87a83926ae"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "c686e7f77d44", "8b854beb872a"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": ["1fcd3f3dee98"] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-worktree.ps-1.json b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-worktree.ps-1.json new file mode 100644 index 00000000000..2eda7c6805a --- /dev/null +++ b/mobile/rpc-foundation/goldens/matrix-query.event-router-catalog-worktree.ps-1.json @@ -0,0 +1,1117 @@ +{ + "goldenFormatVersion": 6, + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "namedDeltas": [], + "values": { + "2159667cf633": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true + } + } + }, + "5bd4621f47d0": { + "name": "runtime.clientEvents.unsubscribe#1", + "ordinal": 6, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.unsubscribe\",\"params\":{\"subscriptionId\":\"sub-1\"}}" + }, + "5ece68a8cbc5": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-2", + "ok": false + } + } + }, + "6030c04ddbcd": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "704ca5c34f99": { + "name": "worktree.ps#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "70f531389976": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "73083f54975f": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true + } + } + }, + "78a0dbbe27a8": { + "name": "worktree.ps#2", + "ordinal": 5, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" + }, + "89b9ba8d8cd7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-2", + "ok": false + } + } + }, + "8db531aac9cb": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "912d0c07da7b": { + "status": "success" + }, + "a839711b15b8": { + "status": "pending" + }, + "ae35b72a6d04": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "worktrees": [] + } + } + } + }, + "ae9f66f12cc9": { + "status": "fulfilled", + "startedAt": 3750, + "settledAt": 3750, + "value": { + "$rpc": "undefined" + } + }, + "b91023634f14": { + "name": "worktree.ps#2", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 3000 + } + }, + "baf8a4d812f1": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, + "c448f53917f7": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "c7fbd9501e80": { + "status": "error" + }, + "e6d56f2fda86": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-2", + "ok": false + } + } + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eef1ee3c2773": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 1, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "efab2a313e0c": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } + } + }, + "f7c49a54fd25": { + "name": "worktree.ps#1", + "ordinal": 2, + "args": [ + { + "name": "method", + "value": "worktree.ps" + }, + { + "name": "params", + "value": { + "acceptRowDelta": true, + "afterSnapshotId": { + "$rpc": "null" + }, + "limit": 10000 + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "error": { + "message": "inner refused" + }, + "ok": false + } + } + } + } + }, + "recording": { + "scenario": "matrix-query.event-router-catalog-worktree.ps-1", + "checkpoints": [ + { + "id": "event-router-failed-read-floor.prelude:listening", + "observation": { + "sender": ["c448f53917f7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:read-refused", + "observation": { + "sender": ["ae35b72a6d04"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "912d0c07da7b", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:five-notices-inside-the-floor", + "observation": { + "sender": ["ae35b72a6d04"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "912d0c07da7b", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:floor-passed", + "observation": { + "sender": ["ae35b72a6d04", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "912d0c07da7b", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.normal:unmounted", + "observation": { + "sender": ["ae35b72a6d04", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "912d0c07da7b", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:read-refused", + "observation": { + "sender": ["2159667cf633"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:five-notices-inside-the-floor", + "observation": { + "sender": ["2159667cf633"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:floor-passed", + "observation": { + "sender": ["2159667cf633", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-absent:unmounted", + "observation": { + "sender": ["2159667cf633", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:read-refused", + "observation": { + "sender": ["baf8a4d812f1"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:five-notices-inside-the-floor", + "observation": { + "sender": ["baf8a4d812f1"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:floor-passed", + "observation": { + "sender": ["baf8a4d812f1", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.result-null:unmounted", + "observation": { + "sender": ["baf8a4d812f1", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:read-refused", + "observation": { + "sender": ["8db531aac9cb"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:five-notices-inside-the-floor", + "observation": { + "sender": ["8db531aac9cb"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:floor-passed", + "observation": { + "sender": ["8db531aac9cb", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-ok-missing:unmounted", + "observation": { + "sender": ["8db531aac9cb", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:read-refused", + "observation": { + "sender": ["efab2a313e0c"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:five-notices-inside-the-floor", + "observation": { + "sender": ["efab2a313e0c"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:floor-passed", + "observation": { + "sender": ["efab2a313e0c", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-string-error:unmounted", + "observation": { + "sender": ["efab2a313e0c", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:read-refused", + "observation": { + "sender": ["f7c49a54fd25"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:five-notices-inside-the-floor", + "observation": { + "sender": ["f7c49a54fd25"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:floor-passed", + "observation": { + "sender": ["f7c49a54fd25", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.inner-false-object-error:unmounted", + "observation": { + "sender": ["f7c49a54fd25", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:read-refused", + "observation": { + "sender": ["89b9ba8d8cd7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:five-notices-inside-the-floor", + "observation": { + "sender": ["89b9ba8d8cd7"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:floor-passed", + "observation": { + "sender": ["89b9ba8d8cd7", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused:unmounted", + "observation": { + "sender": ["89b9ba8d8cd7", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:read-refused", + "observation": { + "sender": ["e6d56f2fda86"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["e6d56f2fda86"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:floor-passed", + "observation": { + "sender": ["e6d56f2fda86", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.outer-refused-no-message:unmounted", + "observation": { + "sender": ["e6d56f2fda86", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:read-refused", + "observation": { + "sender": ["5ece68a8cbc5"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:five-notices-inside-the-floor", + "observation": { + "sender": ["5ece68a8cbc5"], + "payloads": ["eef1ee3c2773", "704ca5c34f99"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "c7fbd9501e80", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:floor-passed", + "observation": { + "sender": ["5ece68a8cbc5", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.method-not-found:unmounted", + "observation": { + "sender": ["5ece68a8cbc5", "b91023634f14"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection:read-refused", + "observation": { + "sender": ["73083f54975f", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection:five-notices-inside-the-floor", + "observation": { + "sender": ["73083f54975f", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection:floor-passed", + "observation": { + "sender": ["73083f54975f", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection:unmounted", + "observation": { + "sender": ["73083f54975f", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection-no-message:read-refused", + "observation": { + "sender": ["6030c04ddbcd", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection-no-message:five-notices-inside-the-floor", + "observation": { + "sender": ["6030c04ddbcd", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection-no-message:floor-passed", + "observation": { + "sender": ["6030c04ddbcd", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8"], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "a839711b15b8", + "effects": [] + } + }, + { + "id": "event-router-failed-read-floor.transport-rejection-no-message:unmounted", + "observation": { + "sender": ["6030c04ddbcd", "70f531389976"], + "payloads": ["eef1ee3c2773", "704ca5c34f99", "78a0dbbe27a8", "5bd4621f47d0"], + "settlements": { + "mount": "eb79a9b3682a", + "unmount": "ae9f66f12cc9" + }, + "state": "a839711b15b8", + "effects": [] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prchecks-1.json b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prchecks-1.json index 8f71aad930b..7693f29ada4 100644 --- a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prchecks-1.json +++ b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prchecks-1.json @@ -4,44 +4,15 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { - "07f2f3aaaa06": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": { - "error": { - "message": "inner refused" - }, - "ok": false - } - } - } + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" }, "1287167eaf56": { "name": "github.repoSlug#1", @@ -78,55 +49,59 @@ } } }, - "138623e4e324": { - "name": "github.prChecks#1", - "ordinal": 10, + "1287efa543e2": { + "name": "status.get#1", + "ordinal": 12, "args": [ { "name": "method", - "value": "github.prChecks" + "value": "status.get" }, { "name": "params", "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" + "$rpc": "undefined" } }, { "name": "options", "value": { - "failWhenDisconnected": true + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 } } ], "settlement": { - "status": "fulfilled", + "status": "rejected", "startedAt": 0, "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": { - "error": "refused" - } + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, "1f5765918736": { "name": "github.repoSlug#1", "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { + "21069b5e026b": { + "name": "streams-registered-at-teardown", + "ordinal": 15, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "2dc2ca47b4e7": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -135,6 +110,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -159,98 +135,6 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "2aa7c40de795": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "" - }, - "id": "frame-5", - "ok": false - } - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, "341c71d5f61d": { "commentError": { "$rpc": "null" @@ -310,6 +194,53 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "4c6c7242d783": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-6", + "ok": false + } + } + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -348,9 +279,14 @@ } } }, - "5dcef756f74d": { + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "7568e9226f82": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -376,17 +312,292 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-5", + "id": "frame-6", + "ok": true + } + } + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", "ok": true, "result": { - "$rpc": "null" + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" } } } }, - "655a4ec47a79": { + "861c8796ae1f": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "86e0e245ccff": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-6", + "ok": false + } + } + }, + "86fa720b0be0": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "88a93ee200e3": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "checks": [], + "checksError": "Request failed: github.prChecks", + "comments": [ + { + "body": "please fix", + "id": 55, + "resolved": false + } + ], + "kind": "ready", + "pr": { + "headSha": "head-sha-1", + "number": 12, + "title": "Recorded" + }, + "refreshFailed": false + } + }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "8e587952852c": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "checks": [], + "checksError": "", + "comments": [ + { + "body": "please fix", + "id": 55, + "resolved": false + } + ], + "kind": "ready", + "pr": { + "headSha": "head-sha-1", + "number": 12, + "title": "Recorded" + }, + "refreshFailed": false + } + }, + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "97a4d630a57b": { + "name": "github.prChecks#1", + "ordinal": 11, "args": [ { "name": "method", @@ -418,32 +629,25 @@ } } }, - "707f5273fbe1": { - "name": "github.prForBranch#1", - "ordinal": 8, + "99d7140d3603": { + "name": "github.prChecks#1", + "ordinal": 11, "args": [ { "name": "method", - "value": "github.prForBranch" + "value": "github.prChecks" }, { "name": "params", "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, + "headSha": "head-sha-1", + "prNumber": 12, "repo": "id:repo-9" } }, { "name": "options", "value": { - "beforeSend": "[local beforeSend]", "failWhenDisconnected": true } } @@ -453,27 +657,41 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", - "ok": true, - "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-6", + "ok": false } } }, - "7cab7429568b": { + "9a1e69260642": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "checks": [], + "checksError": "Unknown method", + "comments": [ + { + "body": "please fix", + "id": 55, + "resolved": false + } + ], + "kind": "ready", + "pr": { + "headSha": "head-sha-1", + "number": 12, + "title": "Recorded" + }, + "refreshFailed": false + } + }, + "9c18ac090c8c": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -505,9 +723,63 @@ } } }, - "8300ca3ac5c2": { + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "a74156a14b4c": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -528,39 +800,6 @@ } } ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true - } - } - }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], "settlement": { "status": "fulfilled", "startedAt": 0, @@ -569,14 +808,15 @@ "id": "frame-6", "ok": true, "result": { - "runtimeId": "recorded" + "error": "inner refused", + "ok": false } } } }, - "87ba39148f02": { + "a7e609fcb031": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -597,124 +837,14 @@ } } ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] - } - } - }, - "88a93ee200e3": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "checks": [], - "checksError": "Request failed: github.prChecks", - "comments": [ - { - "body": "please fix", - "id": 55, - "resolved": false - } - ], - "kind": "ready", - "pr": { - "headSha": "head-sha-1", - "number": 12, - "title": "Recorded" - }, - "refreshFailed": false - } - }, - "8e587952852c": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "checks": [], - "checksError": "", - "comments": [ - { - "body": "please fix", - "id": 55, - "resolved": false - } - ], - "kind": "ready", - "pr": { - "headSha": "head-sha-1", - "number": 12, - "title": "Recorded" - }, - "refreshFailed": false - } - }, - "9a1e69260642": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "checks": [], - "checksError": "Unknown method", - "comments": [ - { - "body": "please fix", - "id": 55, - "resolved": false - } - ], - "kind": "ready", - "pr": { - "headSha": "head-sha-1", - "number": 12, - "title": "Recorded" - }, - "refreshFailed": false - } - }, - "9c952632b0c0": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], "settlement": { "status": "pending", "startedAt": 0 } }, - "9e247bf3143d": { + "aec2edd8fc3a": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -740,20 +870,14 @@ "startedAt": 0, "settledAt": 0, "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-5", - "ok": false + "id": "frame-6", + "ok": true, + "result": { + "error": "refused" + } } } }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, "bd448e85868e": { "commentError": { "$rpc": "null" @@ -777,9 +901,9 @@ "refreshFailed": false } }, - "cac8d5a10134": { + "bfd4f750fc70": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -805,51 +929,20 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-5", + "id": "frame-6", "ok": true, "result": { - "error": "inner refused", + "error": { + "message": "inner refused" + }, "ok": false } } } }, - "cb071b912510": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -877,7 +970,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -910,15 +1003,51 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "de33f50efdbf": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": { + "$rpc": "null" + } + } } }, "e0a11d8a1005": { @@ -946,6 +1075,11 @@ "refreshFailed": false } }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -953,43 +1087,6 @@ "value": { "$rpc": "undefined" } - }, - "fb0e9f0edb67": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-5", - "ok": false - } - } } }, "recording": { @@ -998,13 +1095,19 @@ { "id": "pr-sidebar-load.prelude:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1012,25 +1115,53 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.prelude:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "86fa720b0be0", + "1287efa543e2" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "35045fa5a752", + "effects": ["9091d133c3b0", "21069b5e026b"] } }, { @@ -1038,27 +1169,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.normal:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1066,27 +1227,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "8300ca3ac5c2", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "7568e9226f82", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "341c71d5f61d", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-absent:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "7568e9226f82", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "341c71d5f61d", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1094,27 +1285,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "5dcef756f74d", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "de33f50efdbf", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "341c71d5f61d", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-null:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "de33f50efdbf", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "341c71d5f61d", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1122,27 +1343,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "138623e4e324", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "aec2edd8fc3a", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "341c71d5f61d", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-ok-missing:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "aec2edd8fc3a", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "341c71d5f61d", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1150,27 +1401,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cac8d5a10134", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "a74156a14b4c", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "341c71d5f61d", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-string-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "a74156a14b4c", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "341c71d5f61d", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1178,27 +1459,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "07f2f3aaaa06", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "bfd4f750fc70", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "341c71d5f61d", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-object-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "bfd4f750fc70", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "341c71d5f61d", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1206,27 +1517,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "fb0e9f0edb67", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "4c6c7242d783", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "bd448e85868e", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "4c6c7242d783", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "bd448e85868e", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1234,27 +1575,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "2aa7c40de795", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "99d7140d3603", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "88a93ee200e3", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "99d7140d3603", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "88a93ee200e3", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1262,27 +1633,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "9e247bf3143d", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "86e0e245ccff", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "9a1e69260642", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.method-not-found:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "86e0e245ccff", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "9a1e69260642", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1290,27 +1691,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "655a4ec47a79", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "97a4d630a57b", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "34fe99d9471b", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "97a4d630a57b", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "34fe99d9471b", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1318,27 +1749,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "7cab7429568b", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "9c18ac090c8c", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "8e587952852c", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "9c18ac090c8c", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "8e587952852c", + "effects": ["9091d133c3b0", "c70e6fd19823"] } } ] diff --git a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prforbranch-1.json b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prforbranch-1.json index 1f5a63c1443..6367cc642fe 100644 --- a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prforbranch-1.json +++ b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.prforbranch-1.json @@ -4,6 +4,58 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "088f322e6eb7": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -39,14 +91,14 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + "1f5765918736": { + "name": "github.repoSlug#1", + "ordinal": 2, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "1dc3b425aa47": { + "20f106bf7e22": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -55,6 +107,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -79,19 +132,18 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", - "ok": true + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-5", + "ok": false } } }, - "1f5765918736": { - "name": "github.repoSlug#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" - }, - "2309f345fb72": { + "2512dcf505e6": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -100,6 +152,60 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, + "29120132bf36": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "error", + "message": "" + } + }, + "2dc2ca47b4e7": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -124,70 +230,6 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "29120132bf36": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "error", - "message": "" - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, "35045fa5a752": { "commentError": { "$rpc": "null" @@ -201,48 +243,26 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, - "37798555c066": { + "3a8e6b13f380": { "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3a96bb9c2176": { + "name": "streams-registered-at-teardown", + "ordinal": 11, + "value": [ { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "$rpc": "null" - } - } - } + ] + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" }, "4da7ea39401b": { "name": "worktree.show#1", @@ -282,26 +302,14 @@ } } }, - "6b1694d3660f": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "none" - } + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" }, - "6ed2d1d6c61b": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "error", - "message": "Unknown method" - } - }, - "707f5273fbe1": { + "60a05a6771b8": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -310,6 +318,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -334,27 +343,20 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-5", "ok": true, "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } + "error": { + "message": "inner refused" + }, + "ok": false } } } }, - "77ff745b56fa": { + "615ca8b7764b": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -363,6 +365,48 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true + } + } + }, + "62fcc5c3eaf3": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -393,9 +437,26 @@ } } }, - "807f60a1f770": { + "6b1694d3660f": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "none" + } + }, + "6ed2d1d6c61b": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "error", + "message": "Unknown method" + } + }, + "70a12ff07dad": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -404,6 +465,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -428,35 +490,37 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-5", "ok": true, "result": { - "error": "inner refused", - "ok": false + "error": "refused" } } } }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", - "value": "status.get" + "value": "hostedReview.forBranch" }, { "name": "params", "value": { - "$rpc": "undefined" + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" } }, { "name": "options", "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 + "failWhenDisconnected": true } } ], @@ -465,17 +529,23 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-6", + "id": "frame-4", "ok": true, "result": { - "runtimeId": "recorded" + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" } } } }, - "87ba39148f02": { + "861c8796ae1f": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -501,7 +571,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-5", + "id": "frame-6", "ok": true, "result": [ { @@ -514,18 +584,73 @@ } } }, - "9165ce8cf517": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "error", - "message": "transport failure" + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 } }, - "938c799557e3": { + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "8c6393c116e0": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -534,6 +659,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -560,13 +686,33 @@ "value": { "error": { "code": "refused", - "message": "" + "message": "outer refused" }, - "id": "frame-4", + "id": "frame-5", "ok": false } } }, + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "9165ce8cf517": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "error", + "message": "transport failure" + } + }, "98aa27f6bdff": { "commentError": { "$rpc": "null" @@ -576,42 +722,9 @@ "message": "The host sent a reply this app could not read (github.prForBranch)" } }, - "9c952632b0c0": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "b36e6dd5be3d": { + "a55c83eeaeea": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -620,6 +733,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -644,81 +758,27 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-5", "ok": true, "result": { - "error": { - "message": "inner refused" - }, - "ok": false + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } } } } }, - "b772fc418001": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "error", - "message": "Request failed: github.prForBranch" - } - }, - "bb7ae1ebe69f": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "error", - "message": "outer refused" - } - }, - "c9329ced0970": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "cb071b912510": { + "a7e609fcb031": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -744,14 +804,27 @@ "startedAt": 0 } }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" + "b772fc418001": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "error", + "message": "Request failed: github.prForBranch" + } }, - "d3426861162d": { + "bb7ae1ebe69f": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "error", + "message": "outer refused" + } + }, + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -779,7 +852,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -812,57 +885,16 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" - } - }, - "d751b4c53cb0": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true - } - } + ] }, "e0a11d8a1005": { "commentError": { @@ -889,9 +921,14 @@ "refreshFailed": false } }, - "e6ce999d34a3": { + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "e2f2c0961b68": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -900,6 +937,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -926,24 +964,16 @@ "value": { "error": { "code": "refused", - "message": "outer refused" + "message": "" }, - "id": "frame-4", + "id": "frame-5", "ok": false } } }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "ed93c0450d76": { + "e43b72b94bc2": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -952,6 +982,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -976,12 +1007,62 @@ "startedAt": 0, "settledAt": 0, "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-4", - "ok": false + "id": "frame-5", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } + } + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "f8e83ca4970c": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true } } } @@ -992,13 +1073,37 @@ { "id": "pr-sidebar-load.prelude:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.prelude:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "f8e83ca4970c"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "35045fa5a752", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { @@ -1006,25 +1111,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1032,267 +1138,597 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.normal:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.result-absent:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "1dc3b425aa47"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "615ca8b7764b"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.result-absent:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "1dc3b425aa47"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "615ca8b7764b"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-absent:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "615ca8b7764b"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "98aa27f6bdff", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.result-null:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "37798555c066"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2512dcf505e6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "6b1694d3660f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.result-null:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "37798555c066"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2512dcf505e6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "6b1694d3660f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-null:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2512dcf505e6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "6b1694d3660f", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.inner-ok-missing:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "c9329ced0970"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "70a12ff07dad"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.inner-ok-missing:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "c9329ced0970"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "70a12ff07dad"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-ok-missing:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "70a12ff07dad"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "98aa27f6bdff", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.inner-false-string-error:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "807f60a1f770"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "e43b72b94bc2"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.inner-false-string-error:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "807f60a1f770"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "e43b72b94bc2"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-string-error:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "e43b72b94bc2"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "98aa27f6bdff", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.inner-false-object-error:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "b36e6dd5be3d"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "60a05a6771b8"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.inner-false-object-error:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "b36e6dd5be3d"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "60a05a6771b8"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "98aa27f6bdff", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-object-error:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "60a05a6771b8"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "98aa27f6bdff", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.outer-refused:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "e6ce999d34a3"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "8c6393c116e0"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "bb7ae1ebe69f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.outer-refused:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "e6ce999d34a3"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "8c6393c116e0"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "bb7ae1ebe69f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "8c6393c116e0"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "bb7ae1ebe69f", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.outer-refused-no-message:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "938c799557e3"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "e2f2c0961b68"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "b772fc418001", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.outer-refused-no-message:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "938c799557e3"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "e2f2c0961b68"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "b772fc418001", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused-no-message:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "e2f2c0961b68"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "b772fc418001", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.method-not-found:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "ed93c0450d76"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "20f106bf7e22"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "6ed2d1d6c61b", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.method-not-found:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "ed93c0450d76"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "20f106bf7e22"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "6ed2d1d6c61b", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.method-not-found:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "20f106bf7e22"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "6ed2d1d6c61b", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.transport-rejection:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "77ff745b56fa"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "62fcc5c3eaf3"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "9165ce8cf517", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.transport-rejection:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "77ff745b56fa"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "62fcc5c3eaf3"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "9165ce8cf517", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "62fcc5c3eaf3"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "9165ce8cf517", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } }, { "id": "pr-sidebar-load.transport-rejection-no-message:pr", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "d751b4c53cb0"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "088f322e6eb7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "29120132bf36", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { "id": "pr-sidebar-load.transport-rejection-no-message:loaded", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "d751b4c53cb0"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "088f322e6eb7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "29120132bf36", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection-no-message:cleanup", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "088f322e6eb7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "29120132bf36", + "effects": ["9091d133c3b0", "3a96bb9c2176"] } } ] diff --git a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.reposlug-1.json b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.reposlug-1.json index 9c82dfbc8d3..7f0fa06771b 100644 --- a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.reposlug-1.json +++ b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.reposlug-1.json @@ -4,6 +4,16 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -39,106 +49,11 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, "1f5765918736": { "name": "github.repoSlug#1", "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, "2c045643bad3": { "name": "github.repoSlug#1", "ordinal": 1, @@ -173,6 +88,42 @@ } } }, + "2dc2ca47b4e7": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "30a3a771295b": { "name": "github.repoSlug#1", "ordinal": 1, @@ -217,6 +168,16 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -255,23 +216,25 @@ } } }, - "707f5273fbe1": { - "name": "github.prForBranch#1", - "ordinal": 8, + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", - "value": "github.prForBranch" + "value": "hostedReview.forBranch" }, { "name": "params", "value": { + "active": true, "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { + "linkedGitHubPR": { "$rpc": "null" }, "repo": "id:repo-9" @@ -280,7 +243,6 @@ { "name": "options", "value": { - "beforeSend": "[local beforeSend]", "failWhenDisconnected": true } } @@ -293,53 +255,13 @@ "id": "frame-4", "ok": true, "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - } - }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" } } } @@ -381,6 +303,75 @@ } } }, + "861c8796ae1f": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "87a169b1b8d4": { "name": "github.repoSlug#1", "ordinal": 1, @@ -416,26 +407,26 @@ } } }, - "87ba39148f02": { - "name": "github.prChecks#1", - "ordinal": 10, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, "args": [ { "name": "method", - "value": "github.prChecks" + "value": "status.get" }, { "name": "params", "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" + "$rpc": "undefined" } }, { "name": "options", "value": { - "failWhenDisconnected": true + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 } } ], @@ -444,16 +435,11 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-5", + "id": "frame-7", "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] + "result": { + "runtimeId": "recorded" + } } } }, @@ -524,26 +510,91 @@ } } }, - "9c952632b0c0": { - "name": "status.get#1", - "ordinal": 11, + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, "args": [ { "name": "method", - "value": "status.get" + "value": "github.prForBranch" }, { "name": "params", "value": { - "$rpc": "undefined" + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" } }, { "name": "options", "value": { "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "a7e609fcb031": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true } } ], @@ -584,11 +635,6 @@ } } }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, "b77761a8ce16": { "name": "github.repoSlug#1", "ordinal": 1, @@ -659,6 +705,69 @@ } } }, + "bfedf583a747": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-8", + "ok": true, + "result": { + "body": "body", + "comments": [ + { + "author": "rev", + "body": "please fix", + "createdAt": "2026-01-01T00:00:00Z", + "id": 55, + "isResolved": false, + "line": 3, + "path": "src/app.ts", + "threadId": "thread-1", + "url": "https://github.com/owner/repo/pull/12#discussion_r55" + } + ], + "headSha": "head-sha-1", + "item": { + "assignees": [], + "id": "PR_1", + "labels": [], + "number": 12, + "state": "open", + "title": "Recorded", + "type": "pr", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, "c1bb3c2243f0": { "name": "github.repoSlug#1", "ordinal": 1, @@ -693,112 +802,16 @@ } } }, - "cb071b912510": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-7", - "ok": true, - "result": { - "body": "body", - "comments": [ - { - "author": "rev", - "body": "please fix", - "createdAt": "2026-01-01T00:00:00Z", - "id": 55, - "isResolved": false, - "line": 3, - "path": "src/app.ts", - "threadId": "thread-1", - "url": "https://github.com/owner/repo/pull/12#discussion_r55" - } - ], - "headSha": "head-sha-1", - "item": { - "assignees": [], - "id": "PR_1", - "labels": [], - "number": 12, - "state": "open", - "title": "Recorded", - "type": "pr", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - } - }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" - } + ] }, "e0a11d8a1005": { "commentError": { @@ -825,6 +838,11 @@ "refreshFailed": false } }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, "ead3ad184e51": { "commentError": { "$rpc": "null" @@ -848,13 +866,19 @@ { "id": "pr-sidebar-load.normal:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -862,25 +886,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -888,27 +913,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.normal:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { diff --git a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.workitemdetails-1.json b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.workitemdetails-1.json index 1de7e703184..548a7b86972 100644 --- a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.workitemdetails-1.json +++ b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-github.workitemdetails-1.json @@ -4,6 +4,16 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -39,19 +49,52 @@ } } }, - "1723d8a5d8be": { + "1a5855cadb2d": { "name": "github.workItemDetails#1", "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-8", + "ok": true, + "result": { + "error": "refused" + } + } + } }, "1f5765918736": { "name": "github.repoSlug#1", "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { + "2dc2ca47b4e7": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -60,6 +103,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -84,77 +128,9 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, - "35045fa5a752": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "loading" - } - }, - "357f9b7862e3": { - "name": "worktree.show#1", - "ordinal": 6, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" - }, - "3c501939dd10": { + "313cd9c49244": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -184,13 +160,77 @@ "value": { "error": { "code": "refused", - "message": "" + "message": "outer refused" }, - "id": "frame-7", + "id": "frame-8", "ok": false } } }, + "35045fa5a752": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "loading" + } + }, + "357f9b7862e3": { + "name": "worktree.show#1", + "ordinal": 6, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" + }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "476aa8b45a85": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-8", + "ok": true, + "result": { + "error": { + "message": "inner refused" + }, + "ok": false + } + } + } + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -229,9 +269,593 @@ } } }, - "4dd3c3919d72": { + "5a5e8aeb9c0f": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "checks": ["build:success"], + "checksError": { + "$rpc": "null" + }, + "comments": [], + "kind": "ready", + "pr": { + "headSha": "head-sha-1", + "number": 12, + "title": "Recorded" + }, + "refreshFailed": false + } + }, + "5d309fcf43a7": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "5f7634e4c4d1": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-8", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } + } + }, + "74b5741dc1b5": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-8", + "ok": false + } + } + }, + "7512c5d8922e": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "checks": ["build:success"], + "checksError": { + "$rpc": "null" + }, + "comments": "loading", + "kind": "ready", + "pr": { + "headSha": "head-sha-1", + "number": 12, + "title": "Recorded" + }, + "refreshFailed": false + } + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + }, + "7a97965fe49a": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "861c8796ae1f": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "a73b8a815948": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-8", + "ok": false + } + } + }, + "a7e609fcb031": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "b242c87f7cf1": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-8", + "ok": true + } + } + }, + "bfedf583a747": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-8", + "ok": true, + "result": { + "body": "body", + "comments": [ + { + "author": "rev", + "body": "please fix", + "createdAt": "2026-01-01T00:00:00Z", + "id": 55, + "isResolved": false, + "line": 3, + "path": "src/app.ts", + "threadId": "thread-1", + "url": "https://github.com/owner/repo/pull/12#discussion_r55" + } + ], + "headSha": "head-sha-1", + "item": { + "assignees": [], + "id": "PR_1", + "labels": [], + "number": 12, + "state": "open", + "title": "Recorded", + "type": "pr", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "caea72638868": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "d006e932f1bf": { + "name": "github.workItemDetails#1", + "ordinal": 15, "args": [ { "name": "method", @@ -265,9 +889,9 @@ } } }, - "553539d5f778": { + "dda65ec60f03": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -295,296 +919,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", - "ok": true - } - } - }, - "5a5e8aeb9c0f": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "checks": ["build:success"], - "checksError": { - "$rpc": "null" - }, - "comments": [], - "kind": "ready", - "pr": { - "headSha": "head-sha-1", - "number": 12, - "title": "Recorded" - }, - "refreshFailed": false - } - }, - "707f5273fbe1": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - } - }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } - } - }, - "87ba39148f02": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] - } - } - }, - "94aa3113193b": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-7", - "ok": false - } - } - }, - "96e55cac0dab": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-7", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "9c952632b0c0": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "9d6b176701fc": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "$rpc": "null" @@ -592,237 +927,6 @@ } } }, - "9eeed6bde74f": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-7", - "ok": true, - "result": { - "error": "inner refused", - "ok": false - } - } - } - }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "befec9e6a3a2": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-7", - "ok": false - } - } - }, - "cb071b912510": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-7", - "ok": true, - "result": { - "body": "body", - "comments": [ - { - "author": "rev", - "body": "please fix", - "createdAt": "2026-01-01T00:00:00Z", - "id": 55, - "isResolved": false, - "line": 3, - "path": "src/app.ts", - "threadId": "thread-1", - "url": "https://github.com/owner/repo/pull/12#discussion_r55" - } - ], - "headSha": "head-sha-1", - "item": { - "assignees": [], - "id": "PR_1", - "labels": [], - "number": 12, - "state": "open", - "title": "Recorded", - "type": "pr", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - } - }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" - } - }, - "dded64e82310": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-7", - "ok": true, - "result": { - "error": { - "message": "inner refused" - }, - "ok": false - } - } - } - }, "e0a11d8a1005": { "commentError": { "$rpc": "null" @@ -848,6 +952,11 @@ "refreshFailed": false } }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -855,42 +964,6 @@ "value": { "$rpc": "undefined" } - }, - "fb8d97e83d5b": { - "name": "github.workItemDetails#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true - } - } } }, "recording": { @@ -899,13 +972,19 @@ { "id": "pr-sidebar-load.prelude:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -913,25 +992,55 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.prelude:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "caea72638868" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "7512c5d8922e", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -939,27 +1048,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.normal:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -967,27 +1106,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "553539d5f778" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "b242c87f7cf1" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-absent:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "b242c87f7cf1" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -995,27 +1164,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "9d6b176701fc" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "dda65ec60f03" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-null:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "dda65ec60f03" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1023,27 +1222,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "96e55cac0dab" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "1a5855cadb2d" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-ok-missing:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "1a5855cadb2d" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1051,27 +1280,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "9eeed6bde74f" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "5f7634e4c4d1" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-string-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "5f7634e4c4d1" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1079,27 +1338,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "dded64e82310" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "476aa8b45a85" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-object-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "476aa8b45a85" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1107,27 +1396,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "94aa3113193b" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "313cd9c49244" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "313cd9c49244" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1135,27 +1454,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "3c501939dd10" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "a73b8a815948" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "a73b8a815948" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1163,27 +1512,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "befec9e6a3a2" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "74b5741dc1b5" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.method-not-found:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "74b5741dc1b5" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1191,27 +1570,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "4dd3c3919d72" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "d006e932f1bf" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "d006e932f1bf" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1219,27 +1628,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "fb8d97e83d5b" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "7a97965fe49a" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "7a97965fe49a" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "c70e6fd19823"] } } ] diff --git a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-hostedreview.forbranch-1.json b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-hostedreview.forbranch-1.json index 4aa0fb791ce..939cf15753f 100644 --- a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-hostedreview.forbranch-1.json +++ b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-hostedreview.forbranch-1.json @@ -4,9 +4,14 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { - "01e44c5eb3a8": { + "0730389db3e9": { "name": "hostedReview.forBranch#1", - "ordinal": 3, + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "079bcff40c58": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", @@ -35,15 +40,20 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-2", - "ok": true, - "result": { - "error": "inner refused", - "ok": false - } + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-4", + "ok": false } } }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -79,19 +89,55 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + "16c650db3f9c": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true + } + } }, "1f5765918736": { "name": "github.repoSlug#1", "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { + "2076083f6899": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":null,\"currentHeadOid\":null}}" + }, + "2dc2ca47b4e7": { + "name": "github.prForBranch#1", + "ordinal": 9, "args": [ { "name": "method", @@ -100,6 +146,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -124,61 +171,6 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, "35045fa5a752": { "commentError": { "$rpc": "null" @@ -192,89 +184,19 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, - "36fa584ff08a": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-2", - "ok": false - } - } - }, - "3cfe7aea50b5": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "" - }, - "id": "frame-2", - "ok": false - } - } - }, - "3f2be140c6f4": { + "3a8e6b13f380": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "46d12ddbac74": { + "name": "github.prForBranch#1", + "ordinal": 9, "args": [ { "name": "method", @@ -309,7 +231,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-5", "ok": true, "result": { "fetchedAt": 0, @@ -327,6 +249,43 @@ } } }, + "4c53775d76f6": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": { + "$rpc": "null" + }, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -365,48 +324,9 @@ } } }, - "64aab527c6dd": { + "518f25fa616b": { "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "7057d3371d62": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, + "ordinal": 5, "args": [ { "name": "method", @@ -436,31 +356,33 @@ "settledAt": 0, "value": { "error": { - "code": "method_not_found", - "message": "Unknown method" + "code": "refused", + "message": "" }, - "id": "frame-2", + "id": "frame-4", "ok": false } } }, - "707f5273fbe1": { - "name": "github.prForBranch#1", - "ordinal": 8, + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", - "value": "github.prForBranch" + "value": "hostedReview.forBranch" }, { "name": "params", "value": { + "active": true, "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { + "linkedGitHubPR": { "$rpc": "null" }, "repo": "id:repo-9" @@ -469,7 +391,6 @@ { "name": "options", "value": { - "beforeSend": "[local beforeSend]", "failWhenDisconnected": true } } @@ -482,60 +403,20 @@ "id": "frame-4", "ok": true, "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" } } } }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } - } - }, - "87ba39148f02": { + "861c8796ae1f": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -561,7 +442,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-5", + "id": "frame-6", "ok": true, "result": [ { @@ -574,9 +455,166 @@ } } }, - "8a392c6391f4": { + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "a7e609fcb031": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "ab3fbaf57733": { "name": "hostedReview.forBranch#1", - "ordinal": 3, + "ordinal": 5, "args": [ { "name": "method", @@ -605,7 +643,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-2", + "id": "frame-4", "ok": true, "result": { "error": { @@ -616,83 +654,9 @@ } } }, - "8fee46bf95e3": { + "ac0c5c576c24": { "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "transport failure", - "isRpcDeliveryUnknown": true - } - } - }, - "955df7128577": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": { - "$rpc": "null" - }, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "9787a82ed96e": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, + "ordinal": 5, "args": [ { "name": "method", @@ -727,52 +691,22 @@ } } }, - "9c952632b0c0": { - "name": "status.get#1", - "ordinal": 11, + "bb380bbd63c8": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", - "value": "status.get" + "value": "hostedReview.forBranch" }, { "name": "params", "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "cb071b912510": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, "repo": "id:repo-9" } }, @@ -784,18 +718,22 @@ } ], "settlement": { - "status": "pending", - "startedAt": 0 + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } } }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -823,7 +761,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -856,15 +794,52 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "ccd83e3fbb1c": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true + } } }, "e0a11d8a1005": { @@ -892,10 +867,49 @@ "refreshFailed": false } }, - "e6d7037c4df4": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":null,\"currentHeadOid\":null}}" + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "ea43d65aa61c": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "error": "refused" + } + } + } }, "eb79a9b3682a": { "status": "fulfilled", @@ -905,9 +919,9 @@ "$rpc": "undefined" } }, - "edf124c35a74": { + "f6329ebf9a21": { "name": "hostedReview.forBranch#1", - "ordinal": 3, + "ordinal": 5, "args": [ { "name": "method", @@ -936,49 +950,53 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-2", + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-4", + "ok": false + } + } + }, + "f8ff4d00b6b5": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", "ok": true, "result": { "$rpc": "null" } } } - }, - "fabc9971bcc9": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true - } - } } }, "recording": { @@ -987,13 +1005,19 @@ { "id": "pr-sidebar-load.normal:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1001,25 +1025,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1027,39 +1052,75 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.normal:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.result-absent:branch-hint", "observation": { - "sender": ["1287167eaf56", "fabc9971bcc9", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "16c650db3f9c", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1067,25 +1128,26 @@ "observation": { "sender": [ "1287167eaf56", - "fabc9971bcc9", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "16c650db3f9c", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1093,39 +1155,75 @@ "observation": { "sender": [ "1287167eaf56", - "fabc9971bcc9", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "16c650db3f9c", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-absent:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "16c650db3f9c", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.result-null:branch-hint", "observation": { - "sender": ["1287167eaf56", "edf124c35a74", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "f8ff4d00b6b5", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1133,25 +1231,26 @@ "observation": { "sender": [ "1287167eaf56", - "edf124c35a74", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "f8ff4d00b6b5", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1159,39 +1258,75 @@ "observation": { "sender": [ "1287167eaf56", - "edf124c35a74", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "f8ff4d00b6b5", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-null:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "f8ff4d00b6b5", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.inner-ok-missing:branch-hint", "observation": { - "sender": ["1287167eaf56", "64aab527c6dd", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "ea43d65aa61c", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1199,25 +1334,26 @@ "observation": { "sender": [ "1287167eaf56", - "64aab527c6dd", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "ea43d65aa61c", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1225,39 +1361,75 @@ "observation": { "sender": [ "1287167eaf56", - "64aab527c6dd", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "ea43d65aa61c", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-ok-missing:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "ea43d65aa61c", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.inner-false-string-error:branch-hint", "observation": { - "sender": ["1287167eaf56", "01e44c5eb3a8", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "bb380bbd63c8", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1265,25 +1437,26 @@ "observation": { "sender": [ "1287167eaf56", - "01e44c5eb3a8", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "bb380bbd63c8", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1291,39 +1464,75 @@ "observation": { "sender": [ "1287167eaf56", - "01e44c5eb3a8", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "bb380bbd63c8", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-string-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "bb380bbd63c8", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.inner-false-object-error:branch-hint", "observation": { - "sender": ["1287167eaf56", "8a392c6391f4", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "ab3fbaf57733", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1331,25 +1540,26 @@ "observation": { "sender": [ "1287167eaf56", - "8a392c6391f4", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "ab3fbaf57733", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1357,39 +1567,75 @@ "observation": { "sender": [ "1287167eaf56", - "8a392c6391f4", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "ab3fbaf57733", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-object-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "ab3fbaf57733", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.outer-refused:branch-hint", "observation": { - "sender": ["1287167eaf56", "36fa584ff08a", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "f6329ebf9a21", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1397,25 +1643,26 @@ "observation": { "sender": [ "1287167eaf56", - "36fa584ff08a", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "f6329ebf9a21", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1423,39 +1670,75 @@ "observation": { "sender": [ "1287167eaf56", - "36fa584ff08a", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "f6329ebf9a21", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "f6329ebf9a21", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.outer-refused-no-message:branch-hint", "observation": { - "sender": ["1287167eaf56", "3cfe7aea50b5", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "518f25fa616b", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1463,25 +1746,26 @@ "observation": { "sender": [ "1287167eaf56", - "3cfe7aea50b5", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "518f25fa616b", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1489,39 +1773,75 @@ "observation": { "sender": [ "1287167eaf56", - "3cfe7aea50b5", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "518f25fa616b", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "518f25fa616b", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.method-not-found:branch-hint", "observation": { - "sender": ["1287167eaf56", "7057d3371d62", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "079bcff40c58", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1529,25 +1849,26 @@ "observation": { "sender": [ "1287167eaf56", - "7057d3371d62", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "079bcff40c58", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1555,39 +1876,75 @@ "observation": { "sender": [ "1287167eaf56", - "7057d3371d62", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "079bcff40c58", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.method-not-found:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "079bcff40c58", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.transport-rejection:branch-hint", "observation": { - "sender": ["1287167eaf56", "8fee46bf95e3", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "ccd83e3fbb1c", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1595,25 +1952,26 @@ "observation": { "sender": [ "1287167eaf56", - "8fee46bf95e3", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "ccd83e3fbb1c", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1621,39 +1979,75 @@ "observation": { "sender": [ "1287167eaf56", - "8fee46bf95e3", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "ccd83e3fbb1c", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "ccd83e3fbb1c", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.transport-rejection-no-message:branch-hint", "observation": { - "sender": ["1287167eaf56", "9787a82ed96e", "4da7ea39401b", "955df7128577"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "e6d7037c4df4"], + "sender": ["1287167eaf56", "4da7ea39401b", "ac0c5c576c24", "4c53775d76f6"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1661,25 +2055,26 @@ "observation": { "sender": [ "1287167eaf56", - "9787a82ed96e", "4da7ea39401b", - "3f2be140c6f4", - "cb071b912510", - "9c952632b0c0" + "ac0c5c576c24", + "46d12ddbac74", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1687,27 +2082,57 @@ "observation": { "sender": [ "1287167eaf56", - "9787a82ed96e", "4da7ea39401b", - "3f2be140c6f4", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "ac0c5c576c24", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "e6d7037c4df4", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "ac0c5c576c24", + "46d12ddbac74", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "2076083f6899", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } } ] diff --git a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-status.get-1.json b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-status.get-1.json index 8bdc4867580..00a29cb5ece 100644 --- a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-status.get-1.json +++ b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-status.get-1.json @@ -4,9 +4,9 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { - "070b061bf3fa": { + "0579dde9370e": { "name": "status.get#1", - "ordinal": 11, + "ordinal": 12, "args": [ { "name": "method", @@ -32,15 +32,24 @@ "startedAt": 0, "settledAt": 0, "value": { - "error": { - "code": "refused", - "message": "" - }, - "id": "frame-6", - "ok": false + "id": "frame-7", + "ok": true, + "result": { + "$rpc": "null" + } } } }, + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -76,14 +85,9 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, - "18e63ddf28fe": { + "1287efa543e2": { "name": "status.get#1", - "ordinal": 11, + "ordinal": 12, "args": [ { "name": "method", @@ -105,22 +109,19 @@ } ], "settlement": { - "status": "fulfilled", + "status": "rejected", "startedAt": 0, "settledAt": 0, - "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-6", - "ok": false + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true } } }, - "1b45b070f3e6": { + "1a73e54fca55": { "name": "status.get#2", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -151,9 +152,20 @@ "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { + "21069b5e026b": { + "name": "streams-registered-at-teardown", + "ordinal": 15, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "2dc2ca47b4e7": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -162,6 +174,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -186,34 +199,26 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, + "30603c5b4d53": { + "name": "status.get#1", + "ordinal": 12, "args": [ { "name": "method", - "value": "hostedReview.forBranch" + "value": "status.get" }, { "name": "params", "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" + "$rpc": "undefined" } }, { "name": "options", "value": { - "failWhenDisconnected": true + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 } } ], @@ -222,25 +227,15 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-7", + "ok": false } } }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, "35045fa5a752": { "commentError": { "$rpc": "null" @@ -254,6 +249,16 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -311,9 +316,119 @@ "refreshFailed": false } }, - "639ee016d5fa": { - "name": "status.get#1", + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "7512c5d8922e": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "checks": ["build:success"], + "checksError": { + "$rpc": "null" + }, + "comments": "loading", + "kind": "ready", + "pr": { + "headSha": "head-sha-1", + "number": 12, + "title": "Recorded" + }, + "refreshFailed": false + } + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + }, + "861c8796ae1f": { + "name": "github.prChecks#1", "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, "args": [ { "name": "method", @@ -335,19 +450,102 @@ } ], "settlement": { - "status": "rejected", + "status": "pending", + "startedAt": 0 + } + }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", "startedAt": 0, "settledAt": 0, - "error": { - "category": "Error", - "message": "transport failure", - "isRpcDeliveryUnknown": true + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } } } }, - "707f5273fbe1": { - "name": "github.prForBranch#1", + "9091d133c3b0": { + "name": "reply-salvage", "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "96ad436bfa1d": { + "name": "status.get#2", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "9b384c87ef98": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } + } + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, "args": [ { "name": "method", @@ -356,6 +554,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -380,7 +579,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-5", "ok": true, "result": { "fetchedAt": 0, @@ -398,9 +597,9 @@ } } }, - "725177241005": { + "a6e599be5005": { "name": "status.get#1", - "ordinal": 11, + "ordinal": 12, "args": [ { "name": "method", @@ -426,7 +625,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-6", + "id": "frame-7", "ok": true, "result": { "error": "refused" @@ -434,69 +633,9 @@ } } }, - "7512c5d8922e": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "checks": ["build:success"], - "checksError": { - "$rpc": "null" - }, - "comments": "loading", - "kind": "ready", - "pr": { - "headSha": "head-sha-1", - "number": 12, - "title": "Recorded" - }, - "refreshFailed": false - } - }, - "827779de86bf": { - "name": "status.get#2", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } - } - }, - "87ba39148f02": { + "a7e609fcb031": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -517,168 +656,14 @@ } } ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] - } - } - }, - "8acaf63197a5": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "$rpc": "null" - } - } - } - }, - "96f70a0f4340": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true - } - } - }, - "9c952632b0c0": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], "settlement": { "status": "pending", "startedAt": 0 } }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "af7f3973dbfb": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "error": { - "message": "inner refused" - }, - "ok": false - } - } - } - }, - "b7fd114dbf3d": { - "name": "status.get#1", - "ordinal": 11, + "b3d8199239f7": { + "name": "status.get#2", + "ordinal": 15, "args": [ { "name": "method", @@ -705,84 +690,14 @@ "settledAt": 0, "error": { "category": "Error", - "message": "", + "message": "Connection closed", "isRpcDeliveryUnknown": true } } }, - "c8f187d4ae2c": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-6", - "ok": false - } - } - }, - "cb071b912510": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -810,7 +725,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -843,15 +758,85 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "ccabffd679ab": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-7", + "ok": false + } + } + }, + "d98b8776ee3f": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true + } } }, "e0a11d8a1005": { @@ -879,6 +864,45 @@ "refreshFailed": false } }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "e177169d7bc8": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -887,9 +911,9 @@ "$rpc": "undefined" } }, - "ee35f6d45b0b": { + "ed8f9a8b7596": { "name": "status.get#1", - "ordinal": 11, + "ordinal": 12, "args": [ { "name": "method", @@ -915,14 +939,87 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-6", + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-7", + "ok": false + } + } + }, + "f276888d56f7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", "ok": true, "result": { - "error": "inner refused", + "error": { + "message": "inner refused" + }, "ok": false } } } + }, + "ff6c5e987ede": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true + } + } } }, "recording": { @@ -931,13 +1028,19 @@ { "id": "pr-sidebar-load.prelude:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -945,25 +1048,53 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.prelude:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "1287efa543e2" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "7512c5d8922e", + "effects": ["9091d133c3b0", "21069b5e026b"] } }, { @@ -971,27 +1102,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.normal:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -999,25 +1160,53 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "96f70a0f4340" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "d98b8776ee3f" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-absent:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "d98b8776ee3f" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "21069b5e026b"] } }, { @@ -1025,25 +1214,53 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8acaf63197a5" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "0579dde9370e" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.result-null:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "0579dde9370e" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "21069b5e026b"] } }, { @@ -1051,27 +1268,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "725177241005", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "a6e599be5005", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-ok-missing:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "a6e599be5005", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1079,27 +1326,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "ee35f6d45b0b", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "9b384c87ef98", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-string-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "9b384c87ef98", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1107,27 +1384,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "af7f3973dbfb", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "f276888d56f7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.inner-false-object-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "f276888d56f7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1135,25 +1442,53 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "c8f187d4ae2c" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "ccabffd679ab" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "ccabffd679ab" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "21069b5e026b"] } }, { @@ -1161,25 +1496,53 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "070b061bf3fa" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "ed8f9a8b7596" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.outer-refused-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "ed8f9a8b7596" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "21069b5e026b"] } }, { @@ -1187,25 +1550,53 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "18e63ddf28fe" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "30603c5b4d53" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "5a5e8aeb9c0f", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.method-not-found:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "30603c5b4d53" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "5a5e8aeb9c0f", + "effects": ["9091d133c3b0", "21069b5e026b"] } }, { @@ -1213,27 +1604,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "639ee016d5fa", - "1b45b070f3e6" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "ff6c5e987ede", + "1a73e54fca55" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "827779de86bf" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "96ad436bfa1d" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "7512c5d8922e", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "ff6c5e987ede", + "b3d8199239f7" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "96ad436bfa1d" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "7512c5d8922e", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { @@ -1241,27 +1662,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "b7fd114dbf3d", - "1b45b070f3e6" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "e177169d7bc8", + "1a73e54fca55" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "827779de86bf" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "96ad436bfa1d" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "7512c5d8922e", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.transport-rejection-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "e177169d7bc8", + "b3d8199239f7" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "96ad436bfa1d" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "7512c5d8922e", + "effects": ["9091d133c3b0", "c70e6fd19823"] } } ] diff --git a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-worktree.show-1.json b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-worktree.show-1.json index 1fc659680c1..d80bfe65746 100644 --- a/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-worktree.show-1.json +++ b/mobile/rpc-foundation/goldens/matrix-session.pr-sidebar-worktree.show-1.json @@ -4,6 +4,16 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -39,39 +49,6 @@ } } }, - "132359f59155": { - "name": "status.get#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, "1a8422eae0e3": { "name": "worktree.show#1", "ordinal": 4, @@ -112,91 +89,6 @@ "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, "2a98ce3bea80": { "name": "worktree.show#1", "ordinal": 4, @@ -231,10 +123,16 @@ } } }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + "2b9f6f1218e4": { + "name": "streams-registered-at-teardown", + "ordinal": 16, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] }, "2c7b67501f26": { "name": "worktree.show#1", @@ -270,25 +168,33 @@ } } }, - "328a2eb7b1e2": { - "name": "github.prChecks#1", + "2dc2ca47b4e7": { + "name": "github.prForBranch#1", "ordinal": 9, "args": [ { "name": "method", - "value": "github.prChecks" + "value": "github.prForBranch" }, { "name": "params", "value": { - "headSha": "head-sha-1", - "prNumber": 12, + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, "repo": "id:repo-9" } }, { "name": "options", "value": { + "beforeSend": "[local beforeSend]", "failWhenDisconnected": true } } @@ -311,6 +217,21 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, + "3744812c5fcd": { + "name": "status.get#1", + "ordinal": 13, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "40b75de17700": { "name": "worktree.show#1", "ordinal": 4, @@ -346,6 +267,83 @@ } } }, + "4776354b25fa": { + "name": "status.get#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "4a2114bd1b7d": { + "name": "github.prChecks#1", + "ordinal": 10, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -384,6 +382,16 @@ } } }, + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "6a20150792b1": { + "name": "github.prForBranch#1", + "ordinal": 9, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, "704943f0f395": { "name": "worktree.show#1", "ordinal": 4, @@ -415,59 +423,6 @@ } } }, - "707f5273fbe1": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - } - }, "7167083ab4d9": { "name": "worktree.show#1", "ordinal": 4, @@ -503,36 +458,29 @@ } } }, - "76263332f0a0": { - "name": "github.prChecks#1", - "ordinal": 11, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, - "7a16946f2448": { - "name": "status.get#1", - "ordinal": 12, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", - "value": "status.get" + "value": "hostedReview.forBranch" }, { "name": "params", "value": { - "$rpc": "undefined" + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" } }, { "name": "options", "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 + "failWhenDisconnected": true } } ], @@ -541,17 +489,77 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-6", + "id": "frame-4", "ok": true, "result": { - "runtimeId": "recorded" + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" } } } }, - "87ba39148f02": { + "804a8709b78c": { + "name": "github.prForBranch#1", + "ordinal": 8, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "861c8796ae1f": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -577,7 +585,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-5", + "id": "frame-6", "ok": true, "result": [ { @@ -590,6 +598,34 @@ } } }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, "8b7816464095": { "name": "worktree.show#1", "ordinal": 4, @@ -622,6 +658,42 @@ } } }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, "8f20397f6101": { "name": "worktree.show#1", "ordinal": 4, @@ -659,73 +731,21 @@ } } }, - "92c7d3e81fc6": { - "name": "github.workItemDetails#1", - "ordinal": 13, - "args": [ - { - "name": "method", - "value": "github.workItemDetails" - }, - { - "name": "params", - "value": { - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-7", - "ok": true, - "result": { - "body": "body", - "comments": [ - { - "author": "rev", - "body": "please fix", - "createdAt": "2026-01-01T00:00:00Z", - "id": 55, - "isResolved": false, - "line": 3, - "path": "src/app.ts", - "threadId": "thread-1", - "url": "https://github.com/owner/repo/pull/12#discussion_r55" - } - ], - "headSha": "head-sha-1", - "item": { - "assignees": [], - "id": "PR_1", - "labels": [], - "number": 12, - "state": "open", - "title": "Recorded", - "type": "pr", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" } }, - "956724a74728": { - "name": "github.prForBranch#1", - "ordinal": 8, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" + "9300396ee3f6": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" }, "9c952632b0c0": { "name": "status.get#1", @@ -755,47 +775,6 @@ "startedAt": 0 } }, - "9e3f98425211": { - "name": "github.prChecks#1", - "ordinal": 9, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] - } - } - }, "a038c89eda45": { "name": "worktree.show#1", "ordinal": 4, @@ -831,14 +810,9 @@ } } }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "ca31a249027a": { + "a55c83eeaeea": { "name": "github.prForBranch#1", - "ordinal": 7, + "ordinal": 9, "args": [ { "name": "method", @@ -847,6 +821,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -867,13 +842,31 @@ } ], "settlement": { - "status": "pending", - "startedAt": 0 + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } } }, - "cb071b912510": { + "a7e609fcb031": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -899,50 +892,50 @@ "startedAt": 0 } }, - "d1ee08e03daa": { - "name": "status.get#1", - "ordinal": 10, + "ad0c6d91ae2c": { + "name": "github.prChecks#1", + "ordinal": 12, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, + "b3a7ec3ab1c7": { + "name": "github.prForBranch#1", + "ordinal": 8, "args": [ { "name": "method", - "value": "status.get" + "value": "github.prForBranch" }, { "name": "params", "value": { - "$rpc": "undefined" + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" } }, { "name": "options", "value": { "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 + "failWhenDisconnected": true } } ], "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } + "status": "pending", + "startedAt": 0 } }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -970,7 +963,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -1003,15 +996,43 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "cb071b912510": { + "name": "github.prChecks#1", + "ordinal": 10, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 } }, "e0a11d8a1005": { @@ -1039,6 +1060,11 @@ "refreshFailed": false } }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, "eadd2f60a3d9": { "name": "worktree.show#1", "ordinal": 4, @@ -1079,38 +1105,28 @@ "$rpc": "undefined" } }, - "edb9efe1b656": { + "f8cc8c00c5dd": { "name": "github.workItemDetails#1", "ordinal": 14, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, - "fdd3e0b4c48b": { - "name": "github.prForBranch#1", - "ordinal": 7, "args": [ { "name": "method", - "value": "github.prForBranch" + "value": "github.workItemDetails" }, { "name": "params", "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" + "number": 12, + "repo": "id:repo-9", + "type": "pr" } }, { "name": "options", "value": { "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true + "failWhenDisconnected": true, + "timeoutMs": 30000 } } ], @@ -1119,17 +1135,32 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-8", "ok": true, "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", + "body": "body", + "comments": [ + { + "author": "rev", + "body": "please fix", + "createdAt": "2026-01-01T00:00:00Z", + "id": 55, + "isResolved": false, + "line": 3, + "path": "src/app.ts", + "threadId": "thread-1", + "url": "https://github.com/owner/repo/pull/12#discussion_r55" + } + ], + "headSha": "head-sha-1", + "item": { + "assignees": [], + "id": "PR_1", + "labels": [], "number": 12, "state": "open", "title": "Recorded", + "type": "pr", "updatedAt": "2026-01-01T00:00:00Z", "url": "https://github.com/owner/repo/pull/12" } @@ -1144,13 +1175,19 @@ { "id": "pr-sidebar-load.normal:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1158,25 +1195,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -1184,34 +1222,70 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr-sidebar-load.normal:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } }, { "id": "pr-sidebar-load.result-absent:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "704943f0f395", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "704943f0f395", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1224,19 +1298,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "704943f0f395", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1250,21 +1325,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "704943f0f395", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1273,11 +1349,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.result-absent:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "704943f0f395", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.result-null:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "2a98ce3bea80", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "2a98ce3bea80", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1290,19 +1401,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "2a98ce3bea80", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1316,21 +1428,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "2a98ce3bea80", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1339,11 +1452,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.result-null:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "2a98ce3bea80", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.inner-ok-missing:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "2c7b67501f26", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "2c7b67501f26", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1356,19 +1504,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "2c7b67501f26", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1382,21 +1531,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "2c7b67501f26", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1405,11 +1555,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.inner-ok-missing:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "2c7b67501f26", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.inner-false-string-error:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "a038c89eda45", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "a038c89eda45", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1422,19 +1607,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "a038c89eda45", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1448,21 +1634,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "a038c89eda45", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1471,11 +1658,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.inner-false-string-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "a038c89eda45", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.inner-false-object-error:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "8f20397f6101", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "8f20397f6101", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1488,19 +1710,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "8f20397f6101", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1514,21 +1737,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "8f20397f6101", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1537,11 +1761,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.inner-false-object-error:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "8f20397f6101", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.outer-refused:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "7167083ab4d9", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "7167083ab4d9", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1554,19 +1813,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "7167083ab4d9", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1580,21 +1840,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "7167083ab4d9", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1603,11 +1864,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.outer-refused:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "7167083ab4d9", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.outer-refused-no-message:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "40b75de17700", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "40b75de17700", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1620,19 +1916,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "40b75de17700", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1646,21 +1943,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "40b75de17700", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1669,11 +1967,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.outer-refused-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "40b75de17700", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.method-not-found:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "1a8422eae0e3", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "1a8422eae0e3", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1686,19 +2019,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "1a8422eae0e3", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1712,21 +2046,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "1a8422eae0e3", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1735,11 +2070,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.method-not-found:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "1a8422eae0e3", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.transport-rejection:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "eadd2f60a3d9", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "eadd2f60a3d9", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1752,19 +2122,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "eadd2f60a3d9", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1778,21 +2149,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "eadd2f60a3d9", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1801,11 +2173,46 @@ "effects": [] } }, + { + "id": "pr-sidebar-load.transport-rejection:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "eadd2f60a3d9", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } + }, { "id": "pr-sidebar-load.transport-rejection-no-message:branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "8b7816464095", "ca31a249027a"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "956724a74728"], + "sender": ["1287167eaf56", "8b7816464095", "75885386f005", "b3a7ec3ab1c7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1" + ], "settlements": { "mount": "eb79a9b3682a" }, @@ -1818,19 +2225,20 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "8b7816464095", - "fdd3e0b4c48b", - "328a2eb7b1e2", - "132359f59155" + "75885386f005", + "804a8709b78c", + "cb071b912510", + "9c952632b0c0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd" ], "settlements": { "mount": "eb79a9b3682a" @@ -1844,21 +2252,22 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "8b7816464095", - "fdd3e0b4c48b", - "9e3f98425211", - "d1ee08e03daa", - "92c7d3e81fc6" + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "956724a74728", - "76263332f0a0", - "7a16946f2448", - "edb9efe1b656" + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" ], "settlements": { "mount": "eb79a9b3682a" @@ -1866,6 +2275,35 @@ "state": "e0a11d8a1005", "effects": [] } + }, + { + "id": "pr-sidebar-load.transport-rejection-no-message:cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "8b7816464095", + "75885386f005", + "804a8709b78c", + "4a2114bd1b7d", + "4776354b25fa", + "f8cc8c00c5dd" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "6a20150792b1", + "ad0c6d91ae2c", + "3744812c5fcd", + "9300396ee3f6" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["2b9f6f1218e4"] + } } ] } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-github-github.addissuecomment-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-github-github.addissuecomment-1.json index 222221a0b91..d2c96c4112f 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-github-github.addissuecomment-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-github-github.addissuecomment-1.json @@ -97,11 +97,6 @@ "targetKey": "repo-1\u0000owner/repo\u0000issue\u00009" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "21d560a20bed": { "name": "error", "ordinal": 14, @@ -300,11 +295,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "5737a7806a0c": { "name": "mutatingStatus", "ordinal": 15, @@ -562,6 +552,11 @@ "targetKey": "repo-1\u0000owner/repo\u0000issue\u00009" } }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, "948fc1352362": { "name": "github.addIssueComment#1", "ordinal": 11, @@ -741,6 +736,11 @@ "targetKey": "repo-1\u0000owner/repo\u0000issue\u00009" } }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "ae745d4c2372": { "name": "detailPayload", "ordinal": 14, @@ -1394,8 +1394,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ae745d4c2372", @@ -1422,8 +1422,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ffd879a2e2be", @@ -1449,8 +1449,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ffd879a2e2be", @@ -1476,8 +1476,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "fa158073af7f", @@ -1504,8 +1504,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "21d560a20bed", @@ -1531,8 +1531,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "cc399e1bb52f", @@ -1559,8 +1559,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "cb543ce964ae", @@ -1586,8 +1586,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", @@ -1613,8 +1613,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "36782b753721", @@ -1640,8 +1640,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "f65e0af02b52", @@ -1667,8 +1667,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-gitlab.addissuecomment-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-gitlab.addissuecomment-1.json index b81073c14b1..c5046f71ae8 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-gitlab.addissuecomment-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-gitlab.addissuecomment-1.json @@ -107,11 +107,6 @@ "provider": "gitlab" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "21d560a20bed": { "name": "error", "ordinal": 14, @@ -313,11 +308,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "5737a7806a0c": { "name": "mutatingStatus", "ordinal": 15, @@ -414,6 +404,11 @@ "provider": "gitlab" } }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, "9932bdaf3500": { "draft": "a comment", "error": "The host sent a reply this app could not read (gitlab.addIssueComment)", @@ -529,6 +524,11 @@ } } }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "ad33e328b827": { "name": "gitlab.addIssueComment#1", "ordinal": 13, @@ -1020,8 +1020,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "02b5df9521e8", @@ -1048,8 +1048,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "d0afe3374825", @@ -1075,8 +1075,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "d0afe3374825", @@ -1102,8 +1102,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "8a21f81d9fc4", @@ -1130,8 +1130,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "21d560a20bed", @@ -1157,8 +1157,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "d986773c38a9", @@ -1185,8 +1185,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "cb543ce964ae", @@ -1212,8 +1212,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", @@ -1239,8 +1239,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "36782b753721", @@ -1266,8 +1266,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "f65e0af02b52", @@ -1293,8 +1293,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-mr-gitlab.addmrcomment-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-mr-gitlab.addmrcomment-1.json index 1e526bae61f..d7ecfd19a58 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-mr-gitlab.addmrcomment-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.item-comment-gitlab-mr-gitlab.addmrcomment-1.json @@ -51,11 +51,6 @@ "provider": "gitlab" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "21d560a20bed": { "name": "error", "ordinal": 14, @@ -146,11 +141,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "5737a7806a0c": { "name": "mutatingStatus", "ordinal": 15, @@ -406,6 +396,11 @@ } } }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, "965bf7fe4cd8": { "draft": "a comment", "error": "Unknown method", @@ -523,6 +518,11 @@ } } }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "b6c88ff35429": { "draft": "a comment", "error": "inner refused", @@ -1020,8 +1020,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "f3cb1a7df6dc", @@ -1048,8 +1048,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "1e866e52fed3", @@ -1075,8 +1075,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "1e866e52fed3", @@ -1102,8 +1102,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "8a21f81d9fc4", @@ -1130,8 +1130,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "21d560a20bed", @@ -1157,8 +1157,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "de7b906df67a", @@ -1185,8 +1185,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "cb543ce964ae", @@ -1212,8 +1212,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", @@ -1239,8 +1239,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "36782b753721", @@ -1266,8 +1266,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "f65e0af02b52", @@ -1293,8 +1293,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.prchecks-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.prchecks-1.json index 4eed3994ef1..5528b3ed142 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.prchecks-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.prchecks-1.json @@ -276,11 +276,6 @@ "title": "A pull request" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "22b1e4293201": { "name": "mutatingStatus", "ordinal": 28, @@ -628,11 +623,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "593c53b594c5": { "draft": "a comment", "error": "", @@ -1138,6 +1128,11 @@ "ordinal": 12, "value": true }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, "94caa29bceef": { "name": "error", "ordinal": 19, @@ -1153,6 +1148,11 @@ "ordinal": 25, "value": "The host sent a reply this app could not read (github.prChecks)" }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "acff45feb249": { "name": "mutatingStatus", "ordinal": 26, @@ -1663,8 +1663,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1694,8 +1694,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1731,8 +1731,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1766,8 +1766,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1801,8 +1801,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1836,8 +1836,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1871,8 +1871,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1906,8 +1906,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1941,8 +1941,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1976,8 +1976,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -2011,8 +2011,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -2046,8 +2046,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.requestprreviewers-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.requestprreviewers-1.json index 7e5912c4c24..a1e16784ad0 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.requestprreviewers-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-github.requestprreviewers-1.json @@ -268,11 +268,6 @@ "title": "A pull request" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "21d560a20bed": { "name": "error", "ordinal": 14, @@ -580,11 +575,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "5737a7806a0c": { "name": "mutatingStatus", "ordinal": 15, @@ -1288,6 +1278,11 @@ } } }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, "949da9fa9fb2": { "name": "github.requestPRReviewers#1", "ordinal": 11, @@ -1632,6 +1627,11 @@ "targetKey": "repo-1\u0000owner/repo\u0000pr\u000012" } }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "acff45feb249": { "name": "mutatingStatus", "ordinal": 26, @@ -2384,8 +2384,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -2415,8 +2415,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -2451,8 +2451,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "407af7575a68", @@ -2479,8 +2479,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "407af7575a68", @@ -2512,8 +2512,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "407af7575a68", @@ -2540,8 +2540,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "407af7575a68", @@ -2573,8 +2573,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -2604,8 +2604,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -2640,8 +2640,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "21d560a20bed", @@ -2668,8 +2668,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "21d560a20bed", @@ -2701,8 +2701,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "124bef35e9e5", @@ -2730,8 +2730,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "124bef35e9e5", @@ -2764,8 +2764,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "cb543ce964ae", @@ -2792,8 +2792,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "cb543ce964ae", @@ -2825,8 +2825,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", @@ -2853,8 +2853,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", @@ -2886,8 +2886,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "36782b753721", @@ -2914,8 +2914,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "36782b753721", @@ -2947,8 +2947,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "f65e0af02b52", @@ -2975,8 +2975,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "f65e0af02b52", @@ -3008,8 +3008,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", @@ -3036,8 +3036,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ef8932b03a8c", diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-pr-check-discovery.json b/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-pr-check-discovery.json index bc5453d504b..c4b1edf7823 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-pr-check-discovery.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.item-review-github-pr-check-discovery.json @@ -244,11 +244,6 @@ } } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "22b1e4293201": { "name": "mutatingStatus", "ordinal": 28, @@ -454,11 +449,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "593c53b594c5": { "draft": "a comment", "error": "", @@ -798,6 +788,11 @@ "ordinal": 12, "value": true }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, "94caa29bceef": { "name": "error", "ordinal": 19, @@ -841,6 +836,11 @@ "ordinal": 18, "value": false }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "ace73bafef56": { "name": "status.get#1", "ordinal": 20, @@ -1187,8 +1187,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1218,8 +1218,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1255,8 +1255,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1292,8 +1292,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1329,8 +1329,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1366,8 +1366,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1403,8 +1403,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1440,8 +1440,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1477,8 +1477,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1514,8 +1514,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1551,8 +1551,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -1588,8 +1588,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.linear-item-linear.addissuecomment-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.linear-item-linear.addissuecomment-1.json index efebc9b7b8a..86cc6641a63 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.linear-item-linear.addissuecomment-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.linear-item-linear.addissuecomment-1.json @@ -383,39 +383,20 @@ "provider": "linear" } }, + "22b1e4293201": { + "name": "mutatingStatus", + "ordinal": 28, + "value": false + }, "29cadc65bcbb": { "name": "error", "ordinal": 15, "value": "" }, - "2ea9c99d4796": { - "name": "detailPayload", - "ordinal": 25, - "value": { - "assignee": { - "$rpc": "undefined" - }, - "children": [ - { - "id": "issue-3", - "identifier": "ENG-3", - "title": "A sub-issue", - "url": "" - } - ], - "comments": [], - "description": "description", - "labels": [], - "project": { - "$rpc": "null" - }, - "provider": "linear" - } - }, - "31dce0186d15": { - "name": "mutatingStatus", + "29ed7524dd3c": { + "name": "error", "ordinal": 22, - "value": true + "value": "" }, "335cdd96334f": { "error": "", @@ -588,11 +569,6 @@ "provider": "linear" } }, - "3f80db506009": { - "name": "linearSubIssueTitle", - "ordinal": 24, - "value": "" - }, "3fcdcfa261ee": { "name": "mutatingStatus", "ordinal": 23, @@ -645,11 +621,6 @@ "provider": "linear" } }, - "427b7993fe85": { - "name": "error", - "ordinal": 20, - "value": "" - }, "44efd00fa69f": { "name": "linearCommentDraft", "ordinal": 7, @@ -798,6 +769,11 @@ } } }, + "5348c8d60b38": { + "name": "linearCommentDraft", + "ordinal": 20, + "value": "" + }, "57207b51913e": { "name": "error", "ordinal": 12, @@ -876,49 +852,10 @@ "provider": "linear" } }, - "65b434738c91": { - "name": "linear.createIssue#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "linear.createIssue" - }, - { - "name": "params", - "value": { - "parentIssueId": "issue-1", - "projectId": { - "$rpc": "null" - }, - "teamId": "team-1", - "title": "A sub-issue", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "id": "issue-3", - "identifier": "ENG-3", - "ok": true, - "title": "A sub-issue", - "url": "" - } - } - } + "68003f9dae22": { + "name": "mutatingStatus", + "ordinal": 24, + "value": true }, "760659bea59b": { "name": "linear.addIssueComment#1", @@ -1074,11 +1011,6 @@ "ordinal": 12, "value": "outer refused" }, - "8167ff6bda4e": { - "name": "linear.createIssue#1", - "ordinal": 23, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"linear.createIssue\",\"params\":{\"teamId\":\"team-1\",\"title\":\"A sub-issue\",\"workspaceId\":\"linear-workspace\",\"parentIssueId\":\"issue-1\",\"projectId\":null}}" - }, "8427fd4151f1": { "name": "mutatingStatus", "ordinal": 14, @@ -1227,6 +1159,11 @@ "ordinal": 12, "value": "inner refused" }, + "9911a44bcc07": { + "name": "linearCommentDraft", + "ordinal": 21, + "value": "" + }, "99b079cb804c": { "name": "linear.addIssueComment#1", "ordinal": 9, @@ -1317,16 +1254,35 @@ } } }, + "9c6909125d76": { + "name": "detailPayload", + "ordinal": 27, + "value": { + "assignee": { + "$rpc": "undefined" + }, + "children": [ + { + "id": "issue-3", + "identifier": "ENG-3", + "title": "A sub-issue", + "url": "" + } + ], + "comments": [], + "description": "description", + "labels": [], + "project": { + "$rpc": "null" + }, + "provider": "linear" + } + }, "9dc1f136772e": { "name": "linearCommentDraft", "ordinal": 4, "value": "" }, - "acff45feb249": { - "name": "mutatingStatus", - "ordinal": 26, - "value": false - }, "b1f0308d3795": { "name": "actionItem", "ordinal": 5, @@ -1366,6 +1322,11 @@ "ordinal": 13, "value": "Failed to add comment" }, + "b2da94d284a1": { + "name": "linearSubIssueTitle", + "ordinal": 26, + "value": "" + }, "b71922b936d3": { "name": "linear.addIssueComment#1", "ordinal": 9, @@ -1516,6 +1477,50 @@ "updatedAt": "2020-01-01T00:00:00.000Z" } }, + "c4bd3e068c64": { + "name": "linear.createIssue#1", + "ordinal": 23, + "args": [ + { + "name": "method", + "value": "linear.createIssue" + }, + { + "name": "params", + "value": { + "parentIssueId": "issue-1", + "projectId": { + "$rpc": "null" + }, + "teamId": "team-1", + "title": "A sub-issue", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "id": "issue-3", + "identifier": "ENG-3", + "ok": true, + "title": "A sub-issue", + "url": "" + } + } + } + }, "c99df17a93d5": { "name": "linear.addIssueComment#1", "ordinal": 9, @@ -1728,6 +1733,11 @@ "ordinal": 13, "value": false }, + "e72b7c40f270": { + "name": "linear.createIssue#1", + "ordinal": 25, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"linear.createIssue\",\"params\":{\"teamId\":\"team-1\",\"title\":\"A sub-issue\",\"workspaceId\":\"linear-workspace\",\"parentIssueId\":\"issue-1\",\"projectId\":null}}" + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -2014,15 +2024,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.result-absent:sub-issue-create-settled", "observation": { - "sender": ["b71922b936d3", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["b71922b936d3", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2046,11 +2057,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } }, @@ -2105,15 +2117,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.result-null:sub-issue-create-settled", "observation": { - "sender": ["99b079cb804c", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["99b079cb804c", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2137,11 +2150,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } }, @@ -2290,15 +2304,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.inner-false-string-error:sub-issue-create-settled", "observation": { - "sender": ["8f6bc911a494", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["8f6bc911a494", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2322,11 +2337,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } }, @@ -2383,15 +2399,16 @@ "29cadc65bcbb", "4dd9211bea32", "3b3ee1b48010", - "3accbb2a4fcb" + "3accbb2a4fcb", + "9911a44bcc07" ] } }, { "id": "tk-linear-item.inner-false-object-error:sub-issue-create-settled", "observation": { - "sender": ["8786f555ebcb", "9c2ca99506b2", "039c2b59e061"], - "payloads": ["760659bea59b", "8e34e506a7f8", "88dbfd66d809"], + "sender": ["8786f555ebcb", "9c2ca99506b2", "c4bd3e068c64"], + "payloads": ["760659bea59b", "8e34e506a7f8", "e72b7c40f270"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2416,11 +2433,12 @@ "4dd9211bea32", "3b3ee1b48010", "3accbb2a4fcb", - "029bb83f402f", - "3fcdcfa261ee", - "7b614cf87045", - "1b7a093f724f", - "fa2f2de4dfe7" + "9911a44bcc07", + "29ed7524dd3c", + "68003f9dae22", + "b2da94d284a1", + "9c6909125d76", + "22b1e4293201" ] } }, @@ -2475,15 +2493,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.outer-refused:sub-issue-create-settled", "observation": { - "sender": ["d970b2195d6d", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["d970b2195d6d", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2507,11 +2526,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } }, @@ -2566,15 +2586,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.outer-refused-no-message:sub-issue-create-settled", "observation": { - "sender": ["167c8724b16b", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["167c8724b16b", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2598,11 +2619,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } }, @@ -2657,15 +2679,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.method-not-found:sub-issue-create-settled", "observation": { - "sender": ["5037193eac5c", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["5037193eac5c", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2689,11 +2712,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } }, @@ -2748,15 +2772,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.transport-rejection:sub-issue-create-settled", "observation": { - "sender": ["cad9f764ce58", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["cad9f764ce58", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2780,11 +2805,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } }, @@ -2839,15 +2865,16 @@ "ef8932b03a8c", "8ebaf0949b6d", "c39516152855", - "bbf2458754b4" + "bbf2458754b4", + "5348c8d60b38" ] } }, { "id": "tk-linear-item.transport-rejection-no-message:sub-issue-create-settled", "observation": { - "sender": ["0534215ae768", "1fa11661cd73", "65b434738c91"], - "payloads": ["760659bea59b", "da485104c1ac", "8167ff6bda4e"], + "sender": ["0534215ae768", "1fa11661cd73", "039c2b59e061"], + "payloads": ["760659bea59b", "da485104c1ac", "88dbfd66d809"], "settlements": { "mount": "eb79a9b3682a", "comment-0": "eb79a9b3682a", @@ -2871,11 +2898,12 @@ "8ebaf0949b6d", "c39516152855", "bbf2458754b4", - "427b7993fe85", - "31dce0186d15", - "3f80db506009", - "2ea9c99d4796", - "acff45feb249" + "5348c8d60b38", + "029bb83f402f", + "3fcdcfa261ee", + "7b614cf87045", + "1b7a093f724f", + "fa2f2de4dfe7" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.listteams-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.listteams-1.json index bfa6195e8f5..2660b5ebccb 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.listteams-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.listteams-1.json @@ -4,93 +4,14 @@ "family": "tasks.linear-team-context", "namedDeltas": [], "values": { - "0086e1c04b47": { + "031c50459130": { + "name": "createTeamId", + "ordinal": 10, + "value": "team-1" + }, + "0393503430d4": { "name": "linear.listTeams#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "linear.listTeams" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true - } - } - }, - "10b6d9eca9a8": { - "name": "linear.listTeams#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "linear.listTeams" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-1", - "ok": false - } - } - }, - "1288b8513745": { - "name": "linearStatesError", - "ordinal": 13, - "value": "" - }, - "2afc4b1311c1": { - "createTeamId": "team-1", - "states": [], - "statesLoading": false, - "teams": [ - { - "id": "team-1", - "key": "ENG", - "name": "Engineering", - "workspaceId": "linear-workspace" - } - ] - }, - "2b0fea7d064e": { - "name": "linear.listTeams#1", - "ordinal": 8, + "ordinal": 7, "args": [ { "name": "method", @@ -125,63 +46,50 @@ } } }, - "33218d06f656": { - "name": "linearStates", - "ordinal": 6, - "value": [] - }, - "356f2cb9a0df": { - "name": "linearStatesLoading", - "ordinal": 17, - "value": false - }, - "3abc893d377b": { - "name": "mutatingStatus", - "ordinal": 3, - "value": false - }, - "475ec9a66266": { - "name": "linearTeams", + "17249df8377f": { + "name": "createTeamId", "ordinal": 10, - "value": [ - { - "id": "team-1", - "key": "ENG", - "name": "Engineering", - "workspaceId": "linear-workspace" - } - ] + "value": { + "$rpc": "null" + } }, - "5711e2717b76": { - "name": "linearStates", - "ordinal": 16, - "value": [ - { - "color": "#000000", - "id": "state-1", - "name": "Todo", - "type": "unstarted" - } - ] - }, - "5e7b9a1d95b3": { - "name": "linearTeams", - "ordinal": 10, - "value": [] - }, - "60a0395d07c7": { - "name": "linearStatesLoading", - "ordinal": 12, - "value": true - }, - "610f6c28e7a1": { - "name": "linearSubIssueTitle", - "ordinal": 5, - "value": "" - }, - "6568a8d15463": { + "1ec7cb477142": { "name": "linear.listTeams#1", - "ordinal": 8, + "ordinal": 7, + "args": [ + { + "name": "method", + "value": "linear.listTeams" + }, + { + "name": "params", + "value": { + "$rpc": "absent" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-1", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, + "295be39dd439": { + "name": "linear.listTeams#1", + "ordinal": 7, "args": [ { "name": "method", @@ -207,24 +115,29 @@ "value": { "error": { "code": "refused", - "message": "" + "message": "outer refused" }, "id": "frame-1", "ok": false } } }, - "74ca99e85dba": { - "createTeamId": { - "$rpc": "null" - }, + "2afc4b1311c1": { + "createTeamId": "team-1", "states": [], "statesLoading": false, - "teams": [] + "teams": [ + { + "id": "team-1", + "key": "ENG", + "name": "Engineering", + "workspaceId": "linear-workspace" + } + ] }, - "8ff86f3a6d6e": { + "3008cf7db0e8": { "name": "linear.listTeams#1", - "ordinal": 8, + "ordinal": 7, "args": [ { "name": "method", @@ -257,14 +170,320 @@ } } }, - "9131972798ca": { - "name": "linear.teamStates#1", - "ordinal": 15, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.teamStates\",\"params\":{\"teamId\":\"team-1\",\"workspaceId\":\"linear-workspace\"}}" + "38ed617d559f": { + "name": "linearTeams", + "ordinal": 9, + "value": [ + { + "id": "team-1", + "key": "ENG", + "name": "Engineering", + "workspaceId": "linear-workspace" + } + ] }, - "95b075d66243": { + "3abc893d377b": { + "name": "mutatingStatus", + "ordinal": 3, + "value": false + }, + "4fcc46dfeb77": { + "name": "linear.listTeams#1", + "ordinal": 8, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listTeams\"}" + }, + "5dcdc7fd7492": { + "name": "linearSubIssueTitle", + "ordinal": 4, + "value": "" + }, + "6e2cda0e22c3": { + "name": "linear.listTeams#1", + "ordinal": 7, + "args": [ + { + "name": "method", + "value": "linear.listTeams" + }, + { + "name": "params", + "value": { + "$rpc": "absent" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true + } + } + }, + "74335ecb4cd2": { + "name": "linearStatesLoading", + "ordinal": 16, + "value": false + }, + "74505ce2789a": { + "name": "linearStates", + "ordinal": 5, + "value": [] + }, + "74ca99e85dba": { + "createTeamId": { + "$rpc": "null" + }, + "states": [], + "statesLoading": false, + "teams": [] + }, + "77a7eff4a3cc": { + "name": "linearStatesLoading", + "ordinal": 11, + "value": true + }, + "7a1d9604491f": { + "name": "linear.listTeams#1", + "ordinal": 7, + "args": [ + { + "name": "method", + "value": "linear.listTeams" + }, + { + "name": "params", + "value": { + "$rpc": "absent" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-1", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "82b36eab5101": { + "name": "creatingTask", + "ordinal": 6, + "value": false + }, + "8640fb2add9b": { + "name": "linearTeams", + "ordinal": 9, + "value": [] + }, + "a14f6c361136": { + "name": "linearStates", + "ordinal": 15, + "value": [ + { + "color": "#000000", + "id": "state-1", + "name": "Todo", + "type": "unstarted" + } + ] + }, + "b57d92c5b837": { + "name": "linear.listTeams#1", + "ordinal": 7, + "args": [ + { + "name": "method", + "value": "linear.listTeams" + }, + { + "name": "params", + "value": { + "$rpc": "absent" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-1", + "ok": false + } + } + }, + "b5ba6f00c4fb": { "name": "linear.teamStates#1", "ordinal": 14, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.teamStates\",\"params\":{\"teamId\":\"team-1\",\"workspaceId\":\"linear-workspace\"}}" + }, + "b6a3835a95e0": { + "name": "linear.listTeams#1", + "ordinal": 7, + "args": [ + { + "name": "method", + "value": "linear.listTeams" + }, + { + "name": "params", + "value": { + "$rpc": "absent" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "b6bf81e9e237": { + "createTeamId": "team-1", + "states": [ + { + "color": "#000000", + "id": "state-1", + "name": "Todo", + "type": "unstarted" + } + ], + "statesLoading": false, + "teams": [ + { + "id": "team-1", + "key": "ENG", + "name": "Engineering", + "workspaceId": "linear-workspace" + } + ] + }, + "bb26ae00041e": { + "createTeamId": { + "$rpc": "null" + }, + "states": [ + { + "color": "#000000", + "id": "state-1", + "name": "Todo", + "type": "unstarted" + } + ], + "statesLoading": false, + "teams": [] + }, + "c3709cdbfa6b": { + "name": "linear.listTeams#1", + "ordinal": 7, + "args": [ + { + "name": "method", + "value": "linear.listTeams" + }, + { + "name": "params", + "value": { + "$rpc": "absent" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-1", + "ok": true + } + } + }, + "c74dd55429c8": { + "name": "linear.listTeams#1", + "ordinal": 7, + "args": [ + { + "name": "method", + "value": "linear.listTeams" + }, + { + "name": "params", + "value": { + "$rpc": "absent" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-1", + "ok": false + } + } + }, + "c88d134e7a42": { + "name": "linear.teamStates#1", + "ordinal": 13, "args": [ { "name": "method", @@ -302,157 +521,6 @@ } } }, - "9dc1f136772e": { - "name": "linearCommentDraft", - "ordinal": 4, - "value": "" - }, - "ab4350eb906f": { - "name": "linear.listTeams#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "linear.listTeams" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "ab739ce318cf": { - "name": "linear.listTeams#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "linear.listTeams" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-1", - "ok": false - } - } - }, - "b164dfd464b3": { - "name": "linear.listTeams#1", - "ordinal": 9, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listTeams\"}" - }, - "b1adae647a3f": { - "name": "createTeamId", - "ordinal": 11, - "value": "team-1" - }, - "b6bf81e9e237": { - "createTeamId": "team-1", - "states": [ - { - "color": "#000000", - "id": "state-1", - "name": "Todo", - "type": "unstarted" - } - ], - "statesLoading": false, - "teams": [ - { - "id": "team-1", - "key": "ENG", - "name": "Engineering", - "workspaceId": "linear-workspace" - } - ] - }, - "bb26ae00041e": { - "createTeamId": { - "$rpc": "null" - }, - "states": [ - { - "color": "#000000", - "id": "state-1", - "name": "Todo", - "type": "unstarted" - } - ], - "statesLoading": false, - "teams": [] - }, - "c6fcb742b15b": { - "name": "linear.listTeams#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "linear.listTeams" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "transport failure", - "isRpcDeliveryUnknown": true - } - } - }, "cc2ece9478f0": { "name": "actionItem", "ordinal": 1, @@ -460,9 +528,29 @@ "$rpc": "null" } }, - "ceb71a750e06": { + "db66582f88a9": { + "name": "linearStatesError", + "ordinal": 12, + "value": "" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eda130337c99": { + "name": "detailPayload", + "ordinal": 2, + "value": { + "$rpc": "null" + } + }, + "ee01f277ffc4": { "name": "linear.listTeams#1", - "ordinal": 8, + "ordinal": 7, "args": [ { "name": "method", @@ -498,99 +586,6 @@ ] } } - }, - "d837ce2317b7": { - "name": "linear.listTeams#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "linear.listTeams" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true - } - } - }, - "db3e553e51e5": { - "name": "linear.listTeams#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "linear.listTeams" - }, - { - "name": "params", - "value": { - "$rpc": "absent" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "$rpc": "null" - } - } - } - }, - "e7edc26c6e24": { - "name": "createTeamId", - "ordinal": 11, - "value": { - "$rpc": "null" - } - }, - "e9a162defc32": { - "name": "creatingTask", - "ordinal": 7, - "value": false - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "eda130337c99": { - "name": "detailPayload", - "ordinal": 2, - "value": { - "$rpc": "null" - } } }, "recording": { @@ -599,8 +594,8 @@ { "id": "tk-linear-team-context.normal:open-composer-settled", "observation": { - "sender": ["ceb71a750e06"], - "payloads": ["b164dfd464b3"], + "sender": ["ee01f277ffc4"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -610,20 +605,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130" ] } }, { "id": "tk-linear-team-context.normal:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -634,24 +628,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.result-absent:open-composer-settled", "observation": { - "sender": ["0086e1c04b47"], - "payloads": ["b164dfd464b3"], + "sender": ["c3709cdbfa6b"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -661,20 +654,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.result-absent:select-metadata-item-settled", "observation": { - "sender": ["0086e1c04b47", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["c3709cdbfa6b", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -685,24 +677,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.result-null:open-composer-settled", "observation": { - "sender": ["db3e553e51e5"], - "payloads": ["b164dfd464b3"], + "sender": ["1ec7cb477142"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -712,20 +703,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.result-null:select-metadata-item-settled", "observation": { - "sender": ["db3e553e51e5", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["1ec7cb477142", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -736,24 +726,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.inner-ok-missing:open-composer-settled", "observation": { - "sender": ["ab4350eb906f"], - "payloads": ["b164dfd464b3"], + "sender": ["7a1d9604491f"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -763,20 +752,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.inner-ok-missing:select-metadata-item-settled", "observation": { - "sender": ["ab4350eb906f", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["7a1d9604491f", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -787,24 +775,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.inner-false-string-error:open-composer-settled", "observation": { - "sender": ["8ff86f3a6d6e"], - "payloads": ["b164dfd464b3"], + "sender": ["3008cf7db0e8"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -814,20 +801,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.inner-false-string-error:select-metadata-item-settled", "observation": { - "sender": ["8ff86f3a6d6e", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["3008cf7db0e8", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -838,24 +824,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.inner-false-object-error:open-composer-settled", "observation": { - "sender": ["2b0fea7d064e"], - "payloads": ["b164dfd464b3"], + "sender": ["0393503430d4"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -865,20 +850,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.inner-false-object-error:select-metadata-item-settled", "observation": { - "sender": ["2b0fea7d064e", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["0393503430d4", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -889,24 +873,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.outer-refused:open-composer-settled", "observation": { - "sender": ["ab739ce318cf"], - "payloads": ["b164dfd464b3"], + "sender": ["295be39dd439"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -916,20 +899,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.outer-refused:select-metadata-item-settled", "observation": { - "sender": ["ab739ce318cf", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["295be39dd439", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -940,24 +922,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.outer-refused-no-message:open-composer-settled", "observation": { - "sender": ["6568a8d15463"], - "payloads": ["b164dfd464b3"], + "sender": ["b57d92c5b837"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -967,20 +948,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.outer-refused-no-message:select-metadata-item-settled", "observation": { - "sender": ["6568a8d15463", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["b57d92c5b837", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -991,24 +971,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.method-not-found:open-composer-settled", "observation": { - "sender": ["10b6d9eca9a8"], - "payloads": ["b164dfd464b3"], + "sender": ["c74dd55429c8"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -1018,20 +997,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.method-not-found:select-metadata-item-settled", "observation": { - "sender": ["10b6d9eca9a8", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["c74dd55429c8", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -1042,24 +1020,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.transport-rejection:open-composer-settled", "observation": { - "sender": ["c6fcb742b15b"], - "payloads": ["b164dfd464b3"], + "sender": ["6e2cda0e22c3"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -1069,20 +1046,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.transport-rejection:select-metadata-item-settled", "observation": { - "sender": ["c6fcb742b15b", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["6e2cda0e22c3", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -1093,24 +1069,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.transport-rejection-no-message:open-composer-settled", "observation": { - "sender": ["d837ce2317b7"], - "payloads": ["b164dfd464b3"], + "sender": ["b6a3835a95e0"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -1120,20 +1095,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f" ] } }, { "id": "tk-linear-team-context.transport-rejection-no-message:select-metadata-item-settled", "observation": { - "sender": ["d837ce2317b7", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["b6a3835a95e0", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -1144,16 +1118,15 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "5e7b9a1d95b3", - "e7edc26c6e24", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "8640fb2add9b", + "17249df8377f", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.teamstates-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.teamstates-1.json index 5543dee089c..487e8942865 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.teamstates-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.linear-team-context-linear.teamstates-1.json @@ -4,14 +4,47 @@ "family": "tasks.linear-team-context", "namedDeltas": [], "values": { - "1288b8513745": { - "name": "linearStatesError", - "ordinal": 13, - "value": "" + "031c50459130": { + "name": "createTeamId", + "ordinal": 10, + "value": "team-1" }, - "1a8a5ec5fc23": { + "08ba0389f3cc": { "name": "linear.teamStates#1", - "ordinal": 14, + "ordinal": 13, + "args": [ + { + "name": "method", + "value": "linear.teamStates" + }, + { + "name": "params", + "value": { + "teamId": "team-1", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true + } + } + }, + "0bbe7048713b": { + "name": "linear.teamStates#1", + "ordinal": 13, "args": [ { "name": "method", @@ -45,9 +78,253 @@ } } }, - "257a7865e607": { + "2afc4b1311c1": { + "createTeamId": "team-1", + "states": [], + "statesLoading": false, + "teams": [ + { + "id": "team-1", + "key": "ENG", + "name": "Engineering", + "workspaceId": "linear-workspace" + } + ] + }, + "3508d5a4f814": { + "name": "linear.teamStates#1", + "ordinal": 13, + "args": [ + { + "name": "method", + "value": "linear.teamStates" + }, + { + "name": "params", + "value": { + "teamId": "team-1", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, + "356f2cb9a0df": { + "name": "linearStatesLoading", + "ordinal": 17, + "value": false + }, + "37b06a0ef857": { + "name": "linear.teamStates#1", + "ordinal": 13, + "args": [ + { + "name": "method", + "value": "linear.teamStates" + }, + { + "name": "params", + "value": { + "teamId": "team-1", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "38ed617d559f": { + "name": "linearTeams", + "ordinal": 9, + "value": [ + { + "id": "team-1", + "key": "ENG", + "name": "Engineering", + "workspaceId": "linear-workspace" + } + ] + }, + "3abc893d377b": { + "name": "mutatingStatus", + "ordinal": 3, + "value": false + }, + "4fcc46dfeb77": { + "name": "linear.listTeams#1", + "ordinal": 8, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listTeams\"}" + }, + "5dcdc7fd7492": { + "name": "linearSubIssueTitle", + "ordinal": 4, + "value": "" + }, + "74335ecb4cd2": { + "name": "linearStatesLoading", + "ordinal": 16, + "value": false + }, + "74505ce2789a": { + "name": "linearStates", + "ordinal": 5, + "value": [] + }, + "77a7eff4a3cc": { + "name": "linearStatesLoading", + "ordinal": 11, + "value": true + }, + "82b36eab5101": { + "name": "creatingTask", + "ordinal": 6, + "value": false + }, + "8bfe92d83df7": { + "name": "linear.teamStates#1", + "ordinal": 13, + "args": [ + { + "name": "method", + "value": "linear.teamStates" + }, + { + "name": "params", + "value": { + "teamId": "team-1", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-2", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } + } + } + }, + "9c2bebd630ca": { + "name": "linear.teamStates#1", + "ordinal": 13, + "args": [ + { + "name": "method", + "value": "linear.teamStates" + }, + { + "name": "params", + "value": { + "teamId": "team-1", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, + "id": "frame-2", + "ok": false + } + } + }, + "a14f6c361136": { + "name": "linearStates", + "ordinal": 15, + "value": [ + { + "color": "#000000", + "id": "state-1", + "name": "Todo", + "type": "unstarted" + } + ] + }, + "b5ba6f00c4fb": { "name": "linear.teamStates#1", "ordinal": 14, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.teamStates\",\"params\":{\"teamId\":\"team-1\",\"workspaceId\":\"linear-workspace\"}}" + }, + "b6bf81e9e237": { + "createTeamId": "team-1", + "states": [ + { + "color": "#000000", + "id": "state-1", + "name": "Todo", + "type": "unstarted" + } + ], + "statesLoading": false, + "teams": [ + { + "id": "team-1", + "key": "ENG", + "name": "Engineering", + "workspaceId": "linear-workspace" + } + ] + }, + "bc9c421bce9d": { + "name": "linear.teamStates#1", + "ordinal": 13, "args": [ { "name": "method", @@ -81,159 +358,9 @@ } } }, - "2afc4b1311c1": { - "createTeamId": "team-1", - "states": [], - "statesLoading": false, - "teams": [ - { - "id": "team-1", - "key": "ENG", - "name": "Engineering", - "workspaceId": "linear-workspace" - } - ] - }, - "33218d06f656": { - "name": "linearStates", - "ordinal": 6, - "value": [] - }, - "356f2cb9a0df": { - "name": "linearStatesLoading", - "ordinal": 17, - "value": false - }, - "38ffd79cd25a": { - "name": "linearStatesLoading", - "ordinal": 18, - "value": false - }, - "3abc893d377b": { - "name": "mutatingStatus", - "ordinal": 3, - "value": false - }, - "3ec904e24cfd": { - "name": "linearStatesError", - "ordinal": 17, - "value": "Couldn't load states. Reopen to try again." - }, - "475ec9a66266": { - "name": "linearTeams", - "ordinal": 10, - "value": [ - { - "id": "team-1", - "key": "ENG", - "name": "Engineering", - "workspaceId": "linear-workspace" - } - ] - }, - "493c7b4199f7": { + "c88d134e7a42": { "name": "linear.teamStates#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "linear.teamStates" - }, - { - "name": "params", - "value": { - "teamId": "team-1", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "5711e2717b76": { - "name": "linearStates", - "ordinal": 16, - "value": [ - { - "color": "#000000", - "id": "state-1", - "name": "Todo", - "type": "unstarted" - } - ] - }, - "5b6eff1db997": { - "name": "linear.teamStates#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "linear.teamStates" - }, - { - "name": "params", - "value": { - "teamId": "team-1", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true - } - } - }, - "60a0395d07c7": { - "name": "linearStatesLoading", - "ordinal": 12, - "value": true - }, - "610f6c28e7a1": { - "name": "linearSubIssueTitle", - "ordinal": 5, - "value": "" - }, - "680165cd199f": { - "name": "linearStates", - "ordinal": 16, - "value": [] - }, - "9131972798ca": { - "name": "linear.teamStates#1", - "ordinal": 15, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.teamStates\",\"params\":{\"teamId\":\"team-1\",\"workspaceId\":\"linear-workspace\"}}" - }, - "95b075d66243": { - "name": "linear.teamStates#1", - "ordinal": 14, + "ordinal": 13, "args": [ { "name": "method", @@ -271,14 +398,16 @@ } } }, - "9dc1f136772e": { - "name": "linearCommentDraft", - "ordinal": 4, - "value": "" + "cc2ece9478f0": { + "name": "actionItem", + "ordinal": 1, + "value": { + "$rpc": "null" + } }, - "a29f541d9116": { + "cc5c41192644": { "name": "linear.teamStates#1", - "ordinal": 14, + "ordinal": 13, "args": [ { "name": "method", @@ -304,46 +433,23 @@ "settledAt": 0, "value": { "id": "frame-2", - "ok": true, - "result": { - "$rpc": "null" - } + "ok": true } } }, - "b164dfd464b3": { - "name": "linear.listTeams#1", - "ordinal": 9, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listTeams\"}" + "cd1bce5e6fae": { + "name": "linearStates", + "ordinal": 15, + "value": [] }, - "b1adae647a3f": { - "name": "createTeamId", - "ordinal": 11, - "value": "team-1" + "db66582f88a9": { + "name": "linearStatesError", + "ordinal": 12, + "value": "" }, - "b6bf81e9e237": { - "createTeamId": "team-1", - "states": [ - { - "color": "#000000", - "id": "state-1", - "name": "Todo", - "type": "unstarted" - } - ], - "statesLoading": false, - "teams": [ - { - "id": "team-1", - "key": "ENG", - "name": "Engineering", - "workspaceId": "linear-workspace" - } - ] - }, - "bba047c7732c": { + "e11f0649d40c": { "name": "linear.teamStates#1", - "ordinal": 14, + "ordinal": 13, "args": [ { "name": "method", @@ -379,16 +485,57 @@ } } }, - "cc2ece9478f0": { - "name": "actionItem", - "ordinal": 1, + "ea8fa14b318f": { + "name": "linear.teamStates#1", + "ordinal": 13, + "args": [ + { + "name": "method", + "value": "linear.teamStates" + }, + { + "name": "params", + "value": { + "teamId": "team-1", + "workspaceId": "linear-workspace" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eda130337c99": { + "name": "detailPayload", + "ordinal": 2, "value": { "$rpc": "null" } }, - "ceb71a750e06": { + "ee01f277ffc4": { "name": "linear.listTeams#1", - "ordinal": 8, + "ordinal": 7, "args": [ { "name": "method", @@ -425,162 +572,10 @@ } } }, - "cf77783ec600": { - "name": "linear.teamStates#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "linear.teamStates" - }, - { - "name": "params", - "value": { - "teamId": "team-1", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true - } - } - }, - "e9a162defc32": { - "name": "creatingTask", - "ordinal": 7, - "value": false - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "eda130337c99": { - "name": "detailPayload", - "ordinal": 2, - "value": { - "$rpc": "null" - } - }, - "f47f4cf7bd2b": { - "name": "linear.teamStates#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "linear.teamStates" - }, - { - "name": "params", - "value": { - "teamId": "team-1", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-2", - "ok": false - } - } - }, - "fed235ce8e9c": { - "name": "linear.teamStates#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "linear.teamStates" - }, - { - "name": "params", - "value": { - "teamId": "team-1", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "error": "inner refused", - "ok": false - } - } - } - }, - "ff9c7b4bdfb6": { - "name": "linear.teamStates#1", - "ordinal": 14, - "args": [ - { - "name": "method", - "value": "linear.teamStates" - }, - { - "name": "params", - "value": { - "teamId": "team-1", - "workspaceId": "linear-workspace" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "transport failure", - "isRpcDeliveryUnknown": true - } - } + "ef290fdf0bf5": { + "name": "linearStatesError", + "ordinal": 16, + "value": "Couldn't load states. Reopen to try again." } }, "recording": { @@ -589,8 +584,8 @@ { "id": "tk-linear-team-context.prelude:open-composer-settled", "observation": { - "sender": ["ceb71a750e06"], - "payloads": ["b164dfd464b3"], + "sender": ["ee01f277ffc4"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -600,20 +595,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130" ] } }, { "id": "tk-linear-team-context.normal:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -624,24 +618,23 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } }, { "id": "tk-linear-team-context.result-absent:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "cf77783ec600"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "cc5c41192644"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -652,25 +645,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.result-null:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "a29f541d9116"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "3508d5a4f814"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -681,25 +673,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.inner-ok-missing:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "493c7b4199f7"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "37b06a0ef857"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -710,25 +701,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.inner-false-string-error:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "fed235ce8e9c"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "8bfe92d83df7"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -739,25 +729,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.inner-false-object-error:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "bba047c7732c"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "e11f0649d40c"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -768,25 +757,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.outer-refused:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "1a8a5ec5fc23"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "0bbe7048713b"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -797,25 +785,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.outer-refused-no-message:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "257a7865e607"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "bc9c421bce9d"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -826,25 +813,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.method-not-found:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "f47f4cf7bd2b"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "9c2bebd630ca"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -855,25 +841,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.transport-rejection:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "ff9c7b4bdfb6"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "08ba0389f3cc"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -884,25 +869,24 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } }, { "id": "tk-linear-team-context.transport-rejection-no-message:select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "5b6eff1db997"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "ea8fa14b318f"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -913,17 +897,16 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "680165cd199f", - "3ec904e24cfd", - "38ffd79cd25a" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "cd1bce5e6fae", + "ef290fdf0bf5", + "356f2cb9a0df" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listaccessible-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listaccessible-1.json index 1d4cbac096d..572def72fab 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listaccessible-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listaccessible-1.json @@ -4,55 +4,16 @@ "family": "tasks.project-board-load", "namedDeltas": [], "values": { - "00ef2dbe5026": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "host": "github.com", - "number": 3, - "ok": true, - "owner": "owner", - "ownerType": "organization", - "title": "Board", - "viewNumber": 1 - } - } + "0056704adc0b": { + "name": "githubProjectTable", + "ordinal": 31, + "value": { + "$rpc": "null" } }, - "0388fa155721": { + "060dcedb3fdb": { "name": "githubProjectError", - "ordinal": 11, - "value": "" - }, - "03fc33b06333": { - "name": "githubProjectPasteError", - "ordinal": 17, + "ordinal": 10, "value": "" }, "0a7f23c13d0c": { @@ -90,6 +51,13 @@ } } }, + "0af48d475813": { + "name": "appliedGithubProjectSearch", + "ordinal": 29, + "value": { + "$rpc": "undefined" + } + }, "0e76d492b4f4": { "error": "", "loading": false, @@ -107,306 +75,14 @@ } ] }, - "147d0c98fb46": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [], - "table": { - "$rpc": "null" - }, - "views": [] - }, - "15cb97c93333": { - "name": "github.project.listViews#1", - "ordinal": 8, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "170fad8cb36b": { - "name": "githubProjectPartialFailures", - "ordinal": 6, - "value": [] - }, - "1cb3b185586b": { - "name": "githubProjectLoading", - "ordinal": 31, + "0e8b33b2854d": { + "name": "showGitHubProjectPicker", + "ordinal": 21, "value": false }, - "2085118de92f": { - "name": "githubProjectError", - "ordinal": 1, - "value": "" - }, - "223225c09f07": { - "name": "githubProjectSearch", - "ordinal": 29, - "value": "" - }, - "2423ca7008fd": { + "0f1aa264f581": { "name": "github.project.viewTable#1", "ordinal": 11, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" - }, - "2ab1b35ff194": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "321983341043": { - "name": "github.project.listAccessible#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "github.project.listAccessible" - }, - { - "name": "params", - "value": { - "host": "github.com" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "32a7c0ae7918": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "outer refused", - "isRpcDeliveryUnknown": false - } - }, - "32e88f5c4657": { - "name": "githubProjectPasteInput", - "ordinal": 21, - "value": "" - }, - "34de2d655a0a": { - "name": "githubProjectTable", - "ordinal": 32, - "value": { - "$rpc": "null" - } - }, - "376c9e8bd72a": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "39b306a93afc": { - "name": "githubProjectSearch", - "ordinal": 13, - "value": "is:open" - }, - "43352776b1e1": { - "name": "githubProjectTable", - "ordinal": 14, - "value": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - } - }, - "4607a82f1dd3": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "47507819e28a": { - "name": "githubProjectPasteInput", - "ordinal": 23, - "value": "" - }, - "4dd8cc8f777d": { - "name": "appliedGithubProjectSearch", - "ordinal": 28, - "value": { - "$rpc": "undefined" - } - }, - "4dff29ea88de": { - "name": "github.project.resolveRef#1", - "ordinal": 20, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" - }, - "4eb521bbefdd": { - "name": "githubProjectSearch", - "ordinal": 15, - "value": "is:open" - }, - "5033e4410561": { - "name": "github.project.listAccessible#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "github.project.listAccessible" - }, - { - "name": "params", - "value": { - "host": "github.com" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true - } - } - }, - "528af16518e6": { - "name": "githubProjectViews", - "ordinal": 16, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "5a4fc5c86d0c": { - "name": "githubProjectPasteBusy", - "ordinal": 34, - "value": false - }, - "5a7676ce26d6": { - "name": "githubProjectPasteBusy", - "ordinal": 32, - "value": false - }, - "5c93fbf94a2d": { - "name": "githubProjectTable", - "ordinal": 30, - "value": { - "$rpc": "null" - } - }, - "5f5f56db9d64": { - "name": "github.project.viewTable#1", - "ordinal": 12, "args": [ { "name": "method", @@ -458,15 +134,295 @@ } } }, - "61ce1ab88e79": { + "147d0c98fb46": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [], + "table": { + "$rpc": "null" + }, + "views": [] + }, + "15cb97c93333": { + "name": "github.project.listViews#1", + "ordinal": 8, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + }, + "170fad8cb36b": { + "name": "githubProjectPartialFailures", + "ordinal": 6, + "value": [] + }, + "1742a082916c": { + "name": "githubProjectLoading", + "ordinal": 7, + "value": true + }, + "1b3350f71e56": { + "name": "githubProjectError", + "ordinal": 19, + "value": "" + }, + "1f4f9fd563d9": { + "name": "githubProjectError", + "ordinal": 17, + "value": "" + }, + "2085118de92f": { + "name": "githubProjectError", + "ordinal": 1, + "value": "" + }, + "26921f3a7c09": { + "name": "githubProjectPasteError", + "ordinal": 18, + "value": "" + }, + "29c85aeaeafe": { + "name": "githubProjectError", + "ordinal": 8, + "value": "" + }, + "2ab1b35ff194": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "2f290fa2acf5": { + "name": "githubProjectLoading", + "ordinal": 9, + "value": true + }, + "309bbebe1e4b": { + "name": "githubProjectTable", + "ordinal": 29, + "value": { + "$rpc": "null" + } + }, + "321983341043": { + "name": "github.project.listAccessible#1", + "ordinal": 3, + "args": [ + { + "name": "method", + "value": "github.project.listAccessible" + }, + { + "name": "params", + "value": { + "host": "github.com" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-1", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "32a7c0ae7918": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "outer refused", + "isRpcDeliveryUnknown": false + } + }, + "3493818a7239": { + "name": "githubProjectPasteBusy", + "ordinal": 33, + "value": false + }, + "358856006a81": { + "name": "githubProjectPasteError", + "ordinal": 16, + "value": "" + }, + "376c9e8bd72a": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "3985399034a2": { + "name": "githubProjectPasteBusy", + "ordinal": 17, + "value": true + }, + "3a8617cc8fd8": { + "name": "githubProjectSearch", + "ordinal": 14, + "value": "is:open" + }, + "43846f79098a": { + "name": "githubProjectSearch", + "ordinal": 28, + "value": "" + }, + "4607a82f1dd3": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "47b4a4ed1197": { + "name": "appliedGithubProjectSearch", + "ordinal": 27, + "value": { + "$rpc": "undefined" + } + }, + "4809ea7ad5b0": { "name": "github.project.viewTable#1", - "ordinal": 13, + "ordinal": 12, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" }, - "654693493b51": { - "name": "githubProjectLoading", - "ordinal": 10, - "value": true + "4c9b1e4ad1f5": { + "name": "githubProjectViews", + "ordinal": 28, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "4db99cb82cd3": { + "name": "githubProjectError", + "ordinal": 23, + "value": "" + }, + "5033e4410561": { + "name": "github.project.listAccessible#1", + "ordinal": 3, + "args": [ + { + "name": "method", + "value": "github.project.listAccessible" + }, + { + "name": "params", + "value": { + "host": "github.com" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "53954ecf4db4": { + "name": "githubProjectPasteBusy", + "ordinal": 31, + "value": false }, "685bc2bda05d": { "name": "githubProjects", @@ -481,9 +437,14 @@ } ] }, - "6d7ebc9b7830": { - "name": "github.project.listViews#2", + "6b03ace1146a": { + "name": "githubProjectError", "ordinal": 25, + "value": "" + }, + "6c265f3eef22": { + "name": "github.project.listViews#2", + "ordinal": 24, "args": [ { "name": "method", @@ -526,6 +487,23 @@ } } }, + "6d4c77a759a1": { + "name": "githubProjectSearch", + "ordinal": 12, + "value": "is:open" + }, + "736562ff5594": { + "name": "githubProjectViews", + "ordinal": 26, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, "75c11cbc10c6": { "name": "github.project.listAccessible#1", "ordinal": 3, @@ -561,109 +539,9 @@ } } }, - "7a9df0d1a484": { - "name": "githubProjectLoading", - "ordinal": 25, - "value": true - }, - "7b9d3b33c08b": { - "name": "githubProjectPasteError", - "ordinal": 19, - "value": "" - }, - "7d7e6f5ce421": { - "name": "github.project.resolveRef#1", - "ordinal": 19, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "host": "github.com", - "number": 3, - "ok": true, - "owner": "owner", - "ownerType": "organization", - "title": "Board", - "viewNumber": 1 - } - } - } - }, - "853d951cf70a": { - "name": "githubProjectError", - "ordinal": 18, - "value": "" - }, - "8792541c60ad": { - "name": "githubProjectError", - "ordinal": 26, - "value": "" - }, - "8c0c8b07aa3b": { - "name": "githubProjectLoading", - "ordinal": 8, - "value": true - }, - "8e4dec1aad1f": { - "name": "github.project.listViews#2", - "ordinal": 28, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "8f3ee6c510b1": { - "name": "github.project.resolveRef#1", - "ordinal": 22, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" - }, - "9b9f8dd75514": { - "name": "githubProjectViews", - "ordinal": 9, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "9eb658057bc2": { - "name": "githubProjectViews", - "ordinal": 7, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "a012d9c70804": { + "7a60e3d689a2": { "name": "githubProjectTable", - "ordinal": 12, + "ordinal": 11, "value": { "fields": [], "project": { @@ -681,6 +559,112 @@ } } }, + "7d488eda1d1c": { + "name": "githubProjectViews", + "ordinal": 15, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "819f4dade400": { + "name": "github.project.listViews#2", + "ordinal": 25, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + }, + "842c950ee7cc": { + "name": "githubProjectLoading", + "ordinal": 16, + "value": false + }, + "88787b083c0a": { + "name": "githubProjectLoading", + "ordinal": 22, + "value": true + }, + "88db645d6267": { + "name": "githubProjectLoading", + "ordinal": 30, + "value": false + }, + "8a0577280bad": { + "name": "showGitHubProjectPicker", + "ordinal": 23, + "value": false + }, + "8b535c841be8": { + "name": "githubProjectPasteBusy", + "ordinal": 15, + "value": true + }, + "97bc7dc12b92": { + "name": "githubProjectLoading", + "ordinal": 32, + "value": false + }, + "999ec0e10c42": { + "name": "github.project.viewTable#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.project.viewTable" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3, + "viewId": "view-1" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 60000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "data": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "ok": true + } + } + } + }, + "9f9a21ac7b9e": { + "name": "github.project.listViews#2", + "ordinal": 27, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + }, "a0b318040dbf": { "name": "github.project.listAccessible#1", "ordinal": 3, @@ -766,21 +750,23 @@ "ordinal": 6, "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" }, - "a4635ab3551f": { - "name": "githubProjectLoading", - "ordinal": 15, - "value": false - }, - "a4a1ff5df287": { - "name": "githubProjectPasteBusy", - "ordinal": 18, - "value": true - }, "a5a3530ec11c": { "name": "githubProjectPartialFailures", "ordinal": 2, "value": [] }, + "a87b90bd0eb2": { + "name": "githubProjectViews", + "ordinal": 13, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, "a947768bc0ed": { "status": "rejected", "startedAt": 0, @@ -802,31 +788,14 @@ "code": "incompatible_reply" } }, - "b0c25dac9d8e": { + "ab1b10183665": { + "name": "githubProjectLoading", + "ordinal": 24, + "value": true + }, + "ae89e058b351": { "name": "github.project.listViews#2", "ordinal": 26, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "b42c8edc0d53": { - "name": "github.project.listAccessible#1", - "ordinal": 4, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" - }, - "b495d30b1ee0": { - "name": "githubProjectViews", - "ordinal": 14, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "b49ff9f109a5": { - "name": "github.project.listViews#2", - "ordinal": 27, "args": [ { "name": "method", @@ -869,27 +838,15 @@ } } }, - "b5e354ed6023": { - "name": "githubProjectLoading", - "ordinal": 17, - "value": false + "b42c8edc0d53": { + "name": "github.project.listAccessible#1", + "ordinal": 4, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" }, - "b5f49e20fef1": { - "name": "showGitHubProjectPicker", - "ordinal": 22, - "value": false - }, - "b66c4f75c9ae": { - "name": "githubProjectViews", - "ordinal": 29, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] + "b4a1f05e33c8": { + "name": "github.project.resolveRef#1", + "ordinal": 19, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" }, "b948e8307e81": { "status": "rejected", @@ -951,15 +908,30 @@ } ] }, - "c453f220a7e2": { - "name": "githubProjectLoading", - "ordinal": 33, - "value": false + "be93253869e6": { + "name": "github.project.resolveRef#1", + "ordinal": 21, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" }, - "c4c4250b0567": { - "name": "showGitHubProjectPicker", - "ordinal": 24, - "value": false + "c5c018cf9a70": { + "name": "githubProjectTable", + "ordinal": 13, + "value": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + } }, "c668b7f0ba25": { "name": "github.project.listAccessible#1", @@ -1003,18 +975,6 @@ "isRpcDeliveryUnknown": true } }, - "d0248d16609f": { - "name": "githubProjectViews", - "ordinal": 27, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, "d05b2d417b9c": { "status": "rejected", "startedAt": 0, @@ -1070,11 +1030,62 @@ } } }, - "d494afc83352": { - "name": "githubProjectError", - "ordinal": 24, + "d7783b65acee": { + "name": "github.project.resolveRef#1", + "ordinal": 18, + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "host": "github.com", + "number": 3, + "ok": true, + "owner": "owner", + "ownerType": "organization", + "title": "Board", + "viewNumber": 1 + } + } + } + }, + "d9ca148637c0": { + "name": "github.project.viewTable#1", + "ordinal": 10, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" + }, + "dc8dd7739c49": { + "name": "githubProjectPasteInput", + "ordinal": 22, "value": "" }, + "df8adf9c824e": { + "name": "githubProjectLoading", + "ordinal": 14, + "value": false + }, "dfe16215433b": { "name": "github.project.listAccessible#1", "ordinal": 3, @@ -1119,60 +1130,6 @@ } } }, - "e2cc9a61876c": { - "name": "github.project.viewTable#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.project.viewTable" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3, - "viewId": "view-1" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 60000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "data": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "ok": true - } - } - } - }, "e538f46c1fc2": { "name": "github.project.listAccessible#1", "ordinal": 3, @@ -1207,10 +1164,10 @@ } } }, - "ea8f8a6f07b1": { - "name": "githubProjectPasteBusy", - "ordinal": 16, - "value": true + "e87bea4bcd3c": { + "name": "githubProjectSearch", + "ordinal": 30, + "value": "" }, "eb79a9b3682a": { "status": "fulfilled", @@ -1286,11 +1243,6 @@ } } }, - "f163a8ea1a7f": { - "name": "githubProjectError", - "ordinal": 9, - "value": "" - }, "f3b516f62081": { "status": "rejected", "startedAt": 0, @@ -1301,27 +1253,51 @@ "isRpcDeliveryUnknown": false } }, - "f79f5682a27b": { - "name": "githubProjectLoading", - "ordinal": 23, - "value": true - }, - "fa1d1b339394": { - "name": "appliedGithubProjectSearch", - "ordinal": 30, - "value": { - "$rpc": "undefined" - } - }, - "fb9764680a74": { - "name": "githubProjectError", + "f4530e110d4d": { + "name": "githubProjectPasteInput", "ordinal": 20, "value": "" }, - "fe075936e563": { - "name": "githubProjectSearch", - "ordinal": 31, - "value": "" + "f6003aed2098": { + "name": "github.project.resolveRef#1", + "ordinal": 20, + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "host": "github.com", + "number": 3, + "ok": true, + "owner": "owner", + "ownerType": "organization", + "title": "Board", + "viewNumber": 1 + } + } + } }, "ff43b5ec92a9": { "error": "", @@ -1368,21 +1344,15 @@ "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb" }, - "state": "376c9e8bd72a", - "effects": [ - "2085118de92f", - "a5a3530ec11c", - "685bc2bda05d", - "170fad8cb36b", - "9b9f8dd75514" - ] + "state": "ff43b5ec92a9", + "effects": ["2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b"] } }, { "id": "tk-project-board-load.normal:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1395,13 +1365,12 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc" ] } }, @@ -1411,16 +1380,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "b49ff9f109a5" + "0f1aa264f581", + "f6003aed2098", + "ae89e058b351" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1435,26 +1404,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "b66c4f75c9ae", - "fa1d1b339394", - "fe075936e563", - "34de2d655a0a", - "c453f220a7e2", - "5a4fc5c86d0c" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "4c9b1e4ad1f5", + "0af48d475813", + "e87bea4bcd3c", + "0056704adc0b", + "97bc7dc12b92", + "3493818a7239" ] } }, @@ -1481,15 +1449,15 @@ "projects-0": "aaf09e2731f5", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.result-absent:table-settled", "observation": { - "sender": ["ee8fc5edb754", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["ee8fc5edb754", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "aaf09e2731f5", @@ -1500,13 +1468,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -1516,16 +1483,16 @@ "sender": [ "ee8fc5edb754", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -1538,26 +1505,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -1584,15 +1550,15 @@ "projects-0": "aaf09e2731f5", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.result-null:table-settled", "observation": { - "sender": ["e538f46c1fc2", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["e538f46c1fc2", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "aaf09e2731f5", @@ -1603,13 +1569,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -1619,16 +1584,16 @@ "sender": [ "e538f46c1fc2", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -1641,26 +1606,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -1687,15 +1651,15 @@ "projects-0": "aaf09e2731f5", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.inner-ok-missing:table-settled", "observation": { - "sender": ["321983341043", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["321983341043", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "aaf09e2731f5", @@ -1706,13 +1670,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -1722,16 +1685,16 @@ "sender": [ "321983341043", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -1744,26 +1707,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -1790,15 +1752,15 @@ "projects-0": "aaf09e2731f5", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.inner-false-string-error:table-settled", "observation": { - "sender": ["75c11cbc10c6", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["75c11cbc10c6", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "aaf09e2731f5", @@ -1809,13 +1771,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -1825,16 +1786,16 @@ "sender": [ "75c11cbc10c6", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -1847,26 +1808,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -1893,15 +1853,15 @@ "projects-0": "d05b2d417b9c", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.inner-false-object-error:table-settled", "observation": { - "sender": ["bdbcea6d9879", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["bdbcea6d9879", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "d05b2d417b9c", @@ -1912,13 +1872,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -1928,16 +1887,16 @@ "sender": [ "bdbcea6d9879", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -1950,26 +1909,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -1996,15 +1954,15 @@ "projects-0": "32a7c0ae7918", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.outer-refused:table-settled", "observation": { - "sender": ["0a7f23c13d0c", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["0a7f23c13d0c", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "32a7c0ae7918", @@ -2015,13 +1973,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -2031,16 +1988,16 @@ "sender": [ "0a7f23c13d0c", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -2053,26 +2010,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -2099,15 +2055,15 @@ "projects-0": "f3b516f62081", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.outer-refused-no-message:table-settled", "observation": { - "sender": ["ed0115da9c46", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["ed0115da9c46", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "f3b516f62081", @@ -2118,13 +2074,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -2134,16 +2089,16 @@ "sender": [ "ed0115da9c46", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -2156,26 +2111,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -2202,15 +2156,15 @@ "projects-0": "b948e8307e81", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.method-not-found:table-settled", "observation": { - "sender": ["a0b318040dbf", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["a0b318040dbf", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "b948e8307e81", @@ -2221,13 +2175,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -2237,16 +2190,16 @@ "sender": [ "a0b318040dbf", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -2259,26 +2212,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -2305,15 +2257,15 @@ "projects-0": "a947768bc0ed", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.transport-rejection:table-settled", "observation": { - "sender": ["c668b7f0ba25", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["c668b7f0ba25", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "a947768bc0ed", @@ -2324,13 +2276,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -2340,16 +2291,16 @@ "sender": [ "c668b7f0ba25", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -2362,26 +2313,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } }, @@ -2408,15 +2358,15 @@ "projects-0": "c7584e82c72f", "views-1": "be0da5b53ffb" }, - "state": "0e76d492b4f4", - "effects": ["2085118de92f", "a5a3530ec11c", "9eb658057bc2"] + "state": "147d0c98fb46", + "effects": ["2085118de92f", "a5a3530ec11c"] } }, { "id": "tk-project-board-load.transport-rejection-no-message:table-settled", "observation": { - "sender": ["5033e4410561", "a125bd681d4a", "e2cc9a61876c"], - "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "2423ca7008fd"], + "sender": ["5033e4410561", "a125bd681d4a", "999ec0e10c42"], + "payloads": ["b42c8edc0d53", "a2a600cf1ed6", "d9ca148637c0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "c7584e82c72f", @@ -2427,13 +2377,12 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e" ] } }, @@ -2443,16 +2392,16 @@ "sender": [ "5033e4410561", "a125bd681d4a", - "e2cc9a61876c", - "7d7e6f5ce421", - "6d7ebc9b7830" + "999ec0e10c42", + "d7783b65acee", + "6c265f3eef22" ], "payloads": [ "b42c8edc0d53", "a2a600cf1ed6", - "2423ca7008fd", - "4dff29ea88de", - "b0c25dac9d8e" + "d9ca148637c0", + "b4a1f05e33c8", + "819f4dade400" ], "settlements": { "mount": "eb79a9b3682a", @@ -2465,26 +2414,25 @@ "effects": [ "2085118de92f", "a5a3530ec11c", - "9eb658057bc2", - "8c0c8b07aa3b", - "f163a8ea1a7f", - "a012d9c70804", - "39b306a93afc", - "b495d30b1ee0", - "a4635ab3551f", - "ea8f8a6f07b1", - "03fc33b06333", - "853d951cf70a", - "32e88f5c4657", - "b5f49e20fef1", - "f79f5682a27b", - "d494afc83352", - "d0248d16609f", - "4dd8cc8f777d", - "223225c09f07", - "5c93fbf94a2d", - "1cb3b185586b", - "5a7676ce26d6" + "1742a082916c", + "29c85aeaeafe", + "7a60e3d689a2", + "6d4c77a759a1", + "a87b90bd0eb2", + "df8adf9c824e", + "8b535c841be8", + "358856006a81", + "1f4f9fd563d9", + "f4530e110d4d", + "0e8b33b2854d", + "88787b083c0a", + "4db99cb82cd3", + "736562ff5594", + "47b4a4ed1197", + "43846f79098a", + "309bbebe1e4b", + "88db645d6267", + "53954ecf4db4" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-1.json index 983cae9af5c..2e366826ec6 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-1.json @@ -11,52 +11,6 @@ "$rpc": "null" } }, - "00ef2dbe5026": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "host": "github.com", - "number": 3, - "ok": true, - "owner": "owner", - "ownerType": "organization", - "title": "Board", - "viewNumber": 1 - } - } - } - }, - "0388fa155721": { - "name": "githubProjectError", - "ordinal": 11, - "value": "" - }, "060dcedb3fdb": { "name": "githubProjectError", "ordinal": 10, @@ -331,13 +285,6 @@ "ordinal": 33, "value": false }, - "34de2d655a0a": { - "name": "githubProjectTable", - "ordinal": 32, - "value": { - "$rpc": "null" - } - }, "376c9e8bd72a": { "error": "", "loading": false, @@ -407,31 +354,6 @@ "ordinal": 14, "value": "is:open" }, - "43352776b1e1": { - "name": "githubProjectTable", - "ordinal": 14, - "value": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - } - }, - "47507819e28a": { - "name": "githubProjectPasteInput", - "ordinal": 23, - "value": "" - }, "4809ea7ad5b0": { "name": "github.project.viewTable#1", "ordinal": 12, @@ -449,87 +371,6 @@ } ] }, - "4eb521bbefdd": { - "name": "githubProjectSearch", - "ordinal": 15, - "value": "is:open" - }, - "528af16518e6": { - "name": "githubProjectViews", - "ordinal": 16, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "5a4fc5c86d0c": { - "name": "githubProjectPasteBusy", - "ordinal": 34, - "value": false - }, - "5f5f56db9d64": { - "name": "github.project.viewTable#1", - "ordinal": 12, - "args": [ - { - "name": "method", - "value": "github.project.viewTable" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3, - "viewId": "view-1" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 60000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "data": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "ok": true - } - } - } - }, - "61ce1ab88e79": { - "name": "github.project.viewTable#1", - "ordinal": 13, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" - }, "621b6b7b4159": { "name": "github.project.listViews#1", "ordinal": 7, @@ -565,11 +406,6 @@ } } }, - "654693493b51": { - "name": "githubProjectLoading", - "ordinal": 10, - "value": true - }, "685bc2bda05d": { "name": "githubProjects", "ordinal": 5, @@ -623,16 +459,6 @@ "ordinal": 25, "value": "" }, - "7a9df0d1a484": { - "name": "githubProjectLoading", - "ordinal": 25, - "value": true - }, - "7b9d3b33c08b": { - "name": "githubProjectPasteError", - "ordinal": 19, - "value": "" - }, "7d488eda1d1c": { "name": "githubProjectViews", "ordinal": 15, @@ -650,43 +476,16 @@ "ordinal": 16, "value": false }, - "8792541c60ad": { - "name": "githubProjectError", - "ordinal": 26, - "value": "" - }, "8a0577280bad": { "name": "showGitHubProjectPicker", "ordinal": 23, "value": false }, - "8e4dec1aad1f": { - "name": "github.project.listViews#2", - "ordinal": 28, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "8f3ee6c510b1": { - "name": "github.project.resolveRef#1", - "ordinal": 22, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" - }, "97bc7dc12b92": { "name": "githubProjectLoading", "ordinal": 32, "value": false }, - "9b9f8dd75514": { - "name": "githubProjectViews", - "ordinal": 9, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, "9f9a21ac7b9e": { "name": "github.project.listViews#2", "ordinal": 27, @@ -732,11 +531,6 @@ } } }, - "a4a1ff5df287": { - "name": "githubProjectPasteBusy", - "ordinal": 18, - "value": true - }, "a5a3530ec11c": { "name": "githubProjectPartialFailures", "ordinal": 2, @@ -807,68 +601,6 @@ "ordinal": 4, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" }, - "b49ff9f109a5": { - "name": "github.project.listViews#2", - "ordinal": 27, - "args": [ - { - "name": "method", - "value": "github.project.listViews" - }, - { - "name": "params", - "value": { - "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": { - "ok": true, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - } - } - } - }, - "b5e354ed6023": { - "name": "githubProjectLoading", - "ordinal": 17, - "value": false - }, - "b66c4f75c9ae": { - "name": "githubProjectViews", - "ordinal": 29, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, "b948e8307e81": { "status": "rejected", "startedAt": 0, @@ -972,16 +704,6 @@ } } }, - "c453f220a7e2": { - "name": "githubProjectLoading", - "ordinal": 33, - "value": false - }, - "c4c4250b0567": { - "name": "showGitHubProjectPicker", - "ordinal": 24, - "value": false - }, "c5c018cf9a70": { "name": "githubProjectTable", "ordinal": 13, @@ -1180,18 +902,6 @@ } } }, - "fa1d1b339394": { - "name": "appliedGithubProjectSearch", - "ordinal": 30, - "value": { - "$rpc": "undefined" - } - }, - "fb9764680a74": { - "name": "githubProjectError", - "ordinal": 20, - "value": "" - }, "fc799562716c": { "name": "github.project.listViews#1", "ordinal": 7, @@ -1229,11 +939,6 @@ } } }, - "fe075936e563": { - "name": "githubProjectSearch", - "ordinal": 31, - "value": "" - }, "ff43b5ec92a9": { "error": "", "loading": false, @@ -1279,21 +984,15 @@ "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb" }, - "state": "376c9e8bd72a", - "effects": [ - "2085118de92f", - "a5a3530ec11c", - "685bc2bda05d", - "170fad8cb36b", - "9b9f8dd75514" - ] + "state": "ff43b5ec92a9", + "effects": ["2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b"] } }, { "id": "tk-project-board-load.normal:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1306,13 +1005,12 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc" ] } }, @@ -1322,16 +1020,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "b49ff9f109a5" + "0f1aa264f581", + "f6003aed2098", + "ae89e058b351" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1346,26 +1044,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "b66c4f75c9ae", - "fa1d1b339394", - "fe075936e563", - "34de2d655a0a", - "c453f220a7e2", - "5a4fc5c86d0c" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "4c9b1e4ad1f5", + "0af48d475813", + "e87bea4bcd3c", + "0056704adc0b", + "97bc7dc12b92", + "3493818a7239" ] } }, diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-2.json b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-2.json index df7cdf99d9f..7e0dd9c98ad 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-2.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.listviews-2.json @@ -4,253 +4,28 @@ "family": "tasks.project-board-load", "namedDeltas": [], "values": { - "00ef2dbe5026": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "host": "github.com", - "number": 3, - "ok": true, - "owner": "owner", - "ownerType": "organization", - "title": "Board", - "viewNumber": 1 - } - } - } - }, - "0388fa155721": { - "name": "githubProjectError", - "ordinal": 11, - "value": "" - }, - "15cb97c93333": { - "name": "github.project.listViews#1", - "ordinal": 8, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "170fad8cb36b": { - "name": "githubProjectPartialFailures", - "ordinal": 6, - "value": [] - }, - "1b7a7437b046": { - "error": "", - "loading": true, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "2085118de92f": { - "name": "githubProjectError", - "ordinal": 1, - "value": "" - }, - "2ab1b35ff194": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "30e01816f729": { - "name": "githubProjectError", - "ordinal": 29, - "value": "Unknown method" - }, - "34de2d655a0a": { + "0056704adc0b": { "name": "githubProjectTable", - "ordinal": 32, + "ordinal": 31, "value": { "$rpc": "null" } }, - "3647b0f3edc5": { + "060dcedb3fdb": { "name": "githubProjectError", - "ordinal": 29, - "value": "transport failure" - }, - "376c9e8bd72a": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "424eb405bbce": { - "name": "github.project.listViews#2", - "ordinal": 27, - "args": [ - { - "name": "method", - "value": "github.project.listViews" - }, - { - "name": "params", - "value": { - "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": { - "error": { - "message": "inner refused" - }, - "ok": false - } - } - } - }, - "43352776b1e1": { - "name": "githubProjectTable", - "ordinal": 14, - "value": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - } - }, - "47507819e28a": { - "name": "githubProjectPasteInput", - "ordinal": 23, + "ordinal": 10, "value": "" }, - "4c85a08be215": { + "0af48d475813": { + "name": "appliedGithubProjectSearch", + "ordinal": 29, + "value": { + "$rpc": "undefined" + } + }, + "0b0789528a70": { "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, "args": [ { "name": "method", @@ -278,164 +53,22 @@ "settledAt": 0, "value": { "error": { - "code": "refused", - "message": "" + "code": "method_not_found", + "message": "Unknown method" }, "id": "frame-5", "ok": false } } }, - "4cf1a3bc4178": { - "error": "inner refused", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "4eb521bbefdd": { - "name": "githubProjectSearch", - "ordinal": 15, - "value": "is:open" - }, - "4f71c65408bc": { + "0e83c4f2d85c": { "name": "githubProjectError", - "ordinal": 29, - "value": "Connection closed" + "ordinal": 28, + "value": "The host sent a reply this app could not read (github.project.listViews)" }, - "50c2d0683abb": { - "error": "The host sent a reply this app could not read (github.project.listViews)", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "512d99654670": { - "name": "githubProjectError", - "ordinal": 29, - "value": "" - }, - "528af16518e6": { - "name": "githubProjectViews", - "ordinal": 16, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "53954ecf4db4": { - "name": "githubProjectPasteBusy", - "ordinal": 31, - "value": false - }, - "5a4fc5c86d0c": { - "name": "githubProjectPasteBusy", - "ordinal": 34, - "value": false - }, - "5d14c0c6aafb": { - "name": "github.project.listViews#2", - "ordinal": 27, - "args": [ - { - "name": "method", - "value": "github.project.listViews" - }, - { - "name": "params", - "value": { - "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true - } - } - }, - "5f5f56db9d64": { + "0f1aa264f581": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -487,20 +120,31 @@ } } }, - "61ce1ab88e79": { - "name": "github.project.viewTable#1", - "ordinal": 13, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" + "0f65a65096ff": { + "name": "githubProjectPasteBusy", + "ordinal": 30, + "value": false }, - "654693493b51": { - "name": "githubProjectLoading", - "ordinal": 10, - "value": true + "15cb97c93333": { + "name": "github.project.listViews#1", + "ordinal": 8, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" }, - "685bc2bda05d": { - "name": "githubProjects", - "ordinal": 5, - "value": [ + "170fad8cb36b": { + "name": "githubProjectPartialFailures", + "ordinal": 6, + "value": [] + }, + "1b3350f71e56": { + "name": "githubProjectError", + "ordinal": 19, + "value": "" + }, + "1b7a7437b046": { + "error": "", + "loading": true, + "pasteError": "", + "projects": [ { "host": "github.com", "number": 3, @@ -508,96 +152,35 @@ "ownerType": "organization", "title": "Board" } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } ] }, - "74ace6b26c7d": { + "1c37f311588f": { "name": "github.project.listViews#2", - "ordinal": 27, - "args": [ - { - "name": "method", - "value": "github.project.listViews" - }, - { - "name": "params", - "value": { - "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": { - "$rpc": "null" - } - } - } - }, - "7a9df0d1a484": { - "name": "githubProjectLoading", - "ordinal": 25, - "value": true - }, - "7b9d3b33c08b": { - "name": "githubProjectPasteError", - "ordinal": 19, - "value": "" - }, - "840773c717c8": { - "name": "github.project.listViews#2", - "ordinal": 27, - "args": [ - { - "name": "method", - "value": "github.project.listViews" - }, - { - "name": "params", - "value": { - "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-5", - "ok": false - } - } - }, - "84a370049c5f": { - "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, "args": [ { "name": "method", @@ -632,34 +215,274 @@ } } }, - "8792541c60ad": { + "2085118de92f": { "name": "githubProjectError", - "ordinal": 26, + "ordinal": 1, "value": "" }, - "88db645d6267": { + "26921f3a7c09": { + "name": "githubProjectPasteError", + "ordinal": 18, + "value": "" + }, + "2ab1b35ff194": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "2f290fa2acf5": { "name": "githubProjectLoading", - "ordinal": 30, + "ordinal": 9, + "value": true + }, + "3493818a7239": { + "name": "githubProjectPasteBusy", + "ordinal": 33, "value": false }, - "8e4dec1aad1f": { - "name": "github.project.listViews#2", - "ordinal": 28, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + "376c9e8bd72a": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] }, - "8f3ee6c510b1": { - "name": "github.project.resolveRef#1", - "ordinal": 22, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" + "3985399034a2": { + "name": "githubProjectPasteBusy", + "ordinal": 17, + "value": true }, - "9361b1a34966": { + "3a358ec06a2e": { "name": "githubProjectError", - "ordinal": 29, - "value": "inner refused" + "ordinal": 28, + "value": "Unknown method" }, - "98c724fa87df": { + "3a8617cc8fd8": { + "name": "githubProjectSearch", + "ordinal": 14, + "value": "is:open" + }, + "4809ea7ad5b0": { + "name": "github.project.viewTable#1", + "ordinal": 12, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" + }, + "4c9b1e4ad1f5": { + "name": "githubProjectViews", + "ordinal": 28, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "4cf1a3bc4178": { + "error": "inner refused", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "4eec12580715": { + "name": "githubProjectError", + "ordinal": 28, + "value": "Connection closed" + }, + "50c2d0683abb": { + "error": "The host sent a reply this app could not read (github.project.listViews)", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "5f39ee0a111a": { "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, + "args": [ + { + "name": "method", + "value": "github.project.listViews" + }, + { + "name": "params", + "value": { + "host": "github.com", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3 + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true + } + } + }, + "685bc2bda05d": { + "name": "githubProjects", + "ordinal": 5, + "value": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ] + }, + "6b03ace1146a": { + "name": "githubProjectError", + "ordinal": 25, + "value": "" + }, + "751553d01f74": { + "name": "githubProjectError", + "ordinal": 28, + "value": "outer refused" + }, + "7d488eda1d1c": { + "name": "githubProjectViews", + "ordinal": 15, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "7f4d6b5a4c99": { + "name": "github.project.listViews#2", + "ordinal": 26, "args": [ { "name": "method", @@ -695,17 +518,30 @@ } } }, - "9b9f8dd75514": { - "name": "githubProjectViews", - "ordinal": 9, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] + "842c950ee7cc": { + "name": "githubProjectLoading", + "ordinal": 16, + "value": false + }, + "8a0577280bad": { + "name": "showGitHubProjectPicker", + "ordinal": 23, + "value": false + }, + "8d098092a97f": { + "name": "githubProjectLoading", + "ordinal": 29, + "value": false + }, + "97bc7dc12b92": { + "name": "githubProjectLoading", + "ordinal": 32, + "value": false + }, + "9f9a21ac7b9e": { + "name": "github.project.listViews#2", + "ordinal": 27, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" }, "9fb985a7d8f6": { "error": "transport failure", @@ -745,16 +581,51 @@ } ] }, - "a4a1ff5df287": { - "name": "githubProjectPasteBusy", - "ordinal": 18, - "value": true - }, "a5a3530ec11c": { "name": "githubProjectPartialFailures", "ordinal": 2, "value": [] }, + "a6a517418ed9": { + "name": "github.project.listViews#2", + "ordinal": 26, + "args": [ + { + "name": "method", + "value": "github.project.listViews" + }, + { + "name": "params", + "value": { + "host": "github.com", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3 + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true + } + } + }, + "ab1b10183665": { + "name": "githubProjectLoading", + "ordinal": 24, + "value": true + }, "abb28d0939d9": { "error": "Unknown method", "loading": false, @@ -793,47 +664,9 @@ } ] }, - "b1b0d0b13d2e": { - "error": "outer refused", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "b1f9e7039553": { + "ad1c64ff938a": { "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, "args": [ { "name": "method", @@ -856,24 +689,24 @@ } ], "settlement": { - "status": "rejected", + "status": "fulfilled", "startedAt": 0, "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true + "value": { + "id": "frame-5", + "ok": true, + "result": { + "error": { + "message": "inner refused" + }, + "ok": false + } } } }, - "b42c8edc0d53": { - "name": "github.project.listAccessible#1", - "ordinal": 4, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" - }, - "b49ff9f109a5": { + "ae89e058b351": { "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, "args": [ { "name": "method", @@ -916,15 +749,36 @@ } } }, - "b5e354ed6023": { - "name": "githubProjectLoading", - "ordinal": 17, - "value": false - }, - "b66c4f75c9ae": { - "name": "githubProjectViews", - "ordinal": 29, - "value": [ + "b1b0d0b13d2e": { + "error": "outer refused", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ { "id": "view-1", "layout": "TABLE_LAYOUT", @@ -933,42 +787,14 @@ } ] }, - "be0da5b53ffb": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] + "b42c8edc0d53": { + "name": "github.project.listAccessible#1", + "ordinal": 4, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" }, - "bff57ba49c8b": { - "name": "githubProjectError", - "ordinal": 29, - "value": "The host sent a reply this app could not read (github.project.listViews)" - }, - "c180286bc513": { - "name": "githubProjectError", - "ordinal": 29, - "value": "outer refused" - }, - "c453f220a7e2": { - "name": "githubProjectLoading", - "ordinal": 33, - "value": false - }, - "c4c4250b0567": { - "name": "showGitHubProjectPicker", - "ordinal": 24, - "value": false - }, - "c977f7f00437": { + "b61805111271": { "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, "args": [ { "name": "method", @@ -1001,6 +827,162 @@ } } }, + "be0da5b53ffb": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "be93253869e6": { + "name": "github.project.resolveRef#1", + "ordinal": 21, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" + }, + "c26d1df91c18": { + "name": "github.project.listViews#2", + "ordinal": 26, + "args": [ + { + "name": "method", + "value": "github.project.listViews" + }, + { + "name": "params", + "value": { + "host": "github.com", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3 + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-5", + "ok": false + } + } + }, + "c5c018cf9a70": { + "name": "githubProjectTable", + "ordinal": 13, + "value": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + } + }, + "c9b343e9992b": { + "name": "github.project.listViews#2", + "ordinal": 26, + "args": [ + { + "name": "method", + "value": "github.project.listViews" + }, + { + "name": "params", + "value": { + "host": "github.com", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3 + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-5", + "ok": false + } + } + }, + "c9ee089860fc": { + "name": "githubProjectError", + "ordinal": 28, + "value": "" + }, + "cc9ab010bdff": { + "name": "github.project.listViews#2", + "ordinal": 26, + "args": [ + { + "name": "method", + "value": "github.project.listViews" + }, + { + "name": "params", + "value": { + "host": "github.com", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3 + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, "d254913957c1": { "name": "github.project.listViews#1", "ordinal": 7, @@ -1046,40 +1028,10 @@ } } }, - "d9169f17f695": { - "name": "github.project.listViews#2", - "ordinal": 27, - "args": [ - { - "name": "method", - "value": "github.project.listViews" - }, - { - "name": "params", - "value": { - "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "transport failure", - "isRpcDeliveryUnknown": true - } - } + "dc8dd7739c49": { + "name": "githubProjectPasteInput", + "ordinal": 22, + "value": "" }, "dfe16215433b": { "name": "github.project.listAccessible#1", @@ -1125,6 +1077,11 @@ } } }, + "e87bea4bcd3c": { + "name": "githubProjectSearch", + "ordinal": 30, + "value": "" + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -1133,9 +1090,9 @@ "$rpc": "undefined" } }, - "ec5b32385042": { + "ef0715ff99c1": { "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, "args": [ { "name": "method", @@ -1157,36 +1114,67 @@ } } ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "f6003aed2098": { + "name": "github.project.resolveRef#1", + "ordinal": 20, + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], "settlement": { "status": "fulfilled", "startedAt": 0, "settledAt": 0, "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-5", - "ok": false + "id": "frame-4", + "ok": true, + "result": { + "host": "github.com", + "number": 3, + "ok": true, + "owner": "owner", + "ownerType": "organization", + "title": "Board", + "viewNumber": 1 + } } } }, - "fa1d1b339394": { - "name": "appliedGithubProjectSearch", - "ordinal": 30, - "value": { - "$rpc": "undefined" - } - }, - "fb9764680a74": { + "fafc5b2f8260": { "name": "githubProjectError", - "ordinal": 20, - "value": "" + "ordinal": 28, + "value": "inner refused" }, - "fe075936e563": { - "name": "githubProjectSearch", - "ordinal": 31, - "value": "" + "fd895f7d7a4a": { + "name": "githubProjectError", + "ordinal": 28, + "value": "transport failure" }, "ff43b5ec92a9": { "error": "", @@ -1233,21 +1221,15 @@ "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb" }, - "state": "376c9e8bd72a", - "effects": [ - "2085118de92f", - "a5a3530ec11c", - "685bc2bda05d", - "170fad8cb36b", - "9b9f8dd75514" - ] + "state": "ff43b5ec92a9", + "effects": ["2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b"] } }, { "id": "tk-project-board-load.prelude:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1260,13 +1242,12 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc" ] } }, @@ -1276,16 +1257,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "b1f9e7039553" + "0f1aa264f581", + "f6003aed2098", + "ef0715ff99c1" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1300,23 +1281,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "4f71c65408bc", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "4eec12580715", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1326,16 +1306,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "b49ff9f109a5" + "0f1aa264f581", + "f6003aed2098", + "ae89e058b351" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1350,26 +1330,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "b66c4f75c9ae", - "fa1d1b339394", - "fe075936e563", - "34de2d655a0a", - "c453f220a7e2", - "5a4fc5c86d0c" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "4c9b1e4ad1f5", + "0af48d475813", + "e87bea4bcd3c", + "0056704adc0b", + "97bc7dc12b92", + "3493818a7239" ] } }, @@ -1379,16 +1358,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "5d14c0c6aafb" + "0f1aa264f581", + "f6003aed2098", + "5f39ee0a111a" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1403,23 +1382,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "bff57ba49c8b", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "0e83c4f2d85c", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1429,16 +1407,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "74ace6b26c7d" + "0f1aa264f581", + "f6003aed2098", + "cc9ab010bdff" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1453,23 +1431,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "bff57ba49c8b", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "0e83c4f2d85c", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1479,16 +1456,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "84a370049c5f" + "0f1aa264f581", + "f6003aed2098", + "1c37f311588f" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1503,23 +1480,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "bff57ba49c8b", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "0e83c4f2d85c", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1529,16 +1505,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "98c724fa87df" + "0f1aa264f581", + "f6003aed2098", + "7f4d6b5a4c99" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1553,23 +1529,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "bff57ba49c8b", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "0e83c4f2d85c", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1579,16 +1554,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "424eb405bbce" + "0f1aa264f581", + "f6003aed2098", + "ad1c64ff938a" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1603,23 +1578,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "9361b1a34966", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "fafc5b2f8260", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1629,16 +1603,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "ec5b32385042" + "0f1aa264f581", + "f6003aed2098", + "c9b343e9992b" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1653,23 +1627,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "c180286bc513", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "751553d01f74", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1679,16 +1652,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "4c85a08be215" + "0f1aa264f581", + "f6003aed2098", + "c26d1df91c18" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1703,23 +1676,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "512d99654670", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "c9ee089860fc", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1729,16 +1701,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "840773c717c8" + "0f1aa264f581", + "f6003aed2098", + "0b0789528a70" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1753,23 +1725,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "30e01816f729", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "3a358ec06a2e", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1779,16 +1750,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "d9169f17f695" + "0f1aa264f581", + "f6003aed2098", + "a6a517418ed9" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1803,23 +1774,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "3647b0f3edc5", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "fd895f7d7a4a", + "8d098092a97f", + "0f65a65096ff" ] } }, @@ -1829,16 +1799,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "c977f7f00437" + "0f1aa264f581", + "f6003aed2098", + "b61805111271" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1853,23 +1823,22 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "512d99654670", - "88db645d6267", - "53954ecf4db4" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "c9ee089860fc", + "8d098092a97f", + "0f65a65096ff" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.resolveref-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.resolveref-1.json index 58cde3365b9..5e8553f5f4c 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.resolveref-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.resolveref-1.json @@ -4,337 +4,28 @@ "family": "tasks.project-board-load", "namedDeltas": [], "values": { - "00ef2dbe5026": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "host": "github.com", - "number": 3, - "ok": true, - "owner": "owner", - "ownerType": "organization", - "title": "Board", - "viewNumber": 1 - } - } - } - }, - "0388fa155721": { - "name": "githubProjectError", - "ordinal": 11, - "value": "" - }, - "15cb97c93333": { - "name": "github.project.listViews#1", - "ordinal": 8, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "170fad8cb36b": { - "name": "githubProjectPartialFailures", - "ordinal": 6, - "value": [] - }, - "18730c72400e": { - "name": "githubProjectPasteError", - "ordinal": 23, - "value": "transport failure" - }, - "2085118de92f": { - "name": "githubProjectError", - "ordinal": 1, - "value": "" - }, - "2a8155b82ef9": { - "name": "githubProjectPasteError", - "ordinal": 23, - "value": "" - }, - "2ab1b35ff194": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "34de2d655a0a": { + "0056704adc0b": { "name": "githubProjectTable", - "ordinal": 32, + "ordinal": 31, "value": { "$rpc": "null" } }, - "376c9e8bd72a": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "43352776b1e1": { - "name": "githubProjectTable", - "ordinal": 14, - "value": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - } - }, - "465d38db6be4": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "method_not_found", - "message": "Unknown method" - }, - "id": "frame-4", - "ok": false - } - } - }, - "46c31323dfa8": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "$rpc": "null" - } - } - } - }, - "47507819e28a": { - "name": "githubProjectPasteInput", - "ordinal": 23, + "060dcedb3fdb": { + "name": "githubProjectError", + "ordinal": 10, "value": "" }, - "4eb521bbefdd": { - "name": "githubProjectSearch", - "ordinal": 15, - "value": "is:open" - }, - "5024dbdf5e74": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-4", - "ok": false - } + "0af48d475813": { + "name": "appliedGithubProjectSearch", + "ordinal": 29, + "value": { + "$rpc": "undefined" } }, - "528af16518e6": { - "name": "githubProjectViews", - "ordinal": 16, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "542d281c736b": { - "error": "", - "loading": false, - "pasteError": "inner refused", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "5951b5b05f73": { + "0ca4eea3be22": { "name": "github.project.resolveRef#1", - "ordinal": 21, + "ordinal": 20, "args": [ { "name": "method", @@ -365,19 +56,9 @@ } } }, - "5a4fc5c86d0c": { - "name": "githubProjectPasteBusy", - "ordinal": 34, - "value": false - }, - "5d6bee5dd65e": { - "name": "githubProjectPasteError", - "ordinal": 23, - "value": "inner refused" - }, - "5f5f56db9d64": { + "0f1aa264f581": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -429,20 +110,36 @@ } } }, - "61ce1ab88e79": { - "name": "github.project.viewTable#1", - "ordinal": 13, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" + "15cb97c93333": { + "name": "github.project.listViews#1", + "ordinal": 8, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" }, - "654693493b51": { - "name": "githubProjectLoading", - "ordinal": 10, - "value": true + "170fad8cb36b": { + "name": "githubProjectPartialFailures", + "ordinal": 6, + "value": [] }, - "685bc2bda05d": { - "name": "githubProjects", - "ordinal": 5, - "value": [ + "1b3350f71e56": { + "name": "githubProjectError", + "ordinal": 19, + "value": "" + }, + "2085118de92f": { + "name": "githubProjectError", + "ordinal": 1, + "value": "" + }, + "26921f3a7c09": { + "name": "githubProjectPasteError", + "ordinal": 18, + "value": "" + }, + "2ab1b35ff194": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ { "host": "github.com", "number": 3, @@ -450,26 +147,113 @@ "ownerType": "organization", "title": "Board" } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } ] }, - "7a9df0d1a484": { + "2f290fa2acf5": { "name": "githubProjectLoading", - "ordinal": 25, + "ordinal": 9, "value": true }, - "7b9d3b33c08b": { - "name": "githubProjectPasteError", - "ordinal": 19, - "value": "" - }, - "8792541c60ad": { - "name": "githubProjectError", - "ordinal": 26, - "value": "" - }, - "8a72ceddc317": { + "31ab0657cc7f": { "name": "github.project.resolveRef#1", - "ordinal": 21, + "ordinal": 20, + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true + } + } + }, + "3493818a7239": { + "name": "githubProjectPasteBusy", + "ordinal": 33, + "value": false + }, + "376c9e8bd72a": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "391bce43fe1e": { + "name": "githubProjectPasteError", + "ordinal": 22, + "value": "outer refused" + }, + "3985399034a2": { + "name": "githubProjectPasteBusy", + "ordinal": 17, + "value": true + }, + "3a7b38a0c9ac": { + "name": "github.project.resolveRef#1", + "ordinal": 20, "args": [ { "name": "method", @@ -494,29 +278,106 @@ "startedAt": 0, "settledAt": 0, "value": { + "error": { + "code": "method_not_found", + "message": "Unknown method" + }, "id": "frame-4", - "ok": true + "ok": false } } }, - "8adfaab42f53": { - "name": "githubProjectPasteError", + "3a8617cc8fd8": { + "name": "githubProjectSearch", + "ordinal": 14, + "value": "is:open" + }, + "443c462833d9": { + "name": "githubProjectPasteBusy", "ordinal": 23, - "value": "The host sent a reply this app could not read (github.project.resolveRef)" + "value": false }, - "8e4dec1aad1f": { - "name": "github.project.listViews#2", + "4809ea7ad5b0": { + "name": "github.project.viewTable#1", + "ordinal": 12, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" + }, + "4c9b1e4ad1f5": { + "name": "githubProjectViews", "ordinal": 28, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] }, - "8f3ee6c510b1": { - "name": "github.project.resolveRef#1", + "542d281c736b": { + "error": "", + "loading": false, + "pasteError": "inner refused", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "685bc2bda05d": { + "name": "githubProjects", + "ordinal": 5, + "value": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ] + }, + "6b03ace1146a": { + "name": "githubProjectError", + "ordinal": 25, + "value": "" + }, + "7077303e9304": { + "name": "githubProjectPasteError", "ordinal": 22, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" + "value": "" }, - "8fde76b45dd3": { + "739b3c66b6a2": { "name": "github.project.resolveRef#1", - "ordinal": 21, + "ordinal": 20, "args": [ { "name": "method", @@ -549,6 +410,69 @@ } } }, + "788e250ac87a": { + "name": "githubProjectPasteError", + "ordinal": 22, + "value": "transport failure" + }, + "7aa0558cb955": { + "name": "github.project.resolveRef#1", + "ordinal": 20, + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-4", + "ok": false + } + } + }, + "7d488eda1d1c": { + "name": "githubProjectViews", + "ordinal": 15, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "842c950ee7cc": { + "name": "githubProjectLoading", + "ordinal": 16, + "value": false + }, + "8a0577280bad": { + "name": "showGitHubProjectPicker", + "ordinal": 23, + "value": false + }, "933fa40d28dd": { "error": "", "loading": false, @@ -587,17 +511,15 @@ } ] }, - "9b9f8dd75514": { - "name": "githubProjectViews", - "ordinal": 9, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] + "97bc7dc12b92": { + "name": "githubProjectLoading", + "ordinal": 32, + "value": false + }, + "9f9a21ac7b9e": { + "name": "github.project.listViews#2", + "ordinal": 27, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" }, "9fa2b69acf20": { "error": "", @@ -637,16 +559,61 @@ } ] }, - "a4a1ff5df287": { - "name": "githubProjectPasteBusy", - "ordinal": 18, - "value": true - }, "a5a3530ec11c": { "name": "githubProjectPartialFailures", "ordinal": 2, "value": [] }, + "ab1b10183665": { + "name": "githubProjectLoading", + "ordinal": 24, + "value": true + }, + "ae89e058b351": { + "name": "github.project.listViews#2", + "ordinal": 26, + "args": [ + { + "name": "method", + "value": "github.project.listViews" + }, + { + "name": "params", + "value": { + "host": "github.com", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3 + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "ok": true, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + } + } + } + }, "afec7622eabf": { "error": "", "loading": false, @@ -690,21 +657,19 @@ "ordinal": 4, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" }, - "b49ff9f109a5": { - "name": "github.project.listViews#2", - "ordinal": 27, + "b9a0bb850981": { + "name": "github.project.resolveRef#1", + "ordinal": 20, "args": [ { "name": "method", - "value": "github.project.listViews" + "value": "github.project.resolveRef" }, { "name": "params", "value": { "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 + "input": "https://github.com/orgs/owner/projects/3" } }, { @@ -719,48 +684,47 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-5", - "ok": true, - "result": { - "ok": true, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - } + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-4", + "ok": false } } }, - "b5e354ed6023": { - "name": "githubProjectLoading", - "ordinal": 17, - "value": false - }, - "b66c4f75c9ae": { - "name": "githubProjectViews", - "ordinal": 29, - "value": [ + "bafe760119a6": { + "name": "github.project.resolveRef#1", + "ordinal": 20, + "args": [ { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } } - ] - }, - "b6df36be8f90": { - "name": "githubProjectPasteError", - "ordinal": 23, - "value": "outer refused" - }, - "bc2bd1d942ef": { - "name": "githubProjectPasteError", - "ordinal": 23, - "value": "Connection closed" + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } }, "be0da5b53ffb": { "status": "fulfilled", @@ -775,24 +739,14 @@ } ] }, - "c453f220a7e2": { - "name": "githubProjectLoading", - "ordinal": 33, - "value": false - }, - "c4c4250b0567": { - "name": "showGitHubProjectPicker", - "ordinal": 24, - "value": false - }, - "c515348730c9": { - "name": "githubProjectPasteBusy", - "ordinal": 24, - "value": false - }, - "cc98f00a21a3": { + "be93253869e6": { "name": "github.project.resolveRef#1", "ordinal": 21, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" + }, + "c14b88cb8a3c": { + "name": "github.project.resolveRef#1", + "ordinal": 20, "args": [ { "name": "method", @@ -818,16 +772,40 @@ "settledAt": 0, "value": { "id": "frame-4", - "ok": true, - "result": { - "error": { - "message": "inner refused" - }, - "ok": false - } + "ok": true } } }, + "c5c018cf9a70": { + "name": "githubProjectTable", + "ordinal": 13, + "value": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + } + }, + "cb9760e05f8b": { + "name": "githubProjectPasteError", + "ordinal": 22, + "value": "inner refused" + }, + "cdbe61ef88d1": { + "name": "githubProjectPasteError", + "ordinal": 22, + "value": "Unknown method" + }, "d254913957c1": { "name": "github.project.listViews#1", "ordinal": 7, @@ -873,39 +851,6 @@ } } }, - "d4d16c7bdef6": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "d76c24e12352": { "error": "", "loading": false, @@ -944,9 +889,14 @@ } ] }, - "df21422c7f88": { + "da1ff0cf92cb": { + "name": "githubProjectPasteError", + "ordinal": 22, + "value": "Connection closed" + }, + "dbfc3ca85bba": { "name": "github.project.resolveRef#1", - "ordinal": 21, + "ordinal": 20, "args": [ { "name": "method", @@ -980,6 +930,46 @@ } } }, + "dc8dd7739c49": { + "name": "githubProjectPasteInput", + "ordinal": 22, + "value": "" + }, + "df1869ad0832": { + "name": "github.project.resolveRef#1", + "ordinal": 20, + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, "dfe16215433b": { "name": "github.project.listAccessible#1", "ordinal": 3, @@ -1024,9 +1014,9 @@ } } }, - "e30593392371": { + "e0b72749150e": { "name": "github.project.resolveRef#1", - "ordinal": 21, + "ordinal": 20, "args": [ { "name": "method", @@ -1051,19 +1041,26 @@ "startedAt": 0, "settledAt": 0, "value": { - "error": { - "code": "refused", - "message": "" - }, "id": "frame-4", - "ok": false + "ok": true, + "result": { + "error": { + "message": "inner refused" + }, + "ok": false + } } } }, - "e44d2225bc12": { + "e5561b967e66": { "name": "githubProjectPasteError", - "ordinal": 23, - "value": "Unknown method" + "ordinal": 22, + "value": "The host sent a reply this app could not read (github.project.resolveRef)" + }, + "e87bea4bcd3c": { + "name": "githubProjectSearch", + "ordinal": 30, + "value": "" }, "eb79a9b3682a": { "status": "fulfilled", @@ -1073,9 +1070,9 @@ "$rpc": "undefined" } }, - "f938107bbefd": { + "f6003aed2098": { "name": "github.project.resolveRef#1", - "ordinal": 21, + "ordinal": 20, "args": [ { "name": "method", @@ -1096,33 +1093,24 @@ } ], "settlement": { - "status": "rejected", + "status": "fulfilled", "startedAt": 0, "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true + "value": { + "id": "frame-4", + "ok": true, + "result": { + "host": "github.com", + "number": 3, + "ok": true, + "owner": "owner", + "ownerType": "organization", + "title": "Board", + "viewNumber": 1 + } } } }, - "fa1d1b339394": { - "name": "appliedGithubProjectSearch", - "ordinal": 30, - "value": { - "$rpc": "undefined" - } - }, - "fb9764680a74": { - "name": "githubProjectError", - "ordinal": 20, - "value": "" - }, - "fe075936e563": { - "name": "githubProjectSearch", - "ordinal": 31, - "value": "" - }, "ff43b5ec92a9": { "error": "", "loading": false, @@ -1168,21 +1156,15 @@ "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb" }, - "state": "376c9e8bd72a", - "effects": [ - "2085118de92f", - "a5a3530ec11c", - "685bc2bda05d", - "170fad8cb36b", - "9b9f8dd75514" - ] + "state": "ff43b5ec92a9", + "effects": ["2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b"] } }, { "id": "tk-project-board-load.prelude:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1195,21 +1177,20 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc" ] } }, { "id": "tk-project-board-load.prelude:cleanup", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "d4d16c7bdef6"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "bafe760119a6"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1223,18 +1204,17 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "bc2bd1d942ef", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "da1ff0cf92cb", + "443c462833d9" ] } }, @@ -1244,16 +1224,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "b49ff9f109a5" + "0f1aa264f581", + "f6003aed2098", + "ae89e058b351" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1268,34 +1248,33 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "b66c4f75c9ae", - "fa1d1b339394", - "fe075936e563", - "34de2d655a0a", - "c453f220a7e2", - "5a4fc5c86d0c" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "4c9b1e4ad1f5", + "0af48d475813", + "e87bea4bcd3c", + "0056704adc0b", + "97bc7dc12b92", + "3493818a7239" ] } }, { "id": "tk-project-board-load.result-absent:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "8a72ceddc317"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "c14b88cb8a3c"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1309,26 +1288,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "8adfaab42f53", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "e5561b967e66", + "443c462833d9" ] } }, { "id": "tk-project-board-load.result-null:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "46c31323dfa8"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "df1869ad0832"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1342,26 +1320,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "8adfaab42f53", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "e5561b967e66", + "443c462833d9" ] } }, { "id": "tk-project-board-load.inner-ok-missing:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "8fde76b45dd3"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "739b3c66b6a2"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1375,26 +1352,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "8adfaab42f53", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "e5561b967e66", + "443c462833d9" ] } }, { "id": "tk-project-board-load.inner-false-string-error:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "df21422c7f88"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "dbfc3ca85bba"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1408,26 +1384,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "8adfaab42f53", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "e5561b967e66", + "443c462833d9" ] } }, { "id": "tk-project-board-load.inner-false-object-error:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "cc98f00a21a3"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "e0b72749150e"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1441,26 +1416,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "5d6bee5dd65e", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "cb9760e05f8b", + "443c462833d9" ] } }, { "id": "tk-project-board-load.outer-refused:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "5024dbdf5e74"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "7aa0558cb955"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1474,26 +1448,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "b6df36be8f90", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "391bce43fe1e", + "443c462833d9" ] } }, { "id": "tk-project-board-load.outer-refused-no-message:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "e30593392371"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "b9a0bb850981"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1507,26 +1480,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "2a8155b82ef9", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "7077303e9304", + "443c462833d9" ] } }, { "id": "tk-project-board-load.method-not-found:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "465d38db6be4"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "3a7b38a0c9ac"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1540,26 +1512,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "e44d2225bc12", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "cdbe61ef88d1", + "443c462833d9" ] } }, { "id": "tk-project-board-load.transport-rejection:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "5951b5b05f73"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "0ca4eea3be22"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1573,26 +1544,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "18730c72400e", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "788e250ac87a", + "443c462833d9" ] } }, { "id": "tk-project-board-load.transport-rejection-no-message:paste-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64", "f938107bbefd"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79", "8f3ee6c510b1"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581", "31ab0657cc7f"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0", "be93253869e6"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1606,18 +1576,17 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "2a8155b82ef9", - "c515348730c9" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "7077303e9304", + "443c462833d9" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.viewtable-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.viewtable-1.json index d70e7f92067..3a719362572 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.viewtable-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.project-board-load-github.project.viewtable-1.json @@ -11,90 +11,26 @@ "$rpc": "null" } }, - "00ef2dbe5026": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "host": "github.com", - "number": 3, - "ok": true, - "owner": "owner", - "ownerType": "organization", - "title": "Board", - "viewNumber": 1 - } - } - } - }, - "0388fa155721": { - "name": "githubProjectError", - "ordinal": 11, + "03fc33b06333": { + "name": "githubProjectPasteError", + "ordinal": 17, "value": "" }, - "044db2a7250c": { - "name": "github.project.viewTable#1", - "ordinal": 12, - "args": [ - { - "name": "method", - "value": "github.project.viewTable" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3, - "viewId": "view-1" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 60000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true - } + "060dcedb3fdb": { + "name": "githubProjectError", + "ordinal": 10, + "value": "" + }, + "0af48d475813": { + "name": "appliedGithubProjectSearch", + "ordinal": 29, + "value": { + "$rpc": "undefined" } }, - "08b8713b9aa5": { + "0d97c3fd4fe1": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -131,308 +67,9 @@ } } }, - "0af48d475813": { - "name": "appliedGithubProjectSearch", - "ordinal": 29, - "value": { - "$rpc": "undefined" - } - }, - "0efd754f1a5c": { - "name": "githubProjectError", - "ordinal": 15, - "value": "The host sent a reply this app could not read (github.project.viewTable)" - }, - "15cb97c93333": { - "name": "github.project.listViews#1", - "ordinal": 8, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "170fad8cb36b": { - "name": "githubProjectPartialFailures", - "ordinal": 6, - "value": [] - }, - "1b3350f71e56": { - "name": "githubProjectError", - "ordinal": 19, - "value": "" - }, - "1da3c3839c7a": { - "name": "githubProjectError", - "ordinal": 15, - "value": "transport failure" - }, - "2085118de92f": { - "name": "githubProjectError", - "ordinal": 1, - "value": "" - }, - "26921f3a7c09": { - "name": "githubProjectPasteError", - "ordinal": 18, - "value": "" - }, - "273acec61723": { + "0f1aa264f581": { "name": "github.project.viewTable#1", - "ordinal": 12, - "args": [ - { - "name": "method", - "value": "github.project.viewTable" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3, - "viewId": "view-1" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 60000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "$rpc": "null" - } - } - } - }, - "2a4866c4dda3": { - "error": "outer refused", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "2ab1b35ff194": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "2fc294f6693b": { - "error": "The host sent a reply this app could not read (github.project.viewTable)", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "3493818a7239": { - "name": "githubProjectPasteBusy", - "ordinal": 33, - "value": false - }, - "34de2d655a0a": { - "name": "githubProjectTable", - "ordinal": 32, - "value": { - "$rpc": "null" - } - }, - "376c9e8bd72a": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "3985399034a2": { - "name": "githubProjectPasteBusy", - "ordinal": 17, - "value": true - }, - "43352776b1e1": { - "name": "githubProjectTable", - "ordinal": 14, - "value": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - } - }, - "47507819e28a": { - "name": "githubProjectPasteInput", - "ordinal": 23, - "value": "" - }, - "4c9b1e4ad1f5": { - "name": "githubProjectViews", - "ordinal": 28, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "4eb521bbefdd": { - "name": "githubProjectSearch", - "ordinal": 15, - "value": "is:open" - }, - "528af16518e6": { - "name": "githubProjectViews", - "ordinal": 16, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "56f0120745a9": { - "error": "inner refused", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "5a4fc5c86d0c": { - "name": "githubProjectPasteBusy", - "ordinal": 34, - "value": false - }, - "5abab014ad66": { - "name": "githubProjectError", - "ordinal": 15, - "value": "" - }, - "5f5f56db9d64": { - "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -484,37 +121,34 @@ } } }, - "61ce1ab88e79": { - "name": "github.project.viewTable#1", - "ordinal": 13, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" + "15cb97c93333": { + "name": "github.project.listViews#1", + "ordinal": 8, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" }, - "654693493b51": { - "name": "githubProjectLoading", - "ordinal": 10, - "value": true + "170fad8cb36b": { + "name": "githubProjectPartialFailures", + "ordinal": 6, + "value": [] }, - "685bc2bda05d": { - "name": "githubProjects", - "ordinal": 5, - "value": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ] - }, - "6b03ace1146a": { + "1b3350f71e56": { "name": "githubProjectError", - "ordinal": 25, + "ordinal": 19, "value": "" }, - "712a0bd65cc5": { + "1cb3b185586b": { + "name": "githubProjectLoading", + "ordinal": 31, + "value": false + }, + "2085118de92f": { + "name": "githubProjectError", + "ordinal": 1, + "value": "" + }, + "20a31104f552": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -538,67 +172,34 @@ } ], "settlement": { - "status": "fulfilled", + "status": "rejected", "startedAt": 0, "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-3", - "ok": false + "error": { + "category": "Error", + "message": "", + "isRpcDeliveryUnknown": true } } }, - "74f8ab788f2e": { - "error": "", - "loading": true, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "7a9df0d1a484": { - "name": "githubProjectLoading", - "ordinal": 25, - "value": true - }, - "7b9d3b33c08b": { - "name": "githubProjectPasteError", - "ordinal": 19, + "223225c09f07": { + "name": "githubProjectSearch", + "ordinal": 29, "value": "" }, - "842c950ee7cc": { - "name": "githubProjectLoading", - "ordinal": 16, - "value": false - }, - "8792541c60ad": { + "225520fed6bc": { "name": "githubProjectError", - "ordinal": 26, + "ordinal": 14, + "value": "Unknown method" + }, + "24c9c9ebd660": { + "name": "githubProjectError", + "ordinal": 14, "value": "" }, - "882fad444878": { + "255654e42ca3": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -629,34 +230,201 @@ "id": "frame-3", "ok": true, "result": { - "error": "refused" + "error": "inner refused", + "ok": false } } } }, - "8a0577280bad": { - "name": "showGitHubProjectPicker", - "ordinal": 23, - "value": false + "26921f3a7c09": { + "name": "githubProjectPasteError", + "ordinal": 18, + "value": "" }, - "8e4dec1aad1f": { - "name": "github.project.listViews#2", - "ordinal": 28, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + "2ab1b35ff194": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] }, - "8f3ee6c510b1": { - "name": "github.project.resolveRef#1", - "ordinal": 22, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" - }, - "97bc7dc12b92": { + "2f290fa2acf5": { "name": "githubProjectLoading", - "ordinal": 32, + "ordinal": 9, + "value": true + }, + "314fcc8d93cf": { + "name": "githubProjectError", + "ordinal": 14, + "value": "inner refused" + }, + "32e88f5c4657": { + "name": "githubProjectPasteInput", + "ordinal": 21, + "value": "" + }, + "3493818a7239": { + "name": "githubProjectPasteBusy", + "ordinal": 33, "value": false }, - "9883026698a2": { + "376c9e8bd72a": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "386bb2eaf03b": { + "name": "githubProjectError", + "ordinal": 14, + "value": "transport failure" + }, + "3985399034a2": { + "name": "githubProjectPasteBusy", + "ordinal": 17, + "value": true + }, + "3a8617cc8fd8": { + "name": "githubProjectSearch", + "ordinal": 14, + "value": "is:open" + }, + "3b234269eaf1": { + "error": "inner refused", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [] + }, + "40f6e42cd4ab": { + "name": "github.project.viewTable#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.project.viewTable" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3, + "viewId": "view-1" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 60000 + } + } + ], + "settlement": { + "status": "rejected", + "startedAt": 0, + "settledAt": 0, + "error": { + "category": "Error", + "message": "Connection closed", + "isRpcDeliveryUnknown": true + } + } + }, + "4809ea7ad5b0": { "name": "github.project.viewTable#1", "ordinal": 12, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" + }, + "4c9b1e4ad1f5": { + "name": "githubProjectViews", + "ordinal": 28, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "4dd8cc8f777d": { + "name": "appliedGithubProjectSearch", + "ordinal": 28, + "value": { + "$rpc": "undefined" + } + }, + "4dff29ea88de": { + "name": "github.project.resolveRef#1", + "ordinal": 20, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" + }, + "557d7f2cc92b": { + "name": "github.project.viewTable#1", + "ordinal": 11, "args": [ { "name": "method", @@ -684,55 +452,26 @@ "startedAt": 0, "settledAt": 0, "value": { - "error": { - "code": "refused", - "message": "" - }, "id": "frame-3", - "ok": false + "ok": true } } }, - "9b9f8dd75514": { - "name": "githubProjectViews", - "ordinal": 9, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "9bdd7e2522fe": { - "name": "githubProjectError", - "ordinal": 15, - "value": "inner refused" - }, - "9f9a21ac7b9e": { - "name": "github.project.listViews#2", - "ordinal": 27, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "a093143e7c52": { - "name": "githubProjectError", - "ordinal": 15, - "value": "Unknown method" - }, - "a4a1ff5df287": { + "5a7676ce26d6": { "name": "githubProjectPasteBusy", - "ordinal": 18, - "value": true + "ordinal": 32, + "value": false }, - "a5a3530ec11c": { - "name": "githubProjectPartialFailures", - "ordinal": 2, - "value": [] + "5c93fbf94a2d": { + "name": "githubProjectTable", + "ordinal": 30, + "value": { + "$rpc": "null" + } }, - "a8981fbe7e87": { + "684390d0103b": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -766,11 +505,269 @@ } } }, + "685bc2bda05d": { + "name": "githubProjects", + "ordinal": 5, + "value": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ] + }, + "6b03ace1146a": { + "name": "githubProjectError", + "ordinal": 25, + "value": "" + }, + "6d7ebc9b7830": { + "name": "github.project.listViews#2", + "ordinal": 25, + "args": [ + { + "name": "method", + "value": "github.project.listViews" + }, + { + "name": "params", + "value": { + "host": "github.com", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3 + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "ok": true, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + } + } + } + }, + "76df36bab005": { + "error": "The host sent a reply this app could not read (github.project.viewTable)", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [] + }, + "7733d6566538": { + "name": "githubProjectError", + "ordinal": 14, + "value": "outer refused" + }, + "79fdb5f09c0a": { + "name": "github.project.viewTable#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.project.viewTable" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3, + "viewId": "view-1" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 60000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "$rpc": "null" + } + } + } + }, + "7d488eda1d1c": { + "name": "githubProjectViews", + "ordinal": 15, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "7d7e6f5ce421": { + "name": "github.project.resolveRef#1", + "ordinal": 19, + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "host": "github.com", + "number": 3, + "ok": true, + "owner": "owner", + "ownerType": "organization", + "title": "Board", + "viewNumber": 1 + } + } + } + }, + "842c950ee7cc": { + "name": "githubProjectLoading", + "ordinal": 16, + "value": false + }, + "853d951cf70a": { + "name": "githubProjectError", + "ordinal": 18, + "value": "" + }, + "8a0577280bad": { + "name": "showGitHubProjectPicker", + "ordinal": 23, + "value": false + }, + "8dd2b5b6a8af": { + "name": "githubProjectError", + "ordinal": 14, + "value": "Connection closed" + }, + "97bc7dc12b92": { + "name": "githubProjectLoading", + "ordinal": 32, + "value": false + }, + "9ac407eccd6f": { + "error": "", + "loading": true, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [] + }, + "9f9a21ac7b9e": { + "name": "github.project.listViews#2", + "ordinal": 27, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + }, + "9fca7187b60f": { + "name": "githubProjectError", + "ordinal": 14, + "value": "The host sent a reply this app could not read (github.project.viewTable)" + }, + "a4635ab3551f": { + "name": "githubProjectLoading", + "ordinal": 15, + "value": false + }, + "a5a3530ec11c": { + "name": "githubProjectPartialFailures", + "ordinal": 2, + "value": [] + }, "ab1b10183665": { "name": "githubProjectLoading", "ordinal": 24, "value": true }, + "ac891a7d42d5": { + "error": "transport failure", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [] + }, "ae89e058b351": { "name": "github.project.listViews#2", "ordinal": 26, @@ -816,109 +813,9 @@ } } }, - "b42c8edc0d53": { - "name": "github.project.listAccessible#1", - "ordinal": 4, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" - }, - "b49ff9f109a5": { - "name": "github.project.listViews#2", - "ordinal": 27, - "args": [ - { - "name": "method", - "value": "github.project.listViews" - }, - { - "name": "params", - "value": { - "host": "github.com", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3 - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": { - "ok": true, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - } - } - } - }, - "b5e354ed6023": { - "name": "githubProjectLoading", - "ordinal": 17, - "value": false - }, - "b66c4f75c9ae": { - "name": "githubProjectViews", - "ordinal": 29, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "bb54b9df1041": { - "name": "githubProjectError", - "ordinal": 15, - "value": "Connection closed" - }, - "be0da5b53ffb": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "be93253869e6": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" - }, - "c453f220a7e2": { - "name": "githubProjectLoading", - "ordinal": 33, - "value": false - }, - "c4c4250b0567": { - "name": "showGitHubProjectPicker", - "ordinal": 24, - "value": false - }, - "c95a406e53e5": { + "aefed6d1365a": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -942,16 +839,140 @@ } ], "settlement": { - "status": "rejected", + "status": "fulfilled", "startedAt": 0, "settledAt": 0, - "error": { - "category": "Error", - "message": "", - "isRpcDeliveryUnknown": true + "value": { + "error": { + "code": "refused", + "message": "" + }, + "id": "frame-3", + "ok": false } } }, + "b0c25dac9d8e": { + "name": "github.project.listViews#2", + "ordinal": 26, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + }, + "b42c8edc0d53": { + "name": "github.project.listAccessible#1", + "ordinal": 4, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" + }, + "b5f49e20fef1": { + "name": "showGitHubProjectPicker", + "ordinal": 22, + "value": false + }, + "be0da5b53ffb": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "be93253869e6": { + "name": "github.project.resolveRef#1", + "ordinal": 21, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" + }, + "c5c018cf9a70": { + "name": "githubProjectTable", + "ordinal": 13, + "value": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + } + }, + "c930bdc29ecd": { + "error": "Unknown method", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [] + }, + "cf71fba0b2df": { + "name": "github.project.viewTable#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.project.viewTable" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3, + "viewId": "view-1" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 60000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "d0248d16609f": { + "name": "githubProjectViews", + "ordinal": 27, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, "d254913957c1": { "name": "github.project.listViews#1", "ordinal": 7, @@ -997,120 +1018,16 @@ } } }, - "da50b440ea30": { - "name": "githubProjectTable", - "ordinal": 14, - "value": { - "$rpc": "null" - } - }, - "dc231c7924ca": { - "name": "github.project.viewTable#1", - "ordinal": 12, - "args": [ - { - "name": "method", - "value": "github.project.viewTable" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3, - "viewId": "view-1" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 60000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-3", - "ok": true, - "result": { - "error": { - "message": "inner refused" - }, - "ok": false - } - } - } + "d494afc83352": { + "name": "githubProjectError", + "ordinal": 24, + "value": "" }, "dc8dd7739c49": { "name": "githubProjectPasteInput", "ordinal": 22, "value": "" }, - "de19f9b2e75a": { - "error": "transport failure", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "df77a1fd9072": { - "name": "github.project.viewTable#1", - "ordinal": 12, - "args": [ - { - "name": "method", - "value": "github.project.viewTable" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "owner": "owner", - "ownerType": "organization", - "projectNumber": 3, - "viewId": "view-1" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 60000 - } - } - ], - "settlement": { - "status": "rejected", - "startedAt": 0, - "settledAt": 0, - "error": { - "category": "Error", - "message": "Connection closed", - "isRpcDeliveryUnknown": true - } - } - }, "dfe16215433b": { "name": "github.project.listAccessible#1", "ordinal": 3, @@ -1155,16 +1072,75 @@ } } }, - "e3836d43e8f9": { - "name": "githubProjectError", - "ordinal": 15, - "value": "outer refused" + "e585e7eb63ee": { + "name": "github.project.viewTable#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.project.viewTable" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "owner": "owner", + "ownerType": "organization", + "projectNumber": 3, + "viewId": "view-1" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 60000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "error": { + "message": "inner refused" + }, + "ok": false + } + } + } }, "e87bea4bcd3c": { "name": "githubProjectSearch", "ordinal": 30, "value": "" }, + "ea31cb0db515": { + "error": "outer refused", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [] + }, + "ea8f8a6f07b1": { + "name": "githubProjectPasteBusy", + "ordinal": 16, + "value": true + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -1214,9 +1190,21 @@ } } }, - "f63257cab3e5": { + "f79f5682a27b": { + "name": "githubProjectLoading", + "ordinal": 23, + "value": true + }, + "fcd647d64faf": { + "name": "githubProjectTable", + "ordinal": 13, + "value": { + "$rpc": "null" + } + }, + "fe7fc1853f9e": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -1244,57 +1232,15 @@ "startedAt": 0, "settledAt": 0, "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, "id": "frame-3", - "ok": true, - "result": { - "error": "inner refused", - "ok": false - } + "ok": false } } }, - "fa1d1b339394": { - "name": "appliedGithubProjectSearch", - "ordinal": 30, - "value": { - "$rpc": "undefined" - } - }, - "fb9764680a74": { - "name": "githubProjectError", - "ordinal": 20, - "value": "" - }, - "fd9fcbd54752": { - "error": "Unknown method", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "fe075936e563": { - "name": "githubProjectSearch", - "ordinal": 31, - "value": "" - }, "ff43b5ec92a9": { "error": "", "loading": false, @@ -1340,47 +1286,40 @@ "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb" }, - "state": "376c9e8bd72a", - "effects": [ - "2085118de92f", - "a5a3530ec11c", - "685bc2bda05d", - "170fad8cb36b", - "9b9f8dd75514" - ] + "state": "ff43b5ec92a9", + "effects": ["2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b"] } }, { "id": "tk-project-board-load.prelude:cleanup", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "df77a1fd9072"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "40f6e42cd4ab"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "74f8ab788f2e", + "state": "9ac407eccd6f", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "bb54b9df1041", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "8dd2b5b6a8af", + "a4635ab3551f" ] } }, { "id": "tk-project-board-load.normal:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -1393,13 +1332,12 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc" ] } }, @@ -1409,16 +1347,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "b49ff9f109a5" + "0f1aa264f581", + "f6003aed2098", + "ae89e058b351" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1433,52 +1371,50 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "b66c4f75c9ae", - "fa1d1b339394", - "fe075936e563", - "34de2d655a0a", - "c453f220a7e2", - "5a4fc5c86d0c" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "4c9b1e4ad1f5", + "0af48d475813", + "e87bea4bcd3c", + "0056704adc0b", + "97bc7dc12b92", + "3493818a7239" ] } }, { "id": "tk-project-board-load.result-absent:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "044db2a7250c"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "557d7f2cc92b"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "2fc294f6693b", + "state": "76df36bab005", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f" ] } }, @@ -1488,16 +1424,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "044db2a7250c", - "f6003aed2098", - "ae89e058b351" + "557d7f2cc92b", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1512,51 +1448,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.result-null:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "273acec61723"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "79fdb5f09c0a"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "2fc294f6693b", + "state": "76df36bab005", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f" ] } }, @@ -1566,16 +1500,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "273acec61723", - "f6003aed2098", - "ae89e058b351" + "79fdb5f09c0a", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1590,51 +1524,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.inner-ok-missing:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "882fad444878"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "cf71fba0b2df"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "2fc294f6693b", + "state": "76df36bab005", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f" ] } }, @@ -1644,16 +1576,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "882fad444878", - "f6003aed2098", - "ae89e058b351" + "cf71fba0b2df", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1668,51 +1600,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.inner-false-string-error:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "f63257cab3e5"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "255654e42ca3"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "2fc294f6693b", + "state": "76df36bab005", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f" ] } }, @@ -1722,16 +1652,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "f63257cab3e5", - "f6003aed2098", - "ae89e058b351" + "255654e42ca3", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1746,51 +1676,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "0efd754f1a5c", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "9fca7187b60f", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.inner-false-object-error:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "dc231c7924ca"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "e585e7eb63ee"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "56f0120745a9", + "state": "3b234269eaf1", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "9bdd7e2522fe", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "314fcc8d93cf", + "a4635ab3551f" ] } }, @@ -1800,16 +1728,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "dc231c7924ca", - "f6003aed2098", - "ae89e058b351" + "e585e7eb63ee", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1824,51 +1752,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "9bdd7e2522fe", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "314fcc8d93cf", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.outer-refused:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "712a0bd65cc5"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "fe7fc1853f9e"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "2a4866c4dda3", + "state": "ea31cb0db515", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "e3836d43e8f9", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "7733d6566538", + "a4635ab3551f" ] } }, @@ -1878,16 +1804,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "712a0bd65cc5", - "f6003aed2098", - "ae89e058b351" + "fe7fc1853f9e", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1902,51 +1828,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "e3836d43e8f9", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "7733d6566538", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.outer-refused-no-message:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "9883026698a2"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "aefed6d1365a"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "376c9e8bd72a", + "state": "ff43b5ec92a9", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "5abab014ad66", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "24c9c9ebd660", + "a4635ab3551f" ] } }, @@ -1956,16 +1880,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "9883026698a2", - "f6003aed2098", - "ae89e058b351" + "aefed6d1365a", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -1980,51 +1904,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "5abab014ad66", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "24c9c9ebd660", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.method-not-found:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "08b8713b9aa5"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "0d97c3fd4fe1"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "fd9fcbd54752", + "state": "c930bdc29ecd", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "a093143e7c52", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "225520fed6bc", + "a4635ab3551f" ] } }, @@ -2034,16 +1956,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "08b8713b9aa5", - "f6003aed2098", - "ae89e058b351" + "0d97c3fd4fe1", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -2058,51 +1980,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "a093143e7c52", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "225520fed6bc", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.transport-rejection:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "a8981fbe7e87"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "684390d0103b"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "de19f9b2e75a", + "state": "ac891a7d42d5", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "1da3c3839c7a", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "386bb2eaf03b", + "a4635ab3551f" ] } }, @@ -2112,16 +2032,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "a8981fbe7e87", - "f6003aed2098", - "ae89e058b351" + "684390d0103b", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -2136,51 +2056,49 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "1da3c3839c7a", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "386bb2eaf03b", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } }, { "id": "tk-project-board-load.transport-rejection-no-message:table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "c95a406e53e5"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "20a31104f552"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb", "table-2": "eb79a9b3682a" }, - "state": "376c9e8bd72a", + "state": "ff43b5ec92a9", "effects": [ "2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "5abab014ad66", - "842c950ee7cc" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "24c9c9ebd660", + "a4635ab3551f" ] } }, @@ -2190,16 +2108,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "c95a406e53e5", - "f6003aed2098", - "ae89e058b351" + "20a31104f552", + "7d7e6f5ce421", + "6d7ebc9b7830" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "be93253869e6", - "9f9a21ac7b9e" + "4809ea7ad5b0", + "4dff29ea88de", + "b0c25dac9d8e" ], "settlements": { "mount": "eb79a9b3682a", @@ -2214,25 +2132,24 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "da50b440ea30", - "5abab014ad66", - "842c950ee7cc", - "3985399034a2", - "26921f3a7c09", - "1b3350f71e56", - "dc8dd7739c49", - "8a0577280bad", - "ab1b10183665", - "6b03ace1146a", - "4c9b1e4ad1f5", - "0af48d475813", - "e87bea4bcd3c", - "0056704adc0b", - "97bc7dc12b92", - "3493818a7239" + "2f290fa2acf5", + "060dcedb3fdb", + "fcd647d64faf", + "24c9c9ebd660", + "a4635ab3551f", + "ea8f8a6f07b1", + "03fc33b06333", + "853d951cf70a", + "32e88f5c4657", + "b5f49e20fef1", + "f79f5682a27b", + "d494afc83352", + "d0248d16609f", + "4dd8cc8f777d", + "223225c09f07", + "5c93fbf94a2d", + "1cb3b185586b", + "5a7676ce26d6" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-tasks.project-row-detail-github.project.workitemdetailsbyslug-1.json b/mobile/rpc-foundation/goldens/matrix-tasks.project-row-detail-github.project.workitemdetailsbyslug-1.json index 28697a03a85..638a36a7192 100644 --- a/mobile/rpc-foundation/goldens/matrix-tasks.project-row-detail-github.project.workitemdetailsbyslug-1.json +++ b/mobile/rpc-foundation/goldens/matrix-tasks.project-row-detail-github.project.workitemdetailsbyslug-1.json @@ -4,99 +4,9 @@ "family": "tasks.project-row-detail", "namedDeltas": [], "values": { - "0679b27a119b": { - "name": "projectFieldDrafts", - "ordinal": 11, - "value": {} - }, - "0fa980ff8396": { - "detail": { - "$rpc": "null" - }, - "error": "outer refused", - "loading": false - }, - "118d9662d37f": { + "0018cf2b103a": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 16, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.workItemDetailsBySlug\",\"params\":{\"owner\":\"owner\",\"repo\":\"repo\",\"host\":\"github.enterprise.test\",\"number\":1,\"type\":\"issue\"}}" - }, - "183c3c26aba7": { - "detail": { - "$rpc": "null" - }, - "error": "The host sent a reply this app could not read (github.project.workItemDetailsBySlug)", - "loading": false - }, - "1e161db29c89": { - "name": "projectRowDetail", - "ordinal": 17, - "value": { - "assignees": [], - "baseSha": "base-sha", - "body": "body", - "checks": [], - "comments": [], - "files": [], - "headSha": "head-sha", - "labels": [], - "latestReviews": [], - "provider": "github", - "pullRequestId": "PR_kwDO", - "reviewDecision": { - "$rpc": "undefined" - }, - "reviewRequests": [] - } - }, - "205699b4093c": { - "detail": { - "$rpc": "null" - }, - "error": "inner refused", - "loading": false - }, - "213a7e810bb6": { - "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, - "args": [ - { - "name": "method", - "value": "github.project.workItemDetailsBySlug" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "number": 1, - "owner": "owner", - "repo": "repo", - "type": "issue" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "error": "refused" - } - } - } - }, - "222e474aa914": { - "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -133,26 +43,9 @@ } } }, - "2dc6bc594542": { - "name": "projectRowDetailError", - "ordinal": 17, - "value": "outer refused" - }, - "2ee1c7329449": { - "name": "projectRowDetail", - "ordinal": 12, - "value": { - "$rpc": "null" - } - }, - "31fcc93f02da": { - "name": "projectEditingCommentDraft", - "ordinal": 9, - "value": "" - }, - "3236e59b43c5": { + "0283d28b3dfb": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -176,13 +69,130 @@ } ], "settlement": { - "status": "rejected", + "status": "fulfilled", "startedAt": 0, "settledAt": 0, - "error": { - "category": "Error", - "message": "transport failure", - "isRpcDeliveryUnknown": true + "value": { + "id": "frame-1", + "ok": true, + "result": { + "error": "refused" + } + } + } + }, + "044bed918d57": { + "name": "projectRowDetailError", + "ordinal": 16, + "value": "Unknown method" + }, + "0a6c63ec0fc1": { + "name": "github.project.workItemDetailsBySlug#1", + "ordinal": 15, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.workItemDetailsBySlug\",\"params\":{\"owner\":\"owner\",\"repo\":\"repo\",\"host\":\"github.enterprise.test\",\"number\":1,\"type\":\"issue\"}}" + }, + "0d5e8bc85abb": { + "name": "projectEditingCommentDraft", + "ordinal": 8, + "value": "" + }, + "0dc3824edb1e": { + "name": "projectRowDetailError", + "ordinal": 16, + "value": "" + }, + "0fa980ff8396": { + "detail": { + "$rpc": "null" + }, + "error": "outer refused", + "loading": false + }, + "183c3c26aba7": { + "detail": { + "$rpc": "null" + }, + "error": "The host sent a reply this app could not read (github.project.workItemDetailsBySlug)", + "loading": false + }, + "1e92a0ffa26a": { + "name": "github.project.workItemDetailsBySlug#1", + "ordinal": 14, + "args": [ + { + "name": "method", + "value": "github.project.workItemDetailsBySlug" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "number": 1, + "owner": "owner", + "repo": "repo", + "type": "issue" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-1", + "ok": true + } + } + }, + "205699b4093c": { + "detail": { + "$rpc": "null" + }, + "error": "inner refused", + "loading": false + }, + "209abb3e5ca9": { + "name": "github.project.workItemDetailsBySlug#1", + "ordinal": 14, + "args": [ + { + "name": "method", + "value": "github.project.workItemDetailsBySlug" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "number": 1, + "owner": "owner", + "repo": "repo", + "type": "issue" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-1", + "ok": true, + "result": { + "error": "inner refused", + "ok": false + } } } }, @@ -193,10 +203,10 @@ "error": "transport failure", "loading": false }, - "368311fc2981": { - "name": "projectCommentDraft", - "ordinal": 7, - "value": "" + "34aecaef096a": { + "name": "projectRowDetailLoading", + "ordinal": 17, + "value": false }, "3a42a92c5487": { "name": "projectBodyDraft", @@ -224,31 +234,9 @@ "error": "", "loading": false }, - "4f23116da7f6": { - "name": "projectReviewersDraft", - "ordinal": 10, - "value": "" - }, - "561861a537bb": { - "name": "projectRowDetailLoading", - "ordinal": 18, - "value": false - }, - "5cebe6c14680": { - "name": "prFileLoadingPath", - "ordinal": 4, - "value": { - "$rpc": "null" - } - }, - "60012e7abb60": { - "name": "prFileCommentDrafts", - "ordinal": 2, - "value": {} - }, - "6c3d811fffe9": { + "4b5e90f7c640": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -284,14 +272,9 @@ } } }, - "7ca2bb47ab1c": { - "name": "prFileContents", - "ordinal": 3, - "value": {} - }, - "899221be28d8": { + "55361bf207c6": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -350,53 +333,38 @@ } } }, - "8bea5c781cb0": { - "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, - "args": [ - { - "name": "method", - "value": "github.project.workItemDetailsBySlug" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "number": 1, - "owner": "owner", - "repo": "repo", - "type": "issue" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "error": { - "code": "refused", - "message": "outer refused" - }, - "id": "frame-1", - "ok": false - } + "5b08d6631c0c": { + "name": "projectRowDetailError", + "ordinal": 12, + "value": "" + }, + "5cebe6c14680": { + "name": "prFileLoadingPath", + "ordinal": 4, + "value": { + "$rpc": "null" } }, - "9239767275ff": { + "60012e7abb60": { + "name": "prFileCommentDrafts", + "ordinal": 2, + "value": {} + }, + "6a0930bd2fdb": { + "name": "projectEditingCommentId", + "ordinal": 7, + "value": { + "$rpc": "null" + } + }, + "6bc1a66fb171": { "name": "projectRowDetailError", - "ordinal": 17, + "ordinal": 16, "value": "The host sent a reply this app could not read (github.project.workItemDetailsBySlug)" }, - "96d6a5752f05": { + "74c575cf3feb": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -420,23 +388,24 @@ } ], "settlement": { - "status": "fulfilled", + "status": "rejected", "startedAt": 0, "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true + "error": { + "category": "Error", + "message": "transport failure", + "isRpcDeliveryUnknown": true } } }, - "9911dd53d1d7": { - "name": "projectTitleDraft", - "ordinal": 5, - "value": "Project issue" + "78b8331a5238": { + "name": "projectRowDetailError", + "ordinal": 16, + "value": "transport failure" }, - "9c91ff2e7fe6": { + "7bfaa68178f3": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -470,96 +439,24 @@ } } }, - "9ef3651bf4ad": { - "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, - "args": [ - { - "name": "method", - "value": "github.project.workItemDetailsBySlug" - }, - { - "name": "params", - "value": { - "host": "github.enterprise.test", - "number": 1, - "owner": "owner", - "repo": "repo", - "type": "issue" - } - }, - { - "name": "options", - "value": { - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-1", - "ok": true, - "result": { - "error": "inner refused", - "ok": false - } - } - } + "7ca2bb47ab1c": { + "name": "prFileContents", + "ordinal": 3, + "value": {} }, - "a90f501112f8": { - "name": "projectRowDetailError", - "ordinal": 17, - "value": "Unknown method" - }, - "ab52357ddee7": { - "name": "projectRowDetailError", - "ordinal": 17, - "value": "inner refused" - }, - "b2a01ad6d4fe": { - "detail": { - "assignees": [], - "baseSha": "base-sha", - "body": "body", - "checks": [], - "comments": [], - "files": [], - "headSha": "head-sha", - "labels": [], - "latestReviews": [], - "provider": "github", - "pullRequestId": "PR_kwDO", - "reviewDecision": { - "$rpc": "undefined" - }, - "reviewRequests": [] - }, - "error": "", - "loading": false - }, - "b63d5911050c": { - "name": "projectRowDetailError", + "93c5cbde2045": { + "name": "projectRowDetailLoading", "ordinal": 13, - "value": "" + "value": true }, - "bff535848bcf": { - "name": "projectRowDetailError", - "ordinal": 17, - "value": "" + "9911dd53d1d7": { + "name": "projectTitleDraft", + "ordinal": 5, + "value": "Project issue" }, - "c0e2c37d8abf": { - "name": "projectEditingCommentId", - "ordinal": 8, - "value": { - "$rpc": "null" - } - }, - "cd23fb9a85c7": { + "a8ed211a5296": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -596,10 +493,108 @@ } } }, - "ea064759ca04": { + "b2a01ad6d4fe": { + "detail": { + "assignees": [], + "baseSha": "base-sha", + "body": "body", + "checks": [], + "comments": [], + "files": [], + "headSha": "head-sha", + "labels": [], + "latestReviews": [], + "provider": "github", + "pullRequestId": "PR_kwDO", + "reviewDecision": { + "$rpc": "undefined" + }, + "reviewRequests": [] + }, + "error": "", + "loading": false + }, + "b3022e1b4bce": { + "name": "github.project.workItemDetailsBySlug#1", + "ordinal": 14, + "args": [ + { + "name": "method", + "value": "github.project.workItemDetailsBySlug" + }, + { + "name": "params", + "value": { + "host": "github.enterprise.test", + "number": 1, + "owner": "owner", + "repo": "repo", + "type": "issue" + } + }, + { + "name": "options", + "value": { + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "error": { + "code": "refused", + "message": "outer refused" + }, + "id": "frame-1", + "ok": false + } + } + }, + "bf07b693e877": { + "name": "projectRowDetail", + "ordinal": 16, + "value": { + "assignees": [], + "baseSha": "base-sha", + "body": "body", + "checks": [], + "comments": [], + "files": [], + "headSha": "head-sha", + "labels": [], + "latestReviews": [], + "provider": "github", + "pullRequestId": "PR_kwDO", + "reviewDecision": { + "$rpc": "undefined" + }, + "reviewRequests": [] + } + }, + "c82fb4f46067": { + "name": "projectReviewersDraft", + "ordinal": 9, + "value": "" + }, + "de8ce98bdd63": { + "name": "projectRowDetail", + "ordinal": 11, + "value": { + "$rpc": "null" + } + }, + "e07f42e59479": { "name": "projectRowDetailError", - "ordinal": 17, - "value": "transport failure" + "ordinal": 16, + "value": "outer refused" + }, + "e5129a14b6e4": { + "name": "projectFieldDrafts", + "ordinal": 10, + "value": {} }, "eb79a9b3682a": { "status": "fulfilled", @@ -609,14 +604,14 @@ "$rpc": "undefined" } }, - "f6a5085dd8e9": { - "name": "projectRowDetailLoading", - "ordinal": 14, - "value": true + "f8970fcf56b2": { + "name": "projectRowDetailError", + "ordinal": 16, + "value": "inner refused" }, - "fc2def66694f": { + "fb55d5c279f3": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -662,8 +657,8 @@ { "id": "tk-project-row-detail.normal:mounted", "observation": { - "sender": ["899221be28d8"], - "payloads": ["118d9662d37f"], + "sender": ["55361bf207c6"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -675,24 +670,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "1e161db29c89", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "bf07b693e877", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.result-absent:mounted", "observation": { - "sender": ["96d6a5752f05"], - "payloads": ["118d9662d37f"], + "sender": ["1e92a0ffa26a"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -704,24 +698,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "9239767275ff", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "6bc1a66fb171", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.result-null:mounted", "observation": { - "sender": ["6c3d811fffe9"], - "payloads": ["118d9662d37f"], + "sender": ["4b5e90f7c640"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -733,24 +726,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "9239767275ff", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "6bc1a66fb171", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.inner-ok-missing:mounted", "observation": { - "sender": ["213a7e810bb6"], - "payloads": ["118d9662d37f"], + "sender": ["0283d28b3dfb"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -762,24 +754,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "9239767275ff", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "6bc1a66fb171", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.inner-false-string-error:mounted", "observation": { - "sender": ["9ef3651bf4ad"], - "payloads": ["118d9662d37f"], + "sender": ["209abb3e5ca9"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -791,24 +782,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "9239767275ff", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "6bc1a66fb171", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.inner-false-object-error:mounted", "observation": { - "sender": ["fc2def66694f"], - "payloads": ["118d9662d37f"], + "sender": ["fb55d5c279f3"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -820,24 +810,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "ab52357ddee7", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "f8970fcf56b2", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.outer-refused:mounted", "observation": { - "sender": ["8bea5c781cb0"], - "payloads": ["118d9662d37f"], + "sender": ["b3022e1b4bce"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -849,24 +838,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "2dc6bc594542", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "e07f42e59479", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.outer-refused-no-message:mounted", "observation": { - "sender": ["cd23fb9a85c7"], - "payloads": ["118d9662d37f"], + "sender": ["a8ed211a5296"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -878,24 +866,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "bff535848bcf", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "0dc3824edb1e", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.method-not-found:mounted", "observation": { - "sender": ["222e474aa914"], - "payloads": ["118d9662d37f"], + "sender": ["0018cf2b103a"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -907,24 +894,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "a90f501112f8", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "044bed918d57", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.transport-rejection:mounted", "observation": { - "sender": ["3236e59b43c5"], - "payloads": ["118d9662d37f"], + "sender": ["74c575cf3feb"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -936,24 +922,23 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "ea064759ca04", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "78b8331a5238", + "34aecaef096a" ] } }, { "id": "tk-project-row-detail.transport-rejection-no-message:mounted", "observation": { - "sender": ["9c91ff2e7fe6"], - "payloads": ["118d9662d37f"], + "sender": ["7bfaa68178f3"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -965,16 +950,15 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "bff535848bcf", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "0dc3824edb1e", + "34aecaef096a" ] } } diff --git a/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json b/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json index ed5e635fd8f..71aabc3e2d2 100644 --- a/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json +++ b/mobile/rpc-foundation/goldens/matrix-worktree.home-catalog-worktree.ps-1.json @@ -123,21 +123,6 @@ } } }, - "19a302575563": { - "host-1": { - "activeCount": 2, - "agents": [], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } - }, "298c6fbd5d42": { "name": "worktree.ps#1", "ordinal": 1, @@ -244,17 +229,6 @@ } } }, - "51d64b49c1ab": { - "host-1": { - "activeCount": 0, - "catalogUnavailable": true, - "hostId": "host-1", - "lastActiveWorktree": { - "$rpc": "null" - }, - "totalWorktrees": 0 - } - }, "5e982fcaacf9": { "name": "worktree.ps#1", "ordinal": 1, @@ -293,25 +267,27 @@ } } }, - "7858e4e82b0f": { + "628656d5b8c6": { "name": "info", "ordinal": 3, "value": { "host-1": { - "activeCount": 2, - "agents": [], - "countsProvenAt": 1767225600000, + "activeCount": 0, + "catalogUnavailable": true, "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 + "totalWorktrees": 0 } } }, + "800962c868e7": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "totalWorktrees": 2 + } + }, "817623c64ce1": { "name": "worktree.ps#1", "ordinal": 1, @@ -347,11 +323,32 @@ } } }, + "89066e878348": { + "name": "info", + "ordinal": 3, + "value": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "totalWorktrees": 2 + } + } + }, "922cb68379ac": { "name": "worktree.ps#1", "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.ps\",\"params\":{\"limit\":10000,\"afterSnapshotId\":null,\"acceptRowDelta\":true,\"supportsWorktreeVisibilitySourceDefaults\":true}}" }, + "92357b2812ef": { + "host-1": { + "activeCount": 0, + "catalogUnavailable": true, + "hostId": "host-1", + "totalWorktrees": 0 + } + }, "9270aeb7d9c6": { "status": "pending", "startedAt": 0 @@ -469,21 +466,6 @@ } } }, - "cf43d74ea93e": { - "name": "info", - "ordinal": 3, - "value": { - "host-1": { - "activeCount": 0, - "catalogUnavailable": true, - "hostId": "host-1", - "lastActiveWorktree": { - "$rpc": "null" - }, - "totalWorktrees": 0 - } - } - }, "e36f43e93321": { "name": "worktree.ps#1", "ordinal": 1, @@ -567,8 +549,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "19a302575563", - "effects": ["7858e4e82b0f"] + "state": "800962c868e7", + "effects": ["89066e878348"] } }, { @@ -579,8 +561,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -591,8 +573,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -603,8 +585,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -615,8 +597,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -627,8 +609,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -639,8 +621,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -651,8 +633,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -663,8 +645,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -675,8 +657,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } }, { @@ -687,8 +669,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "51d64b49c1ab", - "effects": ["cf43d74ea93e"] + "state": "92357b2812ef", + "effects": ["628656d5b8c6"] } } ] diff --git a/mobile/rpc-foundation/goldens/pr-comment-posted-in-place.json b/mobile/rpc-foundation/goldens/pr-comment-posted-in-place.json index 50ec55dd90b..ebd3e2354a8 100644 --- a/mobile/rpc-foundation/goldens/pr-comment-posted-in-place.json +++ b/mobile/rpc-foundation/goldens/pr-comment-posted-in-place.json @@ -4,6 +4,16 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -39,167 +49,9 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, - "19ddadf49030": { - "name": "github.addIssueComment#1", - "ordinal": 16, - "args": [ - { - "name": "method", - "value": "github.addIssueComment" - }, - { - "name": "params", - "value": { - "body": "recorded comment", - "number": 12, - "repo": "id:repo-9", - "type": "pr" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-8", - "ok": true, - "result": { - "comment": { - "id": 57 - }, - "ok": true - } - } - } - }, - "1f5765918736": { - "name": "github.repoSlug#1", - "ordinal": 2, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" - }, - "2309f345fb72": { - "name": "github.prForBranch#1", - "ordinal": 8, - "args": [ - { - "name": "method", - "value": "github.prForBranch" - }, - { - "name": "params", - "value": { - "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, - "35045fa5a752": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "loading" - } - }, - "357f9b7862e3": { - "name": "worktree.show#1", - "ordinal": 6, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" - }, - "39b9c8ebcce5": { - "name": "github.addIssueComment#1", - "ordinal": 17, - "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.addIssueComment\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"body\":\"recorded comment\",\"type\":\"pr\"}}" - }, - "3eeb7e426600": { + "1e1163c70eba": { "name": "github.prComments#1", - "ordinal": 18, + "ordinal": 19, "args": [ { "name": "method", @@ -230,6 +82,110 @@ "startedAt": 0 } }, + "1f5765918736": { + "name": "github.repoSlug#1", + "ordinal": 2, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" + }, + "2dc2ca47b4e7": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "35045fa5a752": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "loading" + } + }, + "357f9b7862e3": { + "name": "worktree.show#1", + "ordinal": 6, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" + }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3b2df6b54829": { + "name": "github.addIssueComment#1", + "ordinal": 17, + "args": [ + { + "name": "method", + "value": "github.addIssueComment" + }, + { + "name": "params", + "value": { + "body": "recorded comment", + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-9", + "ok": true, + "result": { + "comment": { + "id": 57 + }, + "ok": true + } + } + } + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -268,14 +224,206 @@ } } }, - "6f75be8d77df": { - "name": "github.prComments#1", - "ordinal": 19, - "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"github.prComments\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"noCache\":true,\"prRepo\":{\"owner\":\"owner\",\"repo\":\"repo\",\"host\":\"github.com\"}}}" + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" }, - "707f5273fbe1": { - "name": "github.prForBranch#1", + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + }, + "7881ab1fb5d1": { + "name": "github.addIssueComment#1", + "ordinal": 18, + "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"github.addIssueComment\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"body\":\"recorded comment\",\"type\":\"pr\"}}" + }, + "84e5ca07cb7a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": true + }, + "861c8796ae1f": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "8f35f3a8538e": { + "name": "github.prComments#1", + "ordinal": 20, + "json": "{\"id\":\"frame-10\",\"deviceToken\":\"recording-device\",\"method\":\"github.prComments\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"noCache\":true,\"prRepo\":{\"owner\":\"owner\",\"repo\":\"repo\",\"host\":\"github.com\"}}}" + }, + "9091d133c3b0": { + "name": "reply-salvage", "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "9270aeb7d9c6": { + "status": "pending", + "startedAt": 0 + }, + "9be162e088f2": { + "name": "streams-registered-at-teardown", + "ordinal": 21, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, "args": [ { "name": "method", @@ -284,6 +432,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -308,7 +457,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-5", "ok": true, "result": { "fetchedAt": 0, @@ -326,129 +475,9 @@ } } }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } - } - }, - "84e5ca07cb7a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": true - }, - "87ba39148f02": { + "a7e609fcb031": { "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] - } - } - }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "9c952632b0c0": { - "name": "status.get#1", "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "cb071b912510": { - "name": "github.prChecks#1", - "ordinal": 10, "args": [ { "name": "method", @@ -474,14 +503,9 @@ "startedAt": 0 } }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -509,7 +533,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -572,17 +596,6 @@ "refreshFailed": false } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" - } - }, "e0a11d8a1005": { "commentError": { "$rpc": "null" @@ -608,17 +621,14 @@ "refreshFailed": false } }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" }, - "f742d75db77c": { + "e40828b3dc78": { "name": "github.prComments#1", - "ordinal": 18, + "ordinal": 19, "args": [ { "name": "method", @@ -649,7 +659,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-9", + "id": "frame-10", "ok": true, "result": [ { @@ -673,6 +683,14 @@ ] } } + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } } }, "recording": { @@ -681,13 +699,19 @@ { "id": "branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -695,25 +719,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -721,27 +746,28 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -749,32 +775,33 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d", - "19ddadf49030", - "3eeb7e426600" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "3b2df6b54829", + "1e1163c70eba" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be", - "39b9c8ebcce5", - "6f75be8d77df" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "7881ab1fb5d1", + "8f35f3a8538e" ], "settlements": { "mount": "eb79a9b3682a", "post-comment": "9270aeb7d9c6" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -782,32 +809,67 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d", - "19ddadf49030", - "f742d75db77c" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "3b2df6b54829", + "e40828b3dc78" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be", - "39b9c8ebcce5", - "6f75be8d77df" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "7881ab1fb5d1", + "8f35f3a8538e" ], "settlements": { "mount": "eb79a9b3682a", "post-comment": "84e5ca07cb7a" }, "state": "d39b1bf1038a", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "3b2df6b54829", + "e40828b3dc78" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "7881ab1fb5d1", + "8f35f3a8538e" + ], + "settlements": { + "mount": "eb79a9b3682a", + "post-comment": "84e5ca07cb7a" + }, + "state": "d39b1bf1038a", + "effects": ["9091d133c3b0", "9be162e088f2"] } } ] diff --git a/mobile/rpc-foundation/goldens/pr-resolve-refused-rolls-back.json b/mobile/rpc-foundation/goldens/pr-resolve-refused-rolls-back.json index fac1fff77d6..89ca922e009 100644 --- a/mobile/rpc-foundation/goldens/pr-resolve-refused-rolls-back.json +++ b/mobile/rpc-foundation/goldens/pr-resolve-refused-rolls-back.json @@ -4,6 +4,11 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, "0ab0279ef3fe": { "commentError": "Resource not accessible by integration", "pr": { @@ -27,6 +32,11 @@ "refreshFailed": false } }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -62,11 +72,6 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, "18a67e1b19d6": { "commentError": { "$rpc": "null" @@ -97,9 +102,9 @@ "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { + "2dc2ca47b4e7": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -108,6 +113,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -132,64 +138,27 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } + "35045fa5a752": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "loading" } }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + "357f9b7862e3": { + "name": "worktree.show#1", + "ordinal": 6, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, - "3362c89b344f": { + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3d6c69a8143e": { "name": "github.resolveReviewThread#1", - "ordinal": 16, + "ordinal": 17, "args": [ { "name": "method", @@ -219,23 +188,15 @@ "code": "upstream_error", "message": "Resource not accessible by integration" }, - "id": "frame-8", + "id": "frame-9", "ok": false } } }, - "35045fa5a752": { - "commentError": { - "$rpc": "null" - }, - "pr": { - "kind": "loading" - } - }, - "357f9b7862e3": { - "name": "worktree.show#1", - "ordinal": 6, - "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" }, "4da7ea39401b": { "name": "worktree.show#1", @@ -275,28 +236,25 @@ } } }, - "61c7e519a6dc": { - "name": "github.resolveReviewThread#1", - "ordinal": 17, - "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.resolveReviewThread\",\"params\":{\"repo\":\"id:repo-9\",\"threadId\":\"thread-1\",\"resolve\":true}}" + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" }, - "707f5273fbe1": { - "name": "github.prForBranch#1", - "ordinal": 8, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", - "value": "github.prForBranch" + "value": "hostedReview.forBranch" }, { "name": "params", "value": { + "active": true, "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { + "linkedGitHubPR": { "$rpc": "null" }, "repo": "id:repo-9" @@ -305,7 +263,6 @@ { "name": "options", "value": { - "beforeSend": "[local beforeSend]", "failWhenDisconnected": true } } @@ -318,17 +275,13 @@ "id": "frame-4", "ok": true, "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" } } } @@ -339,86 +292,9 @@ "settledAt": 0, "value": false }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } - } - }, - "87ba39148f02": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] - } - } - }, - "901052a1366a": { + "84983e28731b": { "name": "github.resolveReviewThread#1", - "ordinal": 16, + "ordinal": 17, "args": [ { "name": "method", @@ -444,13 +320,50 @@ "startedAt": 0 } }, - "9270aeb7d9c6": { - "status": "pending", - "startedAt": 0 - }, - "9c952632b0c0": { - "name": "status.get#1", + "861c8796ae1f": { + "name": "github.prChecks#1", "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, "args": [ { "name": "method", @@ -476,14 +389,114 @@ "startedAt": 0 } }, - "abcf3bdc5cde": { + "8b7e690466d7": { "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } }, - "cb071b912510": { + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "9270aeb7d9c6": { + "status": "pending", + "startedAt": 0 + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "a7e609fcb031": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, "args": [ { "name": "method", @@ -509,14 +522,9 @@ "startedAt": 0 } }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -544,7 +552,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -577,16 +585,10 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" - } + "c11667112704": { + "name": "github.resolveReviewThread#1", + "ordinal": 18, + "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"github.resolveReviewThread\",\"params\":{\"repo\":\"id:repo-9\",\"threadId\":\"thread-1\",\"resolve\":true}}" }, "e0a11d8a1005": { "commentError": { @@ -613,6 +615,11 @@ "refreshFailed": false } }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -620,6 +627,17 @@ "value": { "$rpc": "undefined" } + }, + "febdecd6dd97": { + "name": "streams-registered-at-teardown", + "ordinal": 19, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] } }, "recording": { @@ -628,13 +646,19 @@ { "id": "branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -642,25 +666,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -668,27 +693,28 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -696,30 +722,31 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d", - "901052a1366a" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "84983e28731b" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be", - "61c7e519a6dc" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "c11667112704" ], "settlements": { "mount": "eb79a9b3682a", "resolve-thread": "9270aeb7d9c6" }, "state": "18a67e1b19d6", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -727,30 +754,63 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d", - "3362c89b344f" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "3d6c69a8143e" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be", - "61c7e519a6dc" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "c11667112704" ], "settlements": { "mount": "eb79a9b3682a", "resolve-thread": "7ed3d39f0607" }, "state": "0ab0279ef3fe", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "3d6c69a8143e" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "c11667112704" + ], + "settlements": { + "mount": "eb79a9b3682a", + "resolve-thread": "7ed3d39f0607" + }, + "state": "0ab0279ef3fe", + "effects": ["9091d133c3b0", "febdecd6dd97"] } } ] diff --git a/mobile/rpc-foundation/goldens/pr-sidebar-checks-refused.json b/mobile/rpc-foundation/goldens/pr-sidebar-checks-refused.json index 34ba75c147c..e1266f43f0b 100644 --- a/mobile/rpc-foundation/goldens/pr-sidebar-checks-refused.json +++ b/mobile/rpc-foundation/goldens/pr-sidebar-checks-refused.json @@ -4,6 +4,16 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -39,19 +49,14 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, "1f5765918736": { "name": "github.repoSlug#1", "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { + "2dc2ca47b4e7": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -60,6 +65,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -84,61 +90,6 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, "341c71d5f61d": { "commentError": { "$rpc": "null" @@ -175,6 +126,16 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -213,23 +174,25 @@ } } }, - "707f5273fbe1": { - "name": "github.prForBranch#1", - "ordinal": 8, + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, "args": [ { "name": "method", - "value": "github.prForBranch" + "value": "hostedReview.forBranch" }, { "name": "params", "value": { + "active": true, "branch": "feature", - "currentHeadOid": { - "$rpc": "null" - }, - "fallbackPRNumber": 12, - "linkedPRNumber": { + "linkedGitHubPR": { "$rpc": "null" }, "repo": "id:repo-9" @@ -238,7 +201,6 @@ { "name": "options", "value": { - "beforeSend": "[local beforeSend]", "failWhenDisconnected": true } } @@ -251,60 +213,20 @@ "id": "frame-4", "ok": true, "result": { - "fetchedAt": 0, - "kind": "found", - "pr": { - "headSha": "head-sha-1", - "mergeable": "MERGEABLE", - "number": 12, - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" } } } }, - "8352e3c99668": { + "870c2b9bacd0": { "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } - } - }, - "9c952632b0c0": { - "name": "status.get#1", - "ordinal": 11, + "ordinal": 12, "args": [ { "name": "method", @@ -330,14 +252,146 @@ "startedAt": 0 } }, - "abcf3bdc5cde": { + "8b7e690466d7": { "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } }, - "cb071b912510": { + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "98eb9b836539": { "name": "github.prChecks#1", - "ordinal": 10, + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": { + "checks": [] + } + } + } + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "a7e609fcb031": { + "name": "github.prChecks#1", + "ordinal": 11, "args": [ { "name": "method", @@ -363,14 +417,9 @@ "startedAt": 0 } }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -398,7 +447,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -431,52 +480,21 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" - } + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] }, - "d43ea39cfd0a": { - "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": { - "checks": [] - } - } - } + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" }, "eb79a9b3682a": { "status": "fulfilled", @@ -493,13 +511,19 @@ { "id": "branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -507,25 +531,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -533,27 +558,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "d43ea39cfd0a", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "98eb9b836539", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "341c71d5f61d", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "98eb9b836539", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "341c71d5f61d", + "effects": ["9091d133c3b0", "c70e6fd19823"] } } ] diff --git a/mobile/rpc-foundation/goldens/pr-sidebar-load.json b/mobile/rpc-foundation/goldens/pr-sidebar-load.json index 42e186747a6..66f4cd67b65 100644 --- a/mobile/rpc-foundation/goldens/pr-sidebar-load.json +++ b/mobile/rpc-foundation/goldens/pr-sidebar-load.json @@ -4,6 +4,16 @@ "family": "session.pr-sidebar", "namedDeltas": [], "values": { + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, "1287167eaf56": { "name": "github.repoSlug#1", "ordinal": 1, @@ -39,19 +49,14 @@ } } }, - "1723d8a5d8be": { - "name": "github.workItemDetails#1", - "ordinal": 15, - "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" - }, "1f5765918736": { "name": "github.repoSlug#1", "ordinal": 2, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" }, - "2309f345fb72": { + "2dc2ca47b4e7": { "name": "github.prForBranch#1", - "ordinal": 8, + "ordinal": 9, "args": [ { "name": "method", @@ -60,6 +65,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -84,61 +90,6 @@ "startedAt": 0 } }, - "27531d8cc301": { - "name": "hostedReview.forBranch#1", - "ordinal": 5, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" - }, - "28428f85f800": { - "name": "hostedReview.forBranch#1", - "ordinal": 3, - "args": [ - { - "name": "method", - "value": "hostedReview.forBranch" - }, - { - "name": "params", - "value": { - "active": true, - "branch": "feature", - "linkedGitHubPR": { - "$rpc": "null" - }, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-2", - "ok": true, - "result": { - "mergeable": "MERGEABLE", - "number": 12, - "provider": "github", - "state": "open", - "title": "Recorded", - "updatedAt": "2026-01-01T00:00:00Z", - "url": "https://github.com/owner/repo/pull/12" - } - } - } - }, - "2bb452e534eb": { - "name": "github.prChecks#1", - "ordinal": 12, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" - }, "35045fa5a752": { "commentError": { "$rpc": "null" @@ -152,6 +103,16 @@ "ordinal": 6, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, "4da7ea39401b": { "name": "worktree.show#1", "ordinal": 4, @@ -190,9 +151,175 @@ } } }, - "707f5273fbe1": { - "name": "github.prForBranch#1", + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + }, + "861c8796ae1f": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "9091d133c3b0": { + "name": "reply-salvage", "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, "args": [ { "name": "method", @@ -201,6 +328,7 @@ { "name": "params", "value": { + "acceptMergedFallbackPR": true, "branch": "feature", "currentHeadOid": { "$rpc": "null" @@ -225,7 +353,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-4", + "id": "frame-5", "ok": true, "result": { "fetchedAt": 0, @@ -243,119 +371,9 @@ } } }, - "8352e3c99668": { - "name": "status.get#1", - "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-6", - "ok": true, - "result": { - "runtimeId": "recorded" - } - } - } - }, - "87ba39148f02": { + "a7e609fcb031": { "name": "github.prChecks#1", - "ordinal": 10, - "args": [ - { - "name": "method", - "value": "github.prChecks" - }, - { - "name": "params", - "value": { - "headSha": "head-sha-1", - "prNumber": 12, - "repo": "id:repo-9" - } - }, - { - "name": "options", - "value": { - "failWhenDisconnected": true - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-5", - "ok": true, - "result": [ - { - "checkRunId": 7, - "conclusion": "success", - "name": "build", - "status": "completed" - } - ] - } - } - }, - "9c952632b0c0": { - "name": "status.get#1", "ordinal": 11, - "args": [ - { - "name": "method", - "value": "status.get" - }, - { - "name": "params", - "value": { - "$rpc": "undefined" - } - }, - { - "name": "options", - "value": { - "beforeSend": "[local beforeSend]", - "failWhenDisconnected": true, - "timeoutMs": 30000 - } - } - ], - "settlement": { - "status": "pending", - "startedAt": 0 - } - }, - "abcf3bdc5cde": { - "name": "status.get#1", - "ordinal": 13, - "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" - }, - "cb071b912510": { - "name": "github.prChecks#1", - "ordinal": 10, "args": [ { "name": "method", @@ -381,14 +399,9 @@ "startedAt": 0 } }, - "d25b12408fe6": { - "name": "github.prForBranch#1", - "ordinal": 9, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"currentHeadOid\":null}}" - }, - "d3426861162d": { + "bfedf583a747": { "name": "github.workItemDetails#1", - "ordinal": 14, + "ordinal": 15, "args": [ { "name": "method", @@ -416,7 +429,7 @@ "startedAt": 0, "settledAt": 0, "value": { - "id": "frame-7", + "id": "frame-8", "ok": true, "result": { "body": "body", @@ -449,16 +462,16 @@ } } }, - "d3d85b61b684": { - "name": "reply-salvage", - "ordinal": 7, - "value": { - "droppedCount": 1, - "droppedPaths": ["linkedPR"], - "method": "worktree.show", - "operation": "worktree.summary-or-skip", - "variant": "worktree-summary" - } + "c70e6fd19823": { + "name": "streams-registered-at-teardown", + "ordinal": 17, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] }, "e0a11d8a1005": { "commentError": { @@ -485,6 +498,11 @@ "refreshFailed": false } }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -500,13 +518,19 @@ { "id": "branch-hint", "observation": { - "sender": ["1287167eaf56", "28428f85f800", "4da7ea39401b", "2309f345fb72"], - "payloads": ["1f5765918736", "27531d8cc301", "357f9b7862e3", "d25b12408fe6"], + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -514,25 +538,26 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "cb071b912510", - "9c952632b0c0" + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "35045fa5a752", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] } }, { @@ -540,27 +565,57 @@ "observation": { "sender": [ "1287167eaf56", - "28428f85f800", "4da7ea39401b", - "707f5273fbe1", - "87ba39148f02", - "8352e3c99668", - "d3426861162d" + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" ], "payloads": [ "1f5765918736", - "27531d8cc301", + "3ecc2d44a209", "357f9b7862e3", - "d25b12408fe6", - "2bb452e534eb", - "abcf3bdc5cde", - "1723d8a5d8be" + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" ], "settlements": { "mount": "eb79a9b3682a" }, "state": "e0a11d8a1005", - "effects": ["d3d85b61b684"] + "effects": ["9091d133c3b0"] + } + }, + { + "id": "cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "c70e6fd19823"] } } ] diff --git a/mobile/rpc-foundation/goldens/pr-sidebar-revisit-and-refresh.json b/mobile/rpc-foundation/goldens/pr-sidebar-revisit-and-refresh.json new file mode 100644 index 00000000000..c17446d4c80 --- /dev/null +++ b/mobile/rpc-foundation/goldens/pr-sidebar-revisit-and-refresh.json @@ -0,0 +1,1201 @@ +{ + "goldenFormatVersion": 6, + "operation": "session.pr-sidebar", + "family": "session.pr-sidebar", + "namedDeltas": [], + "values": { + "03bcac42a924": { + "name": "worktree.show#3", + "ordinal": 26, + "json": "{\"id\":\"frame-11\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" + }, + "0726612d4a89": { + "name": "reply-salvage", + "ordinal": 19, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "0730389db3e9": { + "name": "hostedReview.forBranch#1", + "ordinal": 7, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "0d9f7988ff86": { + "name": "github.prChecks#1", + "ordinal": 13, + "json": "{\"id\":\"frame-6\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"headSha\":\"head-sha-1\"}}" + }, + "1287167eaf56": { + "name": "github.repoSlug#1", + "ordinal": 1, + "args": [ + { + "name": "method", + "value": "github.repoSlug" + }, + { + "name": "params", + "value": { + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-1", + "ok": true, + "result": { + "owner": "owner", + "repo": "repo" + } + } + } + }, + "1c1b5062fc21": { + "name": "github.prForBranch#2", + "ordinal": 21, + "json": "{\"id\":\"frame-10\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "1f5765918736": { + "name": "github.repoSlug#1", + "ordinal": 2, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.repoSlug\",\"params\":{\"repo\":\"id:repo-9\"}}" + }, + "2055aa3ead1b": { + "name": "status.get#3", + "ordinal": 31, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 15000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-15", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "214acb975f72": { + "name": "worktree.show#2", + "ordinal": 17, + "args": [ + { + "name": "method", + "value": "worktree.show" + }, + { + "name": "params", + "value": { + "worktree": "id:repo-9::/w" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-9", + "ok": true, + "result": { + "worktree": { + "linkedPR": { + "$rpc": "null" + } + } + } + } + } + }, + "2dc2ca47b4e7": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "2e217691ed33": { + "name": "hostedReview.forBranch#2", + "ordinal": 23, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-12", + "ok": true, + "result": { + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + }, + "35045fa5a752": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "kind": "loading" + } + }, + "357f9b7862e3": { + "name": "worktree.show#1", + "ordinal": 6, + "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" + }, + "3a8e6b13f380": { + "name": "github.prForBranch#1", + "ordinal": 10, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null}}" + }, + "3ecc2d44a209": { + "name": "runtime.clientEvents.subscribe#1", + "ordinal": 3, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"runtime.clientEvents.subscribe\",\"params\":null}" + }, + "472f9e734ac0": { + "name": "github.prForBranch#3", + "ordinal": 33, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9", + "userRefresh": true + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-16", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "4da7ea39401b": { + "name": "worktree.show#1", + "ordinal": 4, + "args": [ + { + "name": "method", + "value": "worktree.show" + }, + { + "name": "params", + "value": { + "worktree": "id:repo-9::/w" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-3", + "ok": true, + "result": { + "worktree": { + "linkedPR": { + "$rpc": "null" + } + } + } + } + } + }, + "5b1c7d371b2a": { + "name": "worktree.show#2", + "ordinal": 18, + "json": "{\"id\":\"frame-9\",\"deviceToken\":\"recording-device\",\"method\":\"worktree.show\",\"params\":{\"worktree\":\"id:repo-9::/w\"}}" + }, + "5d309fcf43a7": { + "name": "github.workItemDetails#1", + "ordinal": 16, + "json": "{\"id\":\"frame-8\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "75885386f005": { + "name": "hostedReview.forBranch#1", + "ordinal": 5, + "args": [ + { + "name": "method", + "value": "hostedReview.forBranch" + }, + { + "name": "params", + "value": { + "active": true, + "branch": "feature", + "linkedGitHubPR": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "mergeable": "MERGEABLE", + "number": 12, + "provider": "github", + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + }, + "7749a3b2d060": { + "name": "github.prForBranch#3", + "ordinal": 34, + "json": "{\"id\":\"frame-16\",\"deviceToken\":\"recording-device\",\"method\":\"github.prForBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedPRNumber\":null,\"fallbackPRNumber\":12,\"acceptMergedFallbackPR\":true,\"currentHeadOid\":null,\"userRefresh\":true}}" + }, + "7b3f2de1ee65": { + "name": "github.prChecks#2", + "ordinal": 28, + "json": "{\"id\":\"frame-13\",\"deviceToken\":\"recording-device\",\"method\":\"github.prChecks\",\"params\":{\"repo\":\"id:repo-9\",\"prNumber\":12,\"noCache\":true,\"userRefresh\":true,\"headSha\":\"head-sha-1\"}}" + }, + "861c8796ae1f": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-6", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "870c2b9bacd0": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "8b7e690466d7": { + "name": "status.get#1", + "ordinal": 12, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-7", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "9091d133c3b0": { + "name": "reply-salvage", + "ordinal": 8, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "9cfd3529adf9": { + "name": "streams-registered-at-teardown", + "ordinal": 37, + "value": [ + { + "cancelled": true, + "method": "runtime.clientEvents.subscribe", + "payload": "runtime.clientEvents.subscribe#1" + } + ] + }, + "a2c2965e14f8": { + "name": "github.workItemDetails#2", + "ordinal": 36, + "json": "{\"id\":\"frame-17\",\"deviceToken\":\"recording-device\",\"method\":\"github.workItemDetails\",\"params\":{\"repo\":\"id:repo-9\",\"number\":12,\"type\":\"pr\"}}" + }, + "a55c83eeaeea": { + "name": "github.prForBranch#1", + "ordinal": 9, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-5", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "a5aaa57d24bd": { + "name": "reply-salvage", + "ordinal": 30, + "value": { + "droppedCount": 1, + "droppedPaths": ["linkedPR"], + "method": "worktree.show", + "operation": "worktree.summary-or-skip", + "variant": "worktree-summary" + } + }, + "a7e609fcb031": { + "name": "github.prChecks#1", + "ordinal": 11, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "prNumber": 12, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "pending", + "startedAt": 0 + } + }, + "a7feeba7e968": { + "name": "github.prChecks#2", + "ordinal": 24, + "args": [ + { + "name": "method", + "value": "github.prChecks" + }, + { + "name": "params", + "value": { + "headSha": "head-sha-1", + "noCache": true, + "prNumber": 12, + "repo": "id:repo-9", + "userRefresh": true + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-13", + "ok": true, + "result": [ + { + "checkRunId": 7, + "conclusion": "success", + "name": "build", + "status": "completed" + } + ] + } + } + }, + "b8ec75ce4213": { + "name": "status.get#2", + "ordinal": 29, + "json": "{\"id\":\"frame-14\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "bfedf583a747": { + "name": "github.workItemDetails#1", + "ordinal": 15, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-8", + "ok": true, + "result": { + "body": "body", + "comments": [ + { + "author": "rev", + "body": "please fix", + "createdAt": "2026-01-01T00:00:00Z", + "id": 55, + "isResolved": false, + "line": 3, + "path": "src/app.ts", + "threadId": "thread-1", + "url": "https://github.com/owner/repo/pull/12#discussion_r55" + } + ], + "headSha": "head-sha-1", + "item": { + "assignees": [], + "id": "PR_1", + "labels": [], + "number": 12, + "state": "open", + "title": "Recorded", + "type": "pr", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "cdb9ad4feb12": { + "name": "hostedReview.forBranch#2", + "ordinal": 27, + "json": "{\"id\":\"frame-12\",\"deviceToken\":\"recording-device\",\"method\":\"hostedReview.forBranch\",\"params\":{\"repo\":\"id:repo-9\",\"branch\":\"feature\",\"linkedGitHubPR\":null,\"active\":true}}" + }, + "d8daaef1bef7": { + "name": "status.get#2", + "ordinal": 25, + "args": [ + { + "name": "method", + "value": "status.get" + }, + { + "name": "params", + "value": { + "$rpc": "undefined" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-14", + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + } + }, + "e0a11d8a1005": { + "commentError": { + "$rpc": "null" + }, + "pr": { + "checks": ["build:success"], + "checksError": { + "$rpc": "null" + }, + "comments": [ + { + "body": "please fix", + "id": 55, + "resolved": false + } + ], + "kind": "ready", + "pr": { + "headSha": "head-sha-1", + "number": 12, + "title": "Recorded" + }, + "refreshFailed": false + } + }, + "e10925fa98de": { + "name": "status.get#1", + "ordinal": 14, + "json": "{\"id\":\"frame-7\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + }, + "e5e21b070305": { + "name": "github.workItemDetails#2", + "ordinal": 35, + "args": [ + { + "name": "method", + "value": "github.workItemDetails" + }, + { + "name": "params", + "value": { + "number": 12, + "repo": "id:repo-9", + "type": "pr" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true, + "timeoutMs": 30000 + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-17", + "ok": true, + "result": { + "body": "body", + "comments": [ + { + "author": "rev", + "body": "please fix", + "createdAt": "2026-01-01T00:00:00Z", + "id": 55, + "isResolved": false, + "line": 3, + "path": "src/app.ts", + "threadId": "thread-1", + "url": "https://github.com/owner/repo/pull/12#discussion_r55" + } + ], + "headSha": "head-sha-1", + "item": { + "assignees": [], + "id": "PR_1", + "labels": [], + "number": 12, + "state": "open", + "title": "Recorded", + "type": "pr", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "e97818adb1c8": { + "name": "worktree.show#3", + "ordinal": 22, + "args": [ + { + "name": "method", + "value": "worktree.show" + }, + { + "name": "params", + "value": { + "worktree": "id:repo-9::/w" + } + }, + { + "name": "options", + "value": { + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-11", + "ok": true, + "result": { + "worktree": { + "linkedPR": { + "$rpc": "null" + } + } + } + } + } + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "fd8df0a75a2b": { + "name": "github.prForBranch#2", + "ordinal": 20, + "args": [ + { + "name": "method", + "value": "github.prForBranch" + }, + { + "name": "params", + "value": { + "acceptMergedFallbackPR": true, + "branch": "feature", + "currentHeadOid": { + "$rpc": "null" + }, + "fallbackPRNumber": 12, + "linkedPRNumber": { + "$rpc": "null" + }, + "repo": "id:repo-9" + } + }, + { + "name": "options", + "value": { + "beforeSend": "[local beforeSend]", + "failWhenDisconnected": true + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-10", + "ok": true, + "result": { + "fetchedAt": 0, + "kind": "found", + "pr": { + "headSha": "head-sha-1", + "mergeable": "MERGEABLE", + "number": 12, + "state": "open", + "title": "Recorded", + "updatedAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12" + } + } + } + } + }, + "ffe160d981d2": { + "name": "status.get#3", + "ordinal": 32, + "json": "{\"id\":\"frame-15\",\"deviceToken\":\"recording-device\",\"method\":\"status.get\"}" + } + }, + "recording": { + "scenario": "pr-sidebar-revisit-and-refresh", + "checkpoints": [ + { + "id": "branch-hint", + "observation": { + "sender": ["1287167eaf56", "4da7ea39401b", "75885386f005", "2dc2ca47b4e7"], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "35045fa5a752", + "effects": ["9091d133c3b0"] + } + }, + { + "id": "pr", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "a7e609fcb031", + "870c2b9bacd0" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "35045fa5a752", + "effects": ["9091d133c3b0"] + } + }, + { + "id": "loaded", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7" + ], + "settlements": { + "mount": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0"] + } + }, + { + "id": "revisited", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "214acb975f72", + "fd8df0a75a2b" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "5b1c7d371b2a", + "1c1b5062fc21" + ], + "settlements": { + "mount": "eb79a9b3682a", + "revisit": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "0726612d4a89"] + } + }, + { + "id": "refreshed", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "214acb975f72", + "fd8df0a75a2b", + "e97818adb1c8", + "2e217691ed33", + "a7feeba7e968", + "d8daaef1bef7", + "2055aa3ead1b", + "472f9e734ac0", + "e5e21b070305" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "5b1c7d371b2a", + "1c1b5062fc21", + "03bcac42a924", + "cdb9ad4feb12", + "7b3f2de1ee65", + "b8ec75ce4213", + "ffe160d981d2", + "7749a3b2d060", + "a2c2965e14f8" + ], + "settlements": { + "mount": "eb79a9b3682a", + "revisit": "eb79a9b3682a", + "refresh": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "0726612d4a89", "a5aaa57d24bd"] + } + }, + { + "id": "cleanup", + "observation": { + "sender": [ + "1287167eaf56", + "4da7ea39401b", + "75885386f005", + "a55c83eeaeea", + "861c8796ae1f", + "8b7e690466d7", + "bfedf583a747", + "214acb975f72", + "fd8df0a75a2b", + "e97818adb1c8", + "2e217691ed33", + "a7feeba7e968", + "d8daaef1bef7", + "2055aa3ead1b", + "472f9e734ac0", + "e5e21b070305" + ], + "payloads": [ + "1f5765918736", + "3ecc2d44a209", + "357f9b7862e3", + "0730389db3e9", + "3a8e6b13f380", + "0d9f7988ff86", + "e10925fa98de", + "5d309fcf43a7", + "5b1c7d371b2a", + "1c1b5062fc21", + "03bcac42a924", + "cdb9ad4feb12", + "7b3f2de1ee65", + "b8ec75ce4213", + "ffe160d981d2", + "7749a3b2d060", + "a2c2965e14f8" + ], + "settlements": { + "mount": "eb79a9b3682a", + "revisit": "eb79a9b3682a", + "refresh": "eb79a9b3682a" + }, + "state": "e0a11d8a1005", + "effects": ["9091d133c3b0", "0726612d4a89", "a5aaa57d24bd", "9cfd3529adf9"] + } + } + ] + } +} diff --git a/mobile/rpc-foundation/goldens/tk-item-comment-github.json b/mobile/rpc-foundation/goldens/tk-item-comment-github.json index 8a5e337b8a3..082e8e1ec47 100644 --- a/mobile/rpc-foundation/goldens/tk-item-comment-github.json +++ b/mobile/rpc-foundation/goldens/tk-item-comment-github.json @@ -54,11 +54,6 @@ "targetKey": "repo-1\u0000owner/repo\u0000issue\u00009" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "3aefb3006914": { "name": "error", "ordinal": 10, @@ -74,11 +69,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "69e396c2097f": { "name": "github.addIssueComment#1", "ordinal": 13, @@ -94,6 +84,16 @@ "ordinal": 12, "value": true }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "ae745d4c2372": { "name": "detailPayload", "ordinal": 14, @@ -341,8 +341,8 @@ "4031bf455f49", "c43ab05aed16", "1ca30ac68b76", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "ae745d4c2372", diff --git a/mobile/rpc-foundation/goldens/tk-item-comment-gitlab-mr.json b/mobile/rpc-foundation/goldens/tk-item-comment-gitlab-mr.json index bf05600a7bb..c578aa4f5f8 100644 --- a/mobile/rpc-foundation/goldens/tk-item-comment-gitlab-mr.json +++ b/mobile/rpc-foundation/goldens/tk-item-comment-gitlab-mr.json @@ -4,11 +4,6 @@ "family": "tasks.item-comment-gitlab-mr", "namedDeltas": [], "values": { - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "3aefb3006914": { "name": "error", "ordinal": 10, @@ -48,11 +43,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "622bbddf4f05": { "name": "actionItem", "ordinal": 6, @@ -129,6 +119,16 @@ "ordinal": 12, "value": true }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "c650cf641414": { "name": "itemReviewersDraft", "ordinal": 4, @@ -250,8 +250,8 @@ "4031bf455f49", "622bbddf4f05", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "f3cb1a7df6dc", diff --git a/mobile/rpc-foundation/goldens/tk-item-comment-gitlab.json b/mobile/rpc-foundation/goldens/tk-item-comment-gitlab.json index 124b984af93..12c817feb30 100644 --- a/mobile/rpc-foundation/goldens/tk-item-comment-gitlab.json +++ b/mobile/rpc-foundation/goldens/tk-item-comment-gitlab.json @@ -71,11 +71,6 @@ "provider": "gitlab" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "3aefb3006914": { "name": "error", "ordinal": 10, @@ -110,11 +105,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "6f50ec77f02f": { "name": "itemCommentDraft", "ordinal": 15, @@ -145,6 +135,16 @@ "ordinal": 12, "value": true }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "ad33e328b827": { "name": "gitlab.addIssueComment#1", "ordinal": 13, @@ -250,8 +250,8 @@ "4031bf455f49", "779d1b9a2edb", "474412c229f4", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "02b5df9521e8", diff --git a/mobile/rpc-foundation/goldens/tk-item-review-github.json b/mobile/rpc-foundation/goldens/tk-item-review-github.json index 1505ba32bde..82a001bcefa 100644 --- a/mobile/rpc-foundation/goldens/tk-item-review-github.json +++ b/mobile/rpc-foundation/goldens/tk-item-review-github.json @@ -136,11 +136,6 @@ "title": "A pull request" } }, - "1fc52836dac4": { - "name": "itemReviewersDraft", - "ordinal": 9, - "value": "octocat" - }, "22b1e4293201": { "name": "mutatingStatus", "ordinal": 28, @@ -310,11 +305,6 @@ "ordinal": 3, "value": "" }, - "56a29701de21": { - "name": "itemCommentDraft", - "ordinal": 8, - "value": "a comment" - }, "593c53b594c5": { "draft": "a comment", "error": "", @@ -581,6 +571,11 @@ "ordinal": 12, "value": true }, + "9331fbfa07e4": { + "name": "itemCommentDraft", + "ordinal": 9, + "value": "a comment" + }, "94caa29bceef": { "name": "error", "ordinal": 19, @@ -591,6 +586,11 @@ "ordinal": 18, "value": false }, + "ac15f5699a77": { + "name": "itemReviewersDraft", + "ordinal": 8, + "value": "octocat" + }, "baa2764f836f": { "name": "github.prChecks#1", "ordinal": 24, @@ -827,8 +827,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", @@ -858,8 +858,8 @@ "4031bf455f49", "04f768fb79f6", "26f442c9e2e5", - "56a29701de21", - "1fc52836dac4", + "ac15f5699a77", + "9331fbfa07e4", "3aefb3006914", "886c60a7e62e", "c29314fc4896", diff --git a/mobile/rpc-foundation/goldens/tk-linear-team-context.json b/mobile/rpc-foundation/goldens/tk-linear-team-context.json index 05b6f3cd2e2..81ba10022ae 100644 --- a/mobile/rpc-foundation/goldens/tk-linear-team-context.json +++ b/mobile/rpc-foundation/goldens/tk-linear-team-context.json @@ -4,10 +4,10 @@ "family": "tasks.linear-team-context", "namedDeltas": [], "values": { - "1288b8513745": { - "name": "linearStatesError", - "ordinal": 13, - "value": "" + "031c50459130": { + "name": "createTeamId", + "ordinal": 10, + "value": "team-1" }, "2afc4b1311c1": { "createTeamId": "team-1", @@ -22,24 +22,9 @@ } ] }, - "33218d06f656": { - "name": "linearStates", - "ordinal": 6, - "value": [] - }, - "356f2cb9a0df": { - "name": "linearStatesLoading", - "ordinal": 17, - "value": false - }, - "3abc893d377b": { - "name": "mutatingStatus", - "ordinal": 3, - "value": false - }, - "475ec9a66266": { + "38ed617d559f": { "name": "linearTeams", - "ordinal": 10, + "ordinal": 9, "value": [ { "id": "team-1", @@ -49,9 +34,44 @@ } ] }, - "5711e2717b76": { - "name": "linearStates", + "3abc893d377b": { + "name": "mutatingStatus", + "ordinal": 3, + "value": false + }, + "4fcc46dfeb77": { + "name": "linear.listTeams#1", + "ordinal": 8, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listTeams\"}" + }, + "5dcdc7fd7492": { + "name": "linearSubIssueTitle", + "ordinal": 4, + "value": "" + }, + "74335ecb4cd2": { + "name": "linearStatesLoading", "ordinal": 16, + "value": false + }, + "74505ce2789a": { + "name": "linearStates", + "ordinal": 5, + "value": [] + }, + "77a7eff4a3cc": { + "name": "linearStatesLoading", + "ordinal": 11, + "value": true + }, + "82b36eab5101": { + "name": "creatingTask", + "ordinal": 6, + "value": false + }, + "a14f6c361136": { + "name": "linearStates", + "ordinal": 15, "value": [ { "color": "#000000", @@ -61,24 +81,34 @@ } ] }, - "60a0395d07c7": { - "name": "linearStatesLoading", - "ordinal": 12, - "value": true - }, - "610f6c28e7a1": { - "name": "linearSubIssueTitle", - "ordinal": 5, - "value": "" - }, - "9131972798ca": { - "name": "linear.teamStates#1", - "ordinal": 15, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.teamStates\",\"params\":{\"teamId\":\"team-1\",\"workspaceId\":\"linear-workspace\"}}" - }, - "95b075d66243": { + "b5ba6f00c4fb": { "name": "linear.teamStates#1", "ordinal": 14, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"linear.teamStates\",\"params\":{\"teamId\":\"team-1\",\"workspaceId\":\"linear-workspace\"}}" + }, + "b6bf81e9e237": { + "createTeamId": "team-1", + "states": [ + { + "color": "#000000", + "id": "state-1", + "name": "Todo", + "type": "unstarted" + } + ], + "statesLoading": false, + "teams": [ + { + "id": "team-1", + "key": "ENG", + "name": "Engineering", + "workspaceId": "linear-workspace" + } + ] + }, + "c88d134e7a42": { + "name": "linear.teamStates#1", + "ordinal": 13, "args": [ { "name": "method", @@ -116,41 +146,6 @@ } } }, - "9dc1f136772e": { - "name": "linearCommentDraft", - "ordinal": 4, - "value": "" - }, - "b164dfd464b3": { - "name": "linear.listTeams#1", - "ordinal": 9, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"linear.listTeams\"}" - }, - "b1adae647a3f": { - "name": "createTeamId", - "ordinal": 11, - "value": "team-1" - }, - "b6bf81e9e237": { - "createTeamId": "team-1", - "states": [ - { - "color": "#000000", - "id": "state-1", - "name": "Todo", - "type": "unstarted" - } - ], - "statesLoading": false, - "teams": [ - { - "id": "team-1", - "key": "ENG", - "name": "Engineering", - "workspaceId": "linear-workspace" - } - ] - }, "cc2ece9478f0": { "name": "actionItem", "ordinal": 1, @@ -158,9 +153,29 @@ "$rpc": "null" } }, - "ceb71a750e06": { + "db66582f88a9": { + "name": "linearStatesError", + "ordinal": 12, + "value": "" + }, + "eb79a9b3682a": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "$rpc": "undefined" + } + }, + "eda130337c99": { + "name": "detailPayload", + "ordinal": 2, + "value": { + "$rpc": "null" + } + }, + "ee01f277ffc4": { "name": "linear.listTeams#1", - "ordinal": 8, + "ordinal": 7, "args": [ { "name": "method", @@ -196,26 +211,6 @@ ] } } - }, - "e9a162defc32": { - "name": "creatingTask", - "ordinal": 7, - "value": false - }, - "eb79a9b3682a": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "$rpc": "undefined" - } - }, - "eda130337c99": { - "name": "detailPayload", - "ordinal": 2, - "value": { - "$rpc": "null" - } } }, "recording": { @@ -224,8 +219,8 @@ { "id": "open-composer-settled", "observation": { - "sender": ["ceb71a750e06"], - "payloads": ["b164dfd464b3"], + "sender": ["ee01f277ffc4"], + "payloads": ["4fcc46dfeb77"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a" @@ -235,20 +230,19 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130" ] } }, { "id": "select-metadata-item-settled", "observation": { - "sender": ["ceb71a750e06", "95b075d66243"], - "payloads": ["b164dfd464b3", "9131972798ca"], + "sender": ["ee01f277ffc4", "c88d134e7a42"], + "payloads": ["4fcc46dfeb77", "b5ba6f00c4fb"], "settlements": { "mount": "eb79a9b3682a", "open-composer-0": "eb79a9b3682a", @@ -259,16 +253,15 @@ "cc2ece9478f0", "eda130337c99", "3abc893d377b", - "9dc1f136772e", - "610f6c28e7a1", - "33218d06f656", - "e9a162defc32", - "475ec9a66266", - "b1adae647a3f", - "60a0395d07c7", - "1288b8513745", - "5711e2717b76", - "356f2cb9a0df" + "5dcdc7fd7492", + "74505ce2789a", + "82b36eab5101", + "38ed617d559f", + "031c50459130", + "77a7eff4a3cc", + "db66582f88a9", + "a14f6c361136", + "74335ecb4cd2" ] } } diff --git a/mobile/rpc-foundation/goldens/tk-project-board-load.json b/mobile/rpc-foundation/goldens/tk-project-board-load.json index 8b3955f1b9d..d0d996e81c1 100644 --- a/mobile/rpc-foundation/goldens/tk-project-board-load.json +++ b/mobile/rpc-foundation/goldens/tk-project-board-load.json @@ -4,187 +4,28 @@ "family": "tasks.project-board-load", "namedDeltas": [], "values": { - "00ef2dbe5026": { - "name": "github.project.resolveRef#1", - "ordinal": 21, - "args": [ - { - "name": "method", - "value": "github.project.resolveRef" - }, - { - "name": "params", - "value": { - "host": "github.com", - "input": "https://github.com/orgs/owner/projects/3" - } - }, - { - "name": "options", - "value": { - "$rpc": "absent" - } - } - ], - "settlement": { - "status": "fulfilled", - "startedAt": 0, - "settledAt": 0, - "value": { - "id": "frame-4", - "ok": true, - "result": { - "host": "github.com", - "number": 3, - "ok": true, - "owner": "owner", - "ownerType": "organization", - "title": "Board", - "viewNumber": 1 - } - } - } - }, - "0388fa155721": { - "name": "githubProjectError", - "ordinal": 11, - "value": "" - }, - "15cb97c93333": { - "name": "github.project.listViews#1", - "ordinal": 8, - "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "170fad8cb36b": { - "name": "githubProjectPartialFailures", - "ordinal": 6, - "value": [] - }, - "2085118de92f": { - "name": "githubProjectError", - "ordinal": 1, - "value": "" - }, - "2ab1b35ff194": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "34de2d655a0a": { + "0056704adc0b": { "name": "githubProjectTable", - "ordinal": 32, + "ordinal": 31, "value": { "$rpc": "null" } }, - "376c9e8bd72a": { - "error": "", - "loading": false, - "pasteError": "", - "projects": [ - { - "host": "github.com", - "number": 3, - "owner": "owner", - "ownerType": "organization", - "title": "Board" - } - ], - "table": { - "$rpc": "null" - }, - "views": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "43352776b1e1": { - "name": "githubProjectTable", - "ordinal": 14, - "value": { - "fields": [], - "project": { - "id": "project-1", - "number": 3, - "title": "Board" - }, - "rows": [], - "selectedView": { - "filter": "is:open", - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - } - }, - "47507819e28a": { - "name": "githubProjectPasteInput", - "ordinal": 23, + "060dcedb3fdb": { + "name": "githubProjectError", + "ordinal": 10, "value": "" }, - "4eb521bbefdd": { - "name": "githubProjectSearch", - "ordinal": 15, - "value": "is:open" + "0af48d475813": { + "name": "appliedGithubProjectSearch", + "ordinal": 29, + "value": { + "$rpc": "undefined" + } }, - "528af16518e6": { - "name": "githubProjectViews", - "ordinal": 16, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] - }, - "5a4fc5c86d0c": { - "name": "githubProjectPasteBusy", - "ordinal": 34, - "value": false - }, - "5f5f56db9d64": { + "0f1aa264f581": { "name": "github.project.viewTable#1", - "ordinal": 12, + "ordinal": 11, "args": [ { "name": "method", @@ -236,15 +77,130 @@ } } }, - "61ce1ab88e79": { + "15cb97c93333": { + "name": "github.project.listViews#1", + "ordinal": 8, + "json": "{\"id\":\"frame-2\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3}}" + }, + "170fad8cb36b": { + "name": "githubProjectPartialFailures", + "ordinal": 6, + "value": [] + }, + "1b3350f71e56": { + "name": "githubProjectError", + "ordinal": 19, + "value": "" + }, + "2085118de92f": { + "name": "githubProjectError", + "ordinal": 1, + "value": "" + }, + "26921f3a7c09": { + "name": "githubProjectPasteError", + "ordinal": 18, + "value": "" + }, + "2ab1b35ff194": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "2f290fa2acf5": { + "name": "githubProjectLoading", + "ordinal": 9, + "value": true + }, + "3493818a7239": { + "name": "githubProjectPasteBusy", + "ordinal": 33, + "value": false + }, + "376c9e8bd72a": { + "error": "", + "loading": false, + "pasteError": "", + "projects": [ + { + "host": "github.com", + "number": 3, + "owner": "owner", + "ownerType": "organization", + "title": "Board" + } + ], + "table": { + "$rpc": "null" + }, + "views": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] + }, + "3985399034a2": { + "name": "githubProjectPasteBusy", + "ordinal": 17, + "value": true + }, + "3a8617cc8fd8": { + "name": "githubProjectSearch", + "ordinal": 14, + "value": "is:open" + }, + "4809ea7ad5b0": { "name": "github.project.viewTable#1", - "ordinal": 13, + "ordinal": 12, "json": "{\"id\":\"frame-3\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.viewTable\",\"params\":{\"owner\":\"owner\",\"host\":\"github.enterprise.test\",\"ownerType\":\"organization\",\"projectNumber\":3,\"viewId\":\"view-1\"}}" }, - "654693493b51": { - "name": "githubProjectLoading", - "ordinal": 10, - "value": true + "4c9b1e4ad1f5": { + "name": "githubProjectViews", + "ordinal": 28, + "value": [ + { + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + ] }, "685bc2bda05d": { "name": "githubProjects", @@ -259,34 +215,14 @@ } ] }, - "7a9df0d1a484": { - "name": "githubProjectLoading", - "ordinal": 25, - "value": true - }, - "7b9d3b33c08b": { - "name": "githubProjectPasteError", - "ordinal": 19, - "value": "" - }, - "8792541c60ad": { + "6b03ace1146a": { "name": "githubProjectError", - "ordinal": 26, + "ordinal": 25, "value": "" }, - "8e4dec1aad1f": { - "name": "github.project.listViews#2", - "ordinal": 28, - "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" - }, - "8f3ee6c510b1": { - "name": "github.project.resolveRef#1", - "ordinal": 22, - "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" - }, - "9b9f8dd75514": { + "7d488eda1d1c": { "name": "githubProjectViews", - "ordinal": 9, + "ordinal": 15, "value": [ { "id": "view-1", @@ -296,24 +232,39 @@ } ] }, - "a4a1ff5df287": { - "name": "githubProjectPasteBusy", - "ordinal": 18, - "value": true + "842c950ee7cc": { + "name": "githubProjectLoading", + "ordinal": 16, + "value": false + }, + "8a0577280bad": { + "name": "showGitHubProjectPicker", + "ordinal": 23, + "value": false + }, + "97bc7dc12b92": { + "name": "githubProjectLoading", + "ordinal": 32, + "value": false + }, + "9f9a21ac7b9e": { + "name": "github.project.listViews#2", + "ordinal": 27, + "json": "{\"id\":\"frame-5\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listViews\",\"params\":{\"owner\":\"owner\",\"host\":\"github.com\",\"ownerType\":\"organization\",\"projectNumber\":3}}" }, "a5a3530ec11c": { "name": "githubProjectPartialFailures", "ordinal": 2, "value": [] }, - "b42c8edc0d53": { - "name": "github.project.listAccessible#1", - "ordinal": 4, - "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" + "ab1b10183665": { + "name": "githubProjectLoading", + "ordinal": 24, + "value": true }, - "b49ff9f109a5": { + "ae89e058b351": { "name": "github.project.listViews#2", - "ordinal": 27, + "ordinal": 26, "args": [ { "name": "method", @@ -356,22 +307,10 @@ } } }, - "b5e354ed6023": { - "name": "githubProjectLoading", - "ordinal": 17, - "value": false - }, - "b66c4f75c9ae": { - "name": "githubProjectViews", - "ordinal": 29, - "value": [ - { - "id": "view-1", - "layout": "TABLE_LAYOUT", - "name": "Table", - "number": 1 - } - ] + "b42c8edc0d53": { + "name": "github.project.listAccessible#1", + "ordinal": 4, + "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.listAccessible\",\"params\":{\"host\":\"github.com\"}}" }, "be0da5b53ffb": { "status": "fulfilled", @@ -386,15 +325,30 @@ } ] }, - "c453f220a7e2": { - "name": "githubProjectLoading", - "ordinal": 33, - "value": false + "be93253869e6": { + "name": "github.project.resolveRef#1", + "ordinal": 21, + "json": "{\"id\":\"frame-4\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.resolveRef\",\"params\":{\"input\":\"https://github.com/orgs/owner/projects/3\",\"host\":\"github.com\"}}" }, - "c4c4250b0567": { - "name": "showGitHubProjectPicker", - "ordinal": 24, - "value": false + "c5c018cf9a70": { + "name": "githubProjectTable", + "ordinal": 13, + "value": { + "fields": [], + "project": { + "id": "project-1", + "number": 3, + "title": "Board" + }, + "rows": [], + "selectedView": { + "filter": "is:open", + "id": "view-1", + "layout": "TABLE_LAYOUT", + "name": "Table", + "number": 1 + } + } }, "d254913957c1": { "name": "github.project.listViews#1", @@ -441,6 +395,11 @@ } } }, + "dc8dd7739c49": { + "name": "githubProjectPasteInput", + "ordinal": 22, + "value": "" + }, "dfe16215433b": { "name": "github.project.listAccessible#1", "ordinal": 3, @@ -485,6 +444,11 @@ } } }, + "e87bea4bcd3c": { + "name": "githubProjectSearch", + "ordinal": 30, + "value": "" + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -493,22 +457,46 @@ "$rpc": "undefined" } }, - "fa1d1b339394": { - "name": "appliedGithubProjectSearch", - "ordinal": 30, - "value": { - "$rpc": "undefined" - } - }, - "fb9764680a74": { - "name": "githubProjectError", + "f6003aed2098": { + "name": "github.project.resolveRef#1", "ordinal": 20, - "value": "" - }, - "fe075936e563": { - "name": "githubProjectSearch", - "ordinal": 31, - "value": "" + "args": [ + { + "name": "method", + "value": "github.project.resolveRef" + }, + { + "name": "params", + "value": { + "host": "github.com", + "input": "https://github.com/orgs/owner/projects/3" + } + }, + { + "name": "options", + "value": { + "$rpc": "absent" + } + } + ], + "settlement": { + "status": "fulfilled", + "startedAt": 0, + "settledAt": 0, + "value": { + "id": "frame-4", + "ok": true, + "result": { + "host": "github.com", + "number": 3, + "ok": true, + "owner": "owner", + "ownerType": "organization", + "title": "Board", + "viewNumber": 1 + } + } + } }, "ff43b5ec92a9": { "error": "", @@ -555,21 +543,15 @@ "projects-0": "eb79a9b3682a", "views-1": "be0da5b53ffb" }, - "state": "376c9e8bd72a", - "effects": [ - "2085118de92f", - "a5a3530ec11c", - "685bc2bda05d", - "170fad8cb36b", - "9b9f8dd75514" - ] + "state": "ff43b5ec92a9", + "effects": ["2085118de92f", "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b"] } }, { "id": "table-settled", "observation": { - "sender": ["dfe16215433b", "d254913957c1", "5f5f56db9d64"], - "payloads": ["b42c8edc0d53", "15cb97c93333", "61ce1ab88e79"], + "sender": ["dfe16215433b", "d254913957c1", "0f1aa264f581"], + "payloads": ["b42c8edc0d53", "15cb97c93333", "4809ea7ad5b0"], "settlements": { "mount": "eb79a9b3682a", "projects-0": "eb79a9b3682a", @@ -582,13 +564,12 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc" ] } }, @@ -598,16 +579,16 @@ "sender": [ "dfe16215433b", "d254913957c1", - "5f5f56db9d64", - "00ef2dbe5026", - "b49ff9f109a5" + "0f1aa264f581", + "f6003aed2098", + "ae89e058b351" ], "payloads": [ "b42c8edc0d53", "15cb97c93333", - "61ce1ab88e79", - "8f3ee6c510b1", - "8e4dec1aad1f" + "4809ea7ad5b0", + "be93253869e6", + "9f9a21ac7b9e" ], "settlements": { "mount": "eb79a9b3682a", @@ -622,26 +603,25 @@ "a5a3530ec11c", "685bc2bda05d", "170fad8cb36b", - "9b9f8dd75514", - "654693493b51", - "0388fa155721", - "43352776b1e1", - "4eb521bbefdd", - "528af16518e6", - "b5e354ed6023", - "a4a1ff5df287", - "7b9d3b33c08b", - "fb9764680a74", - "47507819e28a", - "c4c4250b0567", - "7a9df0d1a484", - "8792541c60ad", - "b66c4f75c9ae", - "fa1d1b339394", - "fe075936e563", - "34de2d655a0a", - "c453f220a7e2", - "5a4fc5c86d0c" + "2f290fa2acf5", + "060dcedb3fdb", + "c5c018cf9a70", + "3a8617cc8fd8", + "7d488eda1d1c", + "842c950ee7cc", + "3985399034a2", + "26921f3a7c09", + "1b3350f71e56", + "dc8dd7739c49", + "8a0577280bad", + "ab1b10183665", + "6b03ace1146a", + "4c9b1e4ad1f5", + "0af48d475813", + "e87bea4bcd3c", + "0056704adc0b", + "97bc7dc12b92", + "3493818a7239" ] } } diff --git a/mobile/rpc-foundation/goldens/tk-project-row-detail.json b/mobile/rpc-foundation/goldens/tk-project-row-detail.json index b1f0371bb9f..a603880f415 100644 --- a/mobile/rpc-foundation/goldens/tk-project-row-detail.json +++ b/mobile/rpc-foundation/goldens/tk-project-row-detail.json @@ -4,53 +4,20 @@ "family": "tasks.project-row-detail", "namedDeltas": [], "values": { - "0679b27a119b": { - "name": "projectFieldDrafts", - "ordinal": 11, - "value": {} - }, - "118d9662d37f": { + "0a6c63ec0fc1": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 16, + "ordinal": 15, "json": "{\"id\":\"frame-1\",\"deviceToken\":\"recording-device\",\"method\":\"github.project.workItemDetailsBySlug\",\"params\":{\"owner\":\"owner\",\"repo\":\"repo\",\"host\":\"github.enterprise.test\",\"number\":1,\"type\":\"issue\"}}" }, - "1e161db29c89": { - "name": "projectRowDetail", - "ordinal": 17, - "value": { - "assignees": [], - "baseSha": "base-sha", - "body": "body", - "checks": [], - "comments": [], - "files": [], - "headSha": "head-sha", - "labels": [], - "latestReviews": [], - "provider": "github", - "pullRequestId": "PR_kwDO", - "reviewDecision": { - "$rpc": "undefined" - }, - "reviewRequests": [] - } - }, - "2ee1c7329449": { - "name": "projectRowDetail", - "ordinal": 12, - "value": { - "$rpc": "null" - } - }, - "31fcc93f02da": { + "0d5e8bc85abb": { "name": "projectEditingCommentDraft", - "ordinal": 9, + "ordinal": 8, "value": "" }, - "368311fc2981": { - "name": "projectCommentDraft", - "ordinal": 7, - "value": "" + "34aecaef096a": { + "name": "projectRowDetailLoading", + "ordinal": 17, + "value": false }, "3a42a92c5487": { "name": "projectBodyDraft", @@ -64,36 +31,9 @@ "$rpc": "null" } }, - "4f23116da7f6": { - "name": "projectReviewersDraft", - "ordinal": 10, - "value": "" - }, - "561861a537bb": { - "name": "projectRowDetailLoading", - "ordinal": 18, - "value": false - }, - "5cebe6c14680": { - "name": "prFileLoadingPath", - "ordinal": 4, - "value": { - "$rpc": "null" - } - }, - "60012e7abb60": { - "name": "prFileCommentDrafts", - "ordinal": 2, - "value": {} - }, - "7ca2bb47ab1c": { - "name": "prFileContents", - "ordinal": 3, - "value": {} - }, - "899221be28d8": { + "55361bf207c6": { "name": "github.project.workItemDetailsBySlug#1", - "ordinal": 15, + "ordinal": 14, "args": [ { "name": "method", @@ -152,6 +92,40 @@ } } }, + "5b08d6631c0c": { + "name": "projectRowDetailError", + "ordinal": 12, + "value": "" + }, + "5cebe6c14680": { + "name": "prFileLoadingPath", + "ordinal": 4, + "value": { + "$rpc": "null" + } + }, + "60012e7abb60": { + "name": "prFileCommentDrafts", + "ordinal": 2, + "value": {} + }, + "6a0930bd2fdb": { + "name": "projectEditingCommentId", + "ordinal": 7, + "value": { + "$rpc": "null" + } + }, + "7ca2bb47ab1c": { + "name": "prFileContents", + "ordinal": 3, + "value": {} + }, + "93c5cbde2045": { + "name": "projectRowDetailLoading", + "ordinal": 13, + "value": true + }, "9911dd53d1d7": { "name": "projectTitleDraft", "ordinal": 5, @@ -178,18 +152,44 @@ "error": "", "loading": false }, - "b63d5911050c": { - "name": "projectRowDetailError", - "ordinal": 13, + "bf07b693e877": { + "name": "projectRowDetail", + "ordinal": 16, + "value": { + "assignees": [], + "baseSha": "base-sha", + "body": "body", + "checks": [], + "comments": [], + "files": [], + "headSha": "head-sha", + "labels": [], + "latestReviews": [], + "provider": "github", + "pullRequestId": "PR_kwDO", + "reviewDecision": { + "$rpc": "undefined" + }, + "reviewRequests": [] + } + }, + "c82fb4f46067": { + "name": "projectReviewersDraft", + "ordinal": 9, "value": "" }, - "c0e2c37d8abf": { - "name": "projectEditingCommentId", - "ordinal": 8, + "de8ce98bdd63": { + "name": "projectRowDetail", + "ordinal": 11, "value": { "$rpc": "null" } }, + "e5129a14b6e4": { + "name": "projectFieldDrafts", + "ordinal": 10, + "value": {} + }, "eb79a9b3682a": { "status": "fulfilled", "startedAt": 0, @@ -197,11 +197,6 @@ "value": { "$rpc": "undefined" } - }, - "f6a5085dd8e9": { - "name": "projectRowDetailLoading", - "ordinal": 14, - "value": true } }, "recording": { @@ -210,8 +205,8 @@ { "id": "mounted", "observation": { - "sender": ["899221be28d8"], - "payloads": ["118d9662d37f"], + "sender": ["55361bf207c6"], + "payloads": ["0a6c63ec0fc1"], "settlements": { "mount": "eb79a9b3682a" }, @@ -223,16 +218,15 @@ "5cebe6c14680", "9911dd53d1d7", "3a42a92c5487", - "368311fc2981", - "c0e2c37d8abf", - "31fcc93f02da", - "4f23116da7f6", - "0679b27a119b", - "2ee1c7329449", - "b63d5911050c", - "f6a5085dd8e9", - "1e161db29c89", - "561861a537bb" + "6a0930bd2fdb", + "0d5e8bc85abb", + "c82fb4f46067", + "e5129a14b6e4", + "de8ce98bdd63", + "5b08d6631c0c", + "93c5cbde2045", + "bf07b693e877", + "34aecaef096a" ] } } diff --git a/mobile/rpc-foundation/goldens/worktree-home-catalog.json b/mobile/rpc-foundation/goldens/worktree-home-catalog.json index a8c20584939..13a7dde432f 100644 --- a/mobile/rpc-foundation/goldens/worktree-home-catalog.json +++ b/mobile/rpc-foundation/goldens/worktree-home-catalog.json @@ -4,21 +4,6 @@ "family": "worktree.home-catalog", "namedDeltas": [], "values": { - "19a302575563": { - "host-1": { - "activeCount": 2, - "agents": [], - "countsProvenAt": 1767225600000, - "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, - "totalWorktrees": 2 - } - }, "34fb08d01b03": { "name": "worktree.ps#1", "ordinal": 1, @@ -50,7 +35,16 @@ } }, "44136fa355b3": {}, - "7858e4e82b0f": { + "800962c868e7": { + "host-1": { + "activeCount": 2, + "agents": [], + "countsProvenAt": 1767225600000, + "hostId": "host-1", + "totalWorktrees": 2 + } + }, + "89066e878348": { "name": "info", "ordinal": 3, "value": { @@ -59,12 +53,6 @@ "agents": [], "countsProvenAt": 1767225600000, "hostId": "host-1", - "lastActiveWorktree": { - "displayName": "One", - "repo": "Repo", - "status": "working", - "worktreeId": "w-1" - }, "totalWorktrees": 2 } } @@ -161,8 +149,8 @@ "settlements": { "load": "eb79a9b3682a" }, - "state": "19a302575563", - "effects": ["7858e4e82b0f"] + "state": "800962c868e7", + "effects": ["89066e878348"] } } ] diff --git a/mobile/rpc-foundation/pilot-scenarios.json b/mobile/rpc-foundation/pilot-scenarios.json index 5be06b0d6b0..eeb45a4f5ee 100644 --- a/mobile/rpc-foundation/pilot-scenarios.json +++ b/mobile/rpc-foundation/pilot-scenarios.json @@ -8473,6 +8473,7 @@ "branch": "feature", "linkedPRNumber": null, "fallbackPRNumber": 12, + "acceptMergedFallbackPR": true, "currentHeadOid": null }, "paramsFollowDivergence": true, @@ -8572,6 +8573,398 @@ } ] }, + { + "id": "pr-sidebar-revisit-and-refresh", + "operation": "session.pr-sidebar", + "family": "session.pr-sidebar", + "sites": [ + "mobile/src/source-control/review/use-mobile-pr-sidebar-controller.ts", + "mobile/src/source-control/review/mobile-pr-queries.ts", + "mobile/src/source-control/review/mobile-pr-sidebar-state.ts" + ], + "schedules": [], + "steps": [ + { + "action": "mount", + "id": "mount" + }, + { + "complete": "github.repoSlug#1", + "params": { + "repo": "id:repo-9" + }, + "reply": { + "ok": true, + "result": { + "owner": "owner", + "repo": "repo" + } + } + }, + { + "complete": "hostedReview.forBranch#1", + "params": { + "repo": "id:repo-9", + "branch": "feature", + "linkedGitHubPR": null, + "active": true + }, + "reply": { + "ok": true, + "result": { + "provider": "github", + "number": 12, + "title": "Recorded", + "state": "open", + "url": "https://github.com/owner/repo/pull/12", + "updatedAt": "2026-01-01T00:00:00Z", + "mergeable": "MERGEABLE" + } + } + }, + { + "complete": "worktree.show#1", + "params": { + "worktree": "id:repo-9::/w" + }, + "reply": { + "ok": true, + "result": { + "worktree": { + "linkedPR": null + } + } + } + }, + { + "checkpoint": "branch-hint" + }, + { + "complete": "github.prForBranch#1", + "params": { + "repo": "id:repo-9", + "branch": "feature", + "linkedPRNumber": null, + "fallbackPRNumber": 12, + "acceptMergedFallbackPR": true, + "currentHeadOid": null + }, + "paramsFollowDivergence": true, + "reply": { + "ok": true, + "result": { + "kind": "found", + "pr": { + "number": 12, + "state": "open", + "title": "Recorded", + "url": "https://github.com/owner/repo/pull/12", + "headSha": "head-sha-1", + "updatedAt": "2026-01-01T00:00:00Z", + "mergeable": "MERGEABLE" + }, + "fetchedAt": 0 + } + } + }, + { + "checkpoint": "pr" + }, + { + "complete": "github.prChecks#1", + "params": { + "repo": "id:repo-9", + "prNumber": 12, + "headSha": "head-sha-1" + }, + "reply": { + "ok": true, + "result": [ + { + "name": "build", + "status": "completed", + "conclusion": "success", + "checkRunId": 7 + } + ] + } + }, + { + "complete": "status.get#1", + "params": { + "$undefined": true + }, + "reply": { + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + }, + { + "complete": "github.workItemDetails#1", + "params": { + "repo": "id:repo-9", + "number": 12, + "type": "pr" + }, + "paramsFollowDivergence": true, + "reply": { + "ok": true, + "result": { + "item": { + "id": "PR_1", + "number": 12, + "type": "pr", + "state": "open", + "title": "Recorded", + "url": "https://github.com/owner/repo/pull/12", + "updatedAt": "2026-01-01T00:00:00Z", + "labels": [], + "assignees": [] + }, + "body": "body", + "headSha": "head-sha-1", + "comments": [ + { + "id": 55, + "author": "rev", + "body": "please fix", + "createdAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12#discussion_r55", + "threadId": "thread-1", + "path": "src/app.ts", + "line": 3, + "isResolved": false + } + ] + } + } + }, + { + "checkpoint": "loaded" + }, + { + "action": "revisit", + "id": "revisit" + }, + { + "complete": "worktree.show#2", + "params": { + "worktree": "id:repo-9::/w" + }, + "reply": { + "ok": true, + "result": { + "worktree": { + "linkedPR": null + } + } + } + }, + { + "complete": "github.prForBranch#2", + "params": { + "repo": "id:repo-9", + "branch": "feature", + "linkedPRNumber": null, + "fallbackPRNumber": 12, + "acceptMergedFallbackPR": true, + "currentHeadOid": null + }, + "paramsFollowDivergence": true, + "reply": { + "ok": true, + "result": { + "kind": "found", + "pr": { + "number": 12, + "state": "open", + "title": "Recorded", + "url": "https://github.com/owner/repo/pull/12", + "headSha": "head-sha-1", + "updatedAt": "2026-01-01T00:00:00Z", + "mergeable": "MERGEABLE" + }, + "fetchedAt": 0 + } + } + }, + { + "checkpoint": "revisited" + }, + { + "action": "refresh", + "id": "refresh" + }, + { + "complete": "hostedReview.forBranch#2", + "params": { + "repo": "id:repo-9", + "branch": "feature", + "linkedGitHubPR": null, + "active": true + }, + "reply": { + "ok": true, + "result": { + "provider": "github", + "number": 12, + "title": "Recorded", + "state": "open", + "url": "https://github.com/owner/repo/pull/12", + "updatedAt": "2026-01-01T00:00:00Z", + "mergeable": "MERGEABLE" + } + } + }, + { + "complete": "worktree.show#3", + "params": { + "worktree": "id:repo-9::/w" + }, + "reply": { + "ok": true, + "result": { + "worktree": { + "linkedPR": null + } + } + } + }, + { + "complete": "github.prForBranch#3", + "params": { + "repo": "id:repo-9", + "branch": "feature", + "linkedPRNumber": null, + "fallbackPRNumber": 12, + "acceptMergedFallbackPR": true, + "currentHeadOid": null, + "userRefresh": true + }, + "paramsFollowDivergence": true, + "reply": { + "ok": true, + "result": { + "kind": "found", + "pr": { + "number": 12, + "state": "open", + "title": "Recorded", + "url": "https://github.com/owner/repo/pull/12", + "headSha": "head-sha-1", + "updatedAt": "2026-01-01T00:00:00Z", + "mergeable": "MERGEABLE" + }, + "fetchedAt": 0 + } + } + }, + { + "complete": "github.prChecks#2", + "params": { + "repo": "id:repo-9", + "prNumber": 12, + "noCache": true, + "userRefresh": true, + "headSha": "head-sha-1" + }, + "reply": { + "ok": true, + "result": [ + { + "name": "build", + "status": "completed", + "conclusion": "success", + "checkRunId": 7 + } + ] + } + }, + { + "bind": "refresh-status-2", + "request": "status.get#2", + "params": { + "$undefined": true + } + }, + { + "complete": "refresh-status-2", + "params": { + "$undefined": true + }, + "reply": { + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + }, + { + "bind": "refresh-status-3", + "request": "status.get#3", + "params": { + "$undefined": true + } + }, + { + "complete": "refresh-status-3", + "params": { + "$undefined": true + }, + "reply": { + "ok": true, + "result": { + "runtimeId": "recorded" + } + } + }, + { + "complete": "github.workItemDetails#2", + "params": { + "repo": "id:repo-9", + "number": 12, + "type": "pr" + }, + "paramsFollowDivergence": true, + "reply": { + "ok": true, + "result": { + "item": { + "id": "PR_1", + "number": 12, + "type": "pr", + "state": "open", + "title": "Recorded", + "url": "https://github.com/owner/repo/pull/12", + "updatedAt": "2026-01-01T00:00:00Z", + "labels": [], + "assignees": [] + }, + "body": "body", + "headSha": "head-sha-1", + "comments": [ + { + "id": 55, + "author": "rev", + "body": "please fix", + "createdAt": "2026-01-01T00:00:00Z", + "url": "https://github.com/owner/repo/pull/12#discussion_r55", + "threadId": "thread-1", + "path": "src/app.ts", + "line": 3, + "isResolved": false + } + ] + } + } + }, + { + "checkpoint": "refreshed" + } + ] + }, { "id": "pr-sidebar-checks-refused", "operation": "session.pr-sidebar", @@ -8645,6 +9038,7 @@ "branch": "feature", "linkedPRNumber": null, "fallbackPRNumber": 12, + "acceptMergedFallbackPR": true, "currentHeadOid": null }, "paramsFollowDivergence": true, @@ -8813,6 +9207,7 @@ "branch": "feature", "linkedPRNumber": null, "fallbackPRNumber": 12, + "acceptMergedFallbackPR": true, "currentHeadOid": null }, "paramsFollowDivergence": true, @@ -9012,6 +9407,7 @@ "branch": "feature", "linkedPRNumber": null, "fallbackPRNumber": 12, + "acceptMergedFallbackPR": true, "currentHeadOid": null }, "paramsFollowDivergence": true, @@ -21684,6 +22080,144 @@ } ] }, + { + "id": "event-router-failed-read-floor", + "operation": "query.event-router-catalog", + "family": "query.event-router-catalog", + "sites": ["mobile/src/query/host-event-router.ts"], + "schedules": [], + "steps": [ + { + "action": "mount", + "id": "mount" + }, + { + "frame": "runtime.clientEvents.subscribe#1", + "params": null, + "reply": { + "ok": true, + "streaming": true, + "result": { + "type": "ready", + "subscriptionId": "sub-1" + } + } + }, + { + "checkpoint": "listening" + }, + { + "complete": "worktree.ps#1", + "params": { + "limit": 10000, + "supportsWorktreeVisibilitySourceDefaults": true, + "afterSnapshotId": null, + "acceptRowDelta": true + }, + "reply": { + "ok": false, + "error": { + "code": "runtime_error", + "message": "worktree list unavailable" + } + } + }, + { + "checkpoint": "read-refused" + }, + { + "frame": "runtime.clientEvents.subscribe#1", + "params": null, + "reply": { + "ok": true, + "streaming": true, + "result": { + "type": "worktreesChanged", + "repoId": "repo-1" + } + } + }, + { + "advance": 150 + }, + { + "frame": "runtime.clientEvents.subscribe#1", + "params": null, + "reply": { + "ok": true, + "streaming": true, + "result": { + "type": "worktreesChanged", + "repoId": "repo-1" + } + } + }, + { + "advance": 150 + }, + { + "frame": "runtime.clientEvents.subscribe#1", + "params": null, + "reply": { + "ok": true, + "streaming": true, + "result": { + "type": "worktreesChanged", + "repoId": "repo-1" + } + } + }, + { + "advance": 150 + }, + { + "frame": "runtime.clientEvents.subscribe#1", + "params": null, + "reply": { + "ok": true, + "streaming": true, + "result": { + "type": "worktreesChanged", + "repoId": "repo-1" + } + } + }, + { + "advance": 150 + }, + { + "frame": "runtime.clientEvents.subscribe#1", + "params": null, + "reply": { + "ok": true, + "streaming": true, + "result": { + "type": "worktreesChanged", + "repoId": "repo-1" + } + } + }, + { + "advance": 150 + }, + { + "checkpoint": "five-notices-inside-the-floor" + }, + { + "advance": 3000 + }, + { + "checkpoint": "floor-passed" + }, + { + "action": "unmount", + "id": "unmount" + }, + { + "checkpoint": "unmounted" + } + ] + }, { "id": "sc-changes-loaded", "operation": "source-control.changes-load", diff --git a/mobile/src/accounts/MobileAccountsScreen.tsx b/mobile/src/accounts/MobileAccountsScreen.tsx index 938fbf6d4bf..2ea1d8b0c18 100644 --- a/mobile/src/accounts/MobileAccountsScreen.tsx +++ b/mobile/src/accounts/MobileAccountsScreen.tsx @@ -5,6 +5,10 @@ import { useFocusEffect, useLocalSearchParams } from 'expo-router' import { ChevronLeft, RefreshCw, User } from 'lucide-react-native' import { loadHosts, peekHosts } from '../transport/hosts/host-store' import { useForceReconnect, useHostClient } from '../transport/connection/host-client-hooks' +import { useHostConnectionInputs } from '../transport/connection/client-context-connection-metrics' +import { classifyConnection, isConnectionOutage } from '../transport/connection/connection-health' +import { HostOfflineBanner, useHostOfflineBanner } from '../components/HostOfflineBanner' +import { useRefreshHint } from '../query/refresh-hint' import { MobileAccountsLoadState } from './MobileAccountsLoadState' import { colors, spacing } from '../theme/mobile-theme' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' @@ -12,9 +16,7 @@ import { useMobileTranslation } from '../i18n/use-mobile-translation' import { styles } from './mobile-accounts-screen-styles' import { useNow } from '../hooks/use-now' import { ClaudeIcon, OpenAIIcon } from '../components/AgentIcons' -import { AccountsSnapshotError, decodeAccountsSnapshot } from '../components/accounts-snapshot' import { - type AccountsSnapshot, type ProviderKey, getActiveProviderRateLimits, getInactiveProviderUsage, @@ -35,7 +37,7 @@ import { NavBar } from '../components/nav-bar/NavBar' import { NavBarButton } from '../components/nav-bar/NavBarButton' import { ListGroup, SectionHeader, ListRow } from '../components/list/ListGroup' import { useRouteHandoff } from '../navigation/route-handoff' -import { subscribeAccountsSnapshots } from './accounts-snapshot-stream' +import { useMobileAccountsSnapshot } from './use-mobile-accounts-snapshot' type AccountsNotice = { title: string; message: string } @@ -50,26 +52,39 @@ export function MobileAccountsScreen() { // Why: shared client per host. See docs/mobile-shared-client-per-host.md. const { client, state: connState } = useHostClient(hostId) const forceReconnect = useForceReconnect() + const connectionInputs = useHostConnectionInputs(hostId) // Seed from the last host read so the subtitle is there on the first frame. const [hostName, setHostName] = useState( () => peekHosts()?.find((host) => host.id === hostId)?.name ?? '' ) - const [snapshot, setSnapshot] = useState(null) - const [error, setError] = useState(null) - const [refreshing, setRefreshing] = useState(false) + const [hostError, setHostError] = useState(null) const [busyAccountId, setBusyAccountId] = useState(null) const [clockEnabled, setClockEnabled] = useState(false) const [notice, setNotice] = useState(null) - const acceptSnapshot = useCallback((nextSnapshot: AccountsSnapshot) => { - setSnapshot(nextSnapshot) - setError(null) - }, []) - const rejectInvalidSnapshot = useCallback(() => { - // Fail closed on unrecognized snapshot: stale data can expose finite reset for wrong account. - setSnapshot(null) - setError(t('accounts.screen.invalidSnapshot', 'Invalid accounts snapshot from host')) - }, [t]) + const accounts = useMobileAccountsSnapshot({ + hostId, + client, + connState, + lastConnectedAt: connectionInputs.lastConnectedAt + }) + const { snapshot, live, refresh, refreshing, acceptSnapshot } = accounts + const error = accounts.error ?? hostError + // Stored accounts stay up while connecting or offline; re-pair and a failed read on a live connection say so instead. + const showsAccounts = + snapshot !== null && + (live || (connState !== 'auth-failed' && !(connState === 'connected' && error))) + const offlineBanner = useHostOfflineBanner({ + client, + connState, + lastConnectedAt: connectionInputs.lastConnectedAt, + outage: isConnectionOutage(classifyConnection({ state: connState, ...connectionInputs })), + forceReconnect: hostId && forceReconnect ? () => void forceReconnect(hostId) : null, + hasData: showsAccounts, + asOf: accounts.readAt + }) + // Stored accounts wait on the stream's first answer for their usage. + const showRefreshLine = useRefreshHint(showsAccounts && !live && offlineBanner === null) const { supported: codexResetSupported, resetting: resettingCodex, @@ -108,7 +123,7 @@ export function MobileAccountsScreen() { } const host = hosts.find((h) => h.id === hostId) if (!host) { - setError(t('accounts.screen.hostNotFound', 'Host not found')) + setHostError(t('accounts.screen.hostNotFound', 'Host not found')) return } setHostName(host.name) @@ -118,41 +133,6 @@ export function MobileAccountsScreen() { } }, [hostId, t]) - const refresh = useCallback(async () => { - if (!client) { - return - } - setRefreshing(true) - try { - const res = await client.sendRequest('accounts.list') - if (res.ok) { - acceptSnapshot(decodeAccountsSnapshot(res.result)) - } else { - setError(res.error.message) - } - } catch (e) { - if (e instanceof AccountsSnapshotError) { - rejectInvalidSnapshot() - } else { - setError(e instanceof Error ? e.message : String(e)) - } - } finally { - setRefreshing(false) - } - }, [acceptSnapshot, client, rejectInvalidSnapshot]) - - // Stream desktop poll/account-switch updates, falling back to one-shot accounts.list on subscription error. - useEffect(() => { - if (!client || connState !== 'connected') { - return - } - return subscribeAccountsSnapshots(client, { - onSnapshot: acceptSnapshot, - onInvalidSnapshot: rejectInvalidSnapshot, - onStreamError: () => void refresh() - }) - }, [acceptSnapshot, client, connState, refresh, rejectInvalidSnapshot]) - const selectAccount = useCallback( async (provider: ProviderKey, accountId: string | null) => { if (!client) { @@ -202,7 +182,8 @@ export function MobileAccountsScreen() { const activeUsage = getActiveProviderRateLimits(snapshot, provider) const resetCredit = provider === 'codex' ? getCodexResetCreditSummary(activeUsage, now) : null const Icon = provider === 'claude' ? ClaudeIcon : OpenAIIcon - const switchBlocked = busyAccountId !== null || resettingCodex || connState !== 'connected' + // Stored rows may name a selection or Codex target the desktop has since changed. + const switchBlocked = busyAccountId !== null || resettingCodex || !live const spinner = return ( @@ -324,6 +305,7 @@ export function MobileAccountsScreen() { } title={t('accounts.screen.title', 'Accounts')} subtitle={hostName || undefined} + refreshing={showRefreshLine} trailing={ - {!snapshot ? ( + {!showsAccounts ? ( ) : ( <> + {offlineBanner ? ( + + + + ) : null} {renderProviderSection('claude')} {renderProviderSection('codex')} {renderOtherProviders()} diff --git a/mobile/src/accounts/accounts-snapshot-stream.ts b/mobile/src/accounts/accounts-snapshot-stream.ts index 8ec30aa7197..09ca407fead 100644 --- a/mobile/src/accounts/accounts-snapshot-stream.ts +++ b/mobile/src/accounts/accounts-snapshot-stream.ts @@ -1,7 +1,52 @@ -import { decodeAccountsSnapshot } from '../components/accounts-snapshot' +import { queryOptions, skipToken } from '@tanstack/react-query' +import { AccountsSnapshotSchema, decodeAccountsSnapshot } from '../components/accounts-snapshot' import type { AccountsSnapshot } from '../components/AccountUsage' +import { hostQueryKey, type HostQueryKey } from '../query/host-query-key' +import type { PersistedHostFamily } from '../query/host-query-persistence' import type { RpcClient } from '../transport/rpc/rpc-client-contract' +/** Usage and rate limits are live facts: a stored snapshot keeps the accounts and drops every number. */ +export function withoutAccountUsage(snapshot: AccountsSnapshot | null): AccountsSnapshot | null { + if (!snapshot) { + return null + } + const { claudeTarget, codexTarget } = snapshot.rateLimits + return { + ...snapshot, + rateLimits: { + claude: null, + codex: null, + claudeTarget, + codexTarget, + inactiveClaudeAccounts: [], + inactiveCodexAccounts: [] + } + } +} + +/** A host's last `accounts.subscribe` snapshot; null when the desktop sent one this phone can't read. */ +export const accountsSnapshotFamily: PersistedHostFamily = { + family: 'accounts.snapshot', + persist: { + version: 1, + dataSchema: AccountsSnapshotSchema.nullable(), + strip: withoutAccountUsage + } +} + +// Host-wide, read on the desktop itself; kept free of the host list's module, which the Accounts page doesn't load. +export const accountsSnapshotKey = (hostId: string) => + hostQueryKey(hostId, accountsSnapshotFamily.family, { exec: 'local' }, {}) + +/** Kept by the accounts stream or an `accounts.list` read, never fetched. */ +export const accountsSnapshotOptions = (hostId: string) => + queryOptions({ + queryKey: accountsSnapshotKey(hostId), + queryFn: skipToken, + gcTime: Infinity, + meta: { streamBacked: true, persist: accountsSnapshotFamily.persist } + }) + /** The desktop's `accounts.subscribe` stream, decoded: rate-limit polls and account switches as they happen. */ export function subscribeAccountsSnapshots( client: RpcClient, diff --git a/mobile/src/accounts/mobile-accounts-screen-styles.ts b/mobile/src/accounts/mobile-accounts-screen-styles.ts index f72f5786ecc..bce57b12934 100644 --- a/mobile/src/accounts/mobile-accounts-screen-styles.ts +++ b/mobile/src/accounts/mobile-accounts-screen-styles.ts @@ -11,6 +11,9 @@ export const styles = themedStyleSheet(() => ({ paddingHorizontal: spacing.lg, paddingTop: spacing.sm }, + offlineBanner: { + paddingBottom: spacing.sm + }, // On a screen, not a sheet: one step above the page, as the other screen groups are. group: { backgroundColor: colors.bgPanel diff --git a/mobile/src/accounts/use-mobile-accounts-snapshot.test.tsx b/mobile/src/accounts/use-mobile-accounts-snapshot.test.tsx new file mode 100644 index 00000000000..a64c3166b1b --- /dev/null +++ b/mobile/src/accounts/use-mobile-accounts-snapshot.test.tsx @@ -0,0 +1,107 @@ +import { createElement } from 'react' +import { QueryClientProvider, type QueryClient } from '@tanstack/react-query' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +// Also tells TanStack observers on a microtask, so act() sees replies. +import '../test-support/query-client-test-renderer' +import { settleQueryNotifications } from '../test-support/rpc-recording/hook-mount' +import { createOrcaQueryClient } from '../query/orca-query-client' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { accountsSnapshotKey } from './accounts-snapshot-stream' +import { useMobileAccountsSnapshot } from './use-mobile-accounts-snapshot' + +const HOST = 'host-1' +const CONNECTED_AT = 1_794_000_000_000 + +const SNAPSHOT = { + claude: { + accounts: [{ id: 'claude-1', email: 'claude@example.test', updatedAt: 100 }], + activeAccountId: 'claude-1' + }, + codex: { accounts: [], activeAccountId: null }, + rateLimits: { + claude: { + provider: 'claude', + session: { usedPercent: 42, windowMinutes: 300, resetsAt: null, resetDescription: null }, + weekly: null, + updatedAt: 100, + error: null, + status: 'ok' + }, + codex: null, + inactiveClaudeAccounts: [], + inactiveCodexAccounts: [] + } +} + +function accountsClient(listReply: unknown) { + let stream: (payload: unknown) => void = () => {} + const sendRequest = vi.fn(async () => ({ id: 'reply', ok: true as const, result: listReply })) + const client: RpcClient = { + sendRequest, + subscribe: (_method, _params, listener) => { + stream = listener + return () => {} + }, + updateTerminalSubscriptionViewport: () => {}, + getState: () => 'connected', + getReconnectAttempt: () => 0, + getLastConnectedAt: () => CONNECTED_AT, + getGeneration: () => 1, + onStateChange: () => () => {}, + notifyForeground: () => {}, + close: () => {} + } + return { client, sendRequest, frame: (payload: unknown) => stream(payload) } +} + +let tree: ReactTestRenderer | null = null +afterEach(() => { + act(() => tree?.unmount()) + tree = null +}) + +async function mountAccounts(queryClient: QueryClient, client: RpcClient) { + let state: ReturnType | null = null + function Probe() { + state = useMobileAccountsSnapshot({ + hostId: HOST, + client, + connState: 'connected', + lastConnectedAt: CONNECTED_AT + }) + return null + } + await act(async () => { + tree = create(createElement(QueryClientProvider, { client: queryClient }, createElement(Probe))) + }) + return () => { + if (!state) { + throw new Error('Not mounted') + } + return state + } +} + +describe('accounts snapshot', () => { + it('still shows usage when the stream fails and accounts.list answers', async () => { + const port = accountsClient(SNAPSHOT) + const read = await mountAccounts(createOrcaQueryClient(), port.client) + await act(async () => port.frame({ type: 'error' })) + await settleQueryNotifications() + expect(port.sendRequest).toHaveBeenCalledWith('accounts.list') + expect(read().live).toBe(true) + expect(read().snapshot?.rateLimits.claude?.session?.usedPercent).toBe(42) + }) + + it('hides usage this screen did not read on the current connection, keeping the accounts', async () => { + const queryClient = createOrcaQueryClient() + queryClient.setQueryData(accountsSnapshotKey(HOST), SNAPSHOT, { updatedAt: CONNECTED_AT - 1 }) + const read = await mountAccounts(queryClient, accountsClient(SNAPSHOT).client) + expect(read().live).toBe(false) + expect(read().snapshot?.rateLimits.claude).toBeNull() + expect(read().snapshot?.claude.accounts.map((account) => account.email)).toEqual([ + 'claude@example.test' + ]) + }) +}) diff --git a/mobile/src/accounts/use-mobile-accounts-snapshot.ts b/mobile/src/accounts/use-mobile-accounts-snapshot.ts new file mode 100644 index 00000000000..d4370bb5310 --- /dev/null +++ b/mobile/src/accounts/use-mobile-accounts-snapshot.ts @@ -0,0 +1,128 @@ +import { useCallback, useEffect, useMemo, useState } from 'react' +import { hashKey, useQuery, useQueryClient } from '@tanstack/react-query' +import { AccountsSnapshotError, decodeAccountsSnapshot } from '../components/accounts-snapshot' +import type { AccountsSnapshot } from '../components/AccountUsage' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { holdsRestoredHostQueryData } from '../query/host-query-persistence' +import type { ConnectionState } from '../transport/connection/connection-state' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { + accountsSnapshotKey, + accountsSnapshotOptions, + subscribeAccountsSnapshots, + withoutAccountUsage +} from './accounts-snapshot-stream' + +/** + * One host's accounts: the last stored snapshot at once, then the desktop's stream, or `accounts.list` when the + * stream fails. Usage shows only from a read on the current connection; anything older shows accounts alone. + */ +export function useMobileAccountsSnapshot({ + hostId, + client, + connState, + lastConnectedAt +}: { + hostId: string + client: RpcClient | null + connState: ConnectionState + lastConnectedAt: number | null +}) { + const t = useMobileTranslation() + const queryClient = useQueryClient() + const { data, dataUpdatedAt } = useQuery(accountsSnapshotOptions(hostId)) + // Dated by when its read was sent, so a failure from an earlier connection doesn't outlive it. + const [failure, setFailure] = useState<{ message: string; at: number } | null>(null) + const [refreshing, setRefreshing] = useState(false) + // Data this screen didn't read itself, such as a previous visit's in the same document, can't vouch for usage. + const [mountedAt] = useState(Date.now) + + const acceptSnapshot = useCallback( + (nextSnapshot: AccountsSnapshot) => { + queryClient.setQueryData(accountsSnapshotKey(hostId), nextSnapshot) + setFailure(null) + }, + [hostId, queryClient] + ) + const rejectInvalidSnapshot = useCallback( + (readAt = Date.now()) => { + // Fail closed on unrecognized snapshot: stale data can expose finite reset for wrong account. + queryClient.setQueryData(accountsSnapshotKey(hostId), null) + setFailure({ + message: t('accounts.screen.invalidSnapshot', 'Invalid accounts snapshot from host'), + at: readAt + }) + }, + [hostId, queryClient, t] + ) + + const refresh = useCallback(async () => { + if (!client) { + return + } + setRefreshing(true) + const sentAt = Date.now() + // A reply sent before a reconnect speaks for the old connection; the new one's stream answers instead. + const reconnectedSince = () => (client.getLastConnectedAt() ?? 0) > sentAt + try { + const res = await client.sendRequest('accounts.list') + if (reconnectedSince()) { + return + } + if (res.ok) { + acceptSnapshot(decodeAccountsSnapshot(res.result)) + } else { + setFailure({ message: res.error.message, at: sentAt }) + } + } catch (e) { + if (reconnectedSince()) { + return + } + if (e instanceof AccountsSnapshotError) { + rejectInvalidSnapshot(sentAt) + } else { + setFailure({ message: e instanceof Error ? e.message : String(e), at: sentAt }) + } + } finally { + setRefreshing(false) + } + }, [acceptSnapshot, client, rejectInvalidSnapshot]) + + // Stream desktop poll/account-switch updates, falling back to one-shot accounts.list on subscription error. + useEffect(() => { + if (!client || connState !== 'connected') { + return + } + return subscribeAccountsSnapshots(client, { + onSnapshot: acceptSnapshot, + onInvalidSnapshot: () => rejectInvalidSnapshot(), + onStreamError: () => void refresh() + }) + }, [acceptSnapshot, client, connState, refresh, rejectInvalidSnapshot]) + + // Only this screen's own read on the current connection shows usage. A stored snapshot never does, whatever its + // date: native Home writes it from its own stream, possibly after this connect or on a clock since set back. + const live = + data != null && + !holdsRestoredHostQueryData(queryClient, hashKey(accountsSnapshotKey(hostId))) && + connState === 'connected' && + lastConnectedAt !== null && + dataUpdatedAt >= Math.max(lastConnectedAt, mountedAt) + const snapshot = useMemo( + () => (live ? (data ?? null) : withoutAccountUsage(data ?? null)), + [live, data] + ) + + const error = + failure && (lastConnectedAt === null || failure.at >= lastConnectedAt) ? failure.message : null + + return { + snapshot, + live, + readAt: data != null ? dataUpdatedAt : null, + error, + refreshing, + refresh, + acceptSnapshot + } +} diff --git a/mobile/src/agents/agent-list-model.test.ts b/mobile/src/agents/agent-list-model.test.ts index 0001a6684d0..1b8ccb3bc2d 100644 --- a/mobile/src/agents/agent-list-model.test.ts +++ b/mobile/src/agents/agent-list-model.test.ts @@ -55,7 +55,7 @@ function input( worktreeInfo: Object.fromEntries( Object.entries(hosts).map(([id, host]) => [ id, - { hostId: id, totalWorktrees: 1, activeCount: 0, lastActiveWorktree: null, ...host.info } + { hostId: id, totalWorktrees: 1, activeCount: 0, ...host.info } ]) ), now: NOW diff --git a/mobile/src/cache/home-snapshot-cache.ts b/mobile/src/cache/home-snapshot-cache.ts deleted file mode 100644 index 01b9e7be1bf..00000000000 --- a/mobile/src/cache/home-snapshot-cache.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Seed cold-start/resume cards from persisted last-good snapshot, then update via RPC; avoids ~1s empty flash while reconnecting. -import AsyncStorage from '@react-native-async-storage/async-storage' -// Persist canonical countsProvenAt so rehydrated counts retain freshness evidence. -import type { HostWorktreeInfo } from '../worktree/home-worktree-info' - -const STORAGE_KEY = 'orca:home-snapshot:v1' - -export type HomeSnapshot = { - worktreeInfo: Record - savedAt: number -} - -let memoryCache: HomeSnapshot | null = null -let writeTimer: ReturnType | null = null - -export async function loadHomeSnapshot(): Promise { - if (memoryCache) { - return memoryCache - } - try { - const raw = await AsyncStorage.getItem(STORAGE_KEY) - if (!raw) { - return null - } - const parsed = JSON.parse(raw) as HomeSnapshot - if ( - typeof parsed !== 'object' || - parsed === null || - typeof parsed.worktreeInfo !== 'object' || - parsed.worktreeInfo === null - ) { - return null - } - memoryCache = parsed - return parsed - } catch { - return null - } -} - -// Throttle AsyncStorage writes during per-provider streamed snapshot bursts. -export function saveHomeSnapshot(snapshot: HomeSnapshot): void { - memoryCache = snapshot - if (writeTimer) { - clearTimeout(writeTimer) - } - writeTimer = setTimeout(() => { - writeTimer = null - void AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot)).catch(() => {}) - }, 250) -} diff --git a/mobile/src/cache/worktree-cache.test.ts b/mobile/src/cache/worktree-cache.test.ts deleted file mode 100644 index 4c076eb4e08..00000000000 --- a/mobile/src/cache/worktree-cache.test.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { setCachedWorktrees, getCachedWorktrees } from './worktree-cache' - -// A persisted cold-start seed must not truncate the rows a live worktree.ps listed. -describe('worktree-cache provenance', () => { - it('keeps a fresh host-listed catalog when a cold-start seed lands after it', () => { - const hostId = 'host-kept' - const listed = [{ worktreeId: 'a' }, { worktreeId: 'b' }] - setCachedWorktrees(hostId, listed, { proven: true }) - - setCachedWorktrees(hostId, [{ worktreeId: 'a' }]) - - expect(getCachedWorktrees(hostId)).toEqual(listed) - }) -}) diff --git a/mobile/src/cache/worktree-cache.ts b/mobile/src/cache/worktree-cache.ts deleted file mode 100644 index ad05d45c98e..00000000000 --- a/mobile/src/cache/worktree-cache.ts +++ /dev/null @@ -1,49 +0,0 @@ -// Home seeds module cache so host detail renders before reconnect/fetch. - -type CachedWorktrees = { - worktrees: unknown[] - at: number - // Live host-listed rows; a persisted cold-start seed must not replace them. - proven: boolean -} - -const cache = new Map() - -const MAX_AGE_MS = 30_000 -const MAX_ENTRIES = 20 - -export function setCachedWorktrees( - hostId: string, - worktrees: unknown[], - options?: { proven?: boolean } -): void { - // A late cold-start seed must not truncate live host-listed rows. - if (options?.proven !== true && readFreshEntry(hostId)?.proven) { - return - } - // Delete before Map.set to move key to newest position for LRU eviction. - cache.delete(hostId) - cache.set(hostId, { worktrees, at: Date.now(), proven: options?.proven === true }) - if (cache.size > MAX_ENTRIES) { - const oldest = cache.keys().next().value - if (oldest) { - cache.delete(oldest) - } - } -} - -export function getCachedWorktrees(hostId: string): unknown[] | null { - return readFreshEntry(hostId)?.worktrees ?? null -} - -function readFreshEntry(hostId: string): CachedWorktrees | null { - const entry = cache.get(hostId) - if (!entry) { - return null - } - if (Date.now() - entry.at > MAX_AGE_MS) { - cache.delete(hostId) - return null - } - return entry -} diff --git a/mobile/src/components/CustomKeyModal.styles.ts b/mobile/src/components/CustomKeyModal.styles.ts index a95b5abe3be..2921025e632 100644 --- a/mobile/src/components/CustomKeyModal.styles.ts +++ b/mobile/src/components/CustomKeyModal.styles.ts @@ -41,6 +41,9 @@ export const customKeyModalStyles = themedStyleSheet(() => ({ borderRadius: radii.surface, overflow: 'hidden' }, + smartRailGroup: { + marginTop: spacing.md + }, shortcutForm: { paddingTop: spacing.sm }, diff --git a/mobile/src/components/CustomKeyModal.tsx b/mobile/src/components/CustomKeyModal.tsx index b6dfac3cdc6..42afc17fd3c 100644 --- a/mobile/src/components/CustomKeyModal.tsx +++ b/mobile/src/components/CustomKeyModal.tsx @@ -19,6 +19,7 @@ import { useMobileTranslation } from '../i18n/use-mobile-translation' import { MobileSwitch } from './MobileSwitch' import { ListGroup, ListRow } from './list/ListGroup' import { FieldTextInput } from './composer-input/FieldTextInput' +import { SmartRailRow } from './SmartRailRow' type Step = 'choose-type' | 'shortcut-combo' | 'special-keys' | 'text-macro' @@ -62,9 +63,11 @@ type Props = { onClose: () => void onKeysChanged: (keys: CustomKey[]) => void onManageShortcuts?: () => void + smartRail?: { enabled: boolean; onChange: (enabled: boolean) => void } } -export function CustomKeyModal({ visible, onClose, onKeysChanged, onManageShortcuts }: Props) { +export function CustomKeyModal(props: Props) { + const { visible, onClose, onKeysChanged, onManageShortcuts, smartRail } = props useMobileColorScheme() const t = useMobileTranslation() const [step, setStep] = useState('choose-type') @@ -235,6 +238,11 @@ export function CustomKeyModal({ visible, onClose, onKeysChanged, onManageShortc ) : null} )} + {step === 'choose-type' && smartRail ? ( + + + + ) : null} {step === 'shortcut-combo' && ( diff --git a/mobile/src/components/NewWorktreeModal.test.tsx b/mobile/src/components/NewWorktreeModal.test.tsx index 201ad65e052..b44507b5157 100644 --- a/mobile/src/components/NewWorktreeModal.test.tsx +++ b/mobile/src/components/NewWorktreeModal.test.tsx @@ -68,6 +68,9 @@ import '../../../src/shared/execution-host' import type { ExecutionHostId } from '../../../src/shared/execution-host' import { NewWorktreeModal } from './NewWorktreeModal' +import { publishPageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' +import { resetDurableDraftFieldsForTests } from '../drafts/durable-draft-fields' +import { publishInMemoryDeviceStore } from '../drafts/in-memory-device-store.test-support' import { findAllByHostType } from '../test-support/react-test-renderer-host-nodes' @@ -347,3 +350,73 @@ describe('NewWorktreeModal project targets', () => { expect(sourceInputs(renderer).map((input) => input.props.value)).toEqual(['', '']) }) }) + +describe('NewWorktreeModal note draft', () => { + // The shell's draft table outlives the page; nothing else does. + const table = new Map() + let renderer: ReactTestRenderer | null = null + + async function open(): Promise { + const client = requestsOnly( + vi.fn((method: string) => + method === 'repo.list' ? replied({ repos }) : new Promise(() => {}) + ) + ) + await act(async () => { + renderer = create( + createElement(NewWorktreeModal, { + visible: true, + client, + hostId: 'host-1', + onCreated: () => {}, + onClose: () => {}, + openExternalUrl: () => {} + }) + ) + await vi.advanceTimersByTimeAsync(0) + }) + return renderer! + } + + const noteInput = (opened: ReactTestRenderer) => + findAllByHostType(opened.root, 'TextInput').find( + (node) => node.props.placeholder === 'Write a note' + )! + const optionsExpanded = (opened: ReactTestRenderer) => + opened.root.find((node) => node.props.title === 'Options' && 'expanded' in node.props).props + .expanded + + // A kill: the page and its memory go, the store stays. + function kill(): void { + act(() => renderer?.unmount()) + renderer = null + resetDurableDraftFieldsForTests() + } + + beforeEach(() => { + vi.useFakeTimers() + setCachedRepos('host-1', repos) + resetDurableDraftFieldsForTests() + publishInMemoryDeviceStore(table) + }) + + afterEach(() => { + kill() + table.clear() + publishPageDeviceStore(null) + vi.useRealTimers() + }) + + it('brings the note back after a kill, with Options open so it is not sent unseen', async () => { + const typed = await open() + act(() => noteInput(typed).props.onChangeText('pairing with Ama on the flaky test')) + await act(async () => { + await vi.advanceTimersByTimeAsync(1000) + }) + kill() + + const reopened = await open() + expect(noteInput(reopened).props.value).toBe('pairing with Ama on the flaky test') + expect(optionsExpanded(reopened)).toBe(true) + }) +}) diff --git a/mobile/src/components/NewWorktreeModal.tsx b/mobile/src/components/NewWorktreeModal.tsx index 3b6ba3870c4..11bf01b970f 100644 --- a/mobile/src/components/NewWorktreeModal.tsx +++ b/mobile/src/components/NewWorktreeModal.tsx @@ -16,6 +16,8 @@ import { buildRetiredWorktreeNamesRefreshKey, useRetiredWorktreeNames } from '../worktree/use-retired-worktree-names' +import { durableDraftRowKey } from '../drafts/durable-draft-rows' +import { useDurableDraftField } from '../drafts/durable-draft-fields' import { BottomDrawerModalHost } from './bottom-drawer/bottom-drawer-modal-host' import { getMobileWorkspaceRepoBadgeColor, @@ -82,7 +84,12 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { const repoServer = selectedRepo ? serverOf(selectedRepo) : undefined const client = repoServer ? (serverClients?.get(repoServer) ?? null) : desktopClient const navigation = useNewWorktreeDrawerNavigation(visible) - const [note, setNote] = useState('') + // Kept per desktop until a create succeeds, and read only once the form shows. The host is in the key + // because the tablet sidebar's native host list has no shell to bind it. + const [note, setNote] = useDurableDraftField( + visible ? durableDraftRowKey('workspaceCreate', '', hostId ?? '') : null, + 'note' + ) const [error, setError] = useState('') const runtime = useNewWorkspaceRuntimeContext(client, visible, hostId, repoServer) const repoRuntime = useNewWorktreeRuntimeCapabilities(client, visible) @@ -103,6 +110,12 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { visible }) const setupScript = useNewWorkspaceSetupScript({ client, selectedRepo }) + // A kept note opens Options until the user folds them, so it isn't sent unseen. + const [noteOptions, setNoteOptions] = useState<'closed' | 'open' | 'folded'>('closed') + if (note && noteOptions === 'closed') { + setNoteOptions('open') + } + const showOptions = setupScript.showAdvanced || noteOptions === 'open' const selectedRepoWorktreeBranches = useMemo( () => getComposerRepoWorktreeBranches(existingWorktrees ?? [], selectedRepo?.id ?? null), [existingWorktrees, selectedRepo] @@ -161,7 +174,11 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { getAgentLaunchSupport, transitionDrawer: navigation.transitionDrawer, setError, - onCreated: (worktreeId, name, warning) => onCreated(worktreeId, name, warning, repoServer), + onCreated: (worktreeId, name, warning) => { + // A note typed in a reopened form while this create ran is not the one it sent. + setNote((current) => (current === note ? '' : current)) + onCreated(worktreeId, name, warning, repoServer) + }, onClose }) @@ -254,7 +271,7 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { sshGate={executionTarget.sshGate} composer={composer} selectedAgent={agentSelection.selectedAgent} - showAdvanced={setupScript.showAdvanced} + showAdvanced={showOptions} note={note} setupCommand={setupScript.setupCommand} setupSource={setupScript.setupSource} @@ -272,7 +289,12 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) { onClearError={() => setError('')} onConnect={() => void executionTarget.connect()} onOpenAgent={() => openPicker('agent')} - onShowAdvancedChange={setupScript.setShowAdvanced} + onShowAdvancedChange={(show) => { + if (!show) { + setNoteOptions('folded') + } + setupScript.setShowAdvanced(show) + }} onNoteChange={setNote} onSetupDecisionChange={setupScript.setSetupDecisionChoice} onRunSetupChange={setupScript.setRunSetup} diff --git a/mobile/src/components/SmartRailRow.tsx b/mobile/src/components/SmartRailRow.tsx new file mode 100644 index 00000000000..8789fcd0f42 --- /dev/null +++ b/mobile/src/components/SmartRailRow.tsx @@ -0,0 +1,24 @@ +import { ListRow } from './list/ListGroup' +import { MobileSwitch } from './MobileSwitch' +import { useMobileTranslation } from '../i18n/use-mobile-translation' + +/** The Smart rail setting: keys for what the terminal's agent is doing, at the front of the key row. */ +export function SmartRailRow({ + enabled, + onChange +}: { + enabled: boolean + onChange: (enabled: boolean) => void +}): React.JSX.Element { + const t = useMobileTranslation() + const title = t('components.smartRailRow.title', 'Smart rail') + return ( + + } + /> + ) +} diff --git a/mobile/src/components/TerminalShortcutSettings.tsx b/mobile/src/components/TerminalShortcutSettings.tsx index db5bfe5b64e..37e14d0620f 100644 --- a/mobile/src/components/TerminalShortcutSettings.tsx +++ b/mobile/src/components/TerminalShortcutSettings.tsx @@ -27,6 +27,7 @@ import { setTerminalAccessoryBuiltInVisible } from '../terminal/terminal-accessory-layout' import { MobileSwitch } from './MobileSwitch' +import { SmartRailRow } from './SmartRailRow' // Absolutely positioned DragReorderList rows require one fixed height per section. const REORDER_ROW_HEIGHT = 56 @@ -148,10 +149,13 @@ export function TerminalShortcutSettings({ [persistLayout] ) + // Resetting the keys leaves the Smart rail setting alone. const resetBuiltInKeys = useCallback(() => { - const next = defaultLayout() - setShortcutLayout(next) - persistLayout(next) + setShortcutLayout((current) => { + const next = { ...defaultLayout(), smartRail: current.smartRail } + persistLayout(next) + return next + }) }, [defaultLayout, persistLayout]) const reorderCustomKeys = useCallback( @@ -182,6 +186,18 @@ export function TerminalShortcutSettings({ return ( <> + + + setShortcutLayout((current) => { + const next = { ...current, smartRail: enabled } + persistLayout(next) + return next + }) + } + /> + {hasPad ? ( { onCoveredHeightChange?.(coveredHeight) }, [coveredHeight, onCoveredHeightChange]) + useMobileDictationClearance(coveredHeight) // Close stays until the keyboard is down: iOS's late click at the tapped spot would otherwise hit the primary action that replaced it. const searching = focused || keyboardUp || (hasSearch ?? value.trim() !== '') diff --git a/mobile/src/components/pr-sidebar/MobilePrTabSheets.tsx b/mobile/src/components/pr-sidebar/MobilePrTabSheets.tsx index 5ed5ede7271..57c5d472bc8 100644 --- a/mobile/src/components/pr-sidebar/MobilePrTabSheets.tsx +++ b/mobile/src/components/pr-sidebar/MobilePrTabSheets.tsx @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useState } from 'react' import { Text, View } from 'react-native' import { GitMerge } from 'lucide-react-native' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' @@ -12,7 +12,7 @@ import { SheetPrimaryButton } from '../SheetPrimaryButton' import { ListGroup, ListRow } from '../list/ListGroup' import { ConfirmModal } from '../ConfirmModal' import { presentPrMerge } from './pr-actions-state' -import { PrCreateSheet, type PrCreateKept } from './PrCreateSheet' +import { PrCreateSheet } from './PrCreateSheet' import { PrReviewersSheet } from './PrReviewersSheet' import { livePrDetails, @@ -22,17 +22,14 @@ import { } from './use-mobile-pr-tab' import { prSheetStyles as sheetStyles } from './pr-tab-styles' import { FieldTextInput } from '../composer-input/FieldTextInput' - -type PrEditKept = { key: string; base: string; text: string } +import { draftTextHash, workspaceDraftRowKey } from '../../drafts/durable-draft-rows' +import { useDurableDraftField } from '../../drafts/durable-draft-fields' +import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host' // Sheets for the PR tab's decisions; one Modal swaps between them so iOS never stacks presentations. export function MobilePrTabSheets({ tab }: { tab: MobilePrTab }) { useMobileColorScheme() const t = useMobileTranslation() - // Each sheet unmounts on Cancel; typed text waits here for the next open. - const [createKept, setCreateKept] = useState(null) - const [titleKept, setTitleKept] = useState(null) - const [bodyKept, setBodyKept] = useState(null) return ( <> case 'editTitle': - return ( - - ) + return case 'editDescription': - return ( - - ) + return case 'createPr': - return + return } }} @@ -182,55 +163,56 @@ function PrMergeSheet({ tab, request }: { tab: MobilePrTab; request: PrTabSheetR function PrEditTextSheet({ tab, request, - field, - kept, - onKeep + field }: { tab: MobilePrTab request: PrTabSheetRequest field: 'title' | 'body' - kept: PrEditKept | null - onKeep: (kept: PrEditKept | null) => void }) { useMobileColorScheme() const t = useMobileTranslation() + const executionHost = useWorkspaceExecutionHost() const data = readyPrData(tab) const details = livePrDetails(data?.details ?? null) const current = field === 'title' ? (details?.item.title ?? data?.pr.title ?? '') : (details?.body ?? '') - const keepKey = request.scope.resource + const resource = request.scope.resource + // An unsaved edit waits through Cancel and the app being killed, with the PR text it was typed against. + const keptKey = resource + ? workspaceDraftRowKey( + 'prEdit', + { hostId: tab.hostId, executionHost, worktreeId: tab.worktreeId }, + `${resource}:${field}` + ) + : null + const [keptAgainst, setKeptAgainst] = useDurableDraftField(keptKey, 'against') + const [keptText, setKeptText] = useDurableDraftField(keptKey, 'text') // An edit typed against text the PR still has comes back; once the PR text changes it would revert someone's edit. const [base] = useState(current) - const [draft, setDraft] = useState(() => - kept && kept.key === keepKey && kept.base === current ? kept.text : current - ) - // Closing keeps a changed, unsaved draft for the next open, and drops this PR's kept one otherwise. - const savedRef = useRef(false) - const closeRef = useRef({ keepKey, base, draft, kept, onKeep }) - useLayoutEffect(() => { - closeRef.current = { keepKey, base, draft, kept, onKeep } - }) - useEffect( - () => () => { - const close = closeRef.current - if (!close.keepKey) { - return - } - if (!savedRef.current && close.draft !== close.base) { - close.onKeep({ key: close.keepKey, base: close.base, text: close.draft }) - } else if (close.kept?.key === close.keepKey) { - close.onKeep(null) - } - }, - [] - ) + // A fingerprint, never empty, so an emptied PR description still marks an edit (an empty field is no field). + const [against] = useState(() => draftTextHash(base)) + const draft = keptAgainst === against ? keptText : base + const setDraft = (text: string) => { + const edited = text !== base + setKeptText(edited ? text : '') + setKeptAgainst(edited ? against : '') + } const { textAction } = tab const save = async () => { if (!tab.ownsSheet(request)) { return } - if (await textAction.save(field, draft, current)) { - savedRef.current = true + const sent = draft + if (await textAction.save(field, sent, current)) { + // Only the saved edit; one typed since in a reopened sheet stays. + let saved = false + setKeptText((text) => { + saved = text === sent + return saved ? '' : text + }) + if (saved) { + setKeptAgainst('') + } tab.closeSheetIf(request) } } diff --git a/mobile/src/components/pr-sidebar/PRCommentCard.tsx b/mobile/src/components/pr-sidebar/PRCommentCard.tsx index 006c8565720..eea6227f480 100644 --- a/mobile/src/components/pr-sidebar/PRCommentCard.tsx +++ b/mobile/src/components/pr-sidebar/PRCommentCard.tsx @@ -29,6 +29,8 @@ export type PRCommentCardActions = { isResolveBusy: (threadId: string) => boolean isEditBusy: (commentId: number) => boolean isDeleteBusy: (commentId: number) => boolean + // Where a reply to a comment waits until it is posted. + draftKey: (replyTo: number) => string | null // Repo slug for the slug-addressed edit/delete RPCs; gates the affordances when absent. prRepo: PRCommentRepoSlug | null } @@ -296,6 +298,7 @@ export const PRCommentCard = memo(function PRCommentCard({ placeholder={t('pullRequest.commentCard.replyPlaceholder', 'Write a reply…')} submitLabel={t('pullRequest.commentCard.reply', 'Reply')} submitting={replyBusy} + draftKey={actions.draftKey(comment.id)} onSubmit={submitReply} onCancel={() => setReplyOpen(false)} autoFocus diff --git a/mobile/src/components/pr-sidebar/PRCommentComposer.tsx b/mobile/src/components/pr-sidebar/PRCommentComposer.tsx index 152469d7281..18f3ac36c6a 100644 --- a/mobile/src/components/pr-sidebar/PRCommentComposer.tsx +++ b/mobile/src/components/pr-sidebar/PRCommentComposer.tsx @@ -7,6 +7,7 @@ import { useMobileTranslation } from '../../i18n/use-mobile-translation' import { isSubmittableCommentBody } from '../../source-control/review/pr-comment-actions' import { MessageBox } from '../composer-input/MessageBox' import { composerInputStyles } from '../composer-input/composer-input-styles' +import { useDurableDraftField } from '../../drafts/durable-draft-fields' type Props = { // Share plain-text composer across root comment, reply and edit. @@ -15,6 +16,8 @@ type Props = { submitting: boolean // Seeds the field for the edit case; the reply/add cases leave it empty. initialBody?: string + // Where a new comment or reply waits until it is posted, through closing and the app being killed. + draftKey?: string | null // Resolves to true on success; the composer clears + collapses (caller-driven via key remount or onSubmitted). onSubmit: (body: string) => Promise onCancel?: () => void @@ -27,6 +30,7 @@ export function PRCommentComposer({ submitLabel, submitting, initialBody, + draftKey = null, onSubmit, onCancel, autoFocus, @@ -34,7 +38,9 @@ export function PRCommentComposer({ }: Props) { useMobileColorScheme() const t = useMobileTranslation() - const [body, setBody] = useState(initialBody ?? '') + const [edited, setEdited] = useState(initialBody ?? '') + const [kept, setKept] = useDurableDraftField(draftKey, 'body') + const [body, setBody] = draftKey === null ? [edited, setEdited] : [kept, setKept] // Guard synchronously against double-submit before parent’s async submitting state rerenders. const inFlightRef = useRef(false) const canSubmit = isSubmittableCommentBody(body) && !submitting @@ -45,9 +51,11 @@ export function PRCommentComposer({ } inFlightRef.current = true try { - const ok = await onSubmit(body.trim()) + const posted = body.trim() + const ok = await onSubmit(posted) + // A reopened composer shares the draft; text typed there since stays. if (ok) { - setBody('') + setBody((current) => (current.trim() === posted ? '' : current)) } } finally { inFlightRef.current = false diff --git a/mobile/src/components/pr-sidebar/PRCommentsSection.tsx b/mobile/src/components/pr-sidebar/PRCommentsSection.tsx index dffdc4028d1..9c44d335d27 100644 --- a/mobile/src/components/pr-sidebar/PRCommentsSection.tsx +++ b/mobile/src/components/pr-sidebar/PRCommentsSection.tsx @@ -239,6 +239,7 @@ export function PRCommentsSection({ )} submitLabel={t('pullRequest.commentsSection.comment', 'Comment')} submitting={actions.isRootBusy} + draftKey={actions.draftKey(null)} onSubmit={actions.addRootComment} /> @@ -267,6 +268,7 @@ export function usePRCommentCardActions( isResolveBusy: actions.isResolveBusy, isEditBusy: actions.isEditBusy, isDeleteBusy: actions.isDeleteBusy, + draftKey: actions.draftKey, prRepo: prRepo ?? null } : undefined, diff --git a/mobile/src/components/pr-sidebar/PrCommentsScreen.tsx b/mobile/src/components/pr-sidebar/PrCommentsScreen.tsx index 7cec48386f9..329fbb36a17 100644 --- a/mobile/src/components/pr-sidebar/PrCommentsScreen.tsx +++ b/mobile/src/components/pr-sidebar/PrCommentsScreen.tsx @@ -91,6 +91,7 @@ export function PrCommentsScreen({ tab, onBack, bottomInset = 0, onOpenFile }: S isResolveBusy: commentActions.isResolveBusy, isEditBusy: commentActions.isEditBusy, isDeleteBusy: commentActions.isDeleteBusy, + draftKey: commentActions.draftKey, prRepo: data?.pr.prRepo ?? null } : undefined, @@ -195,6 +196,7 @@ export function PrCommentsScreen({ tab, onBack, bottomInset = 0, onOpenFile }: S })} submitLabel={t('pullRequest.commentsSection.comment', 'Comment')} submitting={commentActions.isRootBusy} + draftKey={commentActions.draftKey(null)} onSubmit={commentActions.addRootComment} inline /> diff --git a/mobile/src/components/pr-sidebar/PrCreateSheet.tsx b/mobile/src/components/pr-sidebar/PrCreateSheet.tsx index 8b2107d0ea3..8080e0faf27 100644 --- a/mobile/src/components/pr-sidebar/PrCreateSheet.tsx +++ b/mobile/src/components/pr-sidebar/PrCreateSheet.tsx @@ -1,11 +1,4 @@ -import { - useEffect, - useLayoutEffect, - useRef, - useState, - type Dispatch, - type SetStateAction -} from 'react' +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { ActivityIndicator, Pressable, Text, View } from 'react-native' import { ChevronsUpDown, Sparkles } from 'lucide-react-native' import { colors, pressedStyle, spacing } from '../../theme/mobile-theme' @@ -30,8 +23,7 @@ import { import { cancelMobilePrFields, generateMobilePrFields, - loadMobilePrCreateDraft, - type MobilePrCreateDraft + loadMobilePrCreateDraft } from '../../source-control/mobile-pr-create-draft' import { getMobileCommitFailureStagedEntries, @@ -43,33 +35,52 @@ import type { MobilePrTab } from './use-mobile-pr-tab' import { prSheetStyles as sheetStyles } from './pr-tab-styles' import { PrBasePicker } from './PrBasePicker' import { FieldTextInput } from '../composer-input/FieldTextInput' +import { workspaceDraftRowKey } from '../../drafts/durable-draft-rows' +import { updateDurableDraftField, useDurableDraftField } from '../../drafts/durable-draft-fields' +import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host' -type Fields = { title: string; body: string; base: string; draft: boolean } +// The provider rides along so a kept draft reopens without asking the host again. +type Fields = { title: string; body: string; base: string; draft: boolean; provider: string } -/** What Cancel leaves for the next open on the same workspace branch. */ -export type PrCreateKept = { key: string; draft: MobilePrCreateDraft; fields: Fields } +function keepCreateField(key: string, patch: Partial): void { + for (const [name, value] of Object.entries(patch)) { + updateDurableDraftField(key, name, value === true ? 'yes' : value === false ? '' : value) + } +} + +// The first edit keeps the whole form. The provider is never empty, so it is what marks a kept draft. +function keepCreateFields(key: string, fields: Fields | null): void { + keepCreateField(key, fields ?? { provider: '', title: '', body: '', base: '', draft: false }) +} + +function useKeptCreateFields(key: string | null): Fields | null { + const [provider] = useDurableDraftField(key, 'provider') + const [title] = useDurableDraftField(key, 'title') + const [body] = useDurableDraftField(key, 'body') + const [base] = useDurableDraftField(key, 'base') + const [draft] = useDurableDraftField(key, 'draft') + return useMemo( + () => (provider ? { title, body, base, draft: draft === 'yes', provider } : null), + [base, body, draft, provider, title] + ) +} // One Create flow for every entry point and all five providers: seed from commits, push if needed, land on the PR tab. -export function PrCreateSheet({ - tab, - kept, - onKeep -}: { - tab: MobilePrTab - kept: PrCreateKept | null - onKeep: Dispatch> -}) { +export function PrCreateSheet({ tab }: { tab: MobilePrTab }) { useMobileColorScheme() const t = useMobileTranslation() - const { client, worktreeId, gitBranch } = tab + const { client, hostId, worktreeId, gitBranch } = tab + const executionHost = useWorkspaceExecutionHost() const creating = tab.creatingPr const setCreating = tab.setCreatingPr - const keepKey = gitBranch ? `${worktreeId}\u0000${gitBranch}` : null - // Reopening on the same branch restores what was typed instead of re-seeding from commits. - const [restored] = useState(() => (kept && kept.key === keepKey ? kept : null)) - const [draft, setDraft] = useState(restored?.draft ?? null) - const [fields, setFields] = useState(restored?.fields ?? null) - const editedRef = useRef(restored !== null) + // What was typed waits, per workspace branch, through Cancel and the app being killed. + const keptKey = gitBranch + ? workspaceDraftRowKey('prCreate', { hostId, executionHost, worktreeId }, gitBranch) + : null + const kept = useKeptCreateFields(keptKey) + const [seeded, setSeeded] = useState(null) + const [seedError, setSeedError] = useState(null) + const fields = kept ?? seeded const [pickingBase, setPickingBase] = useState(false) const [generating, setGenerating] = useState(false) const [message, setMessage] = useState<{ text: string; error: boolean } | null>(null) @@ -89,11 +100,11 @@ export function PrCreateSheet({ useLayoutEffect(() => { commitsAheadRef.current = tab.commitsAhead }) - // Seed once per open: a reconnect or a status reload must not overwrite what the user typed. - const seededRef = useRef(restored !== null) + // Seed once per open, and not over a kept draft: a reconnect or a status reload must not overwrite what was typed. + const seedRef = useRef(kept !== null) useEffect(() => { - if (!client || !gitBranch || seededRef.current) { + if (!client || !gitBranch || seedRef.current) { return } let cancelled = false @@ -104,14 +115,19 @@ export function PrCreateSheet({ }) .then((loaded) => { if (!cancelled) { - seededRef.current = true - setDraft(loaded) - setFields({ title: loaded.title, body: loaded.body, base: loaded.base, draft: false }) + seedRef.current = true + setSeeded({ + title: loaded.title, + body: loaded.body, + base: loaded.base, + draft: false, + provider: loaded.prefill.provider + }) } }) .catch((err: unknown) => { if (!cancelled) { - setMessage({ text: err instanceof Error ? err.message : String(err), error: true }) + setSeedError(err instanceof Error ? err.message : String(err)) } }) return () => { @@ -119,13 +135,25 @@ export function PrCreateSheet({ } }, [client, gitBranch, worktreeId]) - const copy = hostedReviewCopy(draft?.prefill.provider) + const copy = hostedReviewCopy(fields?.provider) const title = t('pullRequest.createSheet.title', 'Create {{reviewLabel}}', { reviewLabel: copy.reviewLabel }) + // The first edit turns the seeded fields into a kept draft. Later ones write only what they change, so a + // late Write with AI answer can't undo a toggle made meanwhile. + const keptRef = useRef(kept) + useLayoutEffect(() => { + keptRef.current = kept + }) const update = (patch: Partial) => { - editedRef.current = true - setFields((current) => (current ? { ...current, ...patch } : current)) + if (!keptKey || !fields) { + return + } + if (keptRef.current) { + keepCreateField(keptKey, patch) + } else { + keepCreateFields(keptKey, { ...fields, ...patch }) + } } // Closing the sheet cancels a running generation, drops its late answer and keeps typed fields; a reconnect does none. @@ -134,9 +162,9 @@ export function PrCreateSheet({ useLayoutEffect(() => { generatingRef.current = generating }) - const closeTargetRef = useRef({ client, worktreeId, keepKey, draft, fields, onKeep }) + const closeTargetRef = useRef({ client, worktreeId }) useLayoutEffect(() => { - closeTargetRef.current = { client, worktreeId, keepKey, draft, fields, onKeep } + closeTargetRef.current = { client, worktreeId } }) useEffect( () => () => { @@ -145,25 +173,19 @@ export function PrCreateSheet({ if (generatingRef.current && target.client) { void cancelMobilePrFields(target.client, target.worktreeId).catch(() => {}) } - if (editedRef.current && target.keepKey && target.draft && target.fields) { - target.onKeep({ key: target.keepKey, draft: target.draft, fields: target.fields }) - } }, [] ) const writeWithAi = async () => { - if (!client || !fields || !draft || generating) { + if (!client || !fields || generating) { return } const generation = ++generationRef.current setGenerating(true) setMessage(null) try { - const result = await generateMobilePrFields(client, worktreeId, { - ...fields, - provider: draft.prefill.provider - }) + const result = await generateMobilePrFields(client, worktreeId, fields) if (generation !== generationRef.current) { return } @@ -190,7 +212,7 @@ export function PrCreateSheet({ return } createInFlightRef.current = true - const createdKey = keepKey + const createdKey = keptKey setCreating(true) setMessage(null) setCommitFailure(null) @@ -226,10 +248,12 @@ export function PrCreateSheet({ } triggerSuccess() setCreating(false) - // The PR exists now, so nothing carries over to the next Create on this branch, even text kept - // when a branch or client change closed this sheet mid-run. - editedRef.current = false - onKeep((current) => (current?.key === createdKey ? null : current)) + // The PR exists now, so nothing carries over to the next Create on this branch, even when a branch or + // client change closed this sheet mid-run. + setSeeded(fields) + if (createdKey) { + keepCreateFields(createdKey, null) + } const created = { url: outcome.url, warning: outcome.warning ?? null, @@ -281,8 +305,8 @@ export function PrCreateSheet({ 'Check out a branch before creating a pull request.' )} - ) : message ? ( - {message.text} + ) : seedError ? ( + {seedError} ) : ( )} diff --git a/mobile/src/components/pr-sidebar/PrThreadRow.tsx b/mobile/src/components/pr-sidebar/PrThreadRow.tsx index 2d9527ba450..be89feef5e9 100644 --- a/mobile/src/components/pr-sidebar/PrThreadRow.tsx +++ b/mobile/src/components/pr-sidebar/PrThreadRow.tsx @@ -44,6 +44,8 @@ export type PrThreadActions = { isResolveBusy: (threadId: string) => boolean isEditBusy: (commentId: number) => boolean isDeleteBusy: (commentId: number) => boolean + // Where a reply to a comment waits until it is posted. + draftKey: (replyTo: number) => string | null // Repo slug for the slug-addressed edit/delete RPCs; gates the affordances when absent. prRepo: PRCommentRepoSlug | null } diff --git a/mobile/src/components/pr-sidebar/PrThreadScreen.tsx b/mobile/src/components/pr-sidebar/PrThreadScreen.tsx index 3bef4466dd9..b1db7052d92 100644 --- a/mobile/src/components/pr-sidebar/PrThreadScreen.tsx +++ b/mobile/src/components/pr-sidebar/PrThreadScreen.tsx @@ -114,6 +114,7 @@ export function PrThreadScreen({ placeholder={t('pullRequest.screens.replyPlaceholder', 'Reply…')} submitLabel={t('pullRequest.commentCard.reply', 'Reply')} submitting={actions.isReplyBusy(root.id)} + draftKey={actions.draftKey(root.id)} onSubmit={(body) => actions.reply(root, body)} autoFocus={focusReply} inline diff --git a/mobile/src/components/pr-sidebar/pr-comment-composer-drafts.test.tsx b/mobile/src/components/pr-sidebar/pr-comment-composer-drafts.test.tsx new file mode 100644 index 00000000000..2710d18b844 --- /dev/null +++ b/mobile/src/components/pr-sidebar/pr-comment-composer-drafts.test.tsx @@ -0,0 +1,90 @@ +import { createElement, type ReactNode } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +const hosts = vi.hoisted(() => { + const Box = (props: { children?: ReactNode }): ReactNode => props.children ?? null + Box.displayName = 'MessageBox' + return { Box } +}) +vi.mock('react-native', () => ({ Pressable: () => null })) +vi.mock('lucide-react-native', () => ({ X: () => null })) +vi.mock('../../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'light' })) +vi.mock('../composer-input/MessageBox', () => ({ MessageBox: hosts.Box })) +vi.mock('../composer-input/composer-input-styles', () => ({ composerInputStyles: {} })) + +import { publishPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' +import { resetDurableDraftFieldsForTests } from '../../drafts/durable-draft-fields' +import { publishInMemoryDeviceStore } from '../../drafts/in-memory-device-store.test-support' +import { PRCommentComposer } from './PRCommentComposer' + +// The shell's draft table outlives the page; nothing else does. +const table = new Map() +let renderer: ReactTestRenderer | null = null +let onSubmit: (body: string) => Promise = async () => true + +const KEY = 'draft:prComment:wt-1:host-1::/acme/app#12#new' + +async function open(): Promise { + await act(async () => { + renderer = create( + createElement(PRCommentComposer, { + placeholder: 'Comment', + submitLabel: 'Comment', + submitting: false, + draftKey: KEY, + onSubmit: (body: string) => onSubmit(body) + }) + ) + await vi.advanceTimersByTimeAsync(0) + }) +} + +function box(): { value: string; onChangeText: (text: string) => void; onSend: () => void } { + const props = renderer?.root.findByType(hosts.Box).props + return { value: props?.value, onChangeText: props?.onChangeText, onSend: props?.onSend } +} + +async function type(text: string): Promise { + act(() => box().onChangeText(text)) + await act(async () => { + await vi.advanceTimersByTimeAsync(1000) + }) +} + +// A kill: the page and its memory go, the store stays. +function kill(): void { + act(() => renderer?.unmount()) + renderer = null + resetDurableDraftFieldsForTests() +} + +beforeEach(() => { + vi.useFakeTimers() + publishInMemoryDeviceStore(table) +}) + +afterEach(() => { + kill() + table.clear() + publishPageDeviceStore(null) + onSubmit = async () => true + vi.useRealTimers() +}) + +it('keeps text typed in a reopened composer when the earlier post lands', async () => { + let land: (ok: boolean) => void = () => {} + onSubmit = () => new Promise((resolve) => (land = resolve)) + await open() + await type('first thought') + act(() => box().onSend()) + act(() => renderer?.unmount()) + + await open() + await type('a second thought') + await act(async () => { + land(true) + await vi.advanceTimersByTimeAsync(1000) + }) + expect(box().value).toBe('a second thought') +}) diff --git a/mobile/src/components/pr-sidebar/pr-create-sheet-drafts.test.tsx b/mobile/src/components/pr-sidebar/pr-create-sheet-drafts.test.tsx new file mode 100644 index 00000000000..3db7251d9fb --- /dev/null +++ b/mobile/src/components/pr-sidebar/pr-create-sheet-drafts.test.tsx @@ -0,0 +1,144 @@ +import { createElement, type ReactNode } from 'react' +import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' + +const hosts = vi.hoisted(() => { + const make = (name: string) => { + const Host = (props: { children?: ReactNode }): ReactNode => props.children ?? null + Host.displayName = name + return Host + } + return { + View: make('View'), + Text: make('Text'), + Pressable: make('Pressable'), + Field: make('FieldTextInput'), + Button: make('SheetPrimaryButton') + } +}) +vi.mock('react-native', () => ({ + View: hosts.View, + Text: hosts.Text, + Pressable: hosts.Pressable, + ActivityIndicator: hosts.View, + StyleSheet: { create: (styles: T) => styles, hairlineWidth: 1, absoluteFillObject: {} }, + Platform: { OS: 'ios', select: (options: Record) => options.ios } +})) +vi.mock('lucide-react-native', () => ({ ChevronsUpDown: hosts.View, Sparkles: hosts.View })) +vi.mock('../../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'light' })) +vi.mock('../nav-bar/SheetHeader', () => ({ SheetHeader: hosts.View })) +vi.mock('../SheetPrimaryButton', () => ({ SheetPrimaryButton: hosts.Button })) +vi.mock('../list/ListGroup', () => ({ ListGroup: hosts.View, ListRow: hosts.View })) +vi.mock('../MobileSwitch', () => ({ MobileSwitch: hosts.View })) +vi.mock('./PrBasePicker', () => ({ PrBasePicker: hosts.View })) +vi.mock('../composer-input/FieldTextInput', () => ({ FieldTextInput: hosts.Field })) +vi.mock('../../source-control/MobileCommitFailurePanel', () => ({ + MobileCommitFailurePanel: hosts.View +})) +vi.mock('../../source-control/use-mobile-commit-failure-recovery', () => ({ + useMobileCommitFailureRecovery: () => null +})) +const host = vi.hoisted(() => ({ + seed: vi.fn(), + create: vi.fn() +})) +vi.mock('../../source-control/mobile-pr-create-draft', () => ({ + loadMobilePrCreateDraft: host.seed, + generateMobilePrFields: vi.fn(), + cancelMobilePrFields: vi.fn(async () => {}) +})) +vi.mock('../../source-control/mobile-hosted-review-create-intent-runner', () => ({ + runMobileHostedReviewCreateIntent: host.create, + isMobileHostedReviewCommitFailure: () => false +})) + +import { publishPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' +import { resetDurableDraftFieldsForTests } from '../../drafts/durable-draft-fields' +import { publishInMemoryDeviceStore } from '../../drafts/in-memory-device-store.test-support' +import { createFakeRpcClient } from '../../mobile-web-shell/bridge-host-test-fakes' +import { PrCreateSheet } from './PrCreateSheet' +import type { MobilePrTab } from './use-mobile-pr-tab' +import { mountFixture } from '../../test-support/rpc-recording/recorder-fixture-shape' + +// The shell's draft table outlives the page; nothing else does. +const table = new Map() +let renderer: ReactTestRenderer | null = null + +// The sheet reads only these fields of the PR tab. +const tab = mountFixture({ + client: createFakeRpcClient(), + hostId: 'host-1', + worktreeId: 'repo::/work/feature', + gitBranch: 'feature/login', + gitStatus: null, + commitsAhead: null, + connState: 'connected', + workspaceLabel: 'feature', + creatingPr: false, + setCreatingPr: () => {}, + closeSheet: () => {}, + closeSheetThen: () => {} +}) + +async function open(): Promise { + await act(async () => { + renderer = create(createElement(PrCreateSheet, { tab })) + await vi.advanceTimersByTimeAsync(0) + }) +} + +function titleField(): ReactTestInstance | undefined { + return renderer?.root.findAllByType(hosts.Field)[0] +} + +async function typeTitle(title: string): Promise { + act(() => titleField()?.props.onChangeText(title)) + await act(async () => { + await vi.advanceTimersByTimeAsync(1000) + }) +} + +// A kill: the page and its memory go, the store stays. +function kill(): void { + act(() => renderer?.unmount()) + renderer = null + resetDurableDraftFieldsForTests() +} + +beforeEach(() => { + vi.useFakeTimers() + host.seed.mockResolvedValue({ + prefill: { provider: 'github', base: 'main', title: '', body: '' }, + title: 'Seed from commits', + body: '', + base: 'main' + }) + publishInMemoryDeviceStore(table) +}) + +afterEach(() => { + kill() + table.clear() + publishPageDeviceStore(null) + host.seed.mockReset() + host.create.mockReset() + vi.useRealTimers() +}) + +it('keeps nothing for the next Create once a Create lands after its sheet closed', async () => { + let land: (outcome: unknown) => void = () => {} + host.create.mockReturnValue(new Promise((resolve) => (land = resolve))) + await open() + await typeTitle('Fix the login race') + act(() => renderer?.root.findByType(hosts.Button).props.onPress()) + // A branch or client change closes the sheet while the Create is still running. + act(() => renderer?.unmount()) + await act(async () => { + land({ ok: true, url: 'https://example.test/pr/1', prefill: { provider: 'github' } }) + await vi.advanceTimersByTimeAsync(1000) + }) + kill() + + await open() + expect(titleField()?.props.value).toBe('Seed from commits') +}) diff --git a/mobile/src/components/use-detail-card-scope.web.ts b/mobile/src/components/use-detail-card-scope.web.ts index 173e1bb7f44..f83d48a4e61 100644 --- a/mobile/src/components/use-detail-card-scope.web.ts +++ b/mobile/src/components/use-detail-card-scope.web.ts @@ -47,7 +47,7 @@ export function useDetailCardScope({ record.restore = false dismiss() } - const click = (event: MouseEvent) => { + const press = (event: MouseEvent) => { if (!inside(event.target) && !headerBack(event.target)) { outside() } @@ -120,7 +120,9 @@ export function useDetailCardScope({ } } const capture = { capture: true, signal: listeners.signal } - document.addEventListener('click', click, capture) + // Why: the terminal claims its touches, so iOS sends no click for a tap there. + document.addEventListener('pointerdown', press, capture) + document.addEventListener('click', press, capture) document.addEventListener('keydown', key, capture) document.addEventListener('keyup', key, capture) document.addEventListener('keydown', isolate, { signal: listeners.signal }) diff --git a/mobile/src/device-store/device-store.ts b/mobile/src/device-store/device-store.ts index ed0637f1d4a..c1ea8d9cf81 100644 --- a/mobile/src/device-store/device-store.ts +++ b/mobile/src/device-store/device-store.ts @@ -275,10 +275,10 @@ export function processDeviceStore(): DeviceStore { return processStore } -// Once per process, after the splash: nothing reads the store before first paint, and its keychain and -// AsyncStorage reads would otherwise compete with the launch work that holds the splash. Loads the key, -// runs the launch sweeps and index seed in idle slices, and on each return to the foreground retries an -// unavailable store and a pass that missed files. +// Once per process, after the splash: the sweeps' AsyncStorage and file reads would otherwise compete with +// the launch work that holds the splash. Native Home's first read may have loaded the key already. Runs the launch sweeps +// and index seed in idle slices, and on each return to the foreground retries an unavailable store and a +// pass that missed files. export function startDeviceStore(): void { if (started) { return diff --git a/mobile/src/dictation/MobileDictationLiveControls.tsx b/mobile/src/dictation/MobileDictationLiveControls.tsx index 2e298d16c80..0c5ece35fd9 100644 --- a/mobile/src/dictation/MobileDictationLiveControls.tsx +++ b/mobile/src/dictation/MobileDictationLiveControls.tsx @@ -1,14 +1,15 @@ import { useEffect, useMemo, useState, type Ref } from 'react' import { ActivityIndicator, Pressable, Text, View } from 'react-native' -import { Laptop, Mic, Smartphone, Square, X } from 'lucide-react-native' +import { CircleAlert, Laptop, Mic, RotateCcw, Smartphone, Square, X } from 'lucide-react-native' import type { MobileDictationMeter } from '../hooks/mobile-dictation-meter' import type { MobileDictationEngineShown } from '../hooks/mobile-dictation-session-state' import { useMobileTranslation } from '../i18n/use-mobile-translation' import { COMPOSER_CONTROL_HIT_SLOP, + COMPOSER_CONTROL_SIZE, composerInputStyles } from '../components/composer-input/composer-input-styles' -import { colors, spacing, typography } from '../theme/mobile-theme' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' import { themedStyleSheet } from '../theme/themed-styles' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' import { @@ -27,11 +28,14 @@ const FINISHING_NOTE_DELAY_MS = 300 export function MobileDictationCancelButton({ onCancel, targetRef, - compact = false + compact = false, + discards = false }: { onCancel: () => void targetRef?: Ref compact?: boolean + // After a failure, ✕ throws the kept recording away. + discards?: boolean }): React.JSX.Element { useMobileColorScheme() useMobileTranslation() @@ -39,7 +43,9 @@ export function MobileDictationCancelButton({ [ composerInputStyles.controlButton, compact && styles.compactCancel, @@ -86,6 +92,77 @@ export function MobileDictationMicIcon({ ) } +// The failure that kept its recording: a reason and "Recording kept", on two lines in chat and one in the terminal. +export function MobileDictationFailureNote({ + reason, + compact = false +}: { + reason: string + compact?: boolean +}): React.JSX.Element { + useMobileColorScheme() + useMobileTranslation() + const kept = dictationControlsCopy.recordingKept() + return ( + + + {compact ? ( + + {`${reason} · ${kept}`} + + ) : ( + + + {reason} + + + {kept} + + + )} + + ) +} + +// Retry sits where Stop was: a labelled pill in chat, the round control in the terminal. +export function MobileDictationRetryButton({ + onRetry, + labelled +}: { + onRetry: () => void + labelled: boolean +}): React.JSX.Element { + useMobileColorScheme() + useMobileTranslation() + return ( + [ + labelled ? styles.retryPill : composerInputStyles.controlButton, + pressed && composerInputStyles.pressed + ]} + hitSlop={COMPOSER_CONTROL_HIT_SLOP} + onPress={onRetry} + > + + {labelled ? ( + {dictationControlsCopy.retryShort()} + ) : null} + + ) +} + function EngineIcon({ kind, color }: { kind: MobileDictationEngineShown['kind']; color: string }) { return kind === 'phone' ? ( @@ -190,5 +267,38 @@ const styles = themedStyleSheet(() => ({ flexShrink: 1, color: colors.textSecondary, fontSize: typography.metaSize + 1 + }, + failureLines: { + flexShrink: 1, + minWidth: 0 + }, + failureReason: { + color: colors.textPrimary, + fontSize: typography.metaSize + 1, + fontWeight: '500' + }, + failureKept: { + color: colors.textSecondary, + fontSize: typography.metaSize + }, + failureCompact: { + flexShrink: 1, + color: colors.textPrimary, + fontSize: typography.metaSize + }, + retryPill: { + height: COMPOSER_CONTROL_SIZE, + borderRadius: radii.pill, + alignItems: 'center', + justifyContent: 'center', + flexDirection: 'row', + gap: 6, + paddingHorizontal: spacing.md, + backgroundColor: colors.surfaceBright + }, + retryLabel: { + color: colors.bgBase, + fontSize: typography.bodySize, + fontWeight: '600' } })) diff --git a/mobile/src/dictation/MobileDictationPill.tsx b/mobile/src/dictation/MobileDictationPill.tsx new file mode 100644 index 00000000000..e257844d486 --- /dev/null +++ b/mobile/src/dictation/MobileDictationPill.tsx @@ -0,0 +1,314 @@ +import { useContext, useEffect } from 'react' +import { Pressable, Text, View } from 'react-native' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { CircleAlert, Laptop, Smartphone } from 'lucide-react-native' +import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' +import { + MobileDictationGrapes, + MobileDictationTimer, + useMobileDictationElapsed +} from './MobileDictationMeter' +import { + MobileDictationCancelButton, + MobileDictationMicIcon, + MobileDictationRetryButton +} from './MobileDictationLiveControls' +import { + dictationControlsCopy, + dictationFailureReason, + dictationSpokenDuration +} from './mobile-dictation-controls-copy' +import { dictationAwayCopy } from './mobile-dictation-away-copy' +import { composerInputStyles } from '../components/composer-input/composer-input-styles' +import { MobileDictationStatusAnnouncement } from './MobileDictationStatusAnnouncement' +import { + useMobileDictationHost, + useMobileDictationHostLive, + MobileDictationPillContext, + type MobileDictationHostToast +} from './mobile-dictation-host-context' + +const TOAST_MS = 4000 +// Long enough to read the target's name and reach Open. +const TOAST_WITH_OPEN_MS = 6000 + +// The meter needs a live recording; finishing and failures show words instead. +function PillStatus({ + dictation, + elapsedSeconds +}: { + dictation: UseMobileDictationResult + elapsedSeconds: number +}) { + if (dictation.failure) { + return ( + + {`${dictationFailureReason(dictation.failure)} · ${dictationControlsCopy.recordingKept()}`} + + ) + } + if (!dictation.isRecording) { + return ( + + {dictation.isStarting ? dictationAwayCopy.starting() : dictationAwayCopy.finishing()} + + ) + } + return ( + + + {dictationAwayCopy.listening()} + · + + {dictation.engine ? ( + <> + · + {dictation.engine.kind === 'phone' ? ( + + ) : ( + + )} + + ) : null} + + ) +} + +// The dictation whose target is off screen: tap to go back, ✕ and Stop work from here; a failure stays until Retry or ✕. +function MobileDictationPill({ + title, + onOpen, + onStop +}: { + title: string + onOpen: () => void + onStop: () => void +}) { + // Subscribed only while the pill shows, so a hidden pill never re-renders on the dictation's ticks. + const dictation = useMobileDictationHostLive(useMobileDictationHost()) + const { elapsedSeconds } = useMobileDictationElapsed(dictation.meter) + const failed = dictation.failure !== null + return ( + + + {failed ? ( + + ) : ( + + )} + + + {failed ? dictationAwayCopy.stopped() : title} + + + + + void dictation.cancel()} discards={failed} /> + {failed ? ( + void dictation.retry()} labelled /> + ) : ( + [ + composerInputStyles.controlButton, + pressed && composerInputStyles.pressed + ]} + onPress={onStop} + > + + + )} + + ) +} + +function MobileDictationToast({ + toast, + onDone, + bottom +}: { + toast: MobileDictationHostToast | null + onDone: () => void + bottom: number +}) { + useEffect(() => { + if (!toast) { + return + } + const timer = setTimeout(onDone, toast.open ? TOAST_WITH_OPEN_MS : TOAST_MS) + return () => clearTimeout(timer) + }, [onDone, toast]) + // The host's announcer reads the message (shell or live region), so the toast itself stays quiet. + return ( + + {toast ? ( + + + {toast.message} + + {toast.open ? ( + { + onDone() + toast.open?.() + }} + > + {dictationAwayCopy.open()} + + ) : null} + + ) : null} + + ) +} + +// Floats over every screen of the host document, above the bottom inset. +export function MobileDictationPillLayer(): React.JSX.Element | null { + useMobileColorScheme() + useMobileTranslation() + const insets = useSafeAreaInsets() + const { stop } = useMobileDictationHost() + const pill = useContext(MobileDictationPillContext) + if (!pill) { + return null + } + // Above the home indicator, or above a screen's bottom bar when it reported one. + const pillBottom = Math.max(insets.bottom + spacing.md, pill.clearance + spacing.sm) + return ( + <> + {pill.away ? ( + + + + ) : null} + + + + ) +} + +const PILL_HEIGHT = 56 + +const styles = themedStyleSheet(() => ({ + // Above every screen's own floating controls, below drawers and the host's pending cover (1000). + layer: { + position: 'absolute', + left: spacing.lg, + right: spacing.lg, + zIndex: 900, + elevation: 9 + }, + pill: { + height: PILL_HEIGHT, + borderRadius: radii.pill, + backgroundColor: colors.bgRaised, + borderWidth: 1, + borderColor: colors.borderSubtle, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingLeft: spacing.lg, + paddingRight: spacing.sm, + shadowColor: '#000', + shadowOpacity: 0.35, + shadowRadius: 12, + shadowOffset: { width: 0, height: 6 }, + elevation: 8 + }, + body: { + flex: 1, + minWidth: 0, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + alignSelf: 'stretch' + }, + titles: { + flex: 1, + minWidth: 0, + gap: 1 + }, + title: { + color: colors.textPrimary, + fontSize: typography.bodySize + 1, + fontWeight: '600' + }, + subRow: { + flexDirection: 'row', + alignItems: 'center', + gap: 5 + }, + sub: { + color: colors.textSecondary, + fontSize: typography.metaSize, + flexShrink: 1 + }, + recDot: { + width: 8, + height: 8, + borderRadius: 4, + backgroundColor: colors.statusRed + }, + toastRow: { + position: 'absolute', + left: spacing.lg, + right: spacing.lg, + alignItems: 'center', + zIndex: 900, + elevation: 9 + }, + toast: { + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + maxWidth: 360, + backgroundColor: colors.bgRaised, + borderWidth: 1, + borderColor: colors.borderSubtle, + borderRadius: radii.surface, + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm + }, + toastText: { + flexShrink: 1, + color: colors.textPrimary, + fontSize: 13 + }, + toastAction: { + color: colors.accentBlue, + fontSize: 13, + fontWeight: '600' + } +})) diff --git a/mobile/src/dictation/MobileDictationStatusAnnouncement.tsx b/mobile/src/dictation/MobileDictationStatusAnnouncement.tsx index f6a29b86660..bb9f46ce4df 100644 --- a/mobile/src/dictation/MobileDictationStatusAnnouncement.tsx +++ b/mobile/src/dictation/MobileDictationStatusAnnouncement.tsx @@ -1,7 +1,7 @@ import { StyleSheet, Text, View } from 'react-native' import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state' import { translate } from '../i18n/mobile-i18n' -import { useMobileTranslation } from '../i18n/use-mobile-translation' +import type { MobileDictationLiveText } from './use-mobile-dictation-announcements' export type MobileDictationStatusFlags = Pick< UseMobileDictationResult, @@ -18,16 +18,16 @@ export function mobileDictationStatusTitle(dictation: MobileDictationStatusFlags : null } -// Mic labels change silently; one live region tells screen readers for every mic, like desktop's indicator. +// The live region for announcements the shell could not speak itself (TalkBack reads it; older shells fall back to it). +// A new Text per message, so the same words twice are read twice. export function MobileDictationStatusAnnouncement({ - dictation + liveText }: { - dictation: MobileDictationStatusFlags + liveText: MobileDictationLiveText }): React.JSX.Element { - useMobileTranslation() return ( - {mobileDictationStatusTitle(dictation) ?? ''} + {liveText.text} ) } diff --git a/mobile/src/dictation/dictation-reply-schema.ts b/mobile/src/dictation/dictation-reply-schema.ts index 70c3bd707fa..23a738977ac 100644 --- a/mobile/src/dictation/dictation-reply-schema.ts +++ b/mobile/src/dictation/dictation-reply-schema.ts @@ -1,6 +1,7 @@ import * as z from 'zod' import type { RuntimeSpeechModelSummary } from '../../../src/shared/runtime-worktree-contracts' import { hostUnionArms, salvagedOptional, salvagingArray } from '../../../src/shared/zod-salvage' +import { normalizeDictationTerms } from '../../../src/shared/dictation-dictionary' export const SPEECH_MODEL_PROVIDERS = hostUnionArms({ local: true, @@ -36,6 +37,11 @@ export const dictationSetupSchema = z.looseObject({ dictationHoldToRecord: salvagedOptional('dictationHoldToRecord', z.boolean()), // Absent from older hosts, which remove no fillers either; the phone then keeps them on, the host default. removeFillerWords: salvagedOptional('removeFillerWords', z.boolean()), + // Absent from older hosts, which spell nothing; malformed entries are dropped. + dictationTerms: salvagedOptional( + 'dictationTerms', + z.unknown().transform(normalizeDictationTerms) + ), models: salvagingArray(speechModelSchema) }) diff --git a/mobile/src/dictation/mobile-dictation-announce-copy.ts b/mobile/src/dictation/mobile-dictation-announce-copy.ts new file mode 100644 index 00000000000..5a7d3bdab18 --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-announce-copy.ts @@ -0,0 +1,39 @@ +import { translate } from '../i18n/mobile-i18n' + +// What a screen reader hears as a dictation moves along; nothing while you talk, so it never talks over you. +export const dictationAnnounceCopy = { + listening: (engine: 'phone' | 'computer', computer: string | null) => + engine === 'phone' + ? translate('dictation.announce.listeningOnPhone', 'Listening. Transcribing on this phone.') + : computer + ? translate('dictation.announce.listeningOn', 'Listening. Transcribing on {{computer}}.', { + computer + }) + : translate( + 'dictation.announce.listeningOnComputer', + 'Listening. Transcribing on the computer.' + ), + stillListening: () => translate('dictation.announce.stillListening', 'Still listening.'), + finishing: () => translate('dictation.announce.finishing', 'Finishing.'), + inserted: () => translate('dictation.announce.inserted', 'Inserted.'), + cancelled: () => translate('dictation.announce.cancelled', 'Dictation cancelled.'), + movedToComputer: (computer: string | null) => + computer + ? translate( + 'dictation.announce.movedTo', + 'This phone stopped transcribing. Continuing on {{computer}}.', + { computer } + ) + : translate( + 'dictation.announce.movedToComputer', + 'This phone stopped transcribing. Continuing on the computer.' + ), + stoppedKept: (reason: string) => + translate( + 'dictation.announce.stoppedKept', + 'Dictation stopped. {{reason}}. Your recording is kept.', + { + reason + } + ) +} diff --git a/mobile/src/dictation/mobile-dictation-away-copy.ts b/mobile/src/dictation/mobile-dictation-away-copy.ts new file mode 100644 index 00000000000..a7ab5972b64 --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-away-copy.ts @@ -0,0 +1,20 @@ +import { translate } from '../i18n/mobile-i18n' + +// Words for a dictation whose target is off screen: the pill and the toast that offers a way back. +export const dictationAwayCopy = { + insertedIn: ({ title, target }: { title: string; target: { field: string } | null }) => + target?.field === 'live' + ? translate('dictation.announce.typedInto', 'Typed into {{target}}', { target: title }) + : translate('dictation.announce.insertedIn', 'Inserted in {{target}}', { target: title }), + open: () => translate('dictation.pill.open', 'Open'), + listening: () => translate('dictation.pill.listening', 'Listening'), + starting: () => translate('dictation.pill.starting', 'Starting'), + finishing: () => translate('dictation.pill.finishing', 'Finishing'), + stopped: () => translate('dictation.pill.stopped', 'Dictation stopped'), + label: (target: string, duration: string) => + translate('dictation.pill.label', 'Dictation to {{target}}, {{duration}}', { + target, + duration + }), + hint: () => translate('dictation.pill.hint', 'Double-tap to go back') +} diff --git a/mobile/src/dictation/mobile-dictation-away-insert.ts b/mobile/src/dictation/mobile-dictation-away-insert.ts new file mode 100644 index 00000000000..483f08e232e --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-away-insert.ts @@ -0,0 +1,51 @@ +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { editMobileNativeChatDraft } from '../session/native-chat/composer/mobile-native-chat-draft-store' +import { terminalInputSend } from '../terminal/mobile-terminal-operations' +import { + buildTerminalSendParams, + TERMINAL_INPUT_SEND_OPTIONS +} from '../terminal/terminal-send-request' +import { insertDictationText } from './mobile-dictation-text-insertion' + +// Where a dictation's words go when its screen is gone or behind another: the chat's draft, or the terminal's input. +export type MobileDictationAwayTarget = + | { readonly field: 'chat'; readonly scope: string } + | { readonly field: 'live'; readonly handle: string } + | null + +// The draft keeps the words (never sent); a terminal gets them typed in, never Enter. False when they did not land. +export async function insertMobileDictationAway( + owner: { + readonly client: RpcClient | null + readonly target: MobileDictationAwayTarget + }, + text: string +): Promise { + const { target } = owner + if (target?.field === 'chat') { + editMobileNativeChatDraft( + target.scope, + (current) => insertDictationText(current, text, null).text + ) + return true + } + if (target?.field !== 'live' || !owner.client) { + return false + } + try { + const reply = await terminalInputSend.request( + owner.client, + buildTerminalSendParams({ + terminal: target.handle, + text, + enter: false, + // No phone identity: a phone may only claim a terminal it is watching, and this one is off screen; the words go in as plain typed input. + deviceToken: null + }), + TERMINAL_INPUT_SEND_OPTIONS + ) + return terminalInputSend.interpret(reply) === true + } catch { + return false + } +} diff --git a/mobile/src/dictation/mobile-dictation-controls-copy.ts b/mobile/src/dictation/mobile-dictation-controls-copy.ts index 3947035da5c..4de0e3c46c2 100644 --- a/mobile/src/dictation/mobile-dictation-controls-copy.ts +++ b/mobile/src/dictation/mobile-dictation-controls-copy.ts @@ -1,5 +1,11 @@ import { translate } from '../i18n/mobile-i18n' -import type { MobileDictationEngineShown } from '../hooks/mobile-dictation-session-state' +import type { + MobileDictationEngineShown, + MobileDictationKeptFailure +} from '../hooks/mobile-dictation-session-state' +import { MOBILE_DICTATION_CONNECTION_SLOW_ERROR_MESSAGE } from '../hooks/mobile-dictation-pending-audio-budget' +import { phoneDictationFailedMessage } from '../hooks/mobile-dictation-device-engine' +import { dictationFailureMessage, dictationSessionLostMessage } from './mobile-dictation-setup' // Active: starting or recording, so the mic is a Stop. export type MobileDictationMicState = { starting: boolean; active: boolean; processing: boolean } @@ -11,6 +17,10 @@ export const dictationControlsCopy = { stop: () => translate('dictation.controls.stop', 'Stop and insert'), finishing: () => translate('dictation.controls.finishing', 'Finishing dictation'), cancel: () => translate('dictation.controls.cancel', 'Cancel dictation'), + discard: () => translate('dictation.controls.discard', 'Discard recording'), + retry: () => translate('dictation.controls.retry', 'Retry dictation'), + retryShort: () => translate('dictation.controls.retryShort', 'Retry'), + recordingKept: () => translate('dictation.failure.recordingKept', 'Recording kept'), mic: ({ starting, active, processing }: MobileDictationMicState) => starting ? dictationControlsCopy.starting() @@ -29,7 +39,7 @@ export const dictationControlsCopy = { : translate('dictation.status.movedToComputer', 'Moved to the computer') } -function spokenDuration(elapsedSeconds: number): string { +export function dictationSpokenDuration(elapsedSeconds: number): string { const minutes = Math.floor(elapsedSeconds / 60) const count = elapsedSeconds % 60 const seconds = @@ -57,7 +67,7 @@ export function dictationMeterLabel( engine: MobileDictationEngineShown['kind'] | null, computer: string | null ): string { - const duration = spokenDuration(elapsedSeconds) + const duration = dictationSpokenDuration(elapsedSeconds) if (engine === 'phone') { return translate('dictation.controls.meterOnPhone', 'Recording, {{duration}}, on this phone', { duration @@ -79,3 +89,17 @@ export function dictationMeterLabel( } return translate('dictation.controls.meter', 'Recording, {{duration}}', { duration }) } + +// The few words a kept failure shows in the composer row; the full message is too long for it. +export function dictationFailureReason({ message, offline }: MobileDictationKeptFailure): string { + if (offline || dictationFailureMessage(message) === dictationSessionLostMessage()) { + return translate('dictation.failure.connectionLost', 'Connection lost') + } + if (message === MOBILE_DICTATION_CONNECTION_SLOW_ERROR_MESSAGE) { + return translate('dictation.failure.connectionSlow', 'Connection too slow') + } + if (message === phoneDictationFailedMessage()) { + return translate('dictation.failure.phoneStopped', 'Stopped on this phone') + } + return translate('dictation.failure.stopped', 'Dictation stopped') +} diff --git a/mobile/src/dictation/mobile-dictation-host-context.ts b/mobile/src/dictation/mobile-dictation-host-context.ts new file mode 100644 index 00000000000..9f4d3c23798 --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-host-context.ts @@ -0,0 +1,110 @@ +import { createContext, useContext, useEffect, useState, useSyncExternalStore } from 'react' +import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { MobileDictationAwayTarget } from './mobile-dictation-away-insert' +import type { MobileDictationLiveText } from './use-mobile-dictation-announcements' +import type { DictationTerm } from '../../../src/shared/dictation-dictionary' + +export type MobileDictationHostToast = { message: string; open?: () => void } + +// Who started the dictation and where its words go, fixed at the tap: leaving the screen never moves them. +export type MobileDictationOwner = { + // The starting screen instance, and the session it shows (a reopened screen of that session takes over its controls). + readonly instance: object + readonly sessionKey: string + readonly client: RpcClient | null + readonly target: MobileDictationAwayTarget + // The target tab's title, for the pill and its toasts. + readonly title: string + // The session route that opens the target tab again when its screen is gone. + readonly href: string + // The target tab's pane key, for a screen still in the stack to switch back to it. + readonly paneKey: string | undefined + readonly dictationMode: string | undefined + readonly removeFillerWords: boolean + // The computer's terms for this worktree, for words the phone recognizes itself. + readonly dictationTerms: readonly DictationTerm[] | undefined + // The computer spells its own words with this worktree's repo terms. + readonly worktreeId: string + // The computer that would transcribe it, for what a screen reader hears; null when the phone lacks its name. + readonly computerName: string | null +} + +// A mounted session screen, as the dictation host sees it. +export type MobileDictationScreen = { + readonly instance: object + readonly sessionKey: string + // The one "shown" rule (mobile-dictation-shown.ts): true while the in-place controls stand for the dictation. + readonly shown: () => boolean + // The starting screen inserts where it started (cursor, live input); false when it cannot, so the host inserts instead. + readonly insert: (text: string) => boolean + // Setup refusals open its setup sheet; other failures toast on it. + readonly reportFailure: (err: Error) => void + readonly toast: (message: string) => void + // Pop the screens above this one and show the target tab. + readonly bringToFront: (paneKey: string | undefined) => void +} + +// Stable across the dictation's ticks: screens read the live dictation through subscribe, so a word heard re-renders only who shows it. +export type MobileDictationHost = { + readonly owner: MobileDictationOwner | null + readonly start: (owner: MobileDictationOwner) => Promise + // Stop with the selection tick, as every stop button does. + readonly stop: () => void + // Say something to the screen reader; a screen's own toast is not read on the page. + readonly announce: (message: string) => void + readonly attach: (screen: MobileDictationScreen) => () => void + // A screen's shown() answer changed; the pill reads it on render. + readonly refresh: () => void + readonly subscribe: (listener: () => void) => () => void + readonly getDictation: () => UseMobileDictationResult + // The same dictation as nobody's: no status, words or failure; its identity holds until the meter or callbacks change. + readonly getIdleDictation: () => UseMobileDictationResult + // Starting, recording, finishing, or a failure kept for Retry. + readonly getUnderway: () => boolean +} + +// The floating pill's own state, apart from the host's so a bar height or toast re-renders only the pill. +export type MobileDictationPill = { + // Shown while the dictation's own screen is not. + readonly away: boolean + readonly title: string + readonly open: () => void + readonly toast: MobileDictationHostToast | null + readonly clearToast: () => void + // The tallest bottom bar a screen reported, so the pill floats above it. + readonly clearance: number + // Announcements the shell could not speak, for the page's live region (TalkBack, older shells). + readonly liveText: MobileDictationLiveText +} + +export const MobileDictationHostContext = createContext(null) +export const MobileDictationPillContext = createContext(null) + +export function useMobileDictationHost(): MobileDictationHost { + const host = useContext(MobileDictationHostContext) + if (!host) { + throw new Error('useMobileDictationHost needs a MobileDictationHostProvider') + } + return host +} + +// The live dictation, re-rendering on each of its changes. +export function useMobileDictationHostLive(host: MobileDictationHost): UseMobileDictationResult { + return useSyncExternalStore(host.subscribe, host.getDictation) +} + +// Bottom bars report the height they cover, so the pill floats above them rather than over their buttons. +export const MobileDictationClearanceContext = createContext< + ((id: symbol, height: number) => void) | null +>(null) + +// A bottom bar's covered height, cleared when it unmounts; a hidden screen's bar lays out at zero. +export function useMobileDictationClearance(height: number): void { + const setClearance = useContext(MobileDictationClearanceContext) + const [id] = useState(() => Symbol('dictation-clearance')) + useEffect(() => { + setClearance?.(id, height) + }, [height, id, setClearance]) + useEffect(() => () => setClearance?.(id, 0), [id, setClearance]) +} diff --git a/mobile/src/dictation/mobile-dictation-host.tsx b/mobile/src/dictation/mobile-dictation-host.tsx new file mode 100644 index 00000000000..b2276df26aa --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-host.tsx @@ -0,0 +1,292 @@ +import { useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { useMobileDictation } from '../hooks/use-mobile-dictation' +import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state' +import { useRouteHandoff } from '../navigation/route-handoff' +import { triggerError } from '../platform/haptics' +import { useClipboardWriter } from '../platform/clipboard' +import { dictationFailureMessage, isDictationSetupRequiredError } from './mobile-dictation-setup' +import { useMobileDictationHaptics } from './use-mobile-dictation-haptics' +import { useMobileDictationSilenceStop } from './use-mobile-dictation-silence-stop' +import { insertMobileDictationAway } from './mobile-dictation-away-insert' +import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation-copy' +import { dictationAwayCopy } from './mobile-dictation-away-copy' +import { + useMobileDictationAnnouncements, + useMobileDictationSpeech +} from './use-mobile-dictation-announcements' +import { + MobileDictationClearanceContext, + MobileDictationHostContext, + MobileDictationPillContext, + type MobileDictationHost, + type MobileDictationHostToast, + type MobileDictationOwner, + type MobileDictationScreen +} from './mobile-dictation-host-context' + +export { useMobileDictationHost } from './mobile-dictation-host-context' + +// The owner's screen; startingOnly asks only for the screen that started it. +function screenFor( + screens: ReadonlySet, + owner: MobileDictationOwner | null, + startingOnly: boolean +): MobileDictationScreen | null { + const matches = [...screens].filter((screen) => owner && screen.sessionKey === owner.sessionKey) + const starting = matches.find((screen) => screen.instance === owner?.instance) ?? null + if (startingOnly) { + return starting + } + // Else the one in front, then the one that started it, then the newest copy of its session. + return matches.find((screen) => screen.shown()) ?? starting ?? matches.at(-1) ?? null +} + +function isUnderway(dictation: UseMobileDictationResult): boolean { + return ( + dictation.isStarting || + dictation.isRecording || + dictation.isProcessing || + dictation.failure !== null + ) +} + +// One dictation per host document, above its screens, so it keeps going when its session leaves the screen. +export function MobileDictationHostProvider({ children }: { children: ReactNode }) { + const router = useRouteHandoff() + const [owner, setOwner] = useState(null) + const ownerRef = useRef(owner) + const screensRef = useRef(new Set()) + const [, setRevision] = useState(0) + const refresh = useCallback(() => setRevision((revision) => revision + 1), []) + const [toast, setToast] = useState(null) + const clearToast = useCallback(() => setToast(null), []) + const [clearances, setClearances] = useState>(new Map()) + const clipboard = useClipboardWriter() + const speech = useMobileDictationSpeech() + const { say: speak } = speech + + // Bring a dictation's target back: its screen if one is still mounted, otherwise open the session again. + const openOwner = useCallback( + (target: MobileDictationOwner) => { + const screen = screenFor(screensRef.current, target, false) + if (screen) { + screen.bringToFront(target.paneKey) + } else { + router.push(target.href) + } + }, + [router] + ) + const open = useCallback(() => { + if (ownerRef.current) { + openOwner(ownerRef.current) + } + }, [openOwner]) + + // Say it on the screen that shows the dictation, else in the host's toast (with Open for the dictation it is about). + // A screen's toast is not read by VoiceOver on the page, so it is spoken too; the host's toast is spoken when it shows. + const say = (message: string, about?: MobileDictationOwner) => { + const screen = screenFor(screensRef.current, ownerRef.current, false) + if (screen?.shown()) { + screen.toast(message) + speak(message) + } else { + setToast(about ? { message, open: () => openOwner(about) } : { message }) + } + } + const reportFailureRef = useRef((err: Error) => { + const screen = screenFor(screensRef.current, ownerRef.current, false) + if (screen?.shown()) { + screen.reportFailure(err) + // A setup refusal opens the setup sheet, which is read on its own. + if (!isDictationSetupRequiredError(err.message)) { + speak(dictationFailureMessage(err.message)) + } + return + } + triggerError() + setToast({ message: dictationFailureMessage(err.message) }) + }) + + const dictation = useMobileDictation({ + client: owner?.client ?? null, + enabled: true, + removeFillerWords: owner?.removeFillerWords ?? true, + dictationTerms: owner?.dictationTerms, + worktreeId: owner?.worktreeId, + onTranscript: (text) => { + const current = ownerRef.current + if (!current) { + return + } + const starting = screenFor(screensRef.current, current, true) + if (starting?.shown() && starting.insert(text)) { + return + } + void insertMobileDictationAway(current, text).then((inserted) => { + if (inserted) { + say(dictationAwayCopy.insertedIn(current), current) + return + } + triggerError() + void clipboard.writeText(text).then( + () => say(nativeChatDictationCopy.insertFailedCopied()), + () => say(nativeChatDictationCopy.insertFailed()) + ) + }) + }, + onError: (err, { kept }) => { + if (kept) { + triggerError() + } else { + reportFailureRef.current(err) + } + }, + onAudioLimitReached: () => say(nativeChatDictationCopy.stoppedAtCloudLimit()) + }) + const stop = useMobileDictationHaptics(dictation) + useMobileDictationSilenceStop(dictation, owner?.dictationMode, stop, (message) => say(message)) + + // Screens subscribe to the live dictation; the host's context only changes when its owner or pill does. + const liveRef = useRef(dictation) + const listenersRef = useRef(new Set<() => void>()) + const { + meter, + start: startDictation, + stop: stopDictation, + cancel: cancelDictation, + retry + } = dictation + const away = + owner !== null && + isUnderway(dictation) && + screenFor(screensRef.current, owner, false)?.shown() !== true + const { noteCancel } = useMobileDictationAnnouncements( + dictation, + { computerName: owner?.computerName ?? null, away, toast: toast?.message ?? null }, + speak + ) + // Every ✕ (in place, the pill, the terminal's long press) ends here, so a cancel is never read as "Inserted." + const cancel = useCallback(() => { + noteCancel() + return cancelDictation() + }, [cancelDictation, noteCancel]) + const published = useMemo(() => ({ ...dictation, cancel }), [cancel, dictation]) + const idle = useMemo( + () => ({ + status: 'idle', + isStarting: false, + isRecording: false, + isProcessing: false, + transcriptSoFar: '', + error: null, + failure: null, + engine: null, + meter, + start: startDictation, + stop: stopDictation, + cancel, + retry + }), + [cancel, meter, retry, startDictation, stopDictation] + ) + const idleRef = useRef(idle) + useLayoutEffect(() => { + liveRef.current = published + idleRef.current = idle + for (const listener of listenersRef.current) { + listener() + } + }) + const subscribe = useCallback((listener: () => void) => { + listenersRef.current.add(listener) + return () => { + listenersRef.current.delete(listener) + } + }, []) + const getDictation = useCallback(() => liveRef.current, []) + const getIdleDictation = useCallback(() => idleRef.current, []) + const getUnderway = useCallback(() => isUnderway(liveRef.current), []) + + const start = useCallback( + async (next: MobileDictationOwner) => { + ownerRef.current = next + setOwner(next) + try { + await startDictation(next.client) + } catch (err) { + // The starting screen may already be gone, so a refused start is told wherever the user is now. + reportFailureRef.current(err instanceof Error ? err : new Error(String(err))) + } + }, + [startDictation] + ) + + const attach = useCallback( + (screen: MobileDictationScreen) => { + screensRef.current.add(screen) + refresh() + return () => { + screensRef.current.delete(screen) + refresh() + } + }, + [refresh] + ) + const setClearance = useCallback((id: symbol, height: number) => { + setClearances((current) => { + if ((current.get(id) ?? 0) === height) { + return current + } + const next = new Map(current) + if (height > 0) { + next.set(id, height) + } else { + next.delete(id) + } + return next + }) + }, []) + + const title = owner?.title ?? '' + const clearance = Math.max(0, ...clearances.values()) + const pill = useMemo( + () => ({ away, title, open, toast, clearToast, clearance, liveText: speech.liveText }), + [speech.liveText, away, clearToast, clearance, open, title, toast] + ) + const value = useMemo( + () => ({ + owner, + start, + stop, + announce: speak, + attach, + refresh, + subscribe, + getDictation, + getIdleDictation, + getUnderway + }), + [ + attach, + getDictation, + getIdleDictation, + getUnderway, + owner, + refresh, + speak, + start, + stop, + subscribe + ] + ) + return ( + + + + {children} + + + + ) +} diff --git a/mobile/src/dictation/mobile-dictation-leave-hold.ts b/mobile/src/dictation/mobile-dictation-leave-hold.ts index 790b51c796c..7aaaa16a253 100644 --- a/mobile/src/dictation/mobile-dictation-leave-hold.ts +++ b/mobile/src/dictation/mobile-dictation-leave-hold.ts @@ -7,9 +7,11 @@ export type MobileDictationLeaveHold = { hold: () => boolean } -// Leaving unmounts the screen and with it what was said, so starting, recording or transcribing holds the first leave. +// The dictation outlives its screen inside the page, but leaving the page's document ends it; that leave stops and inserts first. export function useMobileDictationLeaveHold( - dictation: UseMobileDictationResult + dictation: UseMobileDictationResult, + // True when leaving stays inside the page, where the floating pill carries the dictation on. + leaveKeepsPage: () => boolean ): MobileDictationLeaveHold { const { isStarting, isRecording, isProcessing, stop } = dictation const active = isStarting || isRecording || isProcessing @@ -20,7 +22,7 @@ export function useMobileDictationLeaveHold( } const holdsLeave = active && !held const hold = useCallback(() => { - if (!holdsLeave) { + if (!holdsLeave || leaveKeepsPage()) { return false } setHeld(true) @@ -28,7 +30,7 @@ export function useMobileDictationLeaveHold( void stop() } return true - }, [holdsLeave, isStarting, isRecording, stop]) + }, [holdsLeave, isStarting, isRecording, leaveKeepsPage, stop]) return { holdsLeave, hold } } diff --git a/mobile/src/dictation/mobile-dictation-live-context.ts b/mobile/src/dictation/mobile-dictation-live-context.ts index 1032c48710b..9f5d6126b3d 100644 --- a/mobile/src/dictation/mobile-dictation-live-context.ts +++ b/mobile/src/dictation/mobile-dictation-live-context.ts @@ -7,7 +7,11 @@ export type MobileDictationLive = { readonly engine: MobileDictationEngineShown | null // The paired computer's name; null when another server runs the workspace and the phone lacks its name. readonly computerName: string | null + // Also discards a failed dictation's kept recording. readonly cancel: () => void + // The short reason a dictation failed with its recording kept; Retry plays it to the computer again. + readonly failureReason: string | null + readonly retry: () => void } // The chat mic sits several composers deep (overlay, queued edits); it reads the live dictation from here. diff --git a/mobile/src/dictation/mobile-dictation-setup.ts b/mobile/src/dictation/mobile-dictation-setup.ts index 9e7f034dbd8..61e607ca7a4 100644 --- a/mobile/src/dictation/mobile-dictation-setup.ts +++ b/mobile/src/dictation/mobile-dictation-setup.ts @@ -44,7 +44,7 @@ function speechlessServerMessage(): string { ) } -function isSpeechlessServerError(message: string): boolean { +export function isSpeechlessServerError(message: string): boolean { return message.startsWith('speech_unavailable') } @@ -126,8 +126,12 @@ export function isDictationSetupRequiredError(message: string): boolean { return SETUP_REQUIRED_CODES.has(message) || message.startsWith('voice_model_not_ready:') } -export async function fetchDictationSetup(client: RpcOperationSender): Promise { - const reply = await requestDictationSetupReply(client) +/** `worktreeId` asks for that repo's dictionary terms too. */ +export async function fetchDictationSetup( + client: RpcOperationSender, + worktreeId?: string +): Promise { + const reply = await requestDictationSetupReply(client, worktreeId ? { worktreeId } : null) if (isLegacyDesktopSpeechSetupReply(reply)) { throw new Error( translate( @@ -145,15 +149,18 @@ export async function fetchDictationSetup(client: RpcOperationSender): Promise { +async function requestDictationSetupReply( + client: RpcOperationSender, + params: { worktreeId: string } | null +): Promise { try { - return await dictationSetupRead.request(client, null) + return await dictationSetupRead.request(client, params) } catch (error) { if (!(error instanceof LogicalClientCutoverError)) { throw error } // Replay this read on authenticated replacement; mutations must surface cutover to avoid replaying unknown commits. - return dictationSetupRead.request(client, null) + return dictationSetupRead.request(client, params) } } diff --git a/mobile/src/dictation/mobile-dictation-shown.ts b/mobile/src/dictation/mobile-dictation-shown.ts new file mode 100644 index 00000000000..cc3b0a27d27 --- /dev/null +++ b/mobile/src/dictation/mobile-dictation-shown.ts @@ -0,0 +1,15 @@ +// The one rule for where a dictation's controls live: in place on its session screen, or the floating pill. +// Today the session screen counts as showing its dictation whenever it is in front, on any of its tabs; the +// words still land in the tab where the dictation started. Showing the pill on another tab too means adding +// "and the dictation's target tab is the active one" here. +export function mobileDictationShownOnScreen({ + ownedHere, + inFront +}: { + // This screen shows the session the dictation was started in. + ownedHere: boolean + // This screen is the one in front (no other screen pushed over it). + inFront: boolean +}): boolean { + return ownedHere && inFront +} diff --git a/mobile/src/dictation/use-mobile-dictation-announcements.ts b/mobile/src/dictation/use-mobile-dictation-announcements.ts new file mode 100644 index 00000000000..c06933349b9 --- /dev/null +++ b/mobile/src/dictation/use-mobile-dictation-announcements.ts @@ -0,0 +1,113 @@ +import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' +import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state' +import { useAccessibilityAnnouncer } from '../platform/accessibility-announcer' +import { dictationAnnounceCopy } from './mobile-dictation-announce-copy' +import { dictationFailureReason } from './mobile-dictation-controls-copy' + +// Finishing is said only when it is slow. +const FINISHING_ANNOUNCE_DELAY_MS = 1000 + +// What the shell could not speak, for the page's live region; the id changes on every message so a repeat is read again. +export type MobileDictationLiveText = { readonly text: string; readonly id: number } + +// Speak to the screen reader through the shell where it can, else into the live region. say keeps its identity. +export function useMobileDictationSpeech(): { + say: (message: string) => void + liveText: MobileDictationLiveText +} { + const announce = useAccessibilityAnnouncer() + const announceRef = useRef(announce) + useLayoutEffect(() => { + announceRef.current = announce + }) + const [liveText, setLiveText] = useState({ text: '', id: 0 }) + const say = useCallback((message: string) => { + void announceRef.current(message).then((spoken) => { + if (!spoken) { + setLiveText((current) => ({ text: message, id: current.id + 1 })) + } + }) + }, []) + return { say, liveText } +} + +// The dictation's own spoken moments: start, leaving its screen, a move to the computer, a slow finish, a cancel, a kept failure, the host's toasts. +// Outcomes (inserted, failed) are said by whoever knows them: the screen that inserted, or the host's failure report. +export function useMobileDictationAnnouncements( + dictation: Pick, + { + computerName, + away, + toast + }: { computerName: string | null; away: boolean; toast: string | null }, + say: (message: string) => void +): { noteCancel: () => void } { + const { status, engine, failure } = dictation + const previousStatus = useRef(status) + const cancelled = useRef(false) + const listeningSaid = useRef(false) + const movedAtSaid = useRef(null) + const statusRef = useRef(status) + + useEffect(() => { + const previous = previousStatus.current + previousStatus.current = status + statusRef.current = status + if (status === 'starting') { + cancelled.current = false + listeningSaid.current = false + } + // Only a ✕ (including Discard on a kept failure); a refused start's reason is said where it is reported. + if (status === 'idle' && previous !== 'idle' && cancelled.current) { + say(dictationAnnounceCopy.cancelled()) + } + if (status === 'idle') { + cancelled.current = false + } + }, [say, status]) + + // Leaving the screen keeps it going; say so once, then the next screen reads as usual. + useEffect(() => { + if (away && statusRef.current === 'recording') { + say(dictationAnnounceCopy.stillListening()) + } + }, [away, say]) + useEffect(() => { + if (toast) { + say(toast) + } + }, [say, toast]) + + useEffect(() => { + if (status === 'recording' && engine && !listeningSaid.current) { + listeningSaid.current = true + say(dictationAnnounceCopy.listening(engine.kind, computerName)) + } + if (engine?.movedAt != null && engine.movedAt !== movedAtSaid.current) { + movedAtSaid.current = engine.movedAt + say(dictationAnnounceCopy.movedToComputer(computerName)) + } + }, [computerName, engine, say, status]) + + useEffect(() => { + if (status !== 'processing') { + return + } + const timer = setTimeout( + () => say(dictationAnnounceCopy.finishing()), + FINISHING_ANNOUNCE_DELAY_MS + ) + return () => clearTimeout(timer) + }, [say, status]) + + useEffect(() => { + if (failure) { + say(dictationAnnounceCopy.stoppedKept(dictationFailureReason(failure))) + } + }, [failure, say]) + + const noteCancel = useCallback(() => { + cancelled.current = true + }, []) + return { noteCancel } +} diff --git a/mobile/src/dictation/use-mobile-dictation-destination.ts b/mobile/src/dictation/use-mobile-dictation-destination.ts index 7af6be82a6a..74f5633c242 100644 --- a/mobile/src/dictation/use-mobile-dictation-destination.ts +++ b/mobile/src/dictation/use-mobile-dictation-destination.ts @@ -39,6 +39,7 @@ export function useMobileDictationDestination({ ? { field: 'live', handle: terminalHandle } : null setTarget(targetRef.current) + return targetRef.current }, [chatComposerScopeKey] ) diff --git a/mobile/src/dictation/use-mobile-dictation-haptics.ts b/mobile/src/dictation/use-mobile-dictation-haptics.ts index a4853c0a04a..ae927fdd6b5 100644 --- a/mobile/src/dictation/use-mobile-dictation-haptics.ts +++ b/mobile/src/dictation/use-mobile-dictation-haptics.ts @@ -11,8 +11,9 @@ export function useMobileDictationHaptics(dictation: UseMobileDictationResult): } }, [dictation.isRecording]) + const { stop } = dictation return useCallback(() => { triggerSelection() - void dictation.stop() - }, [dictation]) + void stop() + }, [stop]) } diff --git a/mobile/src/dictation/use-mobile-dictation-live.ts b/mobile/src/dictation/use-mobile-dictation-live.ts index 5027a930c1f..13aa5f5081a 100644 --- a/mobile/src/dictation/use-mobile-dictation-live.ts +++ b/mobile/src/dictation/use-mobile-dictation-live.ts @@ -4,10 +4,11 @@ import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-hos import { useHostDisplay } from '../transport/hosts/use-host-display' import { useHostProfile } from '../transport/hosts/use-host-profile' import type { MobileDictationLive } from './mobile-dictation-live-context' +import { dictationFailureReason } from './mobile-dictation-controls-copy' -// What every dictation control reads while one runs: meter, engine, the computer's name and cancel. +// What every dictation control reads while one runs or waits for Retry: meter, engine, the computer's name, cancel and Retry. export function useMobileDictationLive( - dictation: Pick, + dictation: Pick, cancel: () => void, hostId: string ): MobileDictationLive { @@ -16,13 +17,25 @@ export function useMobileDictationLive( cancelLatest.current = cancel }, [cancel]) const stableCancel = useCallback(() => cancelLatest.current(), []) - const hostProfile = useHostProfile(hostId) - const hostTitle = useHostDisplay(hostProfile).title - // A workspace routed to another server transcribes there, and the phone lacks that server's name. - const computerName = useWorkspaceExecutionHost() === undefined && hostProfile ? hostTitle : null - const { meter, engine } = dictation + const computerName = useDictationComputerName(hostId) + const { meter, engine, failure, retry } = dictation + const failureReason = failure === null ? null : dictationFailureReason(failure) return useMemo( - () => ({ meter, engine, computerName, cancel: stableCancel }), - [meter, engine, computerName, stableCancel] + () => ({ + meter, + engine, + computerName, + cancel: stableCancel, + failureReason, + retry: () => void retry() + }), + [meter, engine, computerName, stableCancel, failureReason, retry] ) } + +// The computer that transcribes a session's dictation; null when another server runs the workspace and the phone lacks its name. +export function useDictationComputerName(hostId: string): string | null { + const hostProfile = useHostProfile(hostId) + const hostTitle = useHostDisplay(hostProfile).title + return useWorkspaceExecutionHost() === undefined && hostProfile ? hostTitle : null +} diff --git a/mobile/src/drafts/document-edit-draft-rows.ts b/mobile/src/drafts/document-edit-draft-rows.ts index 53b912634f0..2dd2d91ed5e 100644 --- a/mobile/src/drafts/document-edit-draft-rows.ts +++ b/mobile/src/drafts/document-edit-draft-rows.ts @@ -1,14 +1,12 @@ import * as z from 'zod' -import { - DEVICE_STORE_MAX_VALUE_LENGTH, - encodeDeviceStoreValue -} from '../device-store/device-store-value-codec' import { durableDraftRow, - durableDraftRowKey, + fitsDeviceStore, pageDraftRowBackend, resetDurableDraftRowsForTests, - type DurableDraftRow + workspaceDraftRowKey, + type DurableDraftRow, + type WorkspaceDraftScope } from './durable-draft-rows' /** Unsaved edits to a file or Markdown tab, with the hash of the host's version they were made against. */ @@ -26,29 +24,12 @@ type Slot = { } const slots = new Map() -/** The host and remote runtime a worktree lives on, so two hosts' same-named documents never share edits. */ -export type DocumentEditScope = { hostId: string; executionHost?: string; worktreeId: string } - -function scopedId(scope: DocumentEditScope, id: string): string { - return `${scope.hostId}:${scope.executionHost ?? ''}:${id}` +export function markdownTabDraftKey(scope: WorkspaceDraftScope, tabId: string): string { + return workspaceDraftRowKey('markdownTab', scope, tabId) } -export function markdownTabDraftKey(scope: DocumentEditScope, tabId: string): string { - return durableDraftRowKey('markdownTab', scope.worktreeId, scopedId(scope, tabId)) -} - -export function fileEditDraftKey(scope: DocumentEditScope, path: string): string { - return durableDraftRowKey('fileEdit', scope.worktreeId, scopedId(scope, path)) -} - -// A value past the store's cap would be refused and leave older edits behind, so it is not kept at all. -function fitsDeviceStore(draft: DocumentEditDraft): boolean { - const json = JSON.stringify(draft) - // At most 3 UTF-8 bytes per code unit, gzip barely grows any input, base64 adds a third: most documents skip the encode. - if (json.length * 4 + 1024 <= DEVICE_STORE_MAX_VALUE_LENGTH) { - return true - } - return encodeDeviceStoreValue(draft).length <= DEVICE_STORE_MAX_VALUE_LENGTH +export function fileEditDraftKey(scope: WorkspaceDraftScope, path: string): string { + return workspaceDraftRowKey('fileEdit', scope, path) } function slotFor(key: string): Slot { diff --git a/mobile/src/drafts/durable-draft-fields.test.tsx b/mobile/src/drafts/durable-draft-fields.test.tsx new file mode 100644 index 00000000000..9e3b4882f59 --- /dev/null +++ b/mobile/src/drafts/durable-draft-fields.test.tsx @@ -0,0 +1,155 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { + publishPageDeviceStore, + readPageDeviceStore +} from '../mobile-web-shell/bridge/page-device-store' +import { encodeDeviceStoreValue } from '../device-store/device-store-value-codec' +import { resetDurableDraftFieldsForTests, useDurableDraftField } from './durable-draft-fields' +import { publishInMemoryDeviceStore } from './in-memory-device-store.test-support' + +const KEY = 'draft:prEdit:wt:main' +let renderer: ReactTestRenderer | null = null +let field: ReturnType | null = null + +function Field() { + field = useDurableDraftField(KEY, 'body') + return null +} + +afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + resetDurableDraftFieldsForTests() + publishPageDeviceStore(null) +}) + +it('keeps a field the user cleared while the saved copy was still being read', async () => { + // The shell holds an earlier draft, and its read answers only when released. + let release!: () => void + const held = new Promise((resolve) => { + release = resolve + }) + publishPageDeviceStore({ + available: () => true, + read: async () => { + await held + return { status: 'ok', values: [encodeDeviceStoreValue({ body: 'old saved text' })] } + }, + write: async () => ({ written: true }) + }) + await act(async () => { + renderer = create(createElement(Field)) + }) + + act(() => field![1]('')) + await act(async () => { + release() + await held + }) + + expect(field![0]).toBe('') +}) + +it('drops an older draft once the text grows past what the store can hold', async () => { + vi.useFakeTimers() + const table = new Map() + publishInMemoryDeviceStore(table) + const open = async () => { + await act(async () => { + renderer = create(createElement(Field)) + await vi.advanceTimersByTimeAsync(0) + }) + } + const kill = () => { + act(() => renderer?.unmount()) + renderer = null + resetDurableDraftFieldsForTests() + } + await open() + act(() => field![1]('a short description')) + await act(async () => { + await vi.advanceTimersByTimeAsync(1000) + }) + // Text that doesn't compress, well past the store's 512 KiB cap once encoded. + let seed = 7 + const huge = Array.from({ length: 900_000 }, () => { + seed ^= seed << 13 + seed ^= seed >>> 17 + seed ^= seed << 5 + return String.fromCharCode(33 + ((seed >>> 0) % 90)) + }).join('') + act(() => field![1](huge)) + await act(async () => { + await vi.advanceTimersByTimeAsync(1000) + }) + kill() + + await open() + expect(field![0]).toBe('') + vi.useRealTimers() +}) + +it('saves text typed while the store could not be read once the store answers again', async () => { + vi.useFakeTimers() + const table = new Map() + publishInMemoryDeviceStore(table) + const store = readPageDeviceStore()! + let readFails = true + publishPageDeviceStore({ + ...store, + read: async (name, keys) => (readFails ? { status: 'unavailable' } : store.read(name, keys)) + }) + await act(async () => { + renderer = create(createElement(Field)) + await vi.advanceTimersByTimeAsync(0) + }) + act(() => field![1]('typed while the store was down')) + readFails = false + await act(async () => { + await vi.advanceTimersByTimeAsync(15_000) + }) + act(() => renderer?.unmount()) + renderer = null + resetDurableDraftFieldsForTests() + + await act(async () => { + renderer = create(createElement(Field)) + await vi.advanceTimersByTimeAsync(0) + }) + expect(field![0]).toBe('typed while the store was down') + vi.useRealTimers() +}) + +it('does not bring back a saved draft the user cleared while the store could not be read', async () => { + vi.useFakeTimers() + const table = new Map([[KEY, encodeDeviceStoreValue({ body: 'already sent text' })]]) + publishInMemoryDeviceStore(table) + const store = readPageDeviceStore()! + let readFails = true + publishPageDeviceStore({ + ...store, + read: async (name, keys) => (readFails ? { status: 'unavailable' } : store.read(name, keys)) + }) + await act(async () => { + renderer = create(createElement(Field)) + await vi.advanceTimersByTimeAsync(0) + }) + // The send landed: its success handler clears a field that is already empty on this page. + act(() => field![1]('')) + readFails = false + await act(async () => { + await vi.advanceTimersByTimeAsync(15_000) + }) + act(() => renderer?.unmount()) + renderer = null + resetDurableDraftFieldsForTests() + + await act(async () => { + renderer = create(createElement(Field)) + await vi.advanceTimersByTimeAsync(0) + }) + expect(field![0]).toBe('') + vi.useRealTimers() +}) diff --git a/mobile/src/drafts/durable-draft-fields.ts b/mobile/src/drafts/durable-draft-fields.ts new file mode 100644 index 00000000000..70d550ab760 --- /dev/null +++ b/mobile/src/drafts/durable-draft-fields.ts @@ -0,0 +1,148 @@ +import { useCallback, useSyncExternalStore, type SetStateAction } from 'react' +import * as z from 'zod' +import { + durableDraftRow, + fitsDeviceStore, + pageDraftRowBackend, + resetDurableDraftRowsForTests, + type DurableDraftRow +} from './durable-draft-rows' + +// A row's typed text fields; an empty field is left out, and a row with none is removed. +type DraftFields = Readonly> + +const savedFieldsSchema = z.record(z.string(), z.string()) + +type Slot = { + fields: DraftFields + // Fields set on this page, cleared ones included; a read that lands later never overwrites them. + touched: Set + // The shortest JSON length found over the store's cap: longer text is not encoded again on every save. + overCap: number + listeners: Set<() => void> + row: DurableDraftRow +} + +// The page's copy of each row, so a form that closes and reopens shows its text without a read. +const slots = new Map() + +function notify(slot: Slot): void { + for (const listener of slot.listeners) { + listener() + } +} + +function slotFor(key: string): Slot { + const existing = slots.get(key) + if (existing) { + return existing + } + const slot: Slot = { + fields: {}, + touched: new Set(), + overCap: Infinity, + listeners: new Set(), + row: durableDraftRow(key, { + backend: () => pageDraftRowBackend(key), + // Text too big for the store stays in memory and removes the row, so an older, smaller draft can't come back. + snapshot: () => { + if (Object.keys(slot.fields).length === 0) { + return null + } + const length = JSON.stringify(slot.fields).length + if (length >= slot.overCap) { + return null + } + if (fitsDeviceStore(slot.fields)) { + return slot.fields + } + slot.overCap = length + return null + }, + restore: (saved) => { + const parsed = savedFieldsSchema.safeParse(saved) + if (!parsed.success) { + return + } + // Text typed or cleared before the read landed wins over the saved copy. + const restored = Object.entries(parsed.data).filter( + ([field, text]) => text && !slot.touched.has(field) + ) + if (restored.length === 0) { + return + } + slot.fields = { ...Object.fromEntries(restored), ...slot.fields } + notify(slot) + } + }) + } + slots.set(key, slot) + return slot +} + +/** Sets one field of a row, wherever it is shown; a send that settles after its form closed clears its own row. */ +export function updateDurableDraftField( + key: string, + field: string, + update: SetStateAction +): void { + const slot = slotFor(key) + const current = slot.fields[field] ?? '' + const next = typeof update === 'function' ? update(current) : update + // Even an unchanged value is the user's choice: a read still pending must not overwrite it. + slot.touched.add(field) + if (next === current) { + // A clear on a row the page couldn't read yet still removes what the store holds, so sent text can't come back. + if (!next && Object.keys(slot.fields).length === 0) { + slot.row.save('immediate') + } + return + } + const rest = Object.fromEntries(Object.entries(slot.fields).filter(([name]) => name !== field)) + slot.fields = next ? { ...rest, [field]: next } : rest + notify(slot) + // An emptied row is written at once, so sent text can't come back. + slot.row.save(Object.keys(slot.fields).length > 0 ? 'deferred' : 'immediate') +} + +/** + * One typed field kept in a draft row: it survives the form closing and the page being killed, and + * comes back only into a field still empty. A null key (nothing to type into) holds nothing. + */ +export function useDurableDraftField( + key: string | null, + field: string +): readonly [string, (update: SetStateAction) => void] { + const subscribe = useCallback( + (onChange: () => void) => { + if (!key) { + return () => {} + } + const slot = slotFor(key) + slot.listeners.add(onChange) + // Read once per page; a read the store dropped is retried by the next form that opens the row. + void slot.row.load() + return () => { + slot.listeners.delete(onChange) + } + }, + [key] + ) + const read = () => (key ? (slots.get(key)?.fields[field] ?? '') : '') + const value = useSyncExternalStore(subscribe, read, read) + // Bound to this key, so a send that settles after the user moved on clears the row it came from. + const setValue = useCallback( + (update: SetStateAction) => { + if (key) { + updateDurableDraftField(key, field, update) + } + }, + [field, key] + ) + return [value, setValue] as const +} + +export function resetDurableDraftFieldsForTests(): void { + slots.clear() + resetDurableDraftRowsForTests() +} diff --git a/mobile/src/drafts/durable-draft-rows.ts b/mobile/src/drafts/durable-draft-rows.ts index 4d0dbe5c2e6..0fed37a82ef 100644 --- a/mobile/src/drafts/durable-draft-rows.ts +++ b/mobile/src/drafts/durable-draft-rows.ts @@ -3,6 +3,7 @@ import { type PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' import { + DEVICE_STORE_MAX_VALUE_LENGTH, decodeDeviceStoreValue, encodeDeviceStoreValue } from '../device-store/device-store-value-codec' @@ -39,6 +40,8 @@ type Row = { // Every read and write of the row runs in order, the load first. chain: Promise state: 'pending' | 'loaded' + // After a failed read, no hook or save reads again until then; the text stays in memory meanwhile. + retryReadAt: number // What the backend holds; undefined after a failed write, so the next save cannot match it. written: string | undefined timer: ReturnType | null @@ -47,6 +50,19 @@ type Row = { const rows = new Map() +// One retry per row at most this often, however many hooks open it or saves land. +const READ_RETRY_MS = 10_000 + +/** A value past the store's cap is refused and would leave an older value behind, so owners keep none instead. */ +export function fitsDeviceStore(value: unknown): boolean { + const json = JSON.stringify(value) + // At most 3 UTF-8 bytes per code unit, gzip barely grows any input, base64 adds a third: most values skip the encode. + if (json.length * 4 + 1024 <= DEVICE_STORE_MAX_VALUE_LENGTH) { + return true + } + return encodeDeviceStoreValue(value).length <= DEVICE_STORE_MAX_VALUE_LENGTH +} + // The store refuses keys past 512 characters; a long worktree path or id is hashed instead. const MAX_KEY_LENGTH = 512 @@ -58,6 +74,11 @@ function fnv1a(text: string, seed: number): string { return hash.toString(16).padStart(8, '0') } +/** A 64-bit fingerprint of `text`, for keys and for telling whether text a draft was typed against changed. */ +export function draftTextHash(text: string): string { + return `${fnv1a(text, 0x811c9dc5)}${fnv1a(text, 0x01000193)}` +} + /** `draft:::`; the shell binds the host. */ export function durableDraftRowKey(namespace: string, worktreeId: string, id: string): string { const key = `draft:${namespace}:${worktreeId}:${id}` @@ -65,7 +86,22 @@ export function durableDraftRowKey(namespace: string, worktreeId: string, id: st return key } const rest = `${worktreeId}:${id}` - return `draft:${namespace}:#${fnv1a(rest, 0x811c9dc5)}${fnv1a(rest, 0x01000193)}` + return `draft:${namespace}:#${draftTextHash(rest)}` +} + +/** The host and remote runtime a worktree lives on, so two hosts' same-named worktrees never share a draft. */ +export type WorkspaceDraftScope = { hostId: string; executionHost?: string; worktreeId: string } + +export function workspaceDraftRowKey( + namespace: string, + scope: WorkspaceDraftScope, + id: string +): string { + return durableDraftRowKey( + namespace, + scope.worktreeId, + `${scope.hostId}:${scope.executionHost ?? ''}:${id}` + ) } export function deviceStoreDraftBackend( @@ -115,14 +151,15 @@ function enqueue(row: Row, step: () => Promise): Promise { return row.chain } -async function load(row: Row): Promise { - if (row.state !== 'pending') { +async function load(row: Row, ignoreRetryWait = false): Promise { + if (row.state !== 'pending' || (!ignoreRetryWait && Date.now() < row.retryReadAt)) { return } row.backend ??= row.owner.backend() const read = await row.backend.read() if (!read.ok) { - // A dropped or refused read is retried, backend re-picked, at the next save; until then the text stays in memory. + // A dropped or refused read is retried later, backend re-picked; until then the text stays in memory. + row.retryReadAt = Date.now() + READ_RETRY_MS row.backend = null return } @@ -133,9 +170,11 @@ async function load(row: Row): Promise { } } -async function write(row: Row): Promise { - await load(row) +async function write(row: Row, hiding: boolean): Promise { + await load(row, hiding) if (row.state !== 'loaded' || !row.backend) { + // Still unread: save again once a read may be retried, so the text doesn't stay only in memory. + row.timer ??= setTimeout(() => flush(row), Math.max(0, row.retryReadAt - Date.now())) return } const value = row.owner.snapshot() ?? null @@ -149,12 +188,12 @@ async function write(row: Row): Promise { } } -function flush(row: Row): void { +function flush(row: Row, hiding = false): void { if (row.timer !== null) { clearTimeout(row.timer) row.timer = null } - void enqueue(row, () => write(row)) + void enqueue(row, () => write(row, hiding)) } // The app going to the background may be the last chance before it is killed, so pending typing saves then. @@ -164,7 +203,8 @@ function flushPendingOnHide(): void { } for (const row of rows.values()) { if (row.timer !== null) { - flush(row) + // Possibly the last chance before a kill, so a read waiting to be retried is tried now. + flush(row, true) } } } @@ -186,6 +226,7 @@ export function durableDraftRow(key: string, owner: DurableDraftRowOwner): Durab backend: null, chain: Promise.resolve(), state: 'pending', + retryReadAt: 0, written: undefined, timer: null, handle: { diff --git a/mobile/src/drafts/in-memory-device-store.test-support.ts b/mobile/src/drafts/in-memory-device-store.test-support.ts new file mode 100644 index 00000000000..eab27b59619 --- /dev/null +++ b/mobile/src/drafts/in-memory-device-store.test-support.ts @@ -0,0 +1,27 @@ +import { DEVICE_STORE_MAX_VALUE_LENGTH } from '../device-store/device-store-value-codec' +import { publishPageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' + +/** Grants the page a device store backed by `table`, which outlives the page and keeps the shell's value cap. */ +export function publishInMemoryDeviceStore(table: Map): void { + publishPageDeviceStore({ + available: () => true, + read: async (_table, keys) => ({ + status: 'ok', + values: keys.map((key) => table.get(key) ?? null) + }), + write: async (_table, ops) => { + // Like the shell, a value over the cap refuses the whole call. + if (ops.some((op) => (op.value?.length ?? 0) > DEVICE_STORE_MAX_VALUE_LENGTH)) { + return { written: false, refusal: 'too-large' } + } + for (const op of ops) { + if (op.value === null) { + table.delete(op.key) + } else { + table.set(op.key, op.value) + } + } + return { written: true } + } + }) +} diff --git a/mobile/src/drafts/use-document-edit-draft.test.tsx b/mobile/src/drafts/use-document-edit-draft.test.tsx index 166243c1603..a941c117bd4 100644 --- a/mobile/src/drafts/use-document-edit-draft.test.tsx +++ b/mobile/src/drafts/use-document-edit-draft.test.tsx @@ -2,6 +2,7 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { publishPageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' +import { publishInMemoryDeviceStore } from './in-memory-device-store.test-support' import { dropDocumentEditDraft, resetDocumentEditDraftsForTests } from './document-edit-draft-rows' import { useDocumentEditDraft } from './use-document-edit-draft' @@ -42,23 +43,7 @@ function kill(): void { beforeEach(() => { vi.useFakeTimers() - publishPageDeviceStore({ - available: () => true, - read: async (_table, keys) => ({ - status: 'ok', - values: keys.map((key) => table.get(key) ?? null) - }), - write: async (_table, ops) => { - for (const op of ops) { - if (op.value === null) { - table.delete(op.key) - } else { - table.set(op.key, op.value) - } - } - return { written: true } - } - }) + publishInMemoryDeviceStore(table) }) afterEach(() => { diff --git a/mobile/src/files/session-documents/MobileSessionFileReader.tsx b/mobile/src/files/session-documents/MobileSessionFileReader.tsx index 850c52c99a4..d87903a4fe1 100644 --- a/mobile/src/files/session-documents/MobileSessionFileReader.tsx +++ b/mobile/src/files/session-documents/MobileSessionFileReader.tsx @@ -35,6 +35,7 @@ import type { FileDocState, FileSyntaxState } from './session-document-state' import { DiffLineRow } from '../../source-control/review/MobileSessionDiffLineRow' import { sendableMobileDiffComments } from '../../source-control/review/mobile-diff-comments' import { MobileLoadErrorState, MobileStateView } from '../../components/MobileStateView' +import { useDurableDraftField } from '../../drafts/durable-draft-fields' type FileReaderProps = { doc: FileDocState | undefined @@ -44,6 +45,8 @@ type FileReaderProps = { documentId?: string language?: string diffCommentActions?: DiffCommentActions + // Where an unsaved note waits through leaving the file and the app being killed. + noteDraftKey?: string } export function FileReader(props: FileReaderProps) { @@ -58,7 +61,8 @@ function FileReaderDocument({ title, relativePath, language, - diffCommentActions + diffCommentActions, + noteDraftKey }: FileReaderProps) { useMobileColorScheme() const t = useMobileTranslation() @@ -69,7 +73,11 @@ function FileReaderDocument({ const [fileSyntax, setFileSyntax] = useState(null) const [diffSyntax, setDiffSyntax] = useState(null) const [activeCommentLine, setActiveCommentLine] = useState(null) - const [commentDraft, setCommentDraft] = useState('') + const [keptNote, setKeptNote] = useDurableDraftField(noteDraftKey ?? null, 'note') + const [localNote, setLocalNote] = useState('') + const [commentDraft, setCommentDraft] = noteDraftKey + ? [keptNote, setKeptNote] + : [localNote, setLocalNote] const plainDiffLines = useMemo( () => doc?.status === 'ready' && doc.kind === 'diff' @@ -105,10 +113,12 @@ function FileReaderDocument({ if (!diffCommentActions) { return } - void diffCommentActions.onAdd(relativePath, lineNumber, commentDraft).then((added) => { + const note = commentDraft + void diffCommentActions.onAdd(relativePath, lineNumber, note).then((added) => { if (added) { setActiveCommentLine(null) - setCommentDraft('') + // Only the saved text; a note typed since in a reopened reader stays. + setCommentDraft((current) => (current === note ? '' : current)) } }) }, diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index 11c0274f3a1..b54010f1322 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -1,5 +1,6 @@ import { useFocusEffect } from 'expo-router' import { useCallback, useState } from 'react' +import { useQueryClient } from '@tanstack/react-query' import { Alert, BackHandler, View } from 'react-native' import { GestureHandlerRootView } from 'react-native-gesture-handler' import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context' @@ -54,6 +55,7 @@ export function MobileHomeScreen() { const openMobileAccounts = useOpenMobileAccounts() const disconnectHostClient = useDisconnectHostClient() const forgetHostClient = useForgetHostClient() + const queryClient = useQueryClient() const forceReconnectHost = useForceReconnect() const [actionTarget, setActionTarget] = useState(null) const [confirmRemove, setConfirmRemove] = useState<{ id: string; name: string } | null>(null) @@ -128,7 +130,7 @@ export function MobileHomeScreen() { } const host = confirmRemove try { - await removeHostAndCloseClient(host.id, forgetHostClient) + await removeHostAndCloseClient(host.id, forgetHostClient, queryClient) setConfirmRemove(null) data.setHostCatalog(await loadHostCatalog()) } catch { diff --git a/mobile/src/home/MobileHomeTasksSection.tsx b/mobile/src/home/MobileHomeTasksSection.tsx index 36a0a535339..8df195fc8b7 100644 --- a/mobile/src/home/MobileHomeTasksSection.tsx +++ b/mobile/src/home/MobileHomeTasksSection.tsx @@ -1,3 +1,4 @@ +import { memo } from 'react' import { ChevronRight, ListTodo, type LucideIcon } from 'lucide-react-native' import { Pressable, Text, View } from 'react-native' import { useMobileTranslation } from '../i18n/use-mobile-translation' @@ -13,8 +14,16 @@ type HomeHostSectionProps = { onOpen: (hostId: string) => void } +// Home rebuilds its connected list on every connection tick; the same desktops draw the same section. +const sameSection = (previous: HomeHostSectionProps, next: HomeHostSectionProps): boolean => + previous.onOpen === next.onOpen && + previous.connectedHosts.length === next.connectedHosts.length && + previous.connectedHosts.every((host, at) => host === next.connectedHosts[at]) + /** Home's Tasks section, opening on a connected desktop. */ -export function MobileHomeTasksSection(props: HomeHostSectionProps) { +export const MobileHomeTasksSection = memo(function MobileHomeTasksSection( + props: HomeHostSectionProps +) { const t = useMobileTranslation() return ( ) -} +}, sameSection) function HomeSection( props: HomeHostSectionProps & { diff --git a/mobile/src/home/home-query-restore.ts b/mobile/src/home/home-query-restore.ts new file mode 100644 index 00000000000..67f3cda09b4 --- /dev/null +++ b/mobile/src/home/home-query-restore.ts @@ -0,0 +1,124 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import type { QueryClient } from '@tanstack/react-query' +import * as z from 'zod' +import { + HOST_LIST_TARGET, + homeWorktreeCountsKey, + NO_HOST_LIST_INPUT +} from '../host-screen/host-list-queries' +import { hostObserverOptions } from '../query/host-query' +import { accountsSnapshotFamily, accountsSnapshotKey } from '../accounts/accounts-snapshot-stream' +import { persistedHostQueryKey } from '../query/host-query-persistence' +import { keepNativeHostQueries, nativeQueryStoreReady } from '../query/native-query-persistence' +import { homeStatsKey, homeStatsQuery } from '../stats/home-stats-summary-read' +import { + homeWorktreeCountsQuery, + type HomeWorktreeCounts +} from '../worktree/home-host-worktree-fetch' + +// Where Home kept its counts before the device store: read once to seed the store, then removed. +const LEGACY_SNAPSHOT_KEY = 'orca:home-snapshot:v1' + +const legacySnapshotSchema = z.object({ + savedAt: z.number(), + worktreeInfo: z.record( + z.string(), + z.looseObject({ + totalWorktrees: z.number().int().nonnegative(), + activeCount: z.number().int().nonnegative(), + catalogUnavailable: z.boolean().optional(), + staleCounts: z.boolean().optional(), + countsProvenAt: z.number().optional() + }) + ) +}) + +type LegacySnapshot = z.infer + +// Null when there is no old key; an unreadable one seeds nothing and is removed all the same. +async function readLegacySnapshot(): Promise { + const raw = await AsyncStorage.getItem(LEGACY_SNAPSHOT_KEY).catch(() => null) + if (raw === null) { + return null + } + try { + const parsed = legacySnapshotSchema.safeParse(JSON.parse(raw)) + if (parsed.success) { + return parsed.data + } + } catch { + // Falls through to the empty seed. + } + return { savedAt: 0, worktreeInfo: {} } +} + +// Counts nothing stored yet answers; the old key goes once the store holds them. Without a store that can +// write (web, a key that won't load), the key waits for a later launch. +function seedFromLegacySnapshot( + queryClient: QueryClient, + snapshot: LegacySnapshot, + hostIds: readonly string[] +): void { + for (const hostId of hostIds) { + const info = snapshot.worktreeInfo[hostId] + const key = homeWorktreeCountsKey(hostId) + // Counts the old cache never proved are no seed. + if (!info || (info.catalogUnavailable && !info.staleCounts) || queryClient.getQueryData(key)) { + continue + } + const counts: HomeWorktreeCounts = { + totalWorktrees: info.totalWorktrees, + activeCount: info.activeCount, + agents: [] + } + // Built with the family's rules first: setQueryData alone makes a query the store never writes. + queryClient + .getQueryCache() + .build( + queryClient, + hostObserverOptions( + homeWorktreeCountsQuery, + null, + hostId, + HOST_LIST_TARGET, + NO_HOST_LIST_INPUT + ) + ) + queryClient.setQueryData(key, counts, { updatedAt: info.countsProvenAt ?? snapshot.savedAt }) + } + // Off the first paint's path: the seeded counts already show. + void Promise.all( + hostIds.map( + (hostId) => keepNativeHostQueries(queryClient, hostId)?.flush() ?? Promise.resolve() + ) + ).then(() => AsyncStorage.removeItem(LEGACY_SNAPSHOT_KEY).catch(() => undefined)) +} + +/** Restores the paired desktops' stored Home rows; resolves once each is applied or missed. */ +export async function restoreHomeQueries( + queryClient: QueryClient, + hostIds: readonly string[] +): Promise { + // Claimed synchronously, so observers mounting in the same commit join this one batched read. + const restored = Promise.all( + hostIds.map( + (hostId) => + keepNativeHostQueries(queryClient, hostId)?.restore( + [ + persistedHostQueryKey(homeStatsQuery, homeStatsKey(hostId)), + persistedHostQueryKey(homeWorktreeCountsQuery, homeWorktreeCountsKey(hostId)), + // Stored for the Accounts page; read here so Home's own observer doesn't read it alone. + persistedHostQueryKey(accountsSnapshotFamily, accountsSnapshotKey(hostId)) + ].filter((key) => key !== null) + ) ?? Promise.resolve() + ) + ) + const [storeReady, legacy] = await Promise.all([ + nativeQueryStoreReady(), + readLegacySnapshot(), + restored + ]) + if (storeReady && legacy) { + seedFromLegacySnapshot(queryClient, legacy, hostIds) + } +} diff --git a/mobile/src/home/use-home-spare-page.ts b/mobile/src/home/use-home-spare-page.ts index 58aa55953c6..14a883477e1 100644 --- a/mobile/src/home/use-home-spare-page.ts +++ b/mobile/src/home/use-home-spare-page.ts @@ -4,6 +4,7 @@ import { AppState } from 'react-native' import { setForegroundTimer } from '../mobile-web-shell/foreground-timer' import { enterHomeSparePage, + homeSpareRefillWaitMs, leaveHomeSparePage, prepareHomeSparePage } from '../mobile-web-shell/home-spare-page' @@ -29,7 +30,7 @@ export function useHomeSparePage(hostIds: readonly string[]): void { cancelTimer() cancelTimer = setForegroundTimer( () => void prepareHomeSparePage(processGenerationStore(), hosts.split(HOST_ID_SEPARATOR)), - HOME_SPARE_IDLE_MS + Math.max(HOME_SPARE_IDLE_MS, Math.ceil(homeSpareRefillWaitMs())) ) } arm() diff --git a/mobile/src/home/use-mobile-home-data.ts b/mobile/src/home/use-mobile-home-data.ts index d6e802a28b0..d61d920d04f 100644 --- a/mobile/src/home/use-mobile-home-data.ts +++ b/mobile/src/home/use-mobile-home-data.ts @@ -1,5 +1,12 @@ import { useRouter, useFocusEffect } from 'expo-router' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' +import { + notifyManager, + replaceEqualDeep, + useQueries, + useQueryClient, + type QueryObserverResult +} from '@tanstack/react-query' import { warmUpWebShell } from '../../modules/orca-mobile-web-shell/src' import { countAgentsNeedingYouByHost, @@ -7,9 +14,13 @@ import { type AgentListInput } from '../agents/agent-list-rows' import { useAgentActivityWrites } from '../agents/use-agent-activity-writes' -import { loadHomeSnapshot, saveHomeSnapshot } from '../cache/home-snapshot-cache' +import { accountsSnapshotOptions } from '../accounts/accounts-snapshot-stream' import type { AccountsSnapshot } from '../components/AccountUsage' -import { setCachedWorktrees } from '../cache/worktree-cache' +import { + HOST_LIST_TARGET, + homeWorktreeCountsKey, + NO_HOST_LIST_INPUT +} from '../host-screen/host-list-queries' import { useNow } from '../hooks/use-now' import { loadMobileOnboardingSteps, @@ -21,76 +32,146 @@ import { } from '../transport/hosts/host-catalog-selection' import { loadHostCatalog } from '../transport/hosts/host-store' import type { HostCatalogEntry } from '../transport/hosts/host-profile' -import { fetchHomeHostWorktreeInfo } from '../worktree/home-host-worktree-fetch' -import { withoutHomeAgentStates, type HostWorktreeInfo } from '../worktree/home-worktree-info' -import { fetchHomeHostStats } from '../stats/home-stats-summary-read' +import { hostObserverOptions, type HostQuery } from '../query/host-query' +import { isHostNotConnectedError } from '../query/host-query-errors' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { + homeWorktreeCountsQuery, + type HomeWorktreeCounts +} from '../worktree/home-host-worktree-fetch' +import { homeWorktreeInfo, type HostWorktreeInfo } from '../worktree/home-worktree-info' +import { homeStatsQuery } from '../stats/home-stats-summary-read' import { totalHomeStats, type HomeStatsRow } from '../stats/home-stats-total' import { projectHomeHostConnections } from './home-host-connection-projection' +import { restoreHomeQueries } from './home-query-restore' import { useMobileHomeHostConnections } from './use-mobile-home-host-connections' export type MobileHomeData = ReturnType +// A paired desktop with its client, or none while Home holds no connection to it (disconnected, never opened). +type HomeHost = { hostId: string; client: RpcClient | null } + +// Home reads one of each per paired desktop. Reads stay on while a desktop connects: the connected edge +// re-reads them the moment it lands, with no render in between, and a read tried before it is refused at once. +const homeQueryOptions = ( + query: HostQuery, + host: HomeHost +) => hostObserverOptions(query, host.client, host.hostId, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) + +const readOf = (result: QueryObserverResult) => ({ + data: result.data, + dataUpdatedAt: result.dataUpdatedAt, + // A read refused because the desktop isn't connected yet says nothing about its list. + failed: result.isError && !isHostNotConnectedError(result.error) +}) + export function useMobileHomeData() { const router = useRouter() + const queryClient = useQueryClient() const [hostCatalog, setHostCatalog] = useState([]) // Until the catalog read lands, an empty list says nothing; a paired user must not see first-run. const [hostCatalogLoaded, setHostCatalogLoaded] = useState(false) - const [worktreeInfo, setWorktreeInfo] = useState>({}) - const [statsByHost, setStatsByHost] = useState>({}) - const [accountsByHost, setAccountsByHost] = useState>({}) - const hostSetters = useMemo( - () => ({ setWorktreeInfo, setStats: setStatsByHost, setAccounts: setAccountsByHost }), - [] - ) const onboardingCheckedRef = useRef(false) - const hydratedRef = useRef(false) - const focusedRef = useRef(false) - const isHomeFocused = useCallback(() => focusedRef.current, []) - // Drives the agent clock; Home stays mounted under other screens. + // Drives the agent clock and Home's reads; Home stays mounted under other screens. const [homeFocused, setHomeFocused] = useState(false) const hosts = useMemo(() => selectConnectableHostProfiles(hostCatalog), [hostCatalog]) - const connections = useMobileHomeHostConnections(hosts, hostCatalog, hostSetters, isHomeFocused) - const allClientsRef = useRef(connections.allClients) + const connections = useMobileHomeHostConnections(hosts, hostCatalog) + const { allClients, hostLastConnected, hostStates } = connections + const allClientsRef = useRef(allClients) + // Every paired desktop keeps its last counts and totals on Home, connected or not. + const homeHosts = useMemo((): HomeHost[] => { + const clients = new Map(allClients.map((entry) => [entry.hostId, entry.client])) + return hosts.map((host) => ({ hostId: host.id, client: clients.get(host.id) ?? null })) + }, [hosts, allClients]) + // A read from before the desktop's latest connect, or from an earlier launch, can't vouch for agents or usage. + const isLive = useCallback( + (hostId: string, readAt: number): boolean => { + const connectedAt = hostLastConnected[hostId] + return connectedAt != null && readAt >= connectedAt + }, + [hostLastConnected] + ) + // Once the first desktop list is up: counts show only after a desktop connects, so the rows never wait + // for the store, and its keychain read doesn't compete with the list's. Before the queries below, whose + // observers then join this batched read instead of each reading its own row. + const storeRestoredRef = useRef(false) useEffect(() => { - if (hydratedRef.current) { + if (storeRestoredRef.current || hostCatalog.length === 0) { return } - hydratedRef.current = true - let cancelled = false - void loadHomeSnapshot().then((snapshot) => { - if (cancelled || !snapshot) { - return - } - setWorktreeInfo((previous) => - Object.keys(previous).length > 0 - ? previous - : Object.fromEntries( - Object.entries(snapshot.worktreeInfo).map(([hostId, info]) => [ - hostId, - withoutHomeAgentStates(info) - ]) - ) - ) - for (const [hostId, info] of Object.entries(snapshot.worktreeInfo)) { - if (info.lastActiveWorktree) { - setCachedWorktrees(hostId, [info.lastActiveWorktree]) - } - } - }) - return () => { - cancelled = true - } - }, []) + storeRestoredRef.current = true + void restoreHomeQueries( + queryClient, + hostCatalog.map((host) => host.id) + ) + }, [hostCatalog, queryClient]) - useEffect(() => { - if (Object.keys(worktreeInfo).length > 0) { - const saved = Object.fromEntries( - Object.entries(worktreeInfo).map(([hostId, info]) => [hostId, withoutHomeAgentStates(info)]) - ) - saveHomeSnapshot({ worktreeInfo: saved, savedAt: Date.now() }) - } - }, [worktreeInfo]) + const countsQueries = useMemo( + () => homeHosts.map((host) => homeQueryOptions(homeWorktreeCountsQuery, host)), + [homeHosts] + ) + const combineCounts = useCallback( + (results: QueryObserverResult[]): Record => { + const byHost: Record = {} + homeHosts.forEach(({ hostId }, at) => { + const result = results[at] + const info = result && homeWorktreeInfo(hostId, readOf(result), isLive) + if (info) { + byHost[hostId] = info + } + }) + return byHost + }, + [homeHosts, isLive] + ) + // A hidden Home reads nothing; coming back reads what went stale meanwhile. + const worktreeInfo = useQueries({ + queries: countsQueries, + combine: combineCounts, + subscribed: homeFocused + }) + const statsQueries = useMemo( + () => homeHosts.map((host) => homeQueryOptions(homeStatsQuery, host)), + [homeHosts] + ) + const combineStats = useCallback( + (results: QueryObserverResult[]): Record => + Object.fromEntries(homeHosts.map(({ hostId }, at) => [hostId, results[at]?.data])), + [homeHosts] + ) + const statsByHost = useQueries({ + queries: statsQueries, + combine: combineStats, + subscribed: homeFocused + }) + const accountsQueries = useMemo( + () => homeHosts.map(({ hostId }) => accountsSnapshotOptions(hostId)), + [homeHosts] + ) + // Usage is live: only a snapshot from this connection shows, never a stored or disconnected one. + const combineAccounts = useCallback( + (results: QueryObserverResult[]): Record => { + const byHost: Record = {} + homeHosts.forEach(({ hostId }, at) => { + const result = results[at] + if ( + result?.data && + hostStates[hostId] === 'connected' && + isLive(hostId, result.dataUpdatedAt) + ) { + byHost[hostId] = result.data + } + }) + return byHost + }, + [homeHosts, hostStates, isLive] + ) + const accountsByHost = useQueries({ + queries: accountsQueries, + combine: combineAccounts, + subscribed: homeFocused + }) const hasPairedHost = hosts.length > 0 useEffect(() => { @@ -100,13 +181,12 @@ export function useMobileHomeData() { }, [hasPairedHost]) useEffect(() => { - allClientsRef.current = connections.allClients - }, [connections.allClients]) + allClientsRef.current = allClients + }, [allClients]) useFocusEffect( useCallback(() => { let stale = false - focusedRef.current = true setHomeFocused(true) void loadHostCatalog() // A failed read proves nothing about the desktops; keep the ones already shown. @@ -119,7 +199,8 @@ export function useMobileHomeData() { if (!catalog) { return } - setHostCatalog(catalog) + // An unchanged list keeps its identity, so focusing Home again redraws nothing. + setHostCatalog((previous) => replaceEqualDeep(previous, catalog)) if (catalog.length === 0 || onboardingCheckedRef.current) { return } @@ -129,15 +210,8 @@ export function useMobileHomeData() { router.replace(mobileOnboardingDestination(steps)) } }) - for (const entry of allClientsRef.current) { - if (entry.client.getState() === 'connected') { - void fetchHomeHostWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => stale) - fetchHomeHostStats(entry.client, entry.hostId, setStatsByHost, () => stale) - } - } return () => { stale = true - focusedRef.current = false setHomeFocused(false) } }, [router]) @@ -147,23 +221,36 @@ export function useMobileHomeData() { const sortedHostCatalog = useMemo(() => sortHostsByLastConnected(hostCatalog), [hostCatalog]) // One clock for every agent count, so Feed, the Agents badge and each desktop agree. const now = useNow(30_000, homeFocused) - const refetchHostAgents = useCallback((hostId: string) => { - const entry = allClientsRef.current.find((candidate) => candidate.hostId === hostId) - return entry?.client.getState() === 'connected' - ? fetchHomeHostWorktreeInfo(entry.client, hostId, setWorktreeInfo, () => false) - : Promise.resolve() - }, []) - const agentActivity = useAgentActivityWrites(connections.allClients, refetchHostAgents) + // A fresh read, not one already out: that one may predate the write it must carry. The cached rows stay + // its delta base, so the desktop answers with only what changed. + const refetchHostAgents = useCallback( + async (hostId: string): Promise => { + const entry = allClientsRef.current.find((candidate) => candidate.hostId === hostId) + if (entry?.client.getState() !== 'connected') { + return + } + await queryClient + .refetchQueries( + { queryKey: homeWorktreeCountsKey(hostId), exact: true }, + { cancelRefetch: true, throwOnError: false } + ) + .catch(() => undefined) + // Resolves once observers hold the answer, so the write's guess isn't dropped a frame early. + await new Promise((resolve) => notifyManager.schedule(resolve)) + }, + [queryClient] + ) + const agentActivity = useAgentActivityWrites(allClients, refetchHostAgents) const { pendingActivity } = agentActivity const agentList = useMemo( () => ({ hosts: sortedHosts, - hostStates: connections.hostStates, + hostStates, worktreeInfo, now, pendingActivity }), - [sortedHosts, connections.hostStates, worktreeInfo, now, pendingActivity] + [sortedHosts, hostStates, worktreeInfo, now, pendingActivity] ) const agentsNeedingYou = useMemo(() => selectAgentsNeedingYou(agentList), [agentList]) const needsYouByHost = useMemo( @@ -171,20 +258,17 @@ export function useMobileHomeData() { [agentsNeedingYou] ) const connectedHosts = useMemo( - () => sortedHosts.filter((host) => connections.hostStates[host.id] === 'connected'), - [sortedHosts, connections.hostStates] + () => sortedHosts.filter((host) => hostStates[host.id] === 'connected'), + [sortedHosts, hostStates] ) // Before a desktop's first connect settles, "not connected" is not yet true. const hostsConnecting = hosts.some((host) => { - const state = connections.hostStates[host.id] + const state = hostStates[host.id] return state === undefined || state === 'connecting' || state === 'handshaking' }) const hostIds = useMemo(() => hosts.map((host) => host.id), [hosts]) const stats = useMemo(() => totalHomeStats(statsByHost, hostIds), [statsByHost, hostIds]) - const hostConnections = useMemo( - () => projectHomeHostConnections(connections.allClients), - [connections.allClients] - ) + const hostConnections = useMemo(() => projectHomeHostConnections(allClients), [allClients]) return { ...connections, diff --git a/mobile/src/home/use-mobile-home-host-connections.ts b/mobile/src/home/use-mobile-home-host-connections.ts index e10689a2c98..11b26c25c46 100644 --- a/mobile/src/home/use-mobile-home-host-connections.ts +++ b/mobile/src/home/use-mobile-home-host-connections.ts @@ -1,147 +1,70 @@ import { useEffect, useMemo, useRef, useState } from 'react' -import { subscribeAccountsSnapshots } from '../accounts/accounts-snapshot-stream' -import type { AccountsSnapshot } from '../components/AccountUsage' +import { useQueryClient, type QueryClient } from '@tanstack/react-query' +import { + accountsSnapshotKey, + subscribeAccountsSnapshots +} from '../accounts/accounts-snapshot-stream' import { subscribeToDesktopNotifications } from '../notifications/mobile-notifications' +import { retainHostConnectionInvalidation } from '../query/host-connection-invalidation' +import { retainHostEventRouter } from '../query/host-event-router' +import { keepNativeHostQueries } from '../query/native-query-persistence' import { usePrimeHosts } from '../transport/connection/host-client-hooks' -import { createHostConnectRefetchGate } from '../transport/hosts/host-connect-refetch-gate' import { selectHomeAutoConnectHostIds } from '../transport/hosts/home-host-auto-connect' import type { RpcClient } from '../transport/rpc/rpc-client-contract' -import { subscribeSharedClientEvents } from '../transport/connection/shared-client-events' import type { ConnectionState } from '../transport/connection/connection-state' import type { HostCatalogEntry, HostProfile } from '../transport/hosts/host-profile' import { useAllHostClients } from '../transport/connection/use-all-host-clients' -import { - fetchHomeHostWorktreeInfo, - type HostWorktreeInfoSetter -} from '../worktree/home-host-worktree-fetch' -import { withLastSeenHomeAgents } from '../worktree/home-worktree-info' -import { fetchHomeHostStats, type HomeStatsSetter } from '../stats/home-stats-summary-read' import { readMobileHomeLastConnected, readMobileHomeReconnectAttempts, reconcileMobileHomeHostStates } from './mobile-home-connection-state' -// Same pace as the workspace list's poll; agent status notices can arrive many times a second. -const HOME_WORKTREE_REFRESH_MIN_INTERVAL_MS = 3000 -const WORKTREE_CHANGE_EVENTS: ReadonlySet = new Set([ - 'sidebarInputsChanged', - 'worktreesChanged', - 'reposChanged', - // The desktop Agents list changed; worktree.ps carries its verdicts. - 'agentListChanged', - // Agent status changes on hosts without the sidebar feed (worktree.rows-changed-event.v1). - 'worktreeRowsChanged' -]) - -export type HomeAccountsSetter = ( - updater: (previous: Record) => Record -) => void - -export type MobileHomeHostSetters = { - setWorktreeInfo: HostWorktreeInfoSetter - setStats: HomeStatsSetter - setAccounts: HomeAccountsSetter -} - +// Home's per-desktop reads (counts, stats) are queries; this wires what a connection carries besides them. function wireMobileHomeHostSubscriptions( - entry: { hostId: string; client: RpcClient; state: ConnectionState }, - setters: MobileHomeHostSetters, - isHomeFocused: () => boolean + entry: { hostId: string; client: RpcClient }, + queryClient: QueryClient ): () => void { - const { setWorktreeInfo, setStats, setAccounts } = setters + const { hostId, client } = entry + keepNativeHostQueries(queryClient, hostId) + // Reads Home's queries again on each reconnect, and on the desktop's change notices. + const stopInvalidation = retainHostConnectionInvalidation(queryClient, hostId, client) + const router = retainHostEventRouter(queryClient, hostId, client) let unsubscribeNotifications: (() => void) | null = null - let unsubscribeClientEvents: (() => void) | null = null let unsubscribeAccounts: (() => void) | null = null - let lastRefreshAt = 0 - let trailingRefresh: ReturnType | null = null - const refetchGate = createHostConnectRefetchGate() - const refreshWorktrees = (): void => { - lastRefreshAt = Date.now() - void fetchHomeHostWorktreeInfo(entry.client, entry.hostId, setWorktreeInfo, () => false) - } - // Home stays mounted under other screens; focusing it again re-reads every desktop anyway. - const refreshOnChange = (): void => { - if (!isHomeFocused() || trailingRefresh) { - return - } - const wait = lastRefreshAt + HOME_WORKTREE_REFRESH_MIN_INTERVAL_MS - Date.now() - if (wait <= 0) { - refreshWorktrees() - return - } - trailingRefresh = setTimeout(() => { - trailingRefresh = null - if (isHomeFocused()) { - refreshWorktrees() - } - }, wait) - } const wireState = (state: ConnectionState): void => { - const reconnected = refetchGate.observe(state) if (state === 'connected') { - unsubscribeNotifications ??= subscribeToDesktopNotifications(entry.client, entry.hostId) - unsubscribeClientEvents ??= subscribeSharedClientEvents(entry.client, (event) => { - // A replayed ready follows a reopened stream or path switch, which missed notices. - if (WORKTREE_CHANGE_EVENTS.has(event.type) || 'replayed' in event) { - refreshOnChange() - } - }) + unsubscribeNotifications ??= subscribeToDesktopNotifications(client, hostId) // One stream per connection: each subscribe makes the desktop check usage, so focus must not resubscribe. - unsubscribeAccounts ??= subscribeAccountsSnapshots(entry.client, { - onSnapshot: (snapshot) => - setAccounts((previous) => ({ ...previous, [entry.hostId]: snapshot })), - onInvalidSnapshot: () => setAccounts((previous) => withoutHost(previous, entry.hostId)), + unsubscribeAccounts ??= subscribeAccountsSnapshots(client, { + onSnapshot: (snapshot) => queryClient.setQueryData(accountsSnapshotKey(hostId), snapshot), + onInvalidSnapshot: () => queryClient.setQueryData(accountsSnapshotKey(hostId), null), onStreamError: () => {} }) - if (reconnected) { - refreshWorktrees() - fetchHomeHostStats(entry.client, entry.hostId, setStats, () => false) - } return } unsubscribeNotifications?.() unsubscribeNotifications = null - unsubscribeClientEvents?.() - unsubscribeClientEvents = null unsubscribeAccounts?.() unsubscribeAccounts = null - // Usage is live; a disconnected desktop's last numbers would read as current. - setAccounts((previous) => withoutHost(previous, entry.hostId)) - // Agents keep moving while we're away; only the reconnect read may show their states again. - setWorktreeInfo((previous) => { - const current = previous[entry.hostId] - const next = current && withLastSeenHomeAgents(current) - return next === current ? previous : { ...previous, [entry.hostId]: next } - }) } - wireState(entry.state) - const unsubscribeState = entry.client.onStateChange(wireState) + // The live state: the client may have connected since the render that listed it. + wireState(client.getState()) + const unsubscribeState = client.onStateChange(wireState) return () => { unsubscribeState() unsubscribeNotifications?.() - unsubscribeClientEvents?.() unsubscribeAccounts?.() - if (trailingRefresh) { - clearTimeout(trailingRefresh) - } + router.release() + stopInvalidation() } } -function withoutHost(byHost: Record, hostId: string): Record { - if (!(hostId in byHost)) { - return byHost - } - const { [hostId]: _removed, ...rest } = byHost - return rest -} - export function useMobileHomeHostConnections( hosts: HostProfile[], - hostCatalog: HostCatalogEntry[], - setters: MobileHomeHostSetters, - isHomeFocused: () => boolean + hostCatalog: HostCatalogEntry[] ) { + const queryClient = useQueryClient() const [hostStates, setHostStates] = useState>({}) const [hostAttempts, setHostAttempts] = useState>({}) const [hostLastConnected, setHostLastConnected] = useState>({}) @@ -184,11 +107,11 @@ export function useMobileHomeHostConnections( if (!subscriptionsRef.current.has(entry.hostId)) { subscriptionsRef.current.set(entry.hostId, { client: entry.client, - cleanup: wireMobileHomeHostSubscriptions(entry, setters, isHomeFocused) + cleanup: wireMobileHomeHostSubscriptions(entry, queryClient) }) } } - }, [allClients, isHomeFocused, setters]) + }, [allClients, queryClient]) useEffect(() => { const subscriptions = subscriptionsRef.current diff --git a/mobile/src/hooks/mobile-dictation-audio-chunk.ts b/mobile/src/hooks/mobile-dictation-audio-chunk.ts index c9a18b0d721..524c11ec299 100644 --- a/mobile/src/hooks/mobile-dictation-audio-chunk.ts +++ b/mobile/src/hooks/mobile-dictation-audio-chunk.ts @@ -20,6 +20,7 @@ import type { } from '../platform/dictation-capture-contract' import type { MobileDictationPendingAudioBudget } from './mobile-dictation-pending-audio-budget' import type { MobileDictationHeldAudio } from './mobile-dictation-held-audio' +import type { MobileDictationRecording } from './mobile-dictation-recording' import type { RpcClient } from '../transport/rpc/rpc-client-contract' import type { MobileDictationRun } from './mobile-dictation-engine-run' @@ -35,7 +36,7 @@ type MobileDictationAudioChunkQueue = { stopAtAudioLimit: () => void } -// Holding: the microphone runs from the tap while the host's start reply is pending, or for a whole on-device dictation. +// Holding: the microphone runs from the tap while the host's start reply is pending, or while a replay's host start is. export type MobileDictationAudioPhase = 'closed' | 'holding' | 'sending' // Newer hosts report the text so far: shown while speaking, and handed over by a failure instead of dropped. @@ -122,6 +123,7 @@ export function useMobileDictationAudioChunks(capture: DictationCapture, run: Mo failActiveDictation: run.failActiveDictation, transcriptSoFar: run.keptTranscript, heldAudio: run.heldAudio.current, + recording: run.recording.current, // Like desktop: stop as the user would, so what the host kept is transcribed and inserted. stopAtAudioLimit: () => { if (run.status.current === 'recording') { @@ -142,7 +144,7 @@ export function subscribeMobileDictationAudioChunks( getActiveId: () => string | null audioPhase: () => MobileDictationAudioPhase }, - queue: Omit + queue: Omit & { recording: MobileDictationRecording } ): { remove: () => void; sendHeld: () => void } { // Reuse wiring on the microphone hot path instead of allocating per chunk. const chunkQueue = { ...queue, isActive: (id: string) => source.getActiveId() === id } @@ -159,11 +161,15 @@ export function subscribeMobileDictationAudioChunks( } const subscription = capture.onChunk((chunk) => { const dictationId = source.getActiveId() + if (!dictationId) { + return + } + // Kept whatever the phase, so a phone's failure or a failed send can play it to the computer again. + queue.recording.keep(chunk) const phase = source.audioPhase() - if (!dictationId || phase === 'closed') { + if (phase === 'closed') { return } - // An on-device dictation holds its audio with no computer at all. if (phase === 'holding') { queue.heldAudio.hold(chunk) return diff --git a/mobile/src/hooks/mobile-dictation-desktop-start.ts b/mobile/src/hooks/mobile-dictation-desktop-start.ts index 2b6b28cdf0c..1086409ea5c 100644 --- a/mobile/src/hooks/mobile-dictation-desktop-start.ts +++ b/mobile/src/hooks/mobile-dictation-desktop-start.ts @@ -15,6 +15,7 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract' type StartMobileDictationDesktopSessionOptions = { client: RpcClient dictationId: string + worktreeId?: string generation: number getCurrentGeneration: () => number getEnabled: () => boolean @@ -102,7 +103,7 @@ export function startMobileDictationDesktopSession( } async function startOnHost(options: StartMobileDictationDesktopSessionOptions): Promise { - const { client, dictationId } = options + const { client, dictationId, worktreeId } = options let hostDedupesResends = false try { @@ -111,7 +112,7 @@ async function startOnHost(options: StartMobileDictationDesktopSessionOptions): client, dictationSessionStart.request( client, - { dictationId }, + { dictationId, ...(worktreeId ? { worktreeId } : {}) }, { timeoutMs: MOBILE_DICTATION_RECONNECT_GRACE_MS } ) ).catch(() => { diff --git a/mobile/src/hooks/mobile-dictation-engine-run.ts b/mobile/src/hooks/mobile-dictation-engine-run.ts index 5abe593ec17..b61d5390e51 100644 --- a/mobile/src/hooks/mobile-dictation-engine-run.ts +++ b/mobile/src/hooks/mobile-dictation-engine-run.ts @@ -9,11 +9,7 @@ import type { MobileDictationAudioPhase, MobileDictationTranscriptSoFar } from './mobile-dictation-audio-chunk' -import { - cancelDesktopDictation, - settledDesktopDictationWork, - startMobileDictationDesktopSession -} from './mobile-dictation-desktop-start' +import { cancelDesktopDictation } from './mobile-dictation-desktop-start' import { chooseMobileDictationRoute, phoneDictationBusyMessage, @@ -26,6 +22,11 @@ import { } from './mobile-dictation-device-engine' import type { MobileDictationPendingAudioBudget } from './mobile-dictation-pending-audio-budget' import type { MobileDictationHeldAudio } from './mobile-dictation-held-audio' +import type { MobileDictationRecording } from './mobile-dictation-recording' +import { + replayMobileDictationToHost, + startMobileDictationOnHost +} from './mobile-dictation-host-start' import type { ShowMobileDictationEngine } from './mobile-dictation-engine-shown' // What the engines share with useMobileDictation: its refs (read at call time) and its state transitions. @@ -42,15 +43,19 @@ export type MobileDictationRun = { readonly pendingChunks: RefObject>> readonly pendingAudioBudget: RefObject readonly heldAudio: RefObject + readonly recording: RefObject readonly sendHeldAudio: RefObject<() => void> readonly finish: RefObject<(emptyTranscriptMessage: string) => Promise> readonly onTranscript: RefObject<(text: string) => void> readonly onAudioLimitReached: RefObject<(() => void) | undefined> + readonly worktreeId: RefObject readonly keptTranscript: MobileDictationTranscriptSoFar - readonly applyStatus: (next: DictationStatus) => void + // keepText: leave the words so far on screen (recording, finishing, or a failure kept for Retry). + readonly applyStatus: (next: DictationStatus, keepText?: boolean) => void readonly showEngine: ShowMobileDictationEngine readonly closeDictationAudio: () => void - readonly reportError: (err: unknown) => void + // kept: the recording stays for Retry, the words so far stay shown, and nothing is inserted yet. + readonly reportError: (err: unknown, kept?: boolean) => void readonly failActiveDictation: (dictationId: string, err: unknown) => void } @@ -80,6 +85,7 @@ export function settleMobileDictation( run.engine.current = { kind: 'host' } run.audioPhase.current = 'closed' run.heldAudio.current.clear() + run.recording.current.clear() run.pendingChunks.current.clear() run.pendingAudioBudget.current.reset() run.applyStatus('idle') @@ -90,48 +96,7 @@ export function settleMobileDictation( } } -export async function startMobileDictationOnHost( - run: MobileDictationRun, - client: RpcClient, - dictationId: string, - generation: number -): Promise { - await settledDesktopDictationWork(client) - if (run.generation.current !== generation) { - return - } - await startMobileDictationDesktopSession({ - client, - dictationId, - generation, - getCurrentGeneration: () => run.generation.current, - getEnabled: () => run.enabled.current, - getActiveId: () => run.activeId.current, - clearActiveId: (id) => { - if (run.activeId.current === id) { - run.activeId.current = null - } - }, - setIdle: () => run.applyStatus('idle'), - commitRecordingStart: (hostDedupesResends) => { - run.audioPhase.current = 'sending' - run.pendingChunks.current.clear() - run.pendingAudioBudget.current.reset(hostDedupesResends) - // A phone dictation stopped or failed at finish is already processing; it never records again. - if (run.status.current !== 'processing') { - run.applyStatus('recording') - } - run.showEngine('computer') - run.sendHeldAudio.current() - if (run.stopWhenStarted.current) { - void run.finish.current(dictationSessionErrorMessage('no-speech')) - } - }, - rollbackRecordingStart: run.closeDictationAudio - }) -} - -// The phone's recognizer failed: replay the audio it kept to the computer, as a start's held audio (seq from 0), and carry on there. +// The phone's recognizer failed: replay the recording to the computer, as a start's held audio (seq from 0), and carry on there. export async function fallBackMobileDictationToHost( run: MobileDictationRun, dictationId: string, @@ -149,25 +114,15 @@ export async function fallBackMobileDictationToHost( !engine.fallback || !client || client.getState() !== 'connected' || - !run.heldAudio.current.complete + !run.recording.current.complete ) { run.failActiveDictation(dictationId, new Error(phoneDictationFailedMessage())) return } - run.engine.current = { kind: 'host' } run.showEngine('computer', true) // A stop that began while the phone was still live is already processing; the computer must finish it too. run.stopWhenStarted.current = finishing || run.status.current === 'processing' - try { - await startMobileDictationOnHost(run, client, dictationId, run.generation.current) - } catch (err) { - // The host start already released the mic and the dictation; keep what the phone heard. - const kept = run.keptTranscript.take(dictationId) - if (kept) { - run.onTranscript.current(kept) - } - run.reportError(err) - } + await replayMobileDictationToHost(run, client, dictationId, run.generation.current) } // Pick the engine before the mic opens, and arm the phone's recognizer so it hears the first word. @@ -229,10 +184,9 @@ export function commitMobileDictationOnDevice( () => void fallBackMobileDictationToHost(run, dictationId, false) ) } - // This phone never replays to the computer, so it keeps no audio. - if (!fallback) { - run.audioPhase.current = 'closed' - } + // The recording keeps the phone's audio for a replay; nothing goes to the computer while the phone hears it. + run.audioPhase.current = 'closed' + run.heldAudio.current.clear() run.applyStatus('recording') run.showEngine('phone') if (run.stopWhenStarted.current) { diff --git a/mobile/src/hooks/mobile-dictation-failure.ts b/mobile/src/hooks/mobile-dictation-failure.ts new file mode 100644 index 00000000000..99ba7a258fa --- /dev/null +++ b/mobile/src/hooks/mobile-dictation-failure.ts @@ -0,0 +1,44 @@ +import { errorMessage } from '../../../src/shared/error-message' +import { + isDictationSetupRequiredError, + isSpeechlessServerError +} from '../dictation/mobile-dictation-setup' +import type { MobileDictationEngine } from './mobile-dictation-device-engine' +import type { MobileDictationRecording } from './mobile-dictation-recording' +import type { MobileDictationRun } from './mobile-dictation-engine-run' + +// Retry plays the recording to the computer, so it needs the whole recording and an engine that may use the computer (not This phone). +export function mobileDictationFailureRetryable( + recording: MobileDictationRecording, + engine: MobileDictationEngine +): boolean { + return recording.complete && recording.bytes > 0 && (engine.kind === 'host' || engine.fallback) +} + +// A computer that needs setup or an update refuses every Retry the same way; those keep today's path (words inserted, setup sheet or toast). +function retryCanSucceed(err: unknown): boolean { + const message = errorMessage(err) + return !isDictationSetupRequiredError(message) && !isSpeechlessServerError(message) +} + +// Never lose speech quietly: a retryable failure keeps the recording and the words so far for Retry; otherwise the words so far are inserted, as before. +export function concludeMobileDictationFailure( + run: Pick< + MobileDictationRun, + 'recording' | 'engine' | 'keptTranscript' | 'onTranscript' | 'reportError' + >, + dictationId: string, + err: unknown, + retryable = mobileDictationFailureRetryable(run.recording.current, run.engine.current) +): void { + if (retryable && retryCanSucceed(err)) { + run.reportError(err, true) + return + } + run.recording.current.clear() + const kept = run.keptTranscript.take(dictationId) + if (kept) { + run.onTranscript.current(kept) + } + run.reportError(err) +} diff --git a/mobile/src/hooks/mobile-dictation-finish.ts b/mobile/src/hooks/mobile-dictation-finish.ts new file mode 100644 index 00000000000..c676c3de41f --- /dev/null +++ b/mobile/src/hooks/mobile-dictation-finish.ts @@ -0,0 +1,77 @@ +import { rpcPayloadMember } from '../transport/rpc/rpc-reader-payload' +import type { DictationCapture } from '../platform/dictation-capture-contract' +import { isCurrentMobileDictationFinish } from './mobile-dictation-session-state' +import { finishDesktopDictation } from './mobile-dictation-desktop-start' +import { + finishMobileDictationOnDevice, + settleMobileDictation, + type MobileDictationRun +} from './mobile-dictation-engine-run' + +// Stop listening and settle the dictation with its final text, from whichever engine heard it. +export async function finishMobileDictation( + run: MobileDictationRun, + capture: Pick, + emptyTranscriptMessage: string +): Promise { + const client = run.client.current + const dictationId = run.activeId.current + const engine = run.engine.current + if (!dictationId || (engine.kind === 'host' && !client)) { + return + } + // A replay's host start is still pending: finish once it commits and the kept audio has gone. + if (engine.kind === 'host' && run.audioPhase.current === 'holding') { + run.stopWhenStarted.current = true + if (run.status.current === 'recording') { + run.applyStatus('processing') + // Stop listening now; the tail joins the held audio the replay sends. + void capture.end() + } + return + } + + const generation = run.generation.current + 1 + run.generation.current = generation + run.applyStatus('processing') + const isCurrent = () => + isCurrentMobileDictationFinish( + run.generation.current, + generation, + run.enabled.current, + run.activeId.current, + dictationId + ) + try { + // Keep shutdown inside try for finally cleanup; accept its tail chunks and snapshot pending sends only after end settles, or finish can overtake the last audio. + await capture.end() + if (engine.kind === 'device') { + await finishMobileDictationOnDevice( + run, + engine, + dictationId, + emptyTranscriptMessage, + isCurrent + ) + return + } + run.audioPhase.current = 'closed' + await Promise.allSettled(Array.from(run.pendingChunks.current)) + if (!isCurrent() || !client) { + return + } + const sentSeconds = run.pendingAudioBudget.current.sentAudioSeconds + const finished = await finishDesktopDictation(client, dictationId, sentSeconds) + if (!isCurrent()) { + return + } + const transcript = rpcPayloadMember(finished, 'text') + settleMobileDictation( + run, + typeof transcript === 'string' ? transcript.trim() : '', + emptyTranscriptMessage + ) + } catch (err) { + run.failActiveDictation(dictationId, err) + } +} diff --git a/mobile/src/hooks/mobile-dictation-held-audio.ts b/mobile/src/hooks/mobile-dictation-held-audio.ts index 3e57dfad7d7..21e142a5683 100644 --- a/mobile/src/hooks/mobile-dictation-held-audio.ts +++ b/mobile/src/hooks/mobile-dictation-held-audio.ts @@ -5,10 +5,10 @@ import { } from '../../../src/shared/rpc-contract/speech-params' import type { DictationCaptureChunk } from '../platform/dictation-capture-contract' -// Five minutes of 16 kHz PCM (9.6 MB): what an on-device dictation keeps to replay to the computer if the phone fails. -const MAX_HELD_AUDIO_BYTES = DICTATION_SAMPLE_RATE * PCM_BYTES_PER_SAMPLE * 300 +// Five minutes of 16 kHz PCM (9.6 MB): the longest recording kept for a replay to the computer. +export const MAX_HELD_AUDIO_BYTES = DICTATION_SAMPLE_RATE * PCM_BYTES_PER_SAMPLE * 300 -// Speech not sent yet, in order: held between the tap and the host's start reply, while every send slot is busy, and for a whole on-device dictation. +// Speech not sent yet, in order: held between the tap and the host's start reply, while every send slot is busy, and for a replay of the recording. export class MobileDictationHeldAudio { private held: DictationCaptureChunk[] = [] private heldBytes = 0 diff --git a/mobile/src/hooks/mobile-dictation-host-start.ts b/mobile/src/hooks/mobile-dictation-host-start.ts new file mode 100644 index 00000000000..fc9898e3fa0 --- /dev/null +++ b/mobile/src/hooks/mobile-dictation-host-start.ts @@ -0,0 +1,70 @@ +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { dictationSessionErrorMessage } from '../dictation/mobile-dictation-setup' +import { + settledDesktopDictationWork, + startMobileDictationDesktopSession +} from './mobile-dictation-desktop-start' +import { concludeMobileDictationFailure } from './mobile-dictation-failure' +import type { MobileDictationRun } from './mobile-dictation-engine-run' + +export async function startMobileDictationOnHost( + run: MobileDictationRun, + client: RpcClient, + dictationId: string, + generation: number, + // A replay (fallback or Retry) keeps the words so far on screen if its start fails. + replay = false +): Promise { + await settledDesktopDictationWork(client) + if (run.generation.current !== generation) { + return + } + await startMobileDictationDesktopSession({ + client, + dictationId, + worktreeId: run.worktreeId.current, + generation, + getCurrentGeneration: () => run.generation.current, + getEnabled: () => run.enabled.current, + getActiveId: () => run.activeId.current, + clearActiveId: (id) => { + if (run.activeId.current === id) { + run.activeId.current = null + } + }, + setIdle: () => run.applyStatus('idle', replay), + commitRecordingStart: (hostDedupesResends) => { + run.audioPhase.current = 'sending' + run.pendingChunks.current.clear() + run.pendingAudioBudget.current.reset(hostDedupesResends) + // A phone dictation stopped or failed at finish is already processing; it never records again. + if (run.status.current !== 'processing') { + run.applyStatus('recording') + } + run.showEngine('computer') + run.sendHeldAudio.current() + if (run.stopWhenStarted.current) { + void run.finish.current(dictationSessionErrorMessage('no-speech')) + } + }, + rollbackRecordingStart: run.closeDictationAudio + }) +} + +// Play the kept recording to the computer as this dictation's held audio (seq from 0); audio heard after joins it in order until the start commits. +// Fallback and Retry both end here; a failed start keeps the recording for Retry. +export async function replayMobileDictationToHost( + run: MobileDictationRun, + client: RpcClient, + dictationId: string, + generation: number +): Promise { + run.engine.current = { kind: 'host' } + run.recording.current.replayInto(run.heldAudio.current) + run.audioPhase.current = 'holding' + try { + await startMobileDictationOnHost(run, client, dictationId, generation, true) + } catch (err) { + concludeMobileDictationFailure(run, dictationId, err) + } +} diff --git a/mobile/src/hooks/mobile-dictation-recording.ts b/mobile/src/hooks/mobile-dictation-recording.ts new file mode 100644 index 00000000000..872c6231794 --- /dev/null +++ b/mobile/src/hooks/mobile-dictation-recording.ts @@ -0,0 +1,47 @@ +import type { DictationCaptureChunk } from '../platform/dictation-capture-contract' +import { MAX_HELD_AUDIO_BYTES, type MobileDictationHeldAudio } from './mobile-dictation-held-audio' + +// Everything one dictation heard, from the tap, whichever engine hears it: replayed to the computer when the phone fails, and kept after a failure for Retry. +export class MobileDictationRecording { + private chunks: DictationCaptureChunk[] = [] + private keptBytes = 0 + private incomplete = false + + keep(chunk: DictationCaptureChunk): void { + if (this.incomplete) { + return + } + // Past the cap, or with audio the page dropped, a replay would lose speech (and the send refuses it), so keep nothing and say it is incomplete. + if (chunk.droppedBytes > 0 || this.keptBytes + chunk.data.byteLength > MAX_HELD_AUDIO_BYTES) { + this.chunks = [] + this.keptBytes = 0 + this.incomplete = true + return + } + this.chunks.push(chunk) + this.keptBytes += chunk.data.byteLength + } + + // False once speech was lost; the recording no longer covers the whole dictation. + get complete(): boolean { + return !this.incomplete + } + + get bytes(): number { + return this.keptBytes + } + + // Queue a copy for sending; the recording itself stays, so a failed replay can be retried. + replayInto(held: MobileDictationHeldAudio): void { + held.clear() + for (const chunk of this.chunks) { + held.hold(chunk) + } + } + + clear(): void { + this.chunks = [] + this.keptBytes = 0 + this.incomplete = false + } +} diff --git a/mobile/src/hooks/mobile-dictation-retry.test.tsx b/mobile/src/hooks/mobile-dictation-retry.test.tsx new file mode 100644 index 00000000000..474685d5a83 --- /dev/null +++ b/mobile/src/hooks/mobile-dictation-retry.test.tsx @@ -0,0 +1,166 @@ +// A computer dictation that fails mid-session keeps its whole recording; Retry plays all of it to the computer as a new dictation. +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { + createFakeRpcClient, + type FakeRpcClient, + type SentRequest +} from '../mobile-web-shell/bridge-host-test-fakes' +import type { + DictationCapture, + DictationCaptureChunk +} from '../platform/dictation-capture-contract' + +type Seam = { + chunkHandlers: Set<(chunk: DictationCaptureChunk) => void> + tail: Uint8Array | null +} + +const seam = vi.hoisted((): Seam => ({ chunkHandlers: new Set(), tail: null })) + +vi.mock('react-native', () => ({ + AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, + Platform: { OS: 'ios' } +})) + +// Keep capture identity stable like both real seams; a fresh object on render would rerun teardown and cancel dictation. +vi.mock('../platform/dictation-capture', () => { + const capture: DictationCapture = { + open: async () => ({ ok: true }), + begin: () => true, + end: async () => { + // Page capture reads once more here and may deliver audio. + const tail = seam.tail + seam.tail = null + if (tail !== null) { + for (const handler of seam.chunkHandlers) { + handler({ data: tail, droppedBytes: 0 }) + } + } + }, + release: () => {}, + onChunk: (handler) => { + seam.chunkHandlers.add(handler) + return { + remove: () => { + seam.chunkHandlers.delete(handler) + } + } + }, + onInterruption: () => ({ remove: () => {} }) + } + return { useDictationCapture: () => capture } +}) + +import { useMobileDictation, type UseMobileDictationResult } from './use-mobile-dictation' + +type Reply = (request: SentRequest) => 'hold' | { text?: string } | Error + +// Answer every request; one reply can unblock the next. +async function pump(rpc: FakeRpcClient, sent: SentRequest[], reply: Reply): Promise { + for (let round = 0; round < 30; round += 1) { + for (const request of rpc.requests.splice(0)) { + sent.push(request) + const answer = reply(request) + if (answer === 'hold') { + continue + } + if (answer instanceof Error) { + request.reject(answer) + } else { + request.resolve({ id: 'desktop', ok: true, result: answer }) + } + } + await Promise.resolve() + await Promise.resolve() + } +} + +function paramsOf(request: SentRequest): Record { + const params = request.args[1] + return typeof params === 'object' && params !== null ? { ...params } : {} +} + +function deliver(bytes: number[]): void { + for (const handler of seam.chunkHandlers) { + handler({ data: Uint8Array.from(bytes), droppedBytes: 0 }) + } +} + +const held: { dictation: UseMobileDictationResult | null } = { dictation: null } + +function dictation(): UseMobileDictationResult { + const current = held.dictation + if (current === null) { + throw new Error('nothing mounted') + } + return current +} + +beforeEach(() => { + seam.chunkHandlers.clear() + seam.tail = null + held.dictation = null +}) + +describe('a computer dictation whose finish fails', () => { + it('keeps the recording, and Retry sends all of it again and inserts the words', async () => { + const rpc = createFakeRpcClient() + const sent: SentRequest[] = [] + const inserted: string[] = [] + const errors: { message: string; kept: boolean }[] = [] + function Probe(): null { + held.dictation = useMobileDictation({ + client: rpc, + enabled: true, + onTranscript: (text) => inserted.push(text), + onError: (error, outcome) => errors.push({ message: error.message, kept: outcome.kept }) + }) + return null + } + act(() => { + create(createElement(Probe)) + }) + const firstTry: Reply = (request) => + request.method === 'speech.dictation.finish' ? new Error('connection lost') : {} + await act(async () => { + const started = dictation().start() + await pump(rpc, sent, firstTry) + await started + }) + await act(async () => { + deliver([1, 2, 3, 4]) + await pump(rpc, sent, firstTry) + }) + seam.tail = Uint8Array.from([5, 6]) + await act(async () => { + const stopped = dictation().stop() + await pump(rpc, sent, firstTry) + await stopped + }) + expect(inserted).toEqual([]) + expect(errors).toEqual([{ message: 'connection lost', kept: true }]) + expect(dictation().failure).toEqual({ message: 'connection lost', offline: false }) + + const firstId = paramsOf(sent[0]).dictationId + sent.length = 0 + await act(async () => { + const retried = dictation().retry() + await pump(rpc, sent, (request) => + request.method === 'speech.dictation.finish' ? { text: 'all of it' } : {} + ) + await retried + }) + expect(sent.map((request) => request.method)).toEqual([ + 'speech.dictation.start', + 'speech.dictation.chunk', + 'speech.dictation.finish' + ]) + expect(paramsOf(sent[0]).dictationId).not.toBe(firstId) + // The whole recording, from the first byte, as seq 0 of the new dictation. + expect(paramsOf(sent[1])).toMatchObject({ audioBase64: 'AQIDBAUG', seq: 0 }) + expect(inserted).toEqual(['all of it']) + expect(dictation().failure).toBeNull() + }) +}) diff --git a/mobile/src/hooks/mobile-dictation-retry.ts b/mobile/src/hooks/mobile-dictation-retry.ts new file mode 100644 index 00000000000..7581ae378f5 --- /dev/null +++ b/mobile/src/hooks/mobile-dictation-retry.ts @@ -0,0 +1,42 @@ +import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { createMobileDictationId } from './mobile-dictation-session-state' +import { + concludeMobileDictationFailure, + mobileDictationFailureRetryable +} from './mobile-dictation-failure' +import { + releaseMobileDictationEngine, + type MobileDictationRun +} from './mobile-dictation-engine-run' +import { replayMobileDictationToHost } from './mobile-dictation-host-start' + +// A dictation failed after it began hearing: stop it, and keep its recording for Retry when the computer can hear it again. +export function failActiveMobileDictation( + run: MobileDictationRun, + dictationId: string, + err: unknown +): void { + if (run.activeId.current !== dictationId) { + return + } + run.activeId.current = null + const retryable = mobileDictationFailureRetryable(run.recording.current, run.engine.current) + run.closeDictationAudio() + void releaseMobileDictationEngine(run, run.client.current, dictationId) + concludeMobileDictationFailure(run, dictationId, err, retryable) +} + +// Retry: the kept recording goes to the computer as a new dictation (seq from 0), already stopped, so it finishes as soon as it has been sent. +export async function retryMobileDictationOnHost( + run: MobileDictationRun, + client: RpcClient +): Promise { + const generation = run.generation.current + 1 + run.generation.current = generation + const dictationId = createMobileDictationId() + run.activeId.current = dictationId + run.stopWhenStarted.current = true + run.applyStatus('processing', true) + run.showEngine('computer') + await replayMobileDictationToHost(run, client, dictationId, generation) +} diff --git a/mobile/src/hooks/mobile-dictation-session-state.ts b/mobile/src/hooks/mobile-dictation-session-state.ts index a2ab4abb53e..ec122ea47cb 100644 --- a/mobile/src/hooks/mobile-dictation-session-state.ts +++ b/mobile/src/hooks/mobile-dictation-session-state.ts @@ -2,6 +2,7 @@ import { Buffer } from 'buffer' import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import type { DictationTerm } from '../../../src/shared/dictation-dictionary' import type { MobileDictationMeter } from './mobile-dictation-meter' export type DictationStatus = 'idle' | 'starting' | 'recording' | 'processing' | 'error' @@ -9,13 +10,21 @@ export type DictationStatus = 'idle' | 'starting' | 'recording' | 'processing' | // Who is transcribing, for the icon by the timer; movedAt marks when Automatic moved from the phone to the computer. export type MobileDictationEngineShown = { kind: 'phone' | 'computer'; movedAt: number | null } +// offline: the computer was out of reach when it failed, which is the reason the user needs. +export type MobileDictationKeptFailure = { message: string; offline: boolean } + export type UseMobileDictationOptions = { client: RpcClient | null enabled: boolean onTranscript: (text: string) => void - onError?: (error: Error) => void + // kept: the recording is kept for Retry, so the failure shows in place rather than as a toast. + onError?: (error: Error, outcome: { kept: boolean }) => void // The computer's filler switch, for text the phone recognizes itself; unknown means on. removeFillerWords?: boolean + // The computer's dictionary for this worktree, for text the phone recognizes itself. + dictationTerms?: readonly DictationTerm[] + // Lets the computer pick this worktree's repo terms for text it recognizes. + worktreeId?: string // The host's cloud upload is full; the dictation stops and inserts what was kept. onAudioLimitReached?: () => void } @@ -28,10 +37,14 @@ export type UseMobileDictationResult = { // Empty until a newer host reports words; older hosts never do. transcriptSoFar: string error: string | null + // A failure whose recording is kept: Retry plays it to the computer again, cancel discards it. + failure: MobileDictationKeptFailure | null // Null until recording starts on an engine. engine: MobileDictationEngineShown | null - start: () => Promise + // client: the starting session's client, when one hook serves several sessions. + start: (client?: RpcClient | null) => Promise stop: () => Promise + retry: () => Promise cancel: () => Promise meter: MobileDictationMeter } diff --git a/mobile/src/hooks/use-mobile-dictation.ts b/mobile/src/hooks/use-mobile-dictation.ts index bfc0e9cd3c9..027042548be 100644 --- a/mobile/src/hooks/use-mobile-dictation.ts +++ b/mobile/src/hooks/use-mobile-dictation.ts @@ -13,19 +13,20 @@ import { type MobileDictationAudioPhase } from './mobile-dictation-audio-chunk' import { MobileDictationHeldAudio } from './mobile-dictation-held-audio' -import { isCurrentMobileDictationFinish } from './mobile-dictation-session-state' -import { finishDesktopDictation } from './mobile-dictation-desktop-start' +import { MobileDictationRecording } from './mobile-dictation-recording' +import { failActiveMobileDictation, retryMobileDictationOnHost } from './mobile-dictation-retry' +import { mobileDictationFailureRetryable } from './mobile-dictation-failure' +import { finishMobileDictation } from './mobile-dictation-finish' import type { MobileDictationEngine } from './mobile-dictation-device-engine' +import type { RpcClient } from '../transport/rpc/rpc-client-contract' import { - finishMobileDictationOnDevice, releaseMobileDictationEngine, - settleMobileDictation, startMobileDictation, type MobileDictationRun } from './mobile-dictation-engine-run' -import { rpcPayloadMember } from '../transport/rpc/rpc-reader-payload' import type { DictationStatus, + MobileDictationKeptFailure, UseMobileDictationOptions, UseMobileDictationResult } from './mobile-dictation-session-state' @@ -35,11 +36,15 @@ export type { UseMobileDictationResult } from './mobile-dictation-session-state' export function useMobileDictation(options: UseMobileDictationOptions): UseMobileDictationResult { useMobileTranslation() const { client, enabled, onTranscript, onError, removeFillerWords, onAudioLimitReached } = options + const { dictationTerms, worktreeId } = options // Both capture seams hold the screen while the microphone is open; native uses the device directly and page uses shell audio verbs. const capture = useDictationCapture() - const speech = useOnDeviceSpeech(removeFillerWords) + const speech = useOnDeviceSpeech(removeFillerWords, dictationTerms) const [status, setStatus] = useState('idle') const [error, setError] = useState(null) + // A failure whose recording is kept for Retry; cleared by Retry, discard and the next dictation. + const [failure, setFailure] = useState(null) + const failureRef = useRef(failure) const [transcriptSoFar, setTranscriptSoFar, keptTranscript] = useMobileDictationTranscriptSoFar() const { shown: shownEngine, @@ -57,10 +62,12 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil const onTranscriptRef = useRef(onTranscript) const onErrorRef = useRef(onError) const onAudioLimitReachedRef = useRef(onAudioLimitReached) + const worktreeIdRef = useRef(worktreeId) const pendingChunksRef = useRef>>(new Set()) const pendingAudioBudgetRef = useRef(new MobileDictationPendingAudioBudget()) const audioPhaseRef = useRef('closed') const heldAudioRef = useRef(new MobileDictationHeldAudio()) + const recordingRef = useRef(new MobileDictationRecording()) const sendHeldAudioRef = useRef(() => {}) const stopWhenStartedRef = useRef(false) const generationRef = useRef(0) @@ -74,30 +81,40 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil onTranscriptRef.current = onTranscript onErrorRef.current = onError onAudioLimitReachedRef.current = onAudioLimitReached - }, [client, speech, enabled, onTranscript, onError, onAudioLimitReached]) + worktreeIdRef.current = worktreeId + }, [client, speech, enabled, onTranscript, onError, onAudioLimitReached, worktreeId]) const applyStatus = useCallback( - (next: DictationStatus) => { + // Kept through processing so the text so far stays in place until the final transcript replaces it in the same render. + (next: DictationStatus, keepText = next === 'recording' || next === 'processing') => { statusRef.current = next setStatus(next) - // Kept through processing so the text so far stays in place until the final transcript replaces it in the same render. - const live = next === 'recording' || next === 'processing' - setTranscriptSoFar((text) => (live ? text : '')) - if (!live) { + setTranscriptSoFar((text) => (keepText ? text : '')) + if (next !== 'recording' && next !== 'processing') { clearEngine() } }, [clearEngine] ) + const setKeptFailure = useCallback((next: MobileDictationKeptFailure | null) => { + failureRef.current = next + setFailure(next) + }, []) + const reportError = useCallback( - (err: unknown) => { + (err: unknown, kept = false) => { const normalized = err instanceof Error ? err : new Error(String(err)) setError(normalized.message) - applyStatus('error') - onErrorRef.current?.(normalized) + applyStatus('error', kept) + setKeptFailure( + kept + ? { message: normalized.message, offline: clientRef.current?.getState() !== 'connected' } + : null + ) + onErrorRef.current?.(normalized, { kept }) }, - [applyStatus] + [applyStatus, setKeptFailure] ) const closeDictationAudio = useCallback(() => { @@ -113,29 +130,8 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil } }, [capture]) - const failActiveDictation = useCallback( - (dictationId: string, err: unknown) => { - if (activeIdRef.current !== dictationId) { - return - } - activeIdRef.current = null - closeDictationAudio() - void releaseMobileDictationEngine( - { engine: engineRef, speech: speechRef }, - clientRef.current, - dictationId - ) - const kept = keptTranscript.take(dictationId) - if (kept) { - onTranscriptRef.current(kept) - } - reportError(err) - }, - [closeDictationAudio, reportError] - ) - - const run = useMemo( - () => ({ + const run = useMemo(() => { + const created: MobileDictationRun = { status: statusRef, activeId: activeIdRef, client: clientRef, @@ -148,86 +144,28 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil pendingChunks: pendingChunksRef, pendingAudioBudget: pendingAudioBudgetRef, heldAudio: heldAudioRef, + recording: recordingRef, sendHeldAudio: sendHeldAudioRef, finish: finishRef, onTranscript: onTranscriptRef, onAudioLimitReached: onAudioLimitReachedRef, + worktreeId: worktreeIdRef, keptTranscript, applyStatus, showEngine, closeDictationAudio, reportError, - failActiveDictation - }), - [applyStatus, closeDictationAudio, failActiveDictation, keptTranscript, reportError, showEngine] - ) + failActiveDictation: (dictationId, err) => + failActiveMobileDictation(created, dictationId, err) + } + return created + }, [applyStatus, closeDictationAudio, keptTranscript, reportError, showEngine]) useMobileDictationAudioChunks(capture, run) const finishDictation = useCallback( - async (emptyTranscriptMessage: string) => { - const client = clientRef.current - const dictationId = activeIdRef.current - const engine = engineRef.current - if (!dictationId || (engine.kind === 'host' && !client)) { - return - } - // A fallback's host start is still pending: finish once it commits and the kept audio has gone. - if (engine.kind === 'host' && audioPhaseRef.current === 'holding') { - stopWhenStartedRef.current = true - if (statusRef.current === 'recording') { - applyStatus('processing') - // Stop listening now; the tail joins the held audio the replay sends. - void capture.end() - } - return - } - - const generation = generationRef.current + 1 - generationRef.current = generation - applyStatus('processing') - const isCurrent = () => - isCurrentMobileDictationFinish( - generationRef.current, - generation, - enabledRef.current, - activeIdRef.current, - dictationId - ) - try { - // Keep shutdown inside try for finally cleanup; accept its tail chunks and snapshot pending sends only after end settles, or finish can overtake the last audio. - await capture.end() - if (engine.kind === 'device') { - await finishMobileDictationOnDevice( - run, - engine, - dictationId, - emptyTranscriptMessage, - isCurrent - ) - return - } - audioPhaseRef.current = 'closed' - await Promise.allSettled(Array.from(pendingChunksRef.current)) - if (!isCurrent() || !client) { - return - } - const sentSeconds = pendingAudioBudgetRef.current.sentAudioSeconds - const finished = await finishDesktopDictation(client, dictationId, sentSeconds) - if (!isCurrent()) { - return - } - const transcript = rpcPayloadMember(finished, 'text') - settleMobileDictation( - run, - typeof transcript === 'string' ? transcript.trim() : '', - emptyTranscriptMessage - ) - } catch (err) { - failActiveDictation(dictationId, err) - } - }, - [applyStatus, capture, failActiveDictation, run] + (emptyTranscriptMessage: string) => finishMobileDictation(run, capture, emptyTranscriptMessage), + [capture, run] ) useLayoutEffect(() => { finishRef.current = finishDictation @@ -242,13 +180,37 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil await finishDictation(dictationSessionErrorMessage('no-speech')) }, [finishDictation]) - const start = useCallback(async () => { - if ((!clientRef.current && !speechRef.current) || !enabledRef.current || activeIdRef.current) { + const start = useCallback( + async (startClient?: RpcClient | null) => { + // The caller's client, set before the next render commits it: one hook serves whichever session starts. + if (startClient !== undefined) { + clientRef.current = startClient + } + if ( + (!clientRef.current && !speechRef.current) || + !enabledRef.current || + activeIdRef.current + ) { + return + } + setError(null) + // A new dictation replaces a failed one's kept recording. + setKeptFailure(null) + recordingRef.current.clear() + await startMobileDictation(run, capture) + }, + [capture, run, setKeptFailure] + ) + + const retry = useCallback(async () => { + const client = clientRef.current + if (!failureRef.current || !client || activeIdRef.current || !enabledRef.current) { return } setError(null) - await startMobileDictation(run, capture) - }, [capture, run]) + setKeptFailure(null) + await retryMobileDictationOnHost(run, client) + }, [run, setKeptFailure]) // Only the user’s own cancel (reason:null) ends silently; other interruptions call onError so the tap has a visible outcome. const abandonDictation = useCallback( @@ -256,11 +218,26 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil const client = clientRef.current const dictationId = activeIdRef.current const wasUnderway = statusRef.current === 'starting' || statusRef.current === 'recording' + // Only the user's discard drops a kept recording; an interruption while it waits leaves it for Retry. + if (reason !== null && dictationId === null && failureRef.current) { + return + } + // An interruption keeps a recording the computer can hear again, even mid-finish; the user's cancel never does. + const kept = + reason !== null && + dictationId !== null && + mobileDictationFailureRetryable(recordingRef.current, engineRef.current) + if (!kept) { + setKeptFailure(null) + recordingRef.current.clear() + } generationRef.current += 1 activeIdRef.current = null closeDictationAudio() // Settle before the host's cancel reply: a host that went quiet must not hold the mic button in its old state. - if (reason !== null && wasUnderway) { + if (kept) { + reportError(new Error(reason), true) + } else if (reason !== null && wasUnderway) { reportError(new Error(reason)) } else { applyStatus('idle') @@ -268,7 +245,7 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil } await releaseMobileDictationEngine(run, client, dictationId) }, - [applyStatus, closeDictationAudio, reportError, run] + [applyStatus, closeDictationAudio, reportError, run, setKeptFailure] ) const cancel = useCallback(() => abandonDictation(null), [abandonDictation]) @@ -295,6 +272,7 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil generationRef.current += 1 activeIdRef.current = null closeDictationAudio() + recordingRef.current.clear() capture.release() void releaseMobileDictationEngine(run, clientRef.current, dictationId) } @@ -307,8 +285,10 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil isProcessing: status === 'processing', transcriptSoFar, error, + failure, engine: shownEngine, start, + retry, stop, cancel, meter: useMobileDictationMeter(capture, status === 'recording') diff --git a/mobile/src/host-screen/host-list-queries.ts b/mobile/src/host-screen/host-list-queries.ts index caa752201fd..08c966625e2 100644 --- a/mobile/src/host-screen/host-list-queries.ts +++ b/mobile/src/host-screen/host-list-queries.ts @@ -22,7 +22,6 @@ import { type WorktreeCatalogSnapshot } from '../worktree/worktree-catalog-snapshot-client' import type { Worktree } from '../worktree/workspace-list-types' -import { getCachedWorktrees } from '../cache/worktree-cache' import { hostRepoCatalogRepos, hostSshTargetSummarySchema, @@ -108,6 +107,11 @@ export const hostWorktreeCatalogQuery = defineHostQuery< } }) +// Native Home's per-desktop counts (home-host-worktree-fetch.ts); keyed here so the page never loads Home's module. +export const HOME_WORKTREE_COUNTS_FAMILY = 'worktree.homeCounts' +export const homeWorktreeCountsKey = (hostId: string) => + hostQueryKey(hostId, HOME_WORKTREE_COUNTS_FAMILY, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) + export const hostWorktreeCatalogKey = (hostId: string) => hostQueryKey(hostId, hostWorktreeCatalogQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) @@ -119,9 +123,12 @@ export function cachedHostWorktrees( if (!hostId) { return null } - const cached = queryClient.getQueryData(hostWorktreeCatalogKey(hostId)) - // Native Home's own catalog read until Home moves onto this query; shown only, never a delta base. - return cached ? [...cached.worktrees] : (getCachedWorktrees(hostId) as Worktree[] | null) + const cached = + queryClient.getQueryData(hostWorktreeCatalogKey(hostId)) ?? + // Native Home's last read, for the wide layout's host list beside it; shown only, never a delta base. + queryClient.getQueryData<{ catalog?: WorktreeCatalogSnapshot }>(homeWorktreeCountsKey(hostId)) + ?.catalog + return cached ? [...cached.worktrees] : null } const serverRowSnapshots = { diff --git a/mobile/src/host-screen/use-host-worktree-actions.ts b/mobile/src/host-screen/use-host-worktree-actions.ts index 81bb0dfd52c..5d2814b1049 100644 --- a/mobile/src/host-screen/use-host-worktree-actions.ts +++ b/mobile/src/host-screen/use-host-worktree-actions.ts @@ -1,4 +1,5 @@ import { useCallback } from 'react' +import { useQueryClient } from '@tanstack/react-query' import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../src/shared/sidebar-inputs-switch' import type { useRouter } from 'expo-router' import { floatingWorkspaceSessionPath } from '../session/floating-workspace' @@ -71,6 +72,7 @@ export function useHostWorktreeActions(args: { router, state } = args + const queryClient = useQueryClient() const { pinnedIds, setActionError, @@ -216,7 +218,7 @@ export function useHostWorktreeActions(args: { return } try { - await removeHostAndCloseClient(hostId, forgetHostClient) + await removeHostAndCloseClient(hostId, forgetHostClient, queryClient) leaveHostRoute(router) } catch (error) { if (isPageHostRemovalUnavailable(error)) { @@ -229,7 +231,7 @@ export function useHostWorktreeActions(args: { // React Native Web Alert is a no-op; show a dismissible action error while keeping the list, header and confirm usable. setActionError('Could not remove host. Please try again.') } - }, [hostId, router, forgetHostClient, setActionError, setConfirmRemoveHost]) + }, [hostId, router, forgetHostClient, queryClient, setActionError, setConfirmRemoveHost]) // beforeNavigate runs unless the open session holds the leave, so a held tap leaves the target untouched. const navigateFromHostList = useCallback( diff --git a/mobile/src/host-screen/use-host-worktree-catalog.ts b/mobile/src/host-screen/use-host-worktree-catalog.ts index ca3715baef2..edbad9c48fc 100644 --- a/mobile/src/host-screen/use-host-worktree-catalog.ts +++ b/mobile/src/host-screen/use-host-worktree-catalog.ts @@ -1,3 +1,4 @@ +import { MOBILE_RELAY_HOSTS_CHANGED_EVENT_RUNTIME_CAPABILITY } from '../../../src/shared/mobile-desktop-relay-contract' import { WORKTREE_ROWS_CHANGED_EVENT_RUNTIME_CAPABILITY } from '../../../src/shared/worktree-runtime-capabilities' import { readWorktreeFirstPage } from '../worktree/worktree-catalog-first-page' import type { Worktree } from '../worktree/workspace-list-types' @@ -20,6 +21,7 @@ import { savePinnedIds } from '../storage/preferences' import type { HostScreenState } from './use-host-screen-state' import { relaysToServers } from '../worktree/execution-host-scoped-rpc-client' import { NO_SERVER_WORKSPACES } from '../worktree/server-workspaces' +import { useRelayHosts } from '../worktree/relay-hosts-feed' import { WorktreeCatalogReadError } from '../worktree/worktree-catalog-snapshot-client' import { useHostQuery } from '../query/host-query' import { hostReadClient } from '../query/host-read-client' @@ -122,6 +124,11 @@ export function useHostWorktreeCatalog(args: { const relays = client !== null && relaysToServers(client, hostCapabilities) // Until the host's status is read, stored server rows paint and nothing reads them. const relaysRuledOut = hostStatusReadable && !relays + // Held while server rows poll, so a desktop that announces host changes isn't asked for its hosts on every poll. + const announcesHosts = hostCapabilities.includes( + MOBILE_RELAY_HOSTS_CHANGED_EVENT_RUNTIME_CAPABILITY + ) + useRelayHosts(subscribed && relays && announcesHosts ? client : null, hostCapabilities) const servers = useHostQuery( hostServerWorkspacesQuery, host, diff --git a/mobile/src/i18n/en-runtime-required.json b/mobile/src/i18n/en-runtime-required.json index acba365e2f1..ff6c952994d 100644 --- a/mobile/src/i18n/en-runtime-required.json +++ b/mobile/src/i18n/en-runtime-required.json @@ -315,7 +315,11 @@ "forkOriginalMissingNamed": "{{agent}} could not find this response in \"{{detail}}\". Open that chat and fork from there.", "forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat. Open it and fork from there.", "forkOriginalUnavailableNamed": "{{agent}} cannot fork this response in \"{{detail}}\". Open that chat and fork from there.", - "pluginInputRequired": "{{agent}} stopped because the \"{{plugin}}\" plugin is waiting for input in a terminal pane. Disable the plugin for chat sessions, or run the task in a {{agent}} terminal." + "pluginInputRequired": "{{agent}} stopped because the \"{{plugin}}\" plugin is waiting for input in a terminal pane. Disable the plugin for chat sessions, or run the task in a {{agent}} terminal.", + "providerResponseFailed": "{{agent}} couldn't finish this response. Open Details for more information.", + "providerSafetyStopped": "{{agent}} stopped this response after a safety check. Review your request and send again.", + "providerUnavailable": "{{agent}} couldn't respond because the service is busy. Pick another model, or wait a little and send again.", + "selectedModel": "the selected model" }, "fileReader": { "reviewNotes_one": "{{count}} review note", diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 8fdd8ecc62b..6ac9c9e827d 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -300,6 +300,7 @@ "plan": "Plan", "stoppedManually": "Manuell gestoppt", "permissionDenied": "{{agent}} hat die Berechtigung verweigert. Details anzeigen.", + "safetyReviewApproved": "{{agent}} hat diese Aktion genehmigt. Details anzeigen.", "safetyReview": "{{agent}} hat eine Warnung zur Sicherheitsprüfung gemeldet. Details anzeigen.", "truncatedResponse": "Anbieterantwort gekürzt (ursprüngliche Größe: {{bytes}} Bytes).", "modelFallback": "Claude hat das Modell gewechselt: {{from}} → {{to}}.", @@ -602,6 +603,7 @@ "fullCopySaveUpdate": "„Vollständig kopieren“ und Speichern werden für diesen Anhang mit einem Smartphone-Update verfügbar sein." }, "hostOutage": { + "offlineAsOf": "{{host}} ist offline · Stand {{time}}", "reconnecting": "{{hostName}} verbindet sich erneut…", "stopped": "{{hostName}} ist gestoppt. Starte es auf deinem Computer.", "server": "Der Server", @@ -1317,13 +1319,46 @@ "durationSeconds_one": "{{count}} Sekunde", "durationSeconds_other": "{{count}} Sekunden", "durationMinutes_one": "{{count}} Minute", - "durationMinutes_other": "{{count}} Minuten" + "durationMinutes_other": "{{count}} Minuten", + "discard": "Aufnahme verwerfen", + "retry": "Diktat wiederholen", + "retryShort": "Wiederholen" }, "status": { "finishingOn": "Wird auf {{computer}} abgeschlossen", "finishingOnComputer": "Wird auf dem Computer abgeschlossen", "movedTo": "Zu {{computer}} gewechselt", "movedToComputer": "Zum Computer gewechselt" + }, + "failure": { + "connectionLost": "Verbindung unterbrochen", + "connectionSlow": "Verbindung zu langsam", + "phoneStopped": "Auf diesem Telefon gestoppt", + "stopped": "Diktat gestoppt", + "recordingKept": "Aufnahme behalten" + }, + "announce": { + "typedInto": "Eingetippt in {{target}}", + "insertedIn": "Eingefügt in {{target}}", + "listeningOnPhone": "Hört zu. Transkription auf diesem Telefon.", + "listeningOn": "Hört zu. Transkription auf {{computer}}.", + "listeningOnComputer": "Hört zu. Transkription auf dem Computer.", + "finishing": "Wird abgeschlossen.", + "inserted": "Eingefügt.", + "cancelled": "Diktat abgebrochen.", + "movedTo": "Dieses Telefon hat die Transkription beendet. Weiter auf {{computer}}.", + "movedToComputer": "Dieses Telefon hat die Transkription beendet. Weiter auf dem Computer.", + "stoppedKept": "Diktat gestoppt. {{reason}}. Deine Aufnahme bleibt erhalten.", + "stillListening": "Hört weiter zu." + }, + "pill": { + "open": "Öffnen", + "listening": "Hört zu", + "starting": "Startet", + "finishing": "Wird abgeschlossen", + "stopped": "Diktat gestoppt", + "label": "Diktat in {{target}}, {{duration}}", + "hint": "Doppeltippen, um zurückzukehren" } }, "files": { @@ -2128,6 +2163,10 @@ "providerExitedRejection": "{{agent}} wurde gestoppt, bevor diese Nachricht gesendet wurde.", "providerExitedRow": "{{agent}} wurde während dieser Antwort gestoppt. Die Unterhaltung kann fortgesetzt werden.", "providerRateLimited": "{{agent}} hat das Ratenlimit erreicht und versucht es erneut.", + "providerUnavailable": "{{agent}} konnte nicht antworten, weil der Dienst ausgelastet ist. Wähle ein anderes Modell oder warte kurz und sende erneut.", + "providerSafetyStopped": "{{agent}} hat diese Antwort nach einer Sicherheitsprüfung gestoppt. Überprüfe deine Anfrage und sende sie erneut.", + "providerResponseFailed": "{{agent}} konnte diese Antwort nicht abschließen. Öffnen Sie die Details für weitere Informationen.", + "selectedModel": "das ausgewählte Modell", "providerRejected": "{{agent}} hat diese Nachricht nicht angenommen.", "providerRejectedQuoted": "{{agent}} hat diese Nachricht nicht angenommen: {{detail}}.", "providerRetryLastError": "Letzter Fehler: {{detail}}.", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index df763bf71c0..2d9ce8ba6cf 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -534,13 +534,46 @@ "meterOnPhone": "Recording, {{duration}}, on this phone", "meterOn": "Recording, {{duration}}, on {{computer}}", "meterOnComputer": "Recording, {{duration}}, on the computer", - "meter": "Recording, {{duration}}" + "meter": "Recording, {{duration}}", + "discard": "Discard recording", + "retry": "Retry dictation", + "retryShort": "Retry" }, "status": { "finishingOn": "Finishing on {{computer}}", "finishingOnComputer": "Finishing on the computer", "movedTo": "Moved to {{computer}}", "movedToComputer": "Moved to the computer" + }, + "failure": { + "recordingKept": "Recording kept", + "connectionLost": "Connection lost", + "connectionSlow": "Connection too slow", + "phoneStopped": "Stopped on this phone", + "stopped": "Dictation stopped" + }, + "announce": { + "typedInto": "Typed into {{target}}", + "insertedIn": "Inserted in {{target}}", + "listeningOnPhone": "Listening. Transcribing on this phone.", + "listeningOn": "Listening. Transcribing on {{computer}}.", + "listeningOnComputer": "Listening. Transcribing on the computer.", + "finishing": "Finishing.", + "inserted": "Inserted.", + "cancelled": "Dictation cancelled.", + "movedTo": "This phone stopped transcribing. Continuing on {{computer}}.", + "movedToComputer": "This phone stopped transcribing. Continuing on the computer.", + "stoppedKept": "Dictation stopped. {{reason}}. Your recording is kept.", + "stillListening": "Still listening." + }, + "pill": { + "open": "Open", + "listening": "Listening", + "starting": "Starting", + "finishing": "Finishing", + "stopped": "Dictation stopped", + "label": "Dictation to {{target}}, {{duration}}", + "hint": "Double-tap to go back" } }, "home": { @@ -1456,6 +1489,10 @@ }, "offlineAsOfTime": { "yesterday": "yesterday, {{time}}" + }, + "smartRailRow": { + "title": "Smart rail", + "subtitle": "Shows keys for what your agent is doing" } }, "pullRequest": { @@ -2615,6 +2652,10 @@ "modelUnavailable": "{{agent}} couldn't use {{detail}}. Pick another model and send again.", "modelUnavailableUpdate": "{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.", "modelNotSelected": "{{agent}} has no model selected. Check your model selection and {{agent}} sign-in, then send again.", + "providerUnavailable": "{{agent}} couldn't respond because the service is busy. Pick another model, or wait a little and send again.", + "providerSafetyStopped": "{{agent}} stopped this response after a safety check. Review your request and send again.", + "providerResponseFailed": "{{agent}} couldn't finish this response. Open Details for more information.", + "selectedModel": "the selected model", "providerRejected": "{{agent}} didn't accept this message.", "providerRejectedQuoted": "{{agent}} didn't accept this message: {{detail}}.", "attachmentEmpty": "An image on this message is empty, so the message was not sent.", @@ -2860,6 +2901,25 @@ }, "usePrTextAction": { "updateFailed": "Failed to update pull request." + }, + "smartKeys": { + "always": "Always", + "answer": "Answer", + "background": "Background", + "cancel": "Cancel", + "confirm": "Confirm", + "edit": "Edit", + "history": "History", + "keyLabel": "{{word}}, sends {{combo}}", + "mode": "Mode", + "no": "No", + "queue": "Queue", + "reject": "Reject", + "rewind": "Rewind", + "sendNow": "Send now", + "skip": "Skip", + "stop": "Stop", + "yes": "Yes" } }, "chat": { @@ -3054,6 +3114,7 @@ "contextCleared": "Context cleared", "plan": "Plan", "permissionDenied": "{{agent}} denied permission. View details.", + "safetyReviewApproved": "{{agent}} approved this action. View details.", "safetyReview": "{{agent}} reported a safety review warning. View details.", "truncatedResponse": "Provider response truncated (original size: {{bytes}} bytes).", "modelFallback": "Claude switched models: {{from}} → {{to}}.", @@ -3313,6 +3374,7 @@ "unsupported": "This host runs an older Orca. Update Orca on the host, then try again." }, "hostOutage": { + "offlineAsOf": "{{host}} is offline · as of {{time}}", "reconnecting": "{{hostName}} is reconnecting…", "stopped": "{{hostName}} is stopped. Start it on your computer.", "server": "The server", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index 93db73377e9..06a433dc383 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -304,6 +304,7 @@ "plan": "Plan", "stoppedManually": "Detenido manualmente", "permissionDenied": "{{agent}} denegó el permiso. Ver detalles.", + "safetyReviewApproved": "{{agent}} aprobó esta acción. Ver detalles.", "safetyReview": "{{agent}} notificó una advertencia de revisión de seguridad. Ver detalles.", "truncatedResponse": "Respuesta del proveedor truncada (tamaño original: {{bytes}} bytes).", "modelFallback": "Claude cambió de modelo: {{from}} → {{to}}.", @@ -637,6 +638,7 @@ "fullCopySaveUpdate": "Copiar todo y Guardar para este adjunto estarán disponibles en una actualización del teléfono." }, "hostOutage": { + "offlineAsOf": "{{host}} está sin conexión · a las {{time}}", "reconnecting": "{{hostName}} se está reconectando…", "stopped": "{{hostName}} está detenido. Inícialo en tu ordenador.", "server": "El servidor", @@ -1358,13 +1360,46 @@ "durationSeconds_many": "{{count}} segundos", "durationMinutes_one": "{{count}} minuto", "durationMinutes_other": "{{count}} minutos", - "durationMinutes_many": "{{count}} minutos" + "durationMinutes_many": "{{count}} minutos", + "discard": "Descartar grabación", + "retry": "Reintentar dictado", + "retryShort": "Reintentar" }, "status": { "finishingOn": "Terminando en {{computer}}", "finishingOnComputer": "Terminando en el ordenador", "movedTo": "Pasado a {{computer}}", "movedToComputer": "Pasado al ordenador" + }, + "failure": { + "connectionLost": "Conexión perdida", + "connectionSlow": "Conexión demasiado lenta", + "phoneStopped": "Detenido en este teléfono", + "stopped": "Dictado detenido", + "recordingKept": "Grabación guardada" + }, + "announce": { + "typedInto": "Escrito en {{target}}", + "insertedIn": "Insertado en {{target}}", + "listeningOnPhone": "Escuchando. Transcribiendo en este teléfono.", + "listeningOn": "Escuchando. Transcribiendo en {{computer}}.", + "listeningOnComputer": "Escuchando. Transcribiendo en el ordenador.", + "finishing": "Terminando.", + "inserted": "Insertado.", + "cancelled": "Dictado cancelado.", + "movedTo": "Este teléfono dejó de transcribir. Continúa en {{computer}}.", + "movedToComputer": "Este teléfono dejó de transcribir. Continúa en el ordenador.", + "stoppedKept": "Dictado detenido. {{reason}}. Tu grabación se conserva.", + "stillListening": "Sigue escuchando." + }, + "pill": { + "open": "Abrir", + "listening": "Escuchando", + "starting": "Iniciando", + "finishing": "Terminando", + "stopped": "Dictado detenido", + "label": "Dictado en {{target}}, {{duration}}", + "hint": "Toca dos veces para volver" } }, "files": { @@ -2196,6 +2231,10 @@ "providerExitedRejection": "{{agent}} se detuvo antes de que se enviara este mensaje.", "providerExitedRow": "{{agent}} se detuvo mientras esta respuesta estaba en curso. Puede continuar en esta conversación.", "providerRateLimited": "{{agent}} alcanzó un límite de solicitudes y está reintentando.", + "providerUnavailable": "{{agent}} no pudo responder porque el servicio está ocupado. Elige otro modelo o espera un poco y vuelve a enviar el mensaje.", + "providerSafetyStopped": "{{agent}} detuvo esta respuesta tras una comprobación de seguridad. Revisa tu solicitud y vuelve a enviarla.", + "providerResponseFailed": "{{agent}} no pudo terminar esta respuesta. Abre los detalles para obtener más información.", + "selectedModel": "el modelo seleccionado", "providerRejected": "{{agent}} no aceptó este mensaje.", "providerRejectedQuoted": "{{agent}} no aceptó este mensaje: {{detail}}.", "providerRetryLastError": "Último error: {{detail}}.", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index 30c9e9c2b4c..af77cbdb538 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -304,6 +304,7 @@ "plan": "Plan", "stoppedManually": "Arrêté manuellement", "permissionDenied": "{{agent}} a refusé la permission. Voir les détails.", + "safetyReviewApproved": "{{agent}} a approuvé cette action. Voir les détails.", "safetyReview": "{{agent}} a signalé un avertissement de sécurité. Voir les détails.", "truncatedResponse": "Réponse du fournisseur tronquée (taille d’origine : {{bytes}} octets).", "modelFallback": "Claude a changé de modèle : {{from}} → {{to}}.", @@ -637,6 +638,7 @@ "fullCopySaveUpdate": "La copie intégrale et l’enregistrement de cette pièce jointe seront disponibles dans une mise à jour du téléphone." }, "hostOutage": { + "offlineAsOf": "{{host}} est hors ligne · état à {{time}}", "reconnecting": "{{hostName}} se reconnecte…", "stopped": "{{hostName}} est arrêté. Démarrez-le sur votre ordinateur.", "server": "Le serveur", @@ -1358,13 +1360,46 @@ "durationSeconds_many": "{{count}} secondes", "durationMinutes_one": "{{count}} minute", "durationMinutes_other": "{{count}} minutes", - "durationMinutes_many": "{{count}} minutes" + "durationMinutes_many": "{{count}} minutes", + "discard": "Supprimer l’enregistrement", + "retry": "Relancer la dictée", + "retryShort": "Réessayer" }, "status": { "finishingOn": "Finalisation sur {{computer}}", "finishingOnComputer": "Finalisation sur l’ordinateur", "movedTo": "Passé sur {{computer}}", "movedToComputer": "Passé sur l’ordinateur" + }, + "failure": { + "connectionLost": "Connexion perdue", + "connectionSlow": "Connexion trop lente", + "phoneStopped": "Arrêté sur ce téléphone", + "stopped": "Dictée arrêtée", + "recordingKept": "Enregistrement conservé" + }, + "announce": { + "typedInto": "Saisi dans {{target}}", + "insertedIn": "Inséré dans {{target}}", + "listeningOnPhone": "Écoute. Transcription sur ce téléphone.", + "listeningOn": "Écoute. Transcription sur {{computer}}.", + "listeningOnComputer": "Écoute. Transcription sur l’ordinateur.", + "finishing": "Finalisation.", + "inserted": "Inséré.", + "cancelled": "Dictée annulée.", + "movedTo": "Ce téléphone a arrêté de transcrire. Suite sur {{computer}}.", + "movedToComputer": "Ce téléphone a arrêté de transcrire. Suite sur l’ordinateur.", + "stoppedKept": "Dictée arrêtée. {{reason}}. Votre enregistrement est conservé.", + "stillListening": "Toujours à l’écoute." + }, + "pill": { + "open": "Ouvrir", + "listening": "Écoute", + "starting": "Démarrage", + "finishing": "Finalisation", + "stopped": "Dictée arrêtée", + "label": "Dictée vers {{target}}, {{duration}}", + "hint": "Touchez deux fois pour revenir" } }, "files": { @@ -2197,6 +2232,10 @@ "providerExitedRejection": "{{agent}} s'est arrêté avant l'envoi de ce message.", "providerExitedRow": "{{agent}} s'est arrêté pendant que cette réponse était en cours. Vous pouvez continuer dans cette conversation.", "providerRateLimited": "{{agent}} est limité en débit et réessaie.", + "providerUnavailable": "{{agent}} n’a pas pu répondre car le service est occupé. Choisissez un autre modèle ou patientez un peu, puis renvoyez le message.", + "providerSafetyStopped": "{{agent}} a arrêté cette réponse après un contrôle de sécurité. Vérifiez votre demande et renvoyez-la.", + "providerResponseFailed": "{{agent}} n’a pas pu terminer cette réponse. Ouvrez les détails pour en savoir plus.", + "selectedModel": "le modèle sélectionné", "providerRejected": "{{agent}} n'a pas accepté ce message.", "providerRejectedQuoted": "{{agent}} n'a pas accepté ce message : {{detail}}.", "providerRetryLastError": "Dernière erreur : {{detail}}.", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index 7af42d5c585..9b2aa411b82 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -300,6 +300,7 @@ "plan": "プラン", "stoppedManually": "手動で停止しました", "permissionDenied": "{{agent}} が権限を拒否しました。詳細を表示。", + "safetyReviewApproved": "{{agent}} がこの操作を承認しました。詳細を表示。", "safetyReview": "{{agent}} が安全性レビューの警告を報告しました。詳細を表示。", "truncatedResponse": "プロバイダーの応答は切り詰められています(元のサイズ:{{bytes}} バイト)。", "modelFallback": "Claudeがモデルを切り替えました: {{from}} → {{to}}。", @@ -598,6 +599,7 @@ "fullCopySaveUpdate": "この添付ファイルの全内容のコピーと保存は、スマートフォンのアップデートで利用可能になります。" }, "hostOutage": { + "offlineAsOf": "{{host}} はオフラインです · {{time}} 時点", "reconnecting": "{{hostName}} に再接続しています…", "stopped": "{{hostName}} は停止しています。コンピューターで起動してください。", "server": "サーバー", @@ -1313,13 +1315,46 @@ "durationSeconds_one": "{{count}} 秒", "durationSeconds_other": "{{count}} 秒", "durationMinutes_one": "{{count}} 分", - "durationMinutes_other": "{{count}} 分" + "durationMinutes_other": "{{count}} 分", + "discard": "録音を破棄", + "retry": "音声入力を再試行", + "retryShort": "再試行" }, "status": { "finishingOn": "{{computer}} で仕上げています", "finishingOnComputer": "コンピュータで仕上げています", "movedTo": "{{computer}} に切り替えました", "movedToComputer": "コンピュータに切り替えました" + }, + "failure": { + "connectionLost": "接続が切れました", + "connectionSlow": "接続が遅すぎます", + "phoneStopped": "このスマートフォンで停止しました", + "stopped": "音声入力が停止しました", + "recordingKept": "録音は保持されています" + }, + "announce": { + "typedInto": "{{target}} に入力しました", + "insertedIn": "{{target}} に挿入しました", + "listeningOnPhone": "聞き取り中。このスマートフォンで文字起こししています。", + "listeningOn": "聞き取り中。{{computer}} で文字起こししています。", + "listeningOnComputer": "聞き取り中。コンピュータで文字起こししています。", + "finishing": "仕上げ中。", + "inserted": "挿入しました。", + "cancelled": "音声入力をキャンセルしました。", + "movedTo": "このスマートフォンでの文字起こしが止まりました。{{computer}} で続けます。", + "movedToComputer": "このスマートフォンでの文字起こしが止まりました。コンピュータで続けます。", + "stoppedKept": "音声入力が停止しました。{{reason}}。録音は保持されています。", + "stillListening": "聞き取りを続けています。" + }, + "pill": { + "open": "開く", + "listening": "聞き取り中", + "starting": "開始中", + "finishing": "仕上げ中", + "stopped": "音声入力が停止しました", + "label": "{{target}} への音声入力、{{duration}}", + "hint": "ダブルタップで戻る" } }, "files": { @@ -2124,6 +2159,10 @@ "providerExitedRejection": "このメッセージが送信される前に {{agent}} が停止しました。", "providerExitedRow": "この応答の途中で {{agent}} が停止しました。この会話で続けることができます。", "providerRateLimited": "{{agent}} はレート制限を受けているため、再試行しています。", + "providerUnavailable": "サービスが混雑しているため、{{agent}} は応答できませんでした。別のモデルを選ぶか、しばらく待ってから再送してください。", + "providerSafetyStopped": "{{agent}} は安全確認の後、この応答を停止しました。リクエストを見直して再送してください。", + "providerResponseFailed": "{{agent}} はこの応答を完了できませんでした。詳細を開いて確認してください。", + "selectedModel": "選択されたモデル", "providerRejected": "{{agent}} はこのメッセージを受け付けませんでした。", "providerRejectedQuoted": "{{agent}} はこのメッセージを受け付けませんでした: {{detail}}。", "providerRetryLastError": "直近のエラー: {{detail}}。", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index 5f34699729a..c6246089d50 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -300,6 +300,7 @@ "plan": "계획", "stoppedManually": "수동으로 중지됨", "permissionDenied": "{{agent}}이(가) 권한을 거부했습니다. 세부 정보 보기.", + "safetyReviewApproved": "{{agent}}이(가) 이 작업을 승인했습니다. 세부 정보 보기.", "safetyReview": "{{agent}}이(가) 안전 검토 경고를 보고했습니다. 세부 정보 보기.", "truncatedResponse": "공급자 응답이 잘렸습니다(원래 크기: {{bytes}}바이트).", "modelFallback": "Claude가 모델을 변경했습니다: {{from}} → {{to}}.", @@ -598,6 +599,7 @@ "fullCopySaveUpdate": "이 첨부 파일의 전체 복사와 저장 기능은 휴대전화 업데이트에서 제공될 예정입니다." }, "hostOutage": { + "offlineAsOf": "{{host}} 오프라인 · {{time}} 기준", "reconnecting": "{{hostName}}에 다시 연결하는 중…", "stopped": "{{hostName}}이(가) 중지되었습니다. 컴퓨터에서 시작하세요.", "server": "서버", @@ -1313,13 +1315,46 @@ "durationSeconds_one": "{{count}}초", "durationSeconds_other": "{{count}}초", "durationMinutes_one": "{{count}}분", - "durationMinutes_other": "{{count}}분" + "durationMinutes_other": "{{count}}분", + "discard": "녹음 삭제", + "retry": "받아쓰기 다시 시도", + "retryShort": "다시 시도" }, "status": { "finishingOn": "{{computer}}에서 마무리 중", "finishingOnComputer": "컴퓨터에서 마무리 중", "movedTo": "{{computer}}(으)로 전환됨", "movedToComputer": "컴퓨터로 전환됨" + }, + "failure": { + "connectionLost": "연결 끊김", + "connectionSlow": "연결이 너무 느림", + "phoneStopped": "이 휴대폰에서 중지됨", + "stopped": "받아쓰기 중지됨", + "recordingKept": "녹음 보관됨" + }, + "announce": { + "typedInto": "{{target}}에 입력됨", + "insertedIn": "{{target}}에 삽입됨", + "listeningOnPhone": "듣는 중. 이 휴대폰에서 받아쓰는 중입니다.", + "listeningOn": "듣는 중. {{computer}}에서 받아쓰는 중입니다.", + "listeningOnComputer": "듣는 중. 컴퓨터에서 받아쓰는 중입니다.", + "finishing": "마무리 중.", + "inserted": "삽입됨.", + "cancelled": "받아쓰기가 취소되었습니다.", + "movedTo": "이 휴대폰의 받아쓰기가 멈췄습니다. {{computer}}에서 계속합니다.", + "movedToComputer": "이 휴대폰의 받아쓰기가 멈췄습니다. 컴퓨터에서 계속합니다.", + "stoppedKept": "받아쓰기가 중지되었습니다. {{reason}}. 녹음은 보관됩니다.", + "stillListening": "계속 듣는 중입니다." + }, + "pill": { + "open": "열기", + "listening": "듣는 중", + "starting": "시작 중", + "finishing": "마무리 중", + "stopped": "받아쓰기 중지됨", + "label": "{{target}}에 받아쓰기, {{duration}}", + "hint": "두 번 탭하여 돌아가기" } }, "files": { @@ -2124,6 +2159,10 @@ "providerExitedRejection": "이 메시지가 전송되기 전에 {{agent}}이(가) 중지되었습니다.", "providerExitedRow": "이 응답이 진행되는 동안 {{agent}}이(가) 중지되었습니다. 이 대화에서 계속할 수 있습니다.", "providerRateLimited": "{{agent}}이(가) 속도 제한에 걸려 다시 시도하고 있습니다.", + "providerUnavailable": "서비스가 혼잡하여 {{agent}}이(가) 응답하지 못했습니다. 다른 모델을 선택하거나 잠시 기다린 후 다시 보내세요.", + "providerSafetyStopped": "{{agent}}이(가) 안전 검사 후 이 응답을 중단했습니다. 요청을 검토한 후 다시 보내세요.", + "providerResponseFailed": "{{agent}}이(가) 이 응답을 완료하지 못했습니다. 자세한 내용을 열어 확인하세요.", + "selectedModel": "선택한 모델", "providerRejected": "{{agent}}이(가) 이 메시지를 받아들이지 않았습니다.", "providerRejectedQuoted": "{{agent}}이(가) 이 메시지를 받아들이지 않았습니다: {{detail}}.", "providerRetryLastError": "마지막 오류: {{detail}}.", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index 5ecd4f2b77d..e563922fc2e 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -304,6 +304,7 @@ "plan": "Plano", "stoppedManually": "Interrompido manualmente", "permissionDenied": "{{agent}} negou a permissão. Ver detalhes.", + "safetyReviewApproved": "{{agent}} aprovou esta ação. Ver detalhes.", "safetyReview": "{{agent}} relatou um aviso de revisão de segurança. Ver detalhes.", "truncatedResponse": "Resposta do provedor truncada (tamanho original: {{bytes}} bytes).", "modelFallback": "Claude mudou de modelo: {{from}} → {{to}}.", @@ -637,6 +638,7 @@ "fullCopySaveUpdate": "Copiar tudo e Salvar para este anexo estarão disponíveis em uma atualização do celular." }, "hostOutage": { + "offlineAsOf": "{{host}} está off-line · em {{time}}", "reconnecting": "{{hostName}} está reconectando…", "stopped": "{{hostName}} está parado. Inicie-o no seu computador.", "server": "O servidor", @@ -1358,13 +1360,46 @@ "durationSeconds_many": "{{count}} segundos", "durationMinutes_one": "{{count}} minuto", "durationMinutes_other": "{{count}} minutos", - "durationMinutes_many": "{{count}} minutos" + "durationMinutes_many": "{{count}} minutos", + "discard": "Descartar gravação", + "retry": "Tentar ditado novamente", + "retryShort": "Tentar novamente" }, "status": { "finishingOn": "Finalizando em {{computer}}", "finishingOnComputer": "Finalizando no computador", "movedTo": "Passou para {{computer}}", "movedToComputer": "Passou para o computador" + }, + "failure": { + "connectionLost": "Conexão perdida", + "connectionSlow": "Conexão muito lenta", + "phoneStopped": "Parou neste telefone", + "stopped": "Ditado interrompido", + "recordingKept": "Gravação mantida" + }, + "announce": { + "typedInto": "Digitado em {{target}}", + "insertedIn": "Inserido em {{target}}", + "listeningOnPhone": "Ouvindo. Transcrevendo neste telefone.", + "listeningOn": "Ouvindo. Transcrevendo em {{computer}}.", + "listeningOnComputer": "Ouvindo. Transcrevendo no computador.", + "finishing": "Finalizando.", + "inserted": "Inserido.", + "cancelled": "Ditado cancelado.", + "movedTo": "Este telefone parou de transcrever. Continuando em {{computer}}.", + "movedToComputer": "Este telefone parou de transcrever. Continuando no computador.", + "stoppedKept": "Ditado interrompido. {{reason}}. Sua gravação foi mantida.", + "stillListening": "Ainda ouvindo." + }, + "pill": { + "open": "Abrir", + "listening": "Ouvindo", + "starting": "Iniciando", + "finishing": "Finalizando", + "stopped": "Ditado interrompido", + "label": "Ditado para {{target}}, {{duration}}", + "hint": "Toque duas vezes para voltar" } }, "files": { @@ -2196,6 +2231,10 @@ "providerExitedRejection": "{{agent}} parou antes de esta mensagem ser enviada.", "providerExitedRow": "{{agent}} parou enquanto esta resposta estava em andamento. Você pode continuar nesta conversa.", "providerRateLimited": "{{agent}} atingiu o limite de requisições e está tentando novamente.", + "providerUnavailable": "{{agent}} não conseguiu responder porque o serviço está ocupado. Escolha outro modelo ou aguarde um pouco e envie novamente.", + "providerSafetyStopped": "{{agent}} interrompeu esta resposta após uma verificação de segurança. Revise sua solicitação e envie novamente.", + "providerResponseFailed": "{{agent}} não conseguiu concluir esta resposta. Abra os detalhes para obter mais informações.", + "selectedModel": "o modelo selecionado", "providerRejected": "{{agent}} não aceitou esta mensagem.", "providerRejectedQuoted": "{{agent}} não aceitou esta mensagem: {{detail}}.", "providerRetryLastError": "Último erro: {{detail}}.", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index fc5ba8b987e..06a53c287b8 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -308,6 +308,7 @@ "plan": "План", "stoppedManually": "Остановлено вручную", "permissionDenied": "{{agent}} отказал в разрешении. Подробнее.", + "safetyReviewApproved": "{{agent}} одобрил это действие. Подробнее.", "safetyReview": "{{agent}} сообщил о предупреждении проверки безопасности. Подробнее.", "truncatedResponse": "Ответ поставщика обрезан (исходный размер: {{bytes}} байт).", "modelFallback": "Claude переключил модель: {{from}} → {{to}}.", @@ -672,6 +673,7 @@ "fullCopySaveUpdate": "Полное копирование и сохранение этого вложения станут доступны после обновления приложения на телефоне." }, "hostOutage": { + "offlineAsOf": "{{host}} не в сети · на {{time}}", "reconnecting": "{{hostName}} переподключается…", "stopped": "{{hostName}} остановлен. Запустите его на компьютере.", "server": "Сервер", @@ -1399,13 +1401,46 @@ "durationMinutes_one": "{{count}} минута", "durationMinutes_other": "{{count}} минуты", "durationMinutes_few": "{{count}} минуты", - "durationMinutes_many": "{{count}} минут" + "durationMinutes_many": "{{count}} минут", + "discard": "Удалить запись", + "retry": "Повторить диктовку", + "retryShort": "Повторить" }, "status": { "finishingOn": "Завершается на {{computer}}", "finishingOnComputer": "Завершается на компьютере", "movedTo": "Перешло на {{computer}}", "movedToComputer": "Перешло на компьютер" + }, + "failure": { + "connectionLost": "Соединение потеряно", + "connectionSlow": "Соединение слишком медленное", + "phoneStopped": "Остановлено на этом телефоне", + "stopped": "Диктовка остановлена", + "recordingKept": "Запись сохранена" + }, + "announce": { + "typedInto": "Введено в {{target}}", + "insertedIn": "Вставлено в {{target}}", + "listeningOnPhone": "Слушаю. Распознавание на этом телефоне.", + "listeningOn": "Слушаю. Распознавание на {{computer}}.", + "listeningOnComputer": "Слушаю. Распознавание на компьютере.", + "finishing": "Завершение.", + "inserted": "Вставлено.", + "cancelled": "Диктовка отменена.", + "movedTo": "Этот телефон перестал распознавать. Продолжение на {{computer}}.", + "movedToComputer": "Этот телефон перестал распознавать. Продолжение на компьютере.", + "stoppedKept": "Диктовка остановлена. {{reason}}. Запись сохранена.", + "stillListening": "Продолжаю слушать." + }, + "pill": { + "open": "Открыть", + "listening": "Слушаю", + "starting": "Запуск", + "finishing": "Завершение", + "stopped": "Диктовка остановлена", + "label": "Диктовка в {{target}}, {{duration}}", + "hint": "Дважды коснитесь, чтобы вернуться" } }, "files": { @@ -2264,6 +2299,10 @@ "providerExitedRejection": "{{agent}} остановился до отправки этого сообщения.", "providerExitedRow": "{{agent}} остановился во время ответа. Вы можете продолжить этот разговор.", "providerRateLimited": "{{agent}} повторяет попытку из-за ограничения частоты запросов.", + "providerUnavailable": "{{agent}} не смог ответить, поскольку сервис занят. Выберите другую модель или немного подождите и отправьте сообщение снова.", + "providerSafetyStopped": "{{agent}} остановил этот ответ после проверки безопасности. Проверьте запрос и отправьте его снова.", + "providerResponseFailed": "{{agent}} не удалось завершить этот ответ. Откройте подробности, чтобы узнать больше.", + "selectedModel": "выбранную модель", "providerRejected": "{{agent}} не принял это сообщение.", "providerRejectedQuoted": "{{agent}} не принял это сообщение: {{detail}}.", "providerRetryLastError": "Последняя ошибка: {{detail}}.", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index 1648a819495..03704efc034 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -300,6 +300,7 @@ "plan": "Plan", "stoppedManually": "Elle durduruldu", "permissionDenied": "{{agent}} izin vermedi. Ayrıntıları görüntüleyin.", + "safetyReviewApproved": "{{agent}} bu işleme onay verdi. Ayrıntıları görüntüleyin.", "safetyReview": "{{agent}} bir güvenlik incelemesi uyarısı bildirdi. Ayrıntıları görüntüleyin.", "truncatedResponse": "Sağlayıcı yanıtı kısaltıldı (özgün boyut: {{bytes}} bayt).", "modelFallback": "Claude model değiştirdi: {{from}} → {{to}}.", @@ -602,6 +603,7 @@ "fullCopySaveUpdate": "Bu ek için Tümünü Kopyala ve Kaydet özellikleri bir telefon güncellemesiyle kullanılabilecek." }, "hostOutage": { + "offlineAsOf": "{{host}} çevrimdışı · {{time}} itibarıyla", "reconnecting": "{{hostName}} yeniden bağlanıyor…", "stopped": "{{hostName}} durduruldu. Bilgisayarınızda başlatın.", "server": "Sunucu", @@ -1317,13 +1319,46 @@ "durationSeconds_one": "{{count}} saniye", "durationSeconds_other": "{{count}} saniye", "durationMinutes_one": "{{count}} dakika", - "durationMinutes_other": "{{count}} dakika" + "durationMinutes_other": "{{count}} dakika", + "discard": "Kaydı sil", + "retry": "Dikteyi yeniden dene", + "retryShort": "Yeniden dene" }, "status": { "finishingOn": "{{computer}} üzerinde tamamlanıyor", "finishingOnComputer": "Bilgisayarda tamamlanıyor", "movedTo": "{{computer}} cihazına geçildi", "movedToComputer": "Bilgisayara geçildi" + }, + "failure": { + "connectionLost": "Bağlantı kesildi", + "connectionSlow": "Bağlantı çok yavaş", + "phoneStopped": "Bu telefonda durdu", + "stopped": "Dikte durdu", + "recordingKept": "Kayıt saklandı" + }, + "announce": { + "typedInto": "{{target}} içine yazıldı", + "insertedIn": "{{target}} içine eklendi", + "listeningOnPhone": "Dinleniyor. Bu telefonda yazıya dökülüyor.", + "listeningOn": "Dinleniyor. {{computer}} üzerinde yazıya dökülüyor.", + "listeningOnComputer": "Dinleniyor. Bilgisayarda yazıya dökülüyor.", + "finishing": "Tamamlanıyor.", + "inserted": "Eklendi.", + "cancelled": "Dikte iptal edildi.", + "movedTo": "Bu telefon yazıya dökmeyi bıraktı. {{computer}} üzerinde devam ediliyor.", + "movedToComputer": "Bu telefon yazıya dökmeyi bıraktı. Bilgisayarda devam ediliyor.", + "stoppedKept": "Dikte durdu. {{reason}}. Kaydınız saklandı.", + "stillListening": "Dinlemeye devam ediliyor." + }, + "pill": { + "open": "Aç", + "listening": "Dinleniyor", + "starting": "Başlatılıyor", + "finishing": "Tamamlanıyor", + "stopped": "Dikte durdu", + "label": "{{target}} için dikte, {{duration}}", + "hint": "Geri dönmek için iki kez dokunun" } }, "files": { @@ -2128,6 +2163,10 @@ "providerExitedRejection": "Bu mesaj gönderilmeden önce {{agent}} durdu.", "providerExitedRow": "Bu yanıt hazırlanırken {{agent}} durdu. Bu konuşmada devam edebilirsiniz.", "providerRateLimited": "{{agent}} istek hızı sınırına ulaştı ve yeniden deniyor.", + "providerUnavailable": "Hizmet meşgul olduğu için {{agent}} yanıt veremedi. Başka bir model seçin veya biraz bekleyip yeniden gönderin.", + "providerSafetyStopped": "{{agent}}, bir güvenlik kontrolünden sonra bu yanıtı durdurdu. İsteğinizi gözden geçirip yeniden gönderin.", + "providerResponseFailed": "{{agent}} bu yanıtı tamamlayamadı. Daha fazla bilgi için ayrıntıları açın.", + "selectedModel": "seçilen modeli", "providerRejected": "{{agent}} bu mesajı kabul etmedi.", "providerRejectedQuoted": "{{agent}} bu mesajı kabul etmedi: {{detail}}.", "providerRetryLastError": "Son hata: {{detail}}.", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index c9c3df04598..a3c8197a0f6 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -300,6 +300,7 @@ "plan": "計畫", "stoppedManually": "已手動停止", "permissionDenied": "{{agent}} 拒絕了權限。查看詳細資訊。", + "safetyReviewApproved": "{{agent}} 已核准此操作。查看詳細資訊。", "safetyReview": "{{agent}} 回報了安全審查警告。查看詳細資訊。", "truncatedResponse": "供應商回應已截斷(原始大小:{{bytes}} 位元組)。", "modelFallback": "Claude 已切換模型:{{from}} → {{to}}。", @@ -598,6 +599,7 @@ "fullCopySaveUpdate": "完整複製和儲存此附件的功能將在手機更新中提供。" }, "hostOutage": { + "offlineAsOf": "{{host}} 已離線 · 截至 {{time}}", "reconnecting": "{{hostName}} 正在重新連線…", "stopped": "{{hostName}} 已停止。請在你的電腦上啟動它。", "server": "伺服器", @@ -1313,13 +1315,46 @@ "durationSeconds_one": "{{count}} 秒", "durationSeconds_other": "{{count}} 秒", "durationMinutes_one": "{{count}} 分鐘", - "durationMinutes_other": "{{count}} 分鐘" + "durationMinutes_other": "{{count}} 分鐘", + "discard": "捨棄錄音", + "retry": "重試聽寫", + "retryShort": "重試" }, "status": { "finishingOn": "正在 {{computer}} 上完成", "finishingOnComputer": "正在電腦上完成", "movedTo": "已轉到 {{computer}}", "movedToComputer": "已轉到電腦" + }, + "failure": { + "connectionLost": "連線中斷", + "connectionSlow": "連線太慢", + "phoneStopped": "已在此手機上停止", + "stopped": "聽寫已停止", + "recordingKept": "錄音已保留" + }, + "announce": { + "typedInto": "已輸入到 {{target}}", + "insertedIn": "已插入到 {{target}}", + "listeningOnPhone": "正在聽。正在此手機上轉寫。", + "listeningOn": "正在聽。正在 {{computer}} 上轉寫。", + "listeningOnComputer": "正在聽。正在電腦上轉寫。", + "finishing": "正在完成。", + "inserted": "已插入。", + "cancelled": "已取消聽寫。", + "movedTo": "此手機已停止轉寫。在 {{computer}} 上繼續。", + "movedToComputer": "此手機已停止轉寫。在電腦上繼續。", + "stoppedKept": "聽寫已停止。{{reason}}。錄音已保留。", + "stillListening": "仍在聽。" + }, + "pill": { + "open": "開啟", + "listening": "正在聽", + "starting": "正在開始", + "finishing": "正在完成", + "stopped": "聽寫已停止", + "label": "聽寫到 {{target}},{{duration}}", + "hint": "點兩下返回" } }, "files": { @@ -2124,6 +2159,10 @@ "providerExitedRejection": "{{agent}} 在傳送此訊息前已停止。", "providerExitedRow": "{{agent}} 在產生此回覆時停止了。您可以在此對話中繼續。", "providerRateLimited": "{{agent}} 受到速率限制,正在重試。", + "providerUnavailable": "{{agent}} 因服務忙碌而無法回覆。請選擇其他模型,或稍候片刻後重新傳送。", + "providerSafetyStopped": "{{agent}} 在安全檢查後停止了此次回覆。請檢查您的請求後重新傳送。", + "providerResponseFailed": "{{agent}} 未能完成此回覆。開啟詳細資料以取得更多資訊。", + "selectedModel": "所選模型", "providerRejected": "{{agent}} 未接受此訊息。", "providerRejectedQuoted": "{{agent}} 未接受此訊息:{{detail}}。", "providerRetryLastError": "上次錯誤:{{detail}}。", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 611e00ec678..459357aa1e1 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -300,6 +300,7 @@ "plan": "计划", "stoppedManually": "已手动停止", "permissionDenied": "{{agent}} 拒绝了权限。查看详情。", + "safetyReviewApproved": "{{agent}} 已批准此操作。查看详情。", "safetyReview": "{{agent}} 报告了安全审查警告。查看详情。", "truncatedResponse": "提供方响应已截断(原始大小:{{bytes}} 字节)。", "modelFallback": "Claude 已切换模型:{{from}} → {{to}}。", @@ -598,6 +599,7 @@ "fullCopySaveUpdate": "完整复制和保存此附件的功能将在手机更新中提供。" }, "hostOutage": { + "offlineAsOf": "{{host}} 已离线 · 截至 {{time}}", "reconnecting": "{{hostName}} 正在重新连接…", "stopped": "{{hostName}} 已停止。请在你的电脑上启动它。", "server": "服务器", @@ -1313,13 +1315,46 @@ "durationSeconds_one": "{{count}} 秒", "durationSeconds_other": "{{count}} 秒", "durationMinutes_one": "{{count}} 分钟", - "durationMinutes_other": "{{count}} 分钟" + "durationMinutes_other": "{{count}} 分钟", + "discard": "丢弃录音", + "retry": "重试听写", + "retryShort": "重试" }, "status": { "finishingOn": "正在 {{computer}} 上完成", "finishingOnComputer": "正在电脑上完成", "movedTo": "已转到 {{computer}}", "movedToComputer": "已转到电脑" + }, + "failure": { + "connectionLost": "连接已断开", + "connectionSlow": "连接太慢", + "phoneStopped": "已在此手机上停止", + "stopped": "听写已停止", + "recordingKept": "录音已保留" + }, + "announce": { + "typedInto": "已输入到 {{target}}", + "insertedIn": "已插入到 {{target}}", + "listeningOnPhone": "正在听。正在此手机上转写。", + "listeningOn": "正在听。正在 {{computer}} 上转写。", + "listeningOnComputer": "正在听。正在电脑上转写。", + "finishing": "正在完成。", + "inserted": "已插入。", + "cancelled": "已取消听写。", + "movedTo": "此手机已停止转写。在 {{computer}} 上继续。", + "movedToComputer": "此手机已停止转写。在电脑上继续。", + "stoppedKept": "听写已停止。{{reason}}。录音已保留。", + "stillListening": "仍在听。" + }, + "pill": { + "open": "打开", + "listening": "正在听", + "starting": "正在开始", + "finishing": "正在完成", + "stopped": "听写已停止", + "label": "听写到 {{target}},{{duration}}", + "hint": "轻点两下返回" } }, "files": { @@ -2124,6 +2159,10 @@ "providerExitedRejection": "{{agent}} 在发送此消息前已停止。", "providerExitedRow": "{{agent}} 在生成此回复时停止了。您可以在此对话中继续。", "providerRateLimited": "{{agent}} 已被限流,正在重试。", + "providerUnavailable": "{{agent}} 因服务繁忙而无法回复。请选择其他模型,或稍等片刻后重新发送。", + "providerSafetyStopped": "{{agent}} 在安全检查后停止了此次回复。请检查您的请求后重新发送。", + "providerResponseFailed": "{{agent}} 未能完成此回复。打开详情了解更多信息。", + "selectedModel": "所选模型", "providerRejected": "{{agent}} 未接受此消息。", "providerRejectedQuoted": "{{agent}} 未接受此消息:{{detail}}。", "providerRetryLastError": "上次错误:{{detail}}。", diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index 362ef475933..11e05d21660 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -27,6 +27,7 @@ import { useNativeImageActions } from '../platform/native-image-actions' import { processDeviceStore } from '../device-store/device-store' import { serveDeviceStoreVerb } from './device-store-verb-server' import { BRIDGE_STORE_VERB } from './bridge/bridge-store-verb' +import { useAppLeavesForeground } from './use-app-leaves-foreground' import { useShellPageBack } from './use-shell-page-back' import { useShellStackPop } from './use-shell-stack-pop' import { usePageLocationOnFold } from './page-location-on-fold' @@ -263,6 +264,7 @@ export function MobileWebShellScreen({ // The stream survives dropped frames; keep a count because diagnostics print only once per host. onBinaryFramesDropped: reportDroppedBinaryFrames }) + useAppLeavesForeground(bridge.sendAppInactive) // paneKey changes keep the session mounted; the host deduplicates routes and preserves in-flight frames. useShellPageStorageRefresh(refreshStorage, bridge.publishStorage) diff --git a/mobile/src/mobile-web-shell/bridge-host-back.ts b/mobile/src/mobile-web-shell/bridge-host-back.ts index c7bfdc7c1ee..26a49beb452 100644 --- a/mobile/src/mobile-web-shell/bridge-host-back.ts +++ b/mobile/src/mobile-web-shell/bridge-host-back.ts @@ -8,6 +8,8 @@ export type BridgeSessionBack = { readonly storageKeys?: readonly string[] /** The page's `ready` said it reads `connectionPath` frames. */ readonly connectionPathFrames?: true + /** The page's `ready` said it reads `appInactive` frames. */ + readonly appInactiveFrames?: true readonly terminalKeyRailClaim?: { readonly inputOwner?: string } } diff --git a/mobile/src/mobile-web-shell/bridge-host-contract.ts b/mobile/src/mobile-web-shell/bridge-host-contract.ts index efa1f1aca21..aa31263a3e6 100644 --- a/mobile/src/mobile-web-shell/bridge-host-contract.ts +++ b/mobile/src/mobile-web-shell/bridge-host-contract.ts @@ -168,6 +168,8 @@ export type BridgeHost = { * every page older than the frame; the caller then leaves the key to the navigator. */ sendBack: () => boolean + /** Tells a page that reads it that the app is leaving the foreground; nothing for older pages. */ + sendAppInactive: () => void // Transfer the session’s Back state on client-driven host rebuild; the mounted page never reclaims it. Ending sessions simply discard it. readSessionBack: () => BridgeSessionBack dispose: () => void diff --git a/mobile/src/mobile-web-shell/bridge-host-init.test.ts b/mobile/src/mobile-web-shell/bridge-host-init.test.ts index 24ac5913f79..0a64fd9585f 100644 --- a/mobile/src/mobile-web-shell/bridge-host-init.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-init.test.ts @@ -249,6 +249,19 @@ describe('init and state', () => { }) }) + it('tells only a page that reads them that the app is leaving the foreground', () => { + const reads = harness() + reads.host.receive(clientFrame({ type: 'ready', appInactiveFrames: true })) + reads.host.sendAppInactive() + expect(reads.last().type).toBe('appInactive') + + const older = harness() + older.host.receive(clientFrame({ type: 'ready' })) + const sent = older.frames().length + older.host.sendAppInactive() + expect(older.frames()).toHaveLength(sent) + }) + it('sends no path frame to a page that never said it reads them', () => { let notifyPath = () => {} const client = createFakeRpcClient({ diff --git a/mobile/src/mobile-web-shell/bridge-host.ts b/mobile/src/mobile-web-shell/bridge-host.ts index 5fb65c9c340..914b25c9b70 100644 --- a/mobile/src/mobile-web-shell/bridge-host.ts +++ b/mobile/src/mobile-web-shell/bridge-host.ts @@ -1,4 +1,5 @@ import type { ConnectionState } from '../transport/connection/connection-state' +import { BRIDGE_APP_INACTIVE_FRAME } from './bridge/bridge-app-inactive' import { BridgeCapExceededError } from './bridge-host-errors' import { createNativeVerbServer } from './bridge-host-native-verbs' @@ -67,6 +68,7 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { // re-handshake. Null is a page older than `storageKeys`, which gets the legacy keys only. let pageStorageKeys: readonly string[] | null = options.sessionBack?.storageKeys ?? null let pageReadsConnectionPath = options.sessionBack?.connectionPathFrames === true + let pageReadsAppInactive = options.sessionBack?.appInactiveFrames === true const frames = createBridgeHostFrames({ post: options.post, @@ -218,6 +220,7 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { serving = true pageStorageKeys = message.storageKeys ?? null pageReadsConnectionPath = message.connectionPathFrames === true + pageReadsAppInactive = message.appInactiveFrames === true back.readReady() // Dropped like the Back claim: a page still showing a terminal claims again on this `init`. reportRailClaim(false) @@ -331,11 +334,17 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { publishUiLocale: (next) => { routes.publishUiLocale(next, deliverable()) }, + sendAppInactive: () => { + if (pageReadsAppInactive && deliverable()) { + send({ v: BRIDGE_PROTOCOL_VERSION, type: BRIDGE_APP_INACTIVE_FRAME }) + } + }, sendBack: back.send, readSessionBack: () => ({ ...back.read(), ...(pageStorageKeys === null ? {} : { storageKeys: pageStorageKeys }), ...(pageReadsConnectionPath ? { connectionPathFrames: true as const } : {}), + ...(pageReadsAppInactive ? { appInactiveFrames: true as const } : {}), ...(railClaimed ? { terminalKeyRailClaim: { inputOwner: railOwner } } : {}) }), dispose diff --git a/mobile/src/mobile-web-shell/bridge/bridge-app-inactive.ts b/mobile/src/mobile-web-shell/bridge/bridge-app-inactive.ts new file mode 100644 index 00000000000..da8d00eecf0 --- /dev/null +++ b/mobile/src/mobile-web-shell/bridge/bridge-app-inactive.ts @@ -0,0 +1,22 @@ +/** + * Shell to page, a frame: the app is leaving the foreground. iOS sends a page `visibilitychange` + * only once the app reaches the background, and a swipe-kill from the app switcher can stop it + * while it is merely inactive, so the page saves what it would save on hide when this arrives. + * Pages that read it say so in `ready`; older pages never receive one, and older shells never + * send one, so the page keeps saving on hide alone. + */ +export const BRIDGE_APP_INACTIVE_FRAME = 'appInactive' + +const listeners = new Set<() => void>() + +/** Page side: runs `listener` each time the shell says the app is leaving the foreground. */ +export function onPageAppInactive(listener: () => void): () => void { + listeners.add(listener) + return () => listeners.delete(listener) +} + +export function emitPageAppInactive(): void { + for (const listener of listeners) { + listener() + } +} diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts index 57c5300af27..84c5a156be0 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts @@ -11,6 +11,7 @@ import { type BridgeHostMessage } from './bridge-envelope' import { reconstructBridgeError } from './bridge-error-capture' +import { BRIDGE_APP_INACTIVE_FRAME } from './bridge-app-inactive' export type BridgeInboundFramePort = { requests: BridgeClientRequests @@ -21,6 +22,7 @@ export type BridgeInboundFramePort = { acceptConnectionPath: (connection: BridgeConnectionSnapshot) => void acceptBack: () => void acceptParked: () => void + acceptAppInactive: () => void acceptTerminalKey: (key: BridgeTerminalKeyId, inputOwner?: string) => void } @@ -70,6 +72,9 @@ export function createBridgeInboundFrameReader( case 'parked': port.acceptParked() return + case BRIDGE_APP_INACTIVE_FRAME: + port.acceptAppInactive() + return case 'terminalKey': port.acceptTerminalKey(message.key, message.inputOwner) return diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts index cf8f09e1382..818fd030288 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts @@ -46,6 +46,7 @@ export function createPageReadyFrame(): Extract +// The page has no announce call of its own (RNW's is a no-op); the shell speaks for it. Long text is a page bug, so it is refused. +export const a11yAnnounceParamsSchema = z.strictObject({ message: z.string().min(1).max(500) }) +// announced:false when the shell leaves it to the page's live region (Android, where TalkBack reads it). +export const a11yAnnounceResultSchema = z.strictObject({ announced: z.boolean() }) + export const BRIDGE_NATIVE_VERBS: Readonly> = { 'native.clipboard.write': { params: clipboardWriteParamsSchema, @@ -150,6 +156,10 @@ export const BRIDGE_NATIVE_VERBS: Readonly terminalKeys.accept(key, inputOwner) }) diff --git a/mobile/src/mobile-web-shell/bridge/use-native-verbs.ts b/mobile/src/mobile-web-shell/bridge/use-native-verbs.ts index f9f0cc9e62e..1c771635517 100644 --- a/mobile/src/mobile-web-shell/bridge/use-native-verbs.ts +++ b/mobile/src/mobile-web-shell/bridge/use-native-verbs.ts @@ -18,6 +18,7 @@ import { } from './bridge-audio-verbs' import { clipboardReadResultSchema, + a11yAnnounceResultSchema, clipboardWriteResultSchema, pdfViewResultSchema, type BridgeClipboardMime, @@ -70,6 +71,10 @@ export type NativeVerbs = { speechRead: () => Promise speechFinish: () => Promise speechCancel: () => Promise + // Older shells lack it; the page then keeps its live region, which VoiceOver may not read. + canAnnounce: boolean + // True when the shell spoke it. + announce: (message: string) => Promise } // Expose stable reason codes, including local ungranted and frame refusals. Unknown newer-shell codes floor to unreported so caller switches remain exhaustive. @@ -204,7 +209,10 @@ export function useNativeVerbs(): NativeVerbs { speechFinish: () => call(BRIDGE_SPEECH_VERB, { action: 'finish' }, speechFinishResultSchema), speechCancel: async () => { await call(BRIDGE_SPEECH_VERB, { action: 'cancel' }, speechCancelResultSchema) - } + }, + canAnnounce: has('native.a11y.announce'), + announce: async (message) => + (await call('native.a11y.announce', { message }, a11yAnnounceResultSchema)).announced } }, [client]) } diff --git a/mobile/src/mobile-web-shell/home-spare-page.ts b/mobile/src/mobile-web-shell/home-spare-page.ts index 1456e5909b1..bf93ad3d371 100644 --- a/mobile/src/mobile-web-shell/home-spare-page.ts +++ b/mobile/src/mobile-web-shell/home-spare-page.ts @@ -11,12 +11,16 @@ import { mintShellSessionId } from './shell-session-id' // A Home entry claims the spare about 0.2 s after the tap on a simulator; a native screen keeps it no longer. const HOME_SPARE_CLAIM_GRACE_MS = 2000 +// Hopping between Home and native screens would otherwise boot and destroy a whole page on every return. +const HOME_SPARE_REFILL_BACKOFF_MS = 30_000 + // What JS last asked native to park, until a claim or a drop. Native may since have dropped it on // its own (background, memory); this only saves the claim's native round trip when nothing can match. let parkedDirectory: string | null = null let dropTimer: ReturnType | null = null // A prepare still reading the store when Home goes must not park a spare after the drop ran. let homeShown = false +let unclaimedDropAt: number | null = null function cancelDrop(): void { if (dropTimer !== null) { @@ -37,13 +41,13 @@ export async function prepareHomeSparePage( if (active === null) { continue } - if (!homeShown) { + if (!homeShown || homeSpareRefillWaitMs() > 0) { return } const directory = generationDirectoryPath(active.directory) const prepared = await prepareSpareDocument(directory, mintShellSessionId()) if (prepared && !homeShown) { - await dropHomeSparePage() + await dropUnclaimedHomeSparePage() } else if (prepared) { parkedDirectory = directory } @@ -68,6 +72,14 @@ export async function claimHomeSparePage(directory: string): Promise { dropTimer = null - void dropHomeSparePage() + void (parkedDirectory === null ? dropHomeSparePage() : dropUnclaimedHomeSparePage()) }, HOME_SPARE_CLAIM_GRACE_MS) } +function dropUnclaimedHomeSparePage(): Promise { + unclaimedDropAt = performance.now() + return dropHomeSparePage() +} + // Also runs before any host's built files go: that is rare, and a spare must not outlive its files. export function dropHomeSparePage(): Promise { parkedDirectory = null diff --git a/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts b/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts new file mode 100644 index 00000000000..41306009caa --- /dev/null +++ b/mobile/src/mobile-web-shell/use-app-leaves-foreground.ts @@ -0,0 +1,41 @@ +import { useEffect, useLayoutEffect, useRef } from 'react' +import { AppState } from 'react-native' + +/** + * Calls `onLeave` once each time the app leaves the foreground, before the system can kill it from the app + * switcher. iOS: `inactive` (the app switcher, Notification Centre, Face ID); a page is hidden only once the app + * reaches the background, which a swipe-kill can skip. Android: window `blur` (Recents, the notification shade, and + * the app's own dialogs and sheets), because Recents leaves the activity resumed until the swipe kills the process. + * Callers must keep the work cheap and idempotent: it runs on every such flap. + * Not covered: on Android, Recents opened over one of the app's own sheets sends nothing more (the sheet's blur + * already did), so rows streamed in while the sheet was open wait for the next save. + */ +export function useAppLeavesForeground(onLeave: () => void): void { + const onLeaveRef = useRef(onLeave) + useLayoutEffect(() => { + onLeaveRef.current = onLeave + }, [onLeave]) + useEffect(() => { + let away = AppState.currentState !== 'active' + const leave = (): void => { + if (!away) { + away = true + onLeaveRef.current() + } + } + const back = (): void => { + away = false + } + const change = AppState.addEventListener('change', (next) => + next === 'active' ? back() : leave() + ) + // Window focus events come from Android only. + const blur = AppState.addEventListener('blur', leave) + const focus = AppState.addEventListener('focus', back) + return () => { + change.remove() + blur.remove() + focus.remove() + } + }, []) +} diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts index 07a5f2cba67..9c4d2637936 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts @@ -69,6 +69,8 @@ export type MobileWebShellBridgeView = { * serves never said it takes one — the caller then leaves the key to the navigator. */ readonly sendBack: () => boolean + /** Tells the mounted page the app is leaving the foreground; nothing with no host or an older page. */ + readonly sendAppInactive: () => void } export type MobileWebShellBridgeArgs = { @@ -342,6 +344,10 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW sendBack: useCallback(() => { const mounted = hostRef.current return mounted !== null && mounted.sessionId === sessionId && mounted.host.sendBack() + }, [sessionId]), + sendAppInactive: useCallback(() => { + const mounted = hostRef.current + return mounted?.sessionId === sessionId ? mounted.host.sendAppInactive() : undefined }, [sessionId]) } } diff --git a/mobile/src/platform/accessibility-announcer.ts b/mobile/src/platform/accessibility-announcer.ts new file mode 100644 index 00000000000..3f98cfba33b --- /dev/null +++ b/mobile/src/platform/accessibility-announcer.ts @@ -0,0 +1,10 @@ +import { useCallback } from 'react' +import { AccessibilityInfo } from 'react-native' + +// Speak a message to the screen reader; false when the caller should put it in a live region instead. +export function useAccessibilityAnnouncer(): (message: string) => Promise { + return useCallback(async (message: string) => { + AccessibilityInfo.announceForAccessibility(message) + return true + }, []) +} diff --git a/mobile/src/platform/accessibility-announcer.web.ts b/mobile/src/platform/accessibility-announcer.web.ts new file mode 100644 index 00000000000..647555ab841 --- /dev/null +++ b/mobile/src/platform/accessibility-announcer.web.ts @@ -0,0 +1,16 @@ +import { useCallback } from 'react' +import { useNativeVerbs } from '../mobile-web-shell/bridge/use-native-verbs' + +// RNW's announceForAccessibility does nothing, so the shell announces; older shells and Android leave it to the page's live region. +export function useAccessibilityAnnouncer(): (message: string) => Promise { + const verbs = useNativeVerbs() + return useCallback( + async (message: string) => { + if (!verbs.canAnnounce) { + return false + } + return verbs.announce(message).catch(() => false) + }, + [verbs] + ) +} diff --git a/mobile/src/platform/native-accessibility-announce.ts b/mobile/src/platform/native-accessibility-announce.ts new file mode 100644 index 00000000000..b171ff3948e --- /dev/null +++ b/mobile/src/platform/native-accessibility-announce.ts @@ -0,0 +1,12 @@ +import { AccessibilityInfo, Platform } from 'react-native' +import { a11yAnnounceParamsSchema } from '../mobile-web-shell/bridge/bridge-native-verbs' + +// VoiceOver ignores the page's live regions inside the shell's WebView, so the shell announces for it; TalkBack reads them, so Android leaves it to the page. +export function serveNativeAnnounceVerb(params: unknown): { announced: boolean } { + const { message } = a11yAnnounceParamsSchema.parse(params) + if (Platform.OS !== 'ios') { + return { announced: false } + } + AccessibilityInfo.announceForAccessibilityWithOptions(message, { queue: true }) + return { announced: true } +} diff --git a/mobile/src/platform/on-device-speech.ts b/mobile/src/platform/on-device-speech.ts index 143c56c3317..b592de40404 100644 --- a/mobile/src/platform/on-device-speech.ts +++ b/mobile/src/platform/on-device-speech.ts @@ -1,6 +1,10 @@ +import type { DictationTerm } from '../../../src/shared/dictation-dictionary' import type { OnDeviceSpeech } from './on-device-speech-contract' // The session screen is a page in the shell (on-device-speech.web.ts); native screens dictate through the computer. -export function useOnDeviceSpeech(_removeFillerWords?: boolean): OnDeviceSpeech | null { +export function useOnDeviceSpeech( + _removeFillerWords?: boolean, + _dictationTerms?: readonly DictationTerm[] +): OnDeviceSpeech | null { return null } diff --git a/mobile/src/platform/on-device-speech.web.test.tsx b/mobile/src/platform/on-device-speech.web.test.tsx index 03da733f3f7..2bcf77019fa 100644 --- a/mobile/src/platform/on-device-speech.web.test.tsx +++ b/mobile/src/platform/on-device-speech.web.test.tsx @@ -54,14 +54,4 @@ describe('on-device dictation text', () => { failure: null }) }) - - it('keeps every word when the computer turned filler removal off', async () => { - const speech = mountSpeech(false) - await speech.start() - - expect(await speech.finish()).toEqual({ - text: 'Äh, das ist, ähm, um fünf Uhr fertig.', - failure: null - }) - }) }) diff --git a/mobile/src/platform/on-device-speech.web.ts b/mobile/src/platform/on-device-speech.web.ts index 00a8c777803..fbaee133ffe 100644 --- a/mobile/src/platform/on-device-speech.web.ts +++ b/mobile/src/platform/on-device-speech.web.ts @@ -1,4 +1,5 @@ import { useLayoutEffect, useMemo, useRef } from 'react' +import type { DictationTerm } from '../../../src/shared/dictation-dictionary' import { createDictationTextPipeline } from '../../../src/shared/dictation-text-pipeline' import { useNativeVerbs, type NativeVerbs } from '../mobile-web-shell/bridge/use-native-verbs' import type { OnDeviceSpeech } from './on-device-speech-contract' @@ -9,25 +10,32 @@ const keepText = (text: string): string => text // The phone's recognizer transcribes only the locale it started in, so that locale's language picks the fillers, as the host does for its model. function phoneDictationTextCleaner( locale: string | null, - removeFillerWords: boolean + removeFillerWords: boolean, + dictationTerms: readonly DictationTerm[] | undefined ): (text: string) => string { const language = locale?.split('-')[0].toLowerCase() - const clean = createDictationTextPipeline(language ? { language } : undefined, { - removeFillerWords - }) + const clean = createDictationTextPipeline( + language ? { language } : undefined, + { removeFillerWords }, + dictationTerms + ) return clean ?? keepText } function createPageOnDeviceSpeech( verbs: NativeVerbs, - removeFillerWords: () => boolean + textSettings: () => { + removeFillerWords: boolean + dictationTerms: readonly DictationTerm[] | undefined + } ): OnDeviceSpeech { let clean = keepText return { status: () => verbs.speechStatus(onDeviceSpeechLocale()), start: async () => { const started = await verbs.speechStart(onDeviceSpeechLocale()) - clean = phoneDictationTextCleaner(started.locale, removeFillerWords()) + const { removeFillerWords, dictationTerms } = textSettings() + clean = phoneDictationTextCleaner(started.locale, removeFillerWords, dictationTerms) return started }, read: async () => { @@ -46,17 +54,20 @@ function createPageOnDeviceSpeech( } // Null on a shell without the verb, so dictation stays on the computer exactly as before. -// removeFillerWords is the computer's switch, read at each start. -export function useOnDeviceSpeech(removeFillerWords = true): OnDeviceSpeech | null { +// The computer's filler switch and dictionary for this worktree, read at each start. +export function useOnDeviceSpeech( + removeFillerWords = true, + dictationTerms?: readonly DictationTerm[] +): OnDeviceSpeech | null { const verbs = useNativeVerbs() - const removeFillerWordsRef = useRef(removeFillerWords) + const textSettingsRef = useRef({ removeFillerWords, dictationTerms }) useLayoutEffect(() => { - removeFillerWordsRef.current = removeFillerWords - }, [removeFillerWords]) + textSettingsRef.current = { removeFillerWords, dictationTerms } + }, [removeFillerWords, dictationTerms]) return useMemo( () => verbs.canRecognizeSpeech - ? createPageOnDeviceSpeech(verbs, () => removeFillerWordsRef.current) + ? createPageOnDeviceSpeech(verbs, () => textSettingsRef.current) : null, [verbs] ) diff --git a/mobile/src/platform/use-native-device-verbs.test.tsx b/mobile/src/platform/use-native-device-verbs.test.tsx index da46626ef78..757d8cb3805 100644 --- a/mobile/src/platform/use-native-device-verbs.test.tsx +++ b/mobile/src/platform/use-native-device-verbs.test.tsx @@ -17,6 +17,11 @@ const device = vi.hoisted(() => ({ wakeTags: new Array() })) +// The shell's announce verb speaks through React Native's AccessibilityInfo. +vi.mock('react-native', () => ({ + AccessibilityInfo: { announceForAccessibilityWithOptions: () => {} }, + Platform: { OS: 'ios' } +})) vi.mock('expo-clipboard', () => ({ setStringAsync: () => Promise.resolve(true), getStringAsync: device.clipboard.getStringAsync, diff --git a/mobile/src/platform/use-native-device-verbs.ts b/mobile/src/platform/use-native-device-verbs.ts index 3e7579ecd34..647133dea35 100644 --- a/mobile/src/platform/use-native-device-verbs.ts +++ b/mobile/src/platform/use-native-device-verbs.ts @@ -7,6 +7,7 @@ import { NATIVE_AUDIO_DEVICE_SAMPLE_RATE, nativeAudioDeviceEngine } from './nati import { createNativeSpeechServer } from './native-speech' import { nativeSpeechDeviceEngine } from './native-speech-device' import { serveNativeClipboardVerb } from './native-clipboard' +import { serveNativeAnnounceVerb } from './native-accessibility-announce' import { createNativeMediaVerbServer } from './native-media' import { discardStagedMedia, nativeMediaDeviceDeps } from './native-media-device' @@ -37,6 +38,9 @@ export function useNativeDeviceVerbs( if (verb === 'native.speech.act') { return speech.serve(params) } + if (verb === 'native.a11y.announce') { + return Promise.resolve(serveNativeAnnounceVerb(params)) + } if (verb === 'native.audio.start') { return speech.mayCapture().then((may) => may diff --git a/mobile/src/query/first-paint-query-keys.ts b/mobile/src/query/first-paint-query-keys.ts index b916cae5a07..47654004af7 100644 --- a/mobile/src/query/first-paint-query-keys.ts +++ b/mobile/src/query/first-paint-query-keys.ts @@ -1,4 +1,6 @@ +import type { QueryClient } from '@tanstack/react-query' import { normalizeExecutionHostId } from '../../../src/shared/execution-host' +import { accountsSnapshotFamily, accountsSnapshotKey } from '../accounts/accounts-snapshot-stream' import { HOST_LIST_TARGET, hostRepoCatalogQuery, @@ -12,6 +14,9 @@ import { import { hostViewFamily, hostViewKey } from '../host-screen/host-view-memory' import { hostProjectSectionsQuery } from '../host-screen/use-host-project-sections' import { sessionTabsFamily, sessionTabsKey } from '../session/tabs/mobile-session-last-tabs' +import type { MobileSessionTab } from '../session/tabs/mobile-session-tabs' +import { activeSessionTabOf } from '../session/tabs/active-session-tab' +import { storedTabChatTranscriptIdentity } from '../session/native-chat/mobile-native-chat-transcript-store' import { gitStatusQuery } from '../source-control/mobile-git-status-query' import { firstPaintTaskKeys } from '../tasks/task-query-storage' import { hostQueryKey } from './host-query-key' @@ -40,6 +45,11 @@ export function firstPaintQueryKeys(hostId: string, route: URL): PersistedHostQu if (screen === 'tasks') { return firstPaintTaskKeys(hostId) } + if (screen === 'accounts') { + return [persistedHostQueryKey(accountsSnapshotFamily, accountsSnapshotKey(hostId))].filter( + (key) => key !== null + ) + } if (screen === 'new-workspace') { // The drawer's existing-workspace check and host labels. return [ @@ -110,3 +120,25 @@ function workspaceScreenKeys( } return [] } + +/** + * The chat a session route opens on, named by its stored strip once the first read restored it: the boot's + * second, dependent read. Null on other routes and for a strip whose active tab is no chat. + */ +export function firstPaintChatTranscriptIdentity( + queryClient: QueryClient, + hostId: string, + route: URL +): string | null { + const [root, routeHost, screen, worktreeSegment] = route.pathname.split('/').filter(Boolean) + const worktreeId = routeSegment(worktreeSegment) + if (root !== 'h' || routeSegment(routeHost) !== hostId || screen !== 'session' || !worktreeId) { + return null + } + const exec = normalizeExecutionHostId(route.searchParams.get('executionHost')) ?? 'local' + const tabs = queryClient.getQueryData( + sessionTabsKey(hostId, exec, worktreeId) + ) + const active = tabs ? activeSessionTabOf(tabs) : null + return active ? storedTabChatTranscriptIdentity(hostId, worktreeId, active) : null +} diff --git a/mobile/src/query/host-connection-invalidation.ts b/mobile/src/query/host-connection-invalidation.ts index 7c1c3399ca0..4805bfd7a8e 100644 --- a/mobile/src/query/host-connection-invalidation.ts +++ b/mobile/src/query/host-connection-invalidation.ts @@ -14,7 +14,7 @@ function refetchesOnConnect(query: Query): boolean { } // One connected-edge listener per world per host client, however many screens read that host. -function retainHostConnectionInvalidation( +export function retainHostConnectionInvalidation( queryClient: QueryClient, hostId: string, client: RpcClient diff --git a/mobile/src/query/host-event-router.test.ts b/mobile/src/query/host-event-router.test.ts new file mode 100644 index 00000000000..096f908ee9e --- /dev/null +++ b/mobile/src/query/host-event-router.test.ts @@ -0,0 +1,52 @@ +import { QueryObserver } from '@tanstack/react-query' +import { expect, it, vi } from 'vitest' +import { stubRpcClient } from '../transport/rpc/rpc-client-test-stub' +import { retainHostEventRouter } from './host-event-router' +import { createOrcaQueryClient } from './orca-query-client' + +vi.mock('react-native', () => ({ AppState: {}, Platform: { OS: 'ios' } })) + +const KEY = ['orca', 'host-1', 'test.rows', { exec: 'local' }, {}] as const + +it('reads again after a read that was already out when the event stream reopened', async () => { + // One client-events wire at a time; each subscribe hands the test its frames. + const wires: ((payload: unknown) => void)[] = [] + const client = stubRpcClient({ + getLastConnectedAt: () => 1, + subscribe: (_method, _params, onData) => { + wires.push(onData) + return () => {} + } + }) + let desktopRows = 1 + const replies: ((rows: number) => void)[] = [] + const queryClient = createOrcaQueryClient() + const router = retainHostEventRouter(queryClient, 'host-1', client) + wires[0]?.({ type: 'ready', subscriptionId: 'events-1' }) + + const observer = new QueryObserver(queryClient, { + queryKey: KEY, + queryFn: () => new Promise((resolve) => replies.push(resolve)), + meta: { signal: { events: ['worktreesChanged'] } } + }) + const stop = observer.subscribe(() => {}) + await vi.waitFor(() => expect(replies).toHaveLength(1)) + replies[0]?.(desktopRows) + await vi.waitFor(() => expect(observer.getCurrentResult().data).toBe(1)) + + // A read goes out; the stream drops and reopens on the same connection while it is out. + void observer.refetch() + await vi.waitFor(() => expect(replies).toHaveLength(2)) + wires[0]?.({ type: 'end' }) + desktopRows = 2 + await vi.waitFor(() => expect(wires).toHaveLength(2)) + wires[1]?.({ type: 'ready', subscriptionId: 'events-2' }) + // The read sent before the gap answers with what the desktop had then. + replies[1]?.(1) + + await vi.waitFor(() => expect(replies).toHaveLength(3)) + replies[2]?.(desktopRows) + await vi.waitFor(() => expect(observer.getCurrentResult().data).toBe(2)) + stop() + router.release() +}) diff --git a/mobile/src/query/host-event-router.ts b/mobile/src/query/host-event-router.ts index f26fb5f360a..7269e2f8fcc 100644 --- a/mobile/src/query/host-event-router.ts +++ b/mobile/src/query/host-event-router.ts @@ -117,9 +117,11 @@ function startHostEventRouter( if (!readsNow(query) || floorTimers.has(query.queryHash)) { return } - // Change events can come per agent step; keep reads `floorMs` apart, polls and reads in flight included. + // Change events can come per agent step; keep reads `floorMs` apart, polls, failed reads and reads in flight included. const lastReadAt = - query.state.fetchStatus === 'fetching' ? Date.now() : query.state.dataUpdatedAt + query.state.fetchStatus === 'fetching' + ? Date.now() + : Math.max(query.state.dataUpdatedAt, query.state.errorUpdatedAt) const wait = lastReadAt + (signalOf(query)?.floorMs ?? 0) - Date.now() if (wait <= 0) { refetchHostQueryAfterInFlight(queryClient, query) @@ -137,9 +139,16 @@ function startHostEventRouter( } // Reads again (or marks stale, when no one watches) every answer older than `readSince`. + // `readSince` Infinity is a stream reopened on the same connection: a read already out may predate the gap. const catchUp = (readSince: number): void => { for (const query of signalledQueries(() => true)) { - if (query.state.fetchStatus === 'fetching' || query.state.dataUpdatedAt >= readSince) { + if (query.state.fetchStatus === 'fetching') { + if (readSince === Infinity) { + onChange(query) + } + continue + } + if (query.state.dataUpdatedAt >= readSince) { continue } if (readsNow(query)) { @@ -206,7 +215,7 @@ type Router = { holders: number; handle: RouterHandle } const routers = new WeakMap>() // One router per world per host client, however many screens read that host. -function retainHostEventRouter( +export function retainHostEventRouter( queryClient: QueryClient, hostId: string, client: RpcClient diff --git a/mobile/src/query/host-query-persistence.ts b/mobile/src/query/host-query-persistence.ts index ccca23f3207..c505c963235 100644 --- a/mobile/src/query/host-query-persistence.ts +++ b/mobile/src/query/host-query-persistence.ts @@ -48,8 +48,17 @@ function hostQueryPersistOf(query: Query): HostQueryPersist | undefined // Per world, the keys whose data came from the store and no read has replaced yet. const restoredKeys = new WeakMap>() -// Per world, its store; absent in a document that keeps queries in memory only. -const persistences = new WeakMap() +// Per world, a store per host: one in a page document, one per paired host in native Home. Absent keeps memory only. +const persistences = new WeakMap>() + +function restoredKeysOf(queryClient: QueryClient): Set { + let keys = restoredKeys.get(queryClient) + if (!keys) { + keys = new Set() + restoredKeys.set(queryClient, keys) + } + return keys +} /** * Whether a key still holds what an earlier launch stored: shown, but possibly days old and unconfirmed by @@ -75,7 +84,23 @@ export function restoreStoredHostQueries( queryClient: QueryClient, keys: readonly PersistedHostQueryKey[] ): Promise { - return persistences.get(queryClient)?.restore(keys) ?? Promise.resolve() + const byHost = persistences.get(queryClient) + const hostIds = new Set(keys.map((key) => key.queryKey[1])) + return Promise.all( + [...hostIds].map( + (hostId) => + byHost?.get(hostId)?.restore(keys.filter((key) => key.queryKey[1] === hostId)) ?? + Promise.resolve() + ) + ).then(() => undefined) +} + +/** This world's store for one host, if it keeps one. */ +export function hostQueryPersistenceOf( + queryClient: QueryClient, + hostId: string +): HostQueryPersistence | undefined { + return persistences.get(queryClient)?.get(hostId) } export type HostQueryPersistence = { @@ -83,6 +108,8 @@ export type HostQueryPersistence = { restore(keys: readonly PersistedHostQueryKey[]): Promise // Writes what is pending now; for hidden and page close. flush(): Promise + // Stops writing this host's queries, as when the host is removed; writes already pending still flush. + stop(): void } // The boot read fetches every first-paint key in one store call; each key's later getItem takes its value once. @@ -123,6 +150,8 @@ export function createHostQueryPersistence( queryClient: QueryClient, store: OrcaQueryStoreBackend ): HostQueryPersistence { + const byHost = persistences.get(queryClient) ?? new Map() + persistences.set(queryClient, byHost) const primer = primedBackend(store) const storage = createOrcaQueryStorage(primer.backend) const persisters = new Map>() @@ -135,10 +164,9 @@ export function createHostQueryPersistence( // Keys a restore found empty: neither the screen's first observer nor a later restore reads them again. const missedAtBoot = new Set() const triedOnMiss = new WeakSet() - const restored = new Set() + const restored = restoredKeysOf(queryClient) // The key a restore is writing, so its own success leaves the mark. let applyingRestore: string | null = null - restoredKeys.set(queryClient, restored) function storedData(queryHash: string, data: unknown, persist: HostQueryPersist) { const last = lastStored.get(queryHash) @@ -189,8 +217,13 @@ export function createHostQueryPersistence( return scope === 'orca' && hostId === store.hostId && typeof family === 'string' ? family : null } - // Applied only to a key still empty: a live answer that landed first always wins. - function restoreOne(queryKey: readonly unknown[], persist: HostQueryPersist) { + // Applied only to a key still empty: a live answer that landed first always wins. `after` is the boot + // batch read: the key is claimed now, so an observer arriving meanwhile joins instead of reading again. + function restoreOne( + queryKey: readonly unknown[], + persist: HostQueryPersist, + after: Promise = Promise.resolve() + ) { const family = familyOf(queryKey) const queryHash = hashKey(queryKey) if (family === null) { @@ -201,22 +234,24 @@ export function createHostQueryPersistence( return pending } const restore = new Promise((settle) => { - void persisterFor(family, persist) - .retrieveQuery(queryHash, (record) => { - if (queryClient.getQueryData(queryKey) === undefined) { - const { data, dataUpdatedAt } = record.state - settledAt.set(queryHash, dataUpdatedAt) - // Marked first: listeners told of this write must already see it as an earlier launch's. - restored.add(queryHash) - applyingRestore = queryHash - try { - queryClient.setQueryData(queryKey, data, { updatedAt: dataUpdatedAt }) - } finally { - applyingRestore = null + void after + .then(() => + persisterFor(family, persist).retrieveQuery(queryHash, (record) => { + if (queryClient.getQueryData(queryKey) === undefined) { + const { data, dataUpdatedAt } = record.state + settledAt.set(queryHash, dataUpdatedAt) + // Marked first: listeners told of this write must already see it as an earlier launch's. + restored.add(queryHash) + applyingRestore = queryHash + try { + queryClient.setQueryData(queryKey, data, { updatedAt: dataUpdatedAt }) + } finally { + applyingRestore = null + } } - } - settle() - }) + settle() + }) + ) .then( (data) => { // A restored record settles in the scheduled callback above. @@ -231,10 +266,10 @@ export function createHostQueryPersistence( return restore } - queryClient.getQueryCache().subscribe((event) => { + const unsubscribe = queryClient.getQueryCache().subscribe((event) => { const { query } = event const persist = hostQueryPersistOf(query) - if (!persist) { + if (!persist || familyOf(query.queryKey) === null) { return } // An observed key with no data, such as one past its gcTime, reads its record once beside the fetch. @@ -286,24 +321,32 @@ export function createHostQueryPersistence( : [] }) // A key already being read joins that read below instead of reading again. - await primer.prime( + const primed = primer.prime( empty.flatMap(({ queryKey, persist, family }) => restoring.has(hashKey(queryKey)) ? [] : [orcaQueryStoreKey(`${familyPrefix(family, persist)}-${hashKey(queryKey)}`)] ) ) + const batchRead = primed.catch(() => undefined) await Promise.all( empty.map(async ({ queryKey, persist }) => { - await restoreOne(queryKey, persist) + await restoreOne(queryKey, persist, batchRead) if (queryClient.getQueryData(queryKey) === undefined) { missedAtBoot.add(hashKey(queryKey)) } }) ) }, - flush: () => storage.flush() + flush: () => storage.flush(), + stop() { + unsubscribe() + if (byHost.get(store.hostId) === persistence) { + byHost.delete(store.hostId) + } + } } - persistences.set(queryClient, persistence) + byHost.get(store.hostId)?.stop() + byHost.set(store.hostId, persistence) return persistence } diff --git a/mobile/src/query/host-query.ts b/mobile/src/query/host-query.ts index 209ad828d2e..e7b0a36706c 100644 --- a/mobile/src/query/host-query.ts +++ b/mobile/src/query/host-query.ts @@ -142,25 +142,46 @@ export async function readHostQueryLive( } // A cached read through the screen's `read`: reuses a fresh answer and joins a read already out. An answer -// an event marked stale as it landed predates that change, so it is read again. +// an event marked stale as it landed predates that change, so it goes to `onStale` (still the newest one) and is +// read again while `isCurrent` holds: at once after a quiet spell (a write's own event lands mid-read), else +// `floorMs` after it landed. export async function fetchHostQuery( queryClient: QueryClient, query: HostQuery, host: { hostId: string; client: RpcClient }, target: HostQueryTarget, input: TInput, - read: () => Promise + reader: { read: () => Promise; isCurrent: () => boolean; onStale: (data: TData) => void } ): Promise { + const { isCurrent } = reader const options = { ...hostQueryOptions(query, host.client, host.hostId, target, input), - queryFn: read + queryFn: reader.read } + const floorMs = query.signal?.floorMs ?? 0 + const before = queryClient.getQueryState(options.queryKey) + let quiet = + before?.fetchStatus !== 'fetching' && (before?.dataUpdatedAt ?? 0) + floorMs <= Date.now() let data = await queryClient.fetchQuery(options) - // Each pass needs a newer event, so this ends with the event burst. - while (queryClient.getQueryState(options.queryKey)?.isInvalidated) { + for (;;) { + const state = queryClient.getQueryState(options.queryKey) + // A caller that moved on never shows this answer, so it is not read again. + if (!state?.isInvalidated || !isCurrent()) { + return data + } + reader.onStale(data) + if (state.fetchStatus === 'idle') { + const wait = quiet ? 0 : state.dataUpdatedAt + floorMs - Date.now() + quiet = false + if (wait > 0) { + await new Promise((resolve) => setTimeout(resolve, wait)) + if (!isCurrent()) { + return data + } + } + } data = await queryClient.fetchQuery(options) } - return data } // A read ahead of the user: skipped while the key holds current data, joins a read already out. @@ -178,7 +199,8 @@ export function prefetchHostQuery( } // Without a client the observer still reads the cached entry, but never fetches. -function observerOptions( +// Exported for a screen that reads one query per host through useQueries (native Home); it holds each host's router itself. +export function hostObserverOptions( query: HostQuery, client: RpcClient | null, hostId: string, @@ -190,6 +212,8 @@ function observerOptions( : { queryKey: hostQueryKey(hostId, query.family, target, input), queryFn: skipToken, + // A family that keeps its answer longer keeps it while no client reads it, too. + ...(query.gcTime === undefined ? {} : { gcTime: query.gcTime }), meta: { streamBacked: query.streamBacked, signal: query.signal, persist: query.persist } } } @@ -215,7 +239,7 @@ export function useHostQuery( // Same options object while nothing changed (target and input count by value), so TanStack's per-render setOptions is a no-op. const keyHash = hashKey([target, input]) const queryOptions = useMemo((): UseQueryOptions => { - const observer = observerOptions(query, client, hostId, target, input) + const observer = hostObserverOptions(query, client, hostId, target, input) // Disable through the observer, not skipToken: observers share the query's options, so a disabled // screen's skipToken would leave an enabled one's key with no fetch for invalidation or intervals. return enabled ? observer : { ...observer, enabled: false } @@ -241,7 +265,7 @@ export function useHostQueries useHostEventRouter(hostId, query.signal ? client : null) const keyHash = hashKey([target, inputs]) const queries = useMemo( - () => inputs.map((input) => observerOptions(query, client, hostId, target, input)), + () => inputs.map((input) => hostObserverOptions(query, client, hostId, target, input)), [query, client, hostId, keyHash] ) return useQueries({ queries, combine }) diff --git a/mobile/src/query/native-query-persistence.ts b/mobile/src/query/native-query-persistence.ts new file mode 100644 index 00000000000..bc45a9da57b --- /dev/null +++ b/mobile/src/query/native-query-persistence.ts @@ -0,0 +1,70 @@ +import { AppState, Platform } from 'react-native' +import type { QueryClient } from '@tanstack/react-query' +import { processDeviceStore } from '../device-store/device-store' +import { + createHostQueryPersistence, + hostQueryPersistenceOf, + type HostQueryPersistence +} from './host-query-persistence' +import { hostScopeKey } from './host-query-key' + +// Per native world, the paired hosts whose data it keeps in the device store. +const keptHosts = new WeakMap>() + +function keptHostsOf(queryClient: QueryClient): Set { + const existing = keptHosts.get(queryClient) + if (existing) { + return existing + } + const hosts = new Set() + keptHosts.set(queryClient, hosts) + // Pending writes go to disk when the app leaves the foreground, as a page's do on hide. + AppState.addEventListener('change', (state) => { + if (state !== 'active') { + for (const hostId of hosts) { + void hostQueryPersistenceOf(queryClient, hostId)?.flush() + } + } + }) + return hosts +} + +/** Keeps the native world's data for one paired host in the device store, read and written directly. */ +export function keepNativeHostQueries( + queryClient: QueryClient, + hostId: string +): HostQueryPersistence | null { + // The web build of the native app has no device store. + if (Platform.OS === 'web') { + return null + } + const existing = hostQueryPersistenceOf(queryClient, hostId) + if (existing) { + return existing + } + const hosts = keptHostsOf(queryClient) + hosts.add(hostId) + const store = processDeviceStore() + return createHostQueryPersistence(queryClient, { + hostId, + read: (keys) => store.read(hostId, 'cache', keys), + // A write still pending when the host is removed must not land after the wipe. + write: async (ops) => + hosts.has(hostId) + ? { written: (await store.write(hostId, 'cache', ops)).written } + : { written: false } + }) +} + +/** Whether this world's writes can reach disk now: false on web, or while the store's key can't load. */ +export async function nativeQueryStoreReady(): Promise { + return Platform.OS !== 'web' && (await processDeviceStore().open()) === 'ready' +} + +/** Drops a removed host's queries from this world and stops storing them; the store wipe follows. */ +export function forgetNativeHostQueries(queryClient: QueryClient, hostId: string): void { + keptHosts.get(queryClient)?.delete(hostId) + // Removed while the persistence still listens, so it forgets what it restored for this host. + queryClient.removeQueries({ queryKey: hostScopeKey(hostId) }) + hostQueryPersistenceOf(queryClient, hostId)?.stop() +} diff --git a/mobile/src/query/page-query-persistence.ts b/mobile/src/query/page-query-persistence.ts index 92a28bce36e..d0dad07998c 100644 --- a/mobile/src/query/page-query-persistence.ts +++ b/mobile/src/query/page-query-persistence.ts @@ -1,6 +1,7 @@ import type { QueryClient } from '@tanstack/react-query' import type { PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store' -import { firstPaintQueryKeys } from './first-paint-query-keys' +import { primeStoredChatTranscripts } from '../session/native-chat/mobile-native-chat-transcript-store' +import { firstPaintChatTranscriptIdentity, firstPaintQueryKeys } from './first-paint-query-keys' import { createHostQueryPersistence } from './host-query-persistence' // How long a page holds its first render for stored data once everything else it waits on is ready. @@ -32,7 +33,11 @@ export function startPageQueryPersistence( } }) window.addEventListener('pagehide', flush) - return persistence.restore(firstPaintQueryKeys(hostId, route)) + return persistence.restore(firstPaintQueryKeys(hostId, route)).then(() => { + // Read inside the same capped wait, so a relaunched chat paints its stored rows in the first frame. + const chat = firstPaintChatTranscriptIdentity(queryClient, hostId, route) + return chat ? primeStoredChatTranscripts([chat]) : undefined + }) } /** Waits for the stored first screen, but never more than a short cap; a later answer still fills empty keys. */ diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 0ba92bc2aa6..06861569071 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -8,6 +8,7 @@ import { Animated, View, Text, Pressable, ActivityIndicator } from 'react-native import { saveTerminalTextScale } from '../storage/preferences' import { MobileBrowserPane } from '../browser/MobileBrowserPane' import { TerminalPaneView } from '../terminal/session/TerminalPaneView' +import { MountedTerminalPanes } from '../terminal/session/mounted-terminal-lru' import { MobileNativeChatOverlay } from './native-chat/MobileNativeChatOverlay' import { mobileSessionNativeChatHostOutage } from './native-chat/mobile-native-chat-host-outage' import { MobileAgentMessageProvider } from './native-chat/transcript/MobileAgentMessageProvider' @@ -30,6 +31,7 @@ import { FileReader } from '../files/session-documents/MobileSessionFileReader' import { MobileSessionContentState } from './MobileSessionContentState' import { MarkdownReader } from '../files/session-documents/MobileSessionMarkdownReader' import { markdownTabDraftKey } from '../drafts/document-edit-draft-rows' +import { workspaceDraftRowKey } from '../drafts/durable-draft-rows' import { loadMarkdownPreviewImage } from '../files/mobile-markdown-image-source' export function MobileSessionActiveContent({ @@ -86,6 +88,7 @@ export function MobileSessionActiveContent({ discardMarkdownLocalContent, saveMarkdownTab, setTerminalWebViewRef, + releaseTerminalDocument, handleTerminalWebReady, notifyTerminalFrame, notifyTerminalCellBoxChange, @@ -141,6 +144,9 @@ export function MobileSessionActiveContent({ controller ) const { presentedConnState, showOfflineState, forceReconnectHost } = controller + // Review notes are for working-tree diffs only. + const fileTabTakesNotes = + activeFileTab?.diffSource === 'staged' || activeFileTab?.diffSource === 'unstaged' const toast = toastMessage ? ( {toastMessage} @@ -193,8 +199,17 @@ export function MobileSessionActiveContent({ title={activeFileTab.title || t('session.activeContent.fileTitle', 'File')} relativePath={activeFileTab.relativePath} language={activeFileTab.language} + noteDraftKey={ + fileTabTakesNotes + ? workspaceDraftRowKey( + 'fileNote', + { hostId, executionHost, worktreeId }, + activeFileTab.relativePath + ) + : undefined + } diffCommentActions={ - activeFileTab.diffSource === 'staged' || activeFileTab.diffSource === 'unstaged' + fileTabTakesNotes ? { comments: diffComments, sendingCommentIds: sendingDiffCommentIds, @@ -257,69 +272,70 @@ export function MobileSessionActiveContent({ ) : ( - {terminals.map((terminal) => ( - { - // Why: pinch-to-zoom reports a new preset; persist it so the size sticks across panes and launches. - terminalTextScaleRevisionRef.current += 1 - setTerminalTextScale(scale) - void saveTerminalTextScale(scale) - }} - onRef={setTerminalWebViewRef} - onWebReady={handleTerminalWebReady} - onCellBoxChange={notifyTerminalCellBoxChange} - onSelectionMode={handleSelectionMode} - onSelectionCopy={handleSelectionCopy} - onSelectionEvicted={handleSelectionEvicted} - onClipboardWrite={handleClipboardWrite} - onModesChanged={handleModesChanged} - onKeyboardAvoidanceMetrics={handleKeyboardAvoidanceMetrics} - onHaptic={handleHaptic} - onTerminalInput={handleTerminalInput} - onTerminalQueryReply={handleTerminalQueryReply} - onTerminalInteraction={handleTerminalInteraction} - onTerminalTap={handleTerminalTap} - onFileTap={handleFileTap} - onOpenUrl={handleTerminalOpenUrl} - /> - ))} + + {(terminal) => ( + { + // Why: pinch-to-zoom reports a new preset; persist it so the size sticks across panes and launches. + terminalTextScaleRevisionRef.current += 1 + setTerminalTextScale(scale) + void saveTerminalTextScale(scale) + }} + onRef={setTerminalWebViewRef} + onDocumentReleased={releaseTerminalDocument} + onWebReady={handleTerminalWebReady} + onCellBoxChange={notifyTerminalCellBoxChange} + onSelectionMode={handleSelectionMode} + onSelectionCopy={handleSelectionCopy} + onSelectionEvicted={handleSelectionEvicted} + onClipboardWrite={handleClipboardWrite} + onModesChanged={handleModesChanged} + onKeyboardAvoidanceMetrics={handleKeyboardAvoidanceMetrics} + onHaptic={handleHaptic} + onTerminalInput={handleTerminalInput} + onTerminalQueryReply={handleTerminalQueryReply} + onTerminalInteraction={handleTerminalInteraction} + onTerminalTap={handleTerminalTap} + onFileTap={handleFileTap} + onOpenUrl={handleTerminalOpenUrl} + /> + )} + { - // A ctrl/alt/shift held on the Duo rail turns the next typed letter into a combo, while the rail shows it. - if ( - !keysInRail || - !dockKeys.interceptTypedCharacter(text, event.nativeEvent.text, liveInputRef) - ) { + // A held Shift, Ctrl or Alt on the key row or the Duo rail turns the next typed letter into a combo. + if (!dockKeys.interceptTypedCharacter(text, event.nativeEvent.text, liveInputRef)) { handleLiveInputChange(event) } }} diff --git a/mobile/src/session/MobileSessionContentRow.tsx b/mobile/src/session/MobileSessionContentRow.tsx index 9a7cea2d3f1..474f974e441 100644 --- a/mobile/src/session/MobileSessionContentRow.tsx +++ b/mobile/src/session/MobileSessionContentRow.tsx @@ -9,7 +9,6 @@ import { styles } from './mobile-session-styles' import type { MobileSessionController } from './use-mobile-session-controller' import { MobileSessionActiveContent } from './MobileSessionActiveContent' import { MobileSessionCommandDock } from './MobileSessionCommandDock' -import { MobileDictationStatusAnnouncement } from '../dictation/MobileDictationStatusAnnouncement' import { MobileDictationLiveContext } from '../dictation/mobile-dictation-live-context' import { useMobileDictationLive } from '../dictation/use-mobile-dictation-live' @@ -56,7 +55,6 @@ export function MobileSessionContentRow({ controller }: { controller: MobileSess {/* Why: translate instead of resize so keyboard toggles don't trigger a server-side PTY viewport change. */} - {canDockPanel && activePanel !== null && ( setShowCustomKeyModal(false)} onKeysChanged={setCustomKeys} onManageShortcuts={handleManageShortcuts} + smartRail={{ enabled: smartRailEnabled, onChange: handleSmartRailChange }} /> + translate('session.failure.selectedModel', AGENT_SESSION_FAILURE_COPY.selectedModel, values), + providerUnavailable: (values) => + translate( + 'session.failure.providerUnavailable', + AGENT_SESSION_FAILURE_COPY.providerUnavailable, + values + ), + providerSafetyStopped: (values) => + translate( + 'session.failure.providerSafetyStopped', + AGENT_SESSION_FAILURE_COPY.providerSafetyStopped, + values + ), + providerResponseFailed: (values) => + translate( + 'session.failure.providerResponseFailed', + AGENT_SESSION_FAILURE_COPY.providerResponseFailed, + values + ), providerRejected: (values) => translate('session.failure.providerRejected', "{{agent}} didn't accept this message.", values), providerRejectedQuoted: (values) => diff --git a/mobile/src/session/mobile-dictation-session-outcomes.test.tsx b/mobile/src/session/mobile-dictation-session-outcomes.test.tsx index 1950423c351..cfbde9cb924 100644 --- a/mobile/src/session/mobile-dictation-session-outcomes.test.tsx +++ b/mobile/src/session/mobile-dictation-session-outcomes.test.tsx @@ -1,5 +1,5 @@ // Mount the real composing hooks over native capture: refused starts and lost transcripts were in how the session hook and dictation hook meet, which isolated handler tests would miss. -import { createElement, useRef } from 'react' +import { createElement, useContext, useRef } from 'react' import { act } from 'react-test-renderer' import { createWithQueryClient } from '../test-support/query-client-test-renderer' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -26,8 +26,11 @@ const seen = vi.hoisted(() => { vi.mock('react-native', () => ({ AppState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) }, + AccessibilityInfo: { announceForAccessibility: () => {} }, Platform: { OS: 'ios' } })) +// The computer's name only words announcements; the stored host profile pulls in secure storage. +vi.mock('../transport/hosts/use-host-profile', () => ({ useHostProfile: () => null })) vi.mock('@orca/expo-two-way-audio', () => ({ addExpoTwoWayAudioEventListener: (name: string, listener: (event: { data: string }) => void) => { seen.audioListeners.set(name, listener) @@ -45,7 +48,10 @@ vi.mock('expo-keep-awake', () => ({ activateKeepAwakeAsync: () => Promise.resolve(), deactivateKeepAwake: () => Promise.resolve() })) -vi.mock('expo-router', () => ({ useFocusEffect: () => {} })) +vi.mock('expo-router', () => { + const router = { canGoBack: () => false, push: () => {}, dismissTo: () => {} } + return { useFocusEffect: () => {}, useRouter: () => router, useNavigation: () => undefined } +}) vi.mock('../platform/haptics', () => ({ triggerError: () => { seen.errorHaptics += 1 @@ -108,6 +114,14 @@ vi.mock('./use-mobile-send-completion-generation', () => ({ })) import { useMobileSessionNativeChatDictation } from './use-mobile-session-native-chat-dictation' +import { + MobileDictationHostProvider, + useMobileDictationHost +} from '../dictation/mobile-dictation-host' +import { + MobileDictationPillContext, + type MobileDictationPill +} from '../dictation/mobile-dictation-host-context' type Model = ReturnType @@ -117,11 +131,21 @@ const typeIntoTerminal = async (_handle: string, text: string): Promise return true } +type Host = ReturnType & { pill: MobileDictationPill | null } + function mount( client: FakeRpcClient, sendLive: (handle: string, text: string) => Promise = typeIntoTerminal -): { current: () => Model } { - const held: { model: Model | null } = { model: null } +): { current: () => Model; host: () => Host; leave: () => void } { + const held: { model: Model | null; host: Host | null; screen: boolean } = { + model: null, + host: null, + screen: true + } + function HostProbe(): null { + held.host = { ...useMobileDictationHost(), pill: useContext(MobileDictationPillContext) } + return null + } function Probe(): null { const scope = { @@ -132,7 +156,7 @@ function mount( agentSessionHostSupport: { promptCancel: true, questionAnswers: false }, activeHandle: 't1', activeSessionTabId: 'tab1', - activeSessionTab: { id: 'tab1', type: 'terminal', terminal: 't1' }, + activeSessionTab: { id: 'tab1', type: 'terminal', terminal: 't1', title: 'Claude Code' }, diffComments: [], diffCommentsRef: useRef([]), setShowDictationSetup: (next: boolean) => { @@ -152,15 +176,25 @@ function mount( showToast: (message: string) => { seen.toasts.push(message) }, - resetLiveInputFocus: () => {} + resetLiveInputFocus: () => {}, + // Leaving this session would leave the page, so a recording holds the first leave. + router: { canGoBack: () => false } } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the scope carries every member this hook destructures; the rest of the session model is unreachable from the mic path. held.model = useMobileSessionNativeChatDictation(scope as never, sendLive) return null } + const tree = () => + createElement( + MobileDictationHostProvider, + null, + createElement(HostProbe), + held.screen ? createElement(Probe) : null + ) + let renderer: ReturnType | null = null act(() => { - createWithQueryClient(createElement(Probe)) + renderer = createWithQueryClient(tree()) }) return { current: () => { @@ -168,6 +202,17 @@ function mount( throw new Error('Probe did not render') } return held.model + }, + host: () => { + if (!held.host) { + throw new Error('HostProbe did not render') + } + return held.host + }, + // The session screen goes away (Back to the workspace list) while the page and its dictation stay. + leave: () => { + held.screen = false + act(() => renderer?.update(tree())) } } } @@ -203,7 +248,7 @@ async function settle( async function startRecording( rpc: FakeRpcClient, sendLive?: (handle: string, text: string) => Promise -): Promise<{ current: () => Model }> { +): Promise> { const mounted = mount(rpc, sendLive) act(() => mounted.current().handleDictationToggle()) await settle(rpc, '') @@ -322,3 +367,19 @@ describe('a dictation that ends after switching between chat and terminal', () = expect(seen.inputs).toEqual([]) }) }) + +describe('a dictation whose session screen was left', () => { + it('keeps recording, then puts its words in the chat it started in with a toast that opens it', async () => { + seen.chat = { shown: true, scope: 'chat-a' } + const rpc = createFakeRpcClient() + const mounted = await startRecording(rpc) + mounted.leave() + expect(mounted.host().getDictation().isRecording).toBe(true) + expect(mounted.host().pill?.away).toBe(true) + act(() => mounted.host().stop()) + await settle(rpc, 'ship it') + expect(seen.chatWrites).toEqual([['chat-a', 'ship it']]) + expect(mounted.host().pill?.toast?.message).toBe('Inserted in Claude Code') + expect(mounted.host().pill?.toast?.open).toBeTypeOf('function') + }) +}) diff --git a/mobile/src/session/mobile-structured-agent-session-launch.test.ts b/mobile/src/session/mobile-structured-agent-session-launch.test.ts index b5b62c474c0..457d3fb3c2e 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.test.ts +++ b/mobile/src/session/mobile-structured-agent-session-launch.test.ts @@ -57,3 +57,31 @@ it('settles a proven missing-original fork refusal but keeps a lost earlier atte (await createMobileStructuredAgentSession(lost, 'workspace-1', 'opencode', forkFrom)).kind ).toBe('unknown') }) + +it('settles a proven fork read refusal without settling a prior lost copy', async () => { + const refusal = { + ok: true, + result: { + ok: false, + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'transcriptUnreadable' }, + createAttemptRefusedBeforeCommit: true, + message: 'Codex could not read the saved chat.' + } + } + } + const client = clientReturning({ ok: true, result: { supported: true } }, refusal) + const forkFrom = { sessionId: 'source-chat', throughItemId: 'codex:source:selected:1' } + expect( + (await createMobileStructuredAgentSession(client, 'workspace-1', 'codex', forkFrom)).kind + ).toBe('failed') + const lost = clientReturning({ ok: true, result: { supported: true } }, refusal) + lost.sendRequest + .mockImplementationOnce(async () => ({ ok: true, result: { supported: true } })) + .mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('copy reply lost'))) + .mockResolvedValueOnce(refusal) + expect( + (await createMobileStructuredAgentSession(lost, 'workspace-1', 'codex', forkFrom)).kind + ).toBe('unknown') +}) diff --git a/mobile/src/session/mobile-structured-agent-session-launch.ts b/mobile/src/session/mobile-structured-agent-session-launch.ts index 55dbc1ebef0..d7cb85e2a31 100644 --- a/mobile/src/session/mobile-structured-agent-session-launch.ts +++ b/mobile/src/session/mobile-structured-agent-session-launch.ts @@ -7,7 +7,8 @@ import type { } from '../../../src/shared/agent-session/agent-session-wire' import { isDefinitiveAgentSessionCreateRefusal, - isAgentSessionForkSourceAdmissionRefusal + isAgentSessionForkSourceAdmissionRefusal, + isAgentSessionCreateAdmissionRefusal } from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal' import { createStructuredAgentSessionId, @@ -187,7 +188,8 @@ export async function createMobileStructuredAgentSession( forkFrom && !priorCreateOutcomeUnknown && result.refusal.createAttemptRefusedBeforeCommit === true && - isAgentSessionForkSourceAdmissionRefusal(result.refusal) + (isAgentSessionForkSourceAdmissionRefusal(result.refusal) || + isAgentSessionCreateAdmissionRefusal(result.refusal)) ) { return { kind: 'failed', diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx index 2e10e27d24f..b58cdede682 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx @@ -345,7 +345,7 @@ export function MobileNativeChatComposer({ /> {goal.chip} - {micActive || micProcessing ? null : contextRing.ring} {onMicPress ? ( + } return ( void; held: boolean } | null onSend: (intent?: MobileNativeChatSendIntent, keepFocus?: boolean) => void -}): React.JSX.Element { +}): React.JSX.Element | null { + const dictationFailed = useMobileNativeChatDictationFailed() const steerChord = useMobileNativeChatSteerChordPreview({ fieldRef, hasDraft: value.trim() !== '' || attachmentCount > 0, @@ -83,6 +85,10 @@ export function MobileNativeChatComposerSendSlot({ draft: value, attachmentCount }) + // A dictation kept for Retry takes Send's room; a running agent keeps its Stop. + if (dictationFailed && !(showsStop && stop)) { + return null + } if (steerChord.preview && (steerChord.preview === 'steer-queued' || canSend)) { // As desktop, the preview takes Send's slot at once, with no ease. return ( diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatDictationLeading.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatDictationLeading.tsx index 272ac466892..806609bf8f6 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatDictationLeading.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatDictationLeading.tsx @@ -3,28 +3,45 @@ import { View } from 'react-native' import { MobileDictationLiveContext } from '../../../dictation/mobile-dictation-live-context' import { MobileDictationCancelButton, + MobileDictationFailureNote, MobileDictationFinishingNote, MobileDictationRecordingMeter } from '../../../dictation/MobileDictationLiveControls' import { mobileNativeChatComposerStyles as styles } from './mobile-native-chat-composer-styles' -// While dictating, the row's leading side swaps attach and the pickers for ✕ and the meter, so the composer keeps its height. +// While dictating, the row's leading side swaps attach and the pickers for ✕ and the meter (or a kept failure), so the composer keeps its height. export function MobileNativeChatDictationLeading({ micActive, micStarting = false, micProcessing = false, cancelRef, + trailing, children }: { micActive: boolean micStarting?: boolean micProcessing?: boolean cancelRef: RefObject + // The context ring after the leading controls; it steps aside with them. + trailing: ReactNode children: ReactNode }): React.JSX.Element { const live = useContext(MobileDictationLiveContext) + if (live?.failureReason != null) { + return ( + + + + + ) + } if (!live || (!micActive && !micProcessing)) { - return {children} + return ( + <> + {children} + {trailing} + + ) } return ( @@ -42,3 +59,8 @@ export function MobileNativeChatDictationLeading({ ) } + +// A dictation failed with its recording kept: Send gives its room to Retry. +export function useMobileNativeChatDictationFailed(): boolean { + return useContext(MobileDictationLiveContext)?.failureReason != null +} diff --git a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx index d201f87b06d..2ad2426c74b 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatAsk.tsx @@ -12,6 +12,7 @@ import type { AgentJournalFreeTextInput } from '../../../../../src/shared/agent- import { askAcceptsEmptyAnswer, askConfirmAction, + askQuestionShowsPreviews, askConfirmLabel, askTypedText, toggleAskOption @@ -65,7 +66,8 @@ export function MobileNativeChatAsk({ }: Props): React.JSX.Element { useMobileColorScheme() const t = useMobileTranslation() - const { scrollRef, inputRef, revealReply, onViewportLayout } = useMobileNativeChatReplyScroll() + const { scrollRef, inputRef, revealReply, scrollViewProps, revealContent } = + useMobileNativeChatReplyScroll() const [index, setIndex] = useState(0) const [selections, setSelections] = useState(() => prompt.questions.map(() => [])) const [otherText, setOtherText] = useState(() => @@ -109,11 +111,15 @@ export function MobileNativeChatAsk({ return } const cur = selections[qi] ?? [] + // A pick reveals its preview, so a re-tap keeps it and the user confirms. + const keep = optIndex !== OTHER && askQuestionShowsPreviews(prompt.questions[qi]) const picked = !cur.includes(optIndex) - const next = selections.map((s, i) => (i === qi ? toggleAskOption(cur, optIndex, multi) : s)) + const next = selections.map((s, i) => + i === qi ? toggleAskOption(cur, optIndex, multi, keep) : s + ) setSelections(next) autoAdvance.cancel() - if (picked && !multi && optIndex !== OTHER) { + if (picked && !multi && optIndex !== OTHER && !keep) { autoAdvance.schedule(() => void advance(next)) } } @@ -246,12 +252,7 @@ export function MobileNativeChatAsk({ ) : null} - + void selected: boolean multi?: boolean disabled: boolean onPress: () => void }): React.JSX.Element { useMobileColorScheme() - return ( + const row = ( ) + // One root shape whether or not the preview shows, so selecting never remounts the row. + return ( + <> + {row} + {preview && selected ? ( + { + const { y, height } = event.nativeEvent.layout + onPreviewLayout?.(y, y + height) + }} + > + + {/* Mockups are drawn in columns, so they scroll sideways instead of wrapping at phone width. */} + + + {preview} + + + + + ) : null} + + ) } const styles = themedStyleSheet(() => ({ @@ -106,5 +136,19 @@ const styles = themedStyleSheet(() => ({ optionDescription: { color: colors.textSecondary, fontSize: typography.metaSize + }, + preview: { + backgroundColor: colors.bgPanel, + borderWidth: 1, + borderColor: colors.borderSubtle, + borderRadius: concentricRadius(radii.surface, spacing.xs), + padding: spacing.sm, + marginBottom: spacing.xs, + maxHeight: 220 + }, + previewText: { + color: colors.textPrimary, + fontFamily: typography.monoFamily, + fontSize: typography.metaSize } })) diff --git a/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts b/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts index fe9fd376050..9226a6f7f2f 100644 --- a/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts +++ b/mobile/src/session/native-chat/input/use-mobile-native-chat-reply-scroll.ts @@ -1,11 +1,18 @@ import { useRef } from 'react' -import type { LayoutChangeEvent, ScrollView, TextInput } from 'react-native' +import type { + LayoutChangeEvent, + NativeScrollEvent, + NativeSyntheticEvent, + ScrollView, + TextInput +} from 'react-native' // Keep a focused reply in view when its card shrinks above the keyboard. export function useMobileNativeChatReplyScroll() { const scrollRef = useRef(null) const inputRef = useRef(null) const viewportHeight = useRef(0) + const scrollOffset = useRef(0) const revealReply = (): void => { if (inputRef.current?.isFocused()) { scrollRef.current?.scrollToEnd({ animated: false }) @@ -20,5 +27,31 @@ export function useMobileNativeChatReplyScroll() { revealReply() } } - return { scrollRef, inputRef, revealReply, onViewportLayout } + const onScroll = (event: NativeSyntheticEvent): void => { + scrollOffset.current = event.nativeEvent.contentOffset.y + } + // Scroll just enough to show content that opened below the visible edge, never past its top. + const revealContent = (top: number, bottom: number): void => { + const hidden = bottom - (scrollOffset.current + viewportHeight.current) + if (viewportHeight.current > 0 && hidden > 0) { + scrollRef.current?.scrollTo({ + y: Math.min(scrollOffset.current + hidden, top), + animated: true + }) + } + } + const scrollViewProps = { + ref: scrollRef, + onLayout: onViewportLayout, + onScroll, + scrollEventThrottle: 16 + } + return { + scrollRef, + inputRef, + revealReply, + onViewportLayout, + scrollViewProps, + revealContent + } } diff --git a/mobile/src/session/native-chat/mobile-native-chat-host-outage.ts b/mobile/src/session/native-chat/mobile-native-chat-host-outage.ts index fe84d7906f3..040e32baf4e 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-host-outage.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-host-outage.ts @@ -5,6 +5,7 @@ import { import type { ConnectionState } from '../../transport/connection/connection-state' import type { ServerHostDesktopReach } from '../../worktree/server-workspaces' import { translate, type Translate } from '../../i18n/mobile-i18n' +import { formatOfflineAsOfTime } from '../../components/offline-as-of-time' import type { MobileSessionController } from '../use-mobile-session-controller' /** The composer's status line while the chat's host is out, with Reconnect only when redialing can help. */ @@ -19,6 +20,10 @@ export function mobileNativeChatHostOutage( hostName: string /** The session header's Reconnect when it offers one, so the composer offers the same. */ reconnect: (() => void) | null + /** Before this page's first connect (a relaunch), the header covers connecting until an offline verdict. */ + neverConnected?: boolean + /** When the chat on screen was saved, while it is a stored copy no read has confirmed. */ + savedAt?: number | null server?: { state: ConnectionState name?: string | null @@ -31,13 +36,22 @@ export function mobileNativeChatHostOutage( offline ? t('connection.connectionHealth.hostOffline', '{{host}} is offline', { host }) : t('chat.hostOutage.reconnecting', '{{hostName}} is reconnecting…', { hostName: host }) - const { pairedVerdict: verdict } = args + const { pairedVerdict: verdict, savedAt } = args if (args.pairedHostState !== 'connected') { if (verdict.kind === 'auth-failed') { return { text: verdict.label } } const offline = isConnectionOutage(verdict) - const text = linkText(args.hostName, offline) + if (!offline && args.neverConnected) { + return null + } + const text = + offline && savedAt != null + ? t('chat.hostOutage.offlineAsOf', '{{host}} is offline · as of {{time}}', { + host: args.hostName, + time: formatOfflineAsOfTime(savedAt) + }) + : linkText(args.hostName, offline) return offline && args.reconnect ? { text, onReconnect: args.reconnect } : { text } } const { server } = args @@ -77,6 +91,8 @@ export function mobileSessionNativeChatHostOutage( | 'showConnectionRetry' | 'forceReconnectHost' | 'workspaceServer' + | 'lastConnectedAt' + | 'nativeChatController' >, hostName: string, t: Translate @@ -94,6 +110,8 @@ export function mobileSessionNativeChatHostOutage( session.showConnectionRetry && hostId && forceReconnect ? () => void forceReconnect(hostId) : null, + neverConnected: session.lastConnectedAt === null, + savedAt: session.nativeChatController.nativeChatSession.savedAt, server: session.workspaceServer }, t diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-cache.ts b/mobile/src/session/native-chat/mobile-native-chat-transcript-cache.ts index c5c38f4fefe..7ea01a40f66 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-transcript-cache.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-transcript-cache.ts @@ -1,16 +1,19 @@ import { setBoundedScopeCacheEntry } from '../../../../src/shared/native-chat/native-chat-scope-cache' import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' import type { NativeChatResumePoint } from '../../../../src/shared/rpc-contract/native-chat-params' +import { peekStoredChatTranscript } from './mobile-native-chat-transcript-store' const MAX_CACHED_TRANSCRIPTS = 8 -type MobileNativeChatCachedTranscript = { +export type MobileNativeChatCachedTranscript = { messages: NativeChatMessage[] hasMore: boolean beforeOffset: number | null + // Set while the rows are an earlier launch's stored copy that no read in this page has confirmed. + savedAt?: number } -// Lives as long as the page: the WebView has no durable storage, so a relaunch starts empty. +// The first layer, for this page's lifetime; the phone's store (mobile-native-chat-transcript-store) is the second. export const mobileNativeChatTranscriptCache = new Map() export function cacheMobileNativeChatTranscript( @@ -25,6 +28,25 @@ export function cacheMobileNativeChatTranscript( ) } +/** This page's rows for a chat, else the phone's stored copy once read; undefined when neither is held. */ +export function heldMobileNativeChatTranscript( + identity: string +): MobileNativeChatCachedTranscript | undefined { + const cached = mobileNativeChatTranscriptCache.get(identity) + if (cached) { + return cached + } + const stored = peekStoredChatTranscript(identity) + return stored?.kind === 'terminal' + ? { + messages: stored.messages, + hasMore: stored.hasMore, + beforeOffset: stored.beforeOffset, + savedAt: stored.savedAt + } + : undefined +} + /** Older hosts send rows with no file offset; those get a normal snapshot. */ export function mobileNativeChatResumePoint( messages: readonly NativeChatMessage[] diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-encode.ts b/mobile/src/session/native-chat/mobile-native-chat-transcript-encode.ts new file mode 100644 index 00000000000..daeeb767d09 --- /dev/null +++ b/mobile/src/session/native-chat/mobile-native-chat-transcript-encode.ts @@ -0,0 +1,160 @@ +import { Gzip, strToU8 } from 'fflate' +import { + trimRetainedItems, + mergeSubmissions +} from '../../../../src/shared/agent-session/view/structured-agent-session-item-retention' +import { agentSessionHasOlderTranscript } from '../../../../src/shared/agent-session/agent-session-context-clear' +import { DEVICE_STORE_MAX_VALUE_LENGTH } from '../../device-store/device-store-value-codec' +import { encodeBase64Bytes } from '../../transport/encryption/base64-byte-codec' +import { + STORED_TRANSCRIPT_VERSION, + type StoredChatTranscript, + type StoredStructuredChatTranscript, + type StoredTerminalChatTranscript +} from './mobile-native-chat-transcript-store' + +const MAX_STORED_ROWS = 500 +// A sliced encode hands the page back its thread this often, so a big chat never costs a dropped frame run. +const SLICE_MS = 8 +// Gzip input per push; small enough to stay well inside one slice on a phone. +const GZIP_CHUNK_BYTES = 64 * 1024 +// The window aimed for after a value came out too big, under the cap so the next try fits. +const REFIT_SHARE = 0.9 +const MAX_ATTEMPTS = 4 +// Base64 input per slice; a multiple of three, so the slices' outputs join into one valid string. +const BASE64_CHUNK_BYTES = 3 * 21_840 +// Stands in for the rows in the value's JSON, where the rows' own JSON then goes. +const ROWS_SENTINEL = '\u0000rows\u0000' +const ROWS_TOKEN = JSON.stringify(ROWS_SENTINEL) + +/** Gives the page its thread back between slices; null encodes in one go (hide, where the app may stop next). */ +export type EncodePause = (() => Promise) | null + +function rowsOf(stored: StoredChatTranscript): readonly unknown[] { + return stored.kind === 'terminal' ? stored.messages : stored.journal.items +} + +function terminalWindow( + stored: StoredTerminalChatTranscript, + rows: number +): StoredTerminalChatTranscript { + if (rows >= stored.messages.length) { + return stored + } + // Older rows past the window come back through Load earlier's tail read, so its offset no longer applies. + return { ...stored, messages: stored.messages.slice(-rows), hasMore: true, beforeOffset: null } +} + +function structuredWindow( + stored: StoredStructuredChatTranscript, + rows: number +): StoredStructuredChatTranscript { + const { journal } = stored + const items = trimRetainedItems(journal.items, rows, rows) + if (items === journal.items) { + return stored + } + return { + ...stored, + journal: { + ...journal, + items, + submissions: mergeSubmissions(journal.submissions, [], items), + hasOlder: agentSessionHasOlderTranscript(items, true) + } + } +} + +function windowOf(stored: StoredChatTranscript, rows: number): StoredChatTranscript { + return stored.kind === 'terminal' ? terminalWindow(stored, rows) : structuredWindow(stored, rows) +} + +// The value's JSON with its rows array replaced by the token. +function frameJson(stored: StoredChatTranscript): string { + const framed = + stored.kind === 'terminal' + ? { ...stored, messages: ROWS_SENTINEL } + : { ...stored, journal: { ...stored.journal, items: ROWS_SENTINEL } } + return JSON.stringify({ v: STORED_TRANSCRIPT_VERSION, stored: framed }) +} + +/** + * The newest rows that fit one store value (at most 500), as base64(gzip(JSON)); null when not even one row + * fits. With a pause, the work runs in slices of a few ms. Each row is stringified once, and a value over the + * cap is retried with the window its own bytes per row say will fit, never by blind halving. + */ +export async function encodeStoredChatTranscript( + stored: StoredChatTranscript, + pause: EncodePause = null +): Promise { + let sliceStart = performance.now() + const breathe = async (): Promise => { + if (pause && performance.now() - sliceStart >= SLICE_MS) { + await pause() + sliceStart = performance.now() + } + } + const all = rowsOf(stored) + const json = new Map() + for (const row of all.slice(-MAX_STORED_ROWS)) { + json.set(row, JSON.stringify(row)) + await breathe() + } + let rows = Math.min(all.length, MAX_STORED_ROWS) + for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) { + const window = windowOf(stored, rows) + const kept = rowsOf(window).map((row) => json.get(row) ?? JSON.stringify(row)) + const frame = frameJson(window) + const text = frame.replace(ROWS_TOKEN, () => `[${kept.join(',')}]`) + const value = await base64InSlices(await gzipInSlices(strToU8(text), breathe), breathe) + if (value.length <= DEVICE_STORE_MAX_VALUE_LENGTH) { + return value + } + // This attempt's encoded bytes per JSON byte say how many of the newest rows fit. + const perJsonByte = value.length / text.length + let budget = (DEVICE_STORE_MAX_VALUE_LENGTH * REFIT_SHARE) / perJsonByte - frame.length + let fit = 0 + for (let at = kept.length - 1; at >= 0 && budget >= kept[at]!.length + 1; at -= 1) { + budget -= kept[at]!.length + 1 + fit += 1 + } + if (fit === 0) { + return null + } + rows = Math.min(fit, rows - 1) + await breathe() + } + return null +} + +async function gzipInSlices(input: Uint8Array, breathe: () => Promise): Promise { + const parts: Uint8Array[] = [] + const gzip = new Gzip((chunk) => parts.push(chunk)) + for (let offset = 0; offset < input.length; offset += GZIP_CHUNK_BYTES) { + const end = Math.min(offset + GZIP_CHUNK_BYTES, input.length) + gzip.push(input.subarray(offset, end), end === input.length) + await breathe() + } + if (input.length === 0) { + gzip.push(input, true) + } + if (parts.length === 1) { + return parts[0]! + } + const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)) + let at = 0 + for (const part of parts) { + out.set(part, at) + at += part.length + } + return out +} + +async function base64InSlices(bytes: Uint8Array, breathe: () => Promise): Promise { + const parts: string[] = [] + for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_BYTES) { + parts.push(encodeBase64Bytes(bytes.subarray(offset, offset + BASE64_CHUNK_BYTES))) + await breathe() + } + return parts.join('') +} diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-store.ts b/mobile/src/session/native-chat/mobile-native-chat-transcript-store.ts new file mode 100644 index 00000000000..b3c59746c44 --- /dev/null +++ b/mobile/src/session/native-chat/mobile-native-chat-transcript-store.ts @@ -0,0 +1,173 @@ +import { sha256 } from '@noble/hashes/sha256' +import { bytesToHex } from '@noble/hashes/utils' +import { setBoundedScopeCacheEntry } from '../../../../src/shared/native-chat/native-chat-scope-cache' +import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' +import { encodeNativeChatTranscriptIdentity } from '../../../../src/shared/native-chat/transcript/native-chat-transcript-retention' +import type { StructuredAgentSessionState } from '../../../../src/shared/agent-session/structured-agent-session-reducer' +import { decodeDeviceStoreValue } from '../../device-store/device-store-value-codec' +import { readPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' +import { resolveMobileNativeChat, type MobileNativeChatTab } from './mobile-native-chat-eligibility' + +// Bump when a stored shape changes: other versions read as a miss. +export const STORED_TRANSCRIPT_VERSION = 1 +// Decoded copies this document keeps of what the store holds, so a remount skips the read. +const MAX_KNOWN_TRANSCRIPTS = 8 + +export type StoredTerminalChatTranscript = { + kind: 'terminal' + savedAt: number + messages: NativeChatMessage[] + hasMore: boolean + beforeOffset: number | null +} + +// Only the journal: what the agent is doing now (K1) comes from the live read. +export type StoredStructuredJournal = Pick< + StructuredAgentSessionState, + 'epoch' | 'cursor' | 'fence' | 'items' | 'submissions' | 'hasOlder' +> + +export type StoredStructuredChatTranscript = { + kind: 'structured' + savedAt: number + journal: StoredStructuredJournal +} + +export type StoredChatTranscript = StoredTerminalChatTranscript | StoredStructuredChatTranscript + +export function terminalChatTranscriptIdentity( + sourceIdentity: string, + agent: string | null, + sessionId: string | null, + transcriptPath: string | null +): string { + return encodeNativeChatTranscriptIdentity([sourceIdentity, agent, sessionId, transcriptPath]) +} + +export function structuredChatTranscriptIdentity( + sourceIdentity: string, + agent: string | null, + sessionId: string | null +): string { + return encodeNativeChatTranscriptIdentity([sourceIdentity, agent, sessionId]) +} + +/** The identity a stored tab's chat reads under, or null when the tab names no chat. */ +export function storedTabChatTranscriptIdentity( + hostId: string, + worktreeId: string, + tab: MobileNativeChatTab, + // The boot read assumes readable: priming a copy for a chat that can't open yet costs one key. + transcriptReadable = true +): string | null { + const resolution = resolveMobileNativeChat(tab, transcriptReadable) + if (!resolution) { + return null + } + const source = encodeNativeChatTranscriptIdentity([hostId, worktreeId]) + return tab.type === 'agent-session' + ? structuredChatTranscriptIdentity(source, resolution.agent, resolution.sessionId) + : terminalChatTranscriptIdentity( + source, + resolution.agent, + resolution.sessionId, + resolution.transcriptPath + ) +} + +// Identities carry worktree paths and transcript paths, so the key is a hash; the store already fences hosts. +export function chatTranscriptStoreKey(identity: string): string { + return `transcript:${bytesToHex(sha256(identity))}` +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function readStoredValue(raw: string): StoredChatTranscript | null { + const value = decodeDeviceStoreValue(raw) + if (!isRecord(value) || value.v !== STORED_TRANSCRIPT_VERSION) { + return null + } + const { stored } = value + if (!isRecord(stored) || typeof stored.savedAt !== 'number') { + return null + } + if (stored.kind === 'terminal' && Array.isArray(stored.messages)) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this page wrote the value under this version, and the store seals it. + return stored as StoredTerminalChatTranscript + } + if ( + stored.kind === 'structured' && + isRecord(stored.journal) && + Array.isArray(stored.journal.items) + ) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: as above. + return stored as StoredStructuredChatTranscript + } + return null +} + +// What this document knows the store holds per identity: a read in flight, or its answer. +const known = new Map>() +const settled = new Map() + +/** Records what the store now holds for a chat, as a write leaves it. */ +export function rememberStoredChatTranscript( + identity: string, + stored: StoredChatTranscript | null +): void { + setBoundedScopeCacheEntry(known, identity, Promise.resolve(stored), MAX_KNOWN_TRANSCRIPTS) + setBoundedScopeCacheEntry(settled, identity, stored, MAX_KNOWN_TRANSCRIPTS) +} + +function storeAvailable(): boolean { + return readPageDeviceStore()?.available() === true +} + +/** Reads several chats in one store call, as the first paint does for the active tab. */ +export function primeStoredChatTranscripts(identities: readonly string[]): Promise { + const store = readPageDeviceStore() + const unread = identities.filter((identity) => !known.has(identity)) + if (!store?.available() || unread.length === 0) { + return Promise.resolve() + } + const read = store.read('cache', unread.map(chatTranscriptStoreKey)).then( + (result) => (result.status === 'ok' ? result.values : unread.map(() => null)), + () => unread.map(() => null) + ) + unread.forEach((identity, at) => { + const value = read.then((values) => { + const raw = values[at] + const stored = raw ? readStoredValue(raw) : null + // A write that landed meanwhile is newer than this read. + if (!settled.has(identity)) { + rememberStoredChatTranscript(identity, stored) + } + return settled.get(identity) ?? null + }) + setBoundedScopeCacheEntry(known, identity, value, MAX_KNOWN_TRANSCRIPTS) + }) + return read.then(() => undefined) +} + +/** The stored copy when this document already holds the answer; undefined while unread. */ +export function peekStoredChatTranscript( + identity: string +): StoredChatTranscript | null | undefined { + if (!storeAvailable()) { + return null + } + return settled.has(identity) ? (settled.get(identity) ?? null) : undefined +} + +/** The stored copy, reading the store once per identity. */ +export function readStoredChatTranscript(identity: string): Promise { + if (!storeAvailable()) { + return Promise.resolve(null) + } + if (!known.has(identity)) { + void primeStoredChatTranscripts([identity]) + } + return known.get(identity) ?? Promise.resolve(null) +} diff --git a/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts b/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts new file mode 100644 index 00000000000..a500287955f --- /dev/null +++ b/mobile/src/session/native-chat/mobile-native-chat-transcript-writer.ts @@ -0,0 +1,268 @@ +import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' +import { onPageAppInactive } from '../../mobile-web-shell/bridge/bridge-app-inactive' +import { + EMPTY_STRUCTURED_AGENT_SESSION, + reduceStructuredAgentSession, + type StructuredAgentSessionAction, + type StructuredAgentSessionState +} from '../../../../src/shared/agent-session/structured-agent-session-reducer' +import { + MAX_RETAINED_ITEMS, + MAX_RETAINED_OWN_ITEMS +} from '../../../../src/shared/agent-session/view/structured-agent-session-item-retention' +import { readPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' +import { + chatTranscriptStoreKey, + peekStoredChatTranscript, + rememberStoredChatTranscript, + type StoredChatTranscript, + type StoredStructuredChatTranscript +} from './mobile-native-chat-transcript-store' +import { encodeStoredChatTranscript } from './mobile-native-chat-transcript-encode' + +// Writes and restores chat copies; kept apart from the store's reads so the boot read stays small. + +// What a chat's copy is built from: its message list, or its session state. +type TranscriptSource = readonly NativeChatMessage[] | StructuredAgentSessionState + +type NotedTranscript = { + source: TranscriptSource + notedAt: number + isLive: () => boolean + build: (savedAt: number) => StoredChatTranscript +} + +// The newest copy each mounted chat holds, written at turn settle, on hidden and on unmount. +const pending = new Map() +// Per chat, the latest write handed to the store: only that one may come back for a retry. +const latestWrite = new Map() +let writes = 0 +const written = new WeakSet() + +/** + * Remembers a chat's current copy without encoding it; `source` is the array or state it came from. Its saved + * time is the write's while the chat is live, else when the copy last changed, so "as of" never claims more. + */ +export function noteChatTranscript( + identity: string, + source: TranscriptSource, + isLive: () => boolean, + build: (savedAt: number) => StoredChatTranscript +): void { + if (written.has(source)) { + pending.delete(identity) + return + } + pending.set(identity, { source, notedAt: Date.now(), isLive, build }) + listenForHidden() +} + +// An unchanged copy is still rewritten this long after the stored one, so its saved time stays within a minute. +const SAME_COPY_REWRITE_MS = 60_000 + +// Whether two copies hold the same rows: an open that changed nothing then skips re-encoding the whole window. +function sameRows(a: StoredChatTranscript, b: StoredChatTranscript): boolean { + // The merger replaces a row object whenever the row changes, anywhere in the list; a copy read back from the + // store holds other objects, so the first save after a relaunch writes once. + if (a.kind === 'terminal' && b.kind === 'terminal') { + return ( + a.messages.length === b.messages.length && + a.hasMore === b.hasMore && + a.messages.every((row, at) => row === b.messages[at]) + ) + } + // A journal's cursor moves with every change to its rows. + return ( + a.kind === 'structured' && + b.kind === 'structured' && + a.journal.epoch === b.journal.epoch && + a.journal.cursor?.sequence === b.journal.cursor?.sequence && + a.journal.items.length === b.journal.items.length && + a.journal.hasOlder === b.journal.hasOlder + ) +} + +// Chats whose copy is being encoded in slices; a hide takes the copy over and encodes it at once. +const encoding = new Map() + +function yieldToPage(): Promise { + return new Promise((resolve) => setTimeout(resolve, 0)) +} + +/** + * When a copy is written. `settle` (a turn settles, a chat closes) and `leave` (the app leaving the foreground, which + * also fires for Notification Centre, Face ID or an Android dialog) encode in slices, so even a big chat costs no long + * task; a swipe-kill from the app switcher comes a beat later. `leave` writes only rows the store doesn't hold yet and + * otherwise keeps the copy noted for the next hide. `hide` encodes in one go, since the app may stop right after. + */ +type FlushWhen = 'settle' | 'hide' | 'leave' + +/** Writes a chat's noted copy unless the store already holds it. */ +export function flushChatTranscript(identity: string, when: FlushWhen = 'settle'): void { + const now = when === 'hide' + const next = pending.get(identity) ?? (now ? encoding.get(identity) : undefined) + pending.delete(identity) + const store = readPageDeviceStore() + if (!next || !store?.available()) { + return + } + const stored = next.build(next.isLive() ? Date.now() : next.notedAt) + const kept = peekStoredChatTranscript(identity) + if (kept && sameRows(kept, stored)) { + if (when === 'leave') { + pending.set(identity, next) + return + } + if (stored.savedAt - kept.savedAt < SAME_COPY_REWRITE_MS) { + written.add(next.source) + return + } + } + const write = ++writes + latestWrite.set(identity, write) + const superseded = (): boolean => latestWrite.get(identity) !== write + if (now) { + encoding.delete(identity) + } else { + encoding.set(identity, next) + } + // A refused or failed write stays noted, so the next settle, hidden or close tries again. + const retry = (): void => { + if (!superseded() && !pending.has(identity)) { + pending.set(identity, next) + } + } + void encodeStoredChatTranscript(stored, now ? null : yieldToPage) + .then(async (value) => { + if (encoding.get(identity) === next) { + encoding.delete(identity) + } + // A newer flush of this chat started while this one encoded; it carries newer rows. + if (superseded()) { + return + } + // The shell finishes a write it was handed, so a page closing right after still keeps it. + const result = await store.write('cache', [{ key: chatTranscriptStoreKey(identity), value }]) + if (!result.written) { + retry() + return + } + written.add(next.source) + if (!superseded()) { + latestWrite.delete(identity) + rememberStoredChatTranscript(identity, value === null ? null : stored) + } + }) + .catch(retry) +} + +function flushAll(when: Exclude): void { + for (const identity of new Set([...pending.keys(), ...encoding.keys()])) { + flushChatTranscript(identity, when) + } +} + +let listening = false +function listenForHidden(): void { + if (listening) { + return + } + listening = true + // iOS hides the page only once the app is in the background; a swipe-kill from the app switcher comes sooner. + onPageAppInactive(() => flushAll('leave')) + if (typeof document === 'undefined') { + return + } + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + flushAll('hide') + } + }) + // A document torn down while visible fires no hidden and runs no unmount cleanups. + window.addEventListener('pagehide', () => flushAll('hide')) +} + +// Reducer states that still show a stored copy no live read has confirmed, with when it was saved. +const unconfirmedStates = new WeakMap() +const restoredStates = new WeakMap() + +/** A stored structured journal as reducer state: shown, but claiming nothing about current work. One object per copy. */ +export function storedStructuredAgentSessionState( + stored: StoredStructuredChatTranscript +): StructuredAgentSessionState { + const restored = restoredStates.get(stored) + if (restored) { + return restored + } + const state: StructuredAgentSessionState = { + ...EMPTY_STRUCTURED_AGENT_SESSION, + ...stored.journal, + retainedOwnItemLimit: MAX_RETAINED_OWN_ITEMS, + retainedItemCap: MAX_RETAINED_ITEMS, + // The live read restates these; a stored running turn or pending send must not look like work. + working: false, + latestTurn: null, + actionablePromptIds: [] + } + restoredStates.set(stored, state) + unconfirmedStates.set(state, stored.savedAt) + return state +} + +/** The phone's copy of a structured session as reducer state; undefined while unread. */ +export function storedStructuredSessionState( + identity: string +): StructuredAgentSessionState | null | undefined { + const stored = peekStoredChatTranscript(identity) + if (stored === undefined) { + return undefined + } + return stored?.kind === 'structured' ? storedStructuredAgentSessionState(stored) : null +} + +/** When the stored copy a state still shows was saved; null once a live frame has replaced it. */ +export function unconfirmedStructuredStateSavedAt( + state: StructuredAgentSessionState +): number | null { + return unconfirmedStates.get(state) ?? null +} + +/** + * The session reducer over a state that may be a stored copy. A live frame applies to the copy without its + * "nothing running" placeholders, so the host's own fields decide (or an older host's row-derived fallbacks, as + * without a copy), and confirms it. Anything else keeps the copy's mark. Returns `previous` when nothing applied. + */ +export function reduceStructuredChatState( + previous: StructuredAgentSessionState, + action: StructuredAgentSessionAction, + receivedAt: number +): StructuredAgentSessionState { + const savedAt = unconfirmedStates.get(previous) + const live = + action.type === 'history-page' || (action.type === 'event' && action.event.type !== 'end') + const base = + savedAt !== undefined && live + ? { ...previous, working: undefined, latestTurn: undefined, actionablePromptIds: undefined } + : previous + const next = reduceStructuredAgentSession(base, action, receivedAt) + if (next === base) { + return previous + } + if (savedAt !== undefined && !live) { + unconfirmedStates.set(next, savedAt) + } + return next +} + +/** The copy a live structured state is stored as: its journal, saved now. */ +export function storedStructuredCopy( + state: StructuredAgentSessionState, + savedAt: number +): StoredStructuredChatTranscript { + const { epoch, cursor, fence, items, submissions, hasOlder } = state + return { + kind: 'structured', + savedAt, + journal: { epoch, cursor, fence, items, submissions, hasOlder } + } +} diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts index a6e395f3ff7..8adab75b691 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatMessage.status-notices.test.ts @@ -2,11 +2,18 @@ import { createElement, type ReactNode } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentJournalStatusItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { isAdmissibleAgentJournalItemBody } from '../../../../../src/shared/agent-session/journal/agent-session-journal-schemas' import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection' import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { agentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureWords } from '../../../../../src/shared/agent-session/failures/agent-session-failure-words' import { colors } from '../../../theme/mobile-theme' import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler' +import { + MobileNativeChatNoticeContext, + type MobileNativeChatNoticeView +} from '../../mobile-native-chat-notice-context' vi.mock('react-native', async () => { const React = await import('react') @@ -95,6 +102,69 @@ describe('MobileNativeChatMessage status notices', () => { observedAt: 2, body })! + const renderNotice = (body: AgentJournalStatusItem, names: MobileNativeChatNoticeView) => { + act(() => { + renderer = create( + createElement( + MobileNativeChatNoticeContext.Provider, + { value: names }, + createElement(MobileNativeChatMessage, { message: statusRow(body) }) + ) + ) + }) + return renderer!.root.findAll( + (node) => String(node.type) === 'Text' && node.props.selectable === true + )[0]! + } + + it('localizes a canonical failure and discloses its diagnostic only on request', async () => { + await activateMobileUiLocale('fr') + const diagnostic = 'Internal provider diagnostic: modelNotFound' + const notice = renderNotice( + { + kind: 'status', + tone: 'error', + ...agentSessionFailureWords(agentSessionFailureFact('modelUnavailable'), { + agentName: 'Codex', + surface: 'row' + }), + providerFrame: { + provider: 'codex', + kind: 'notification:error', + payload: { + head: diagnostic, + byteLength: diagnostic.length, + digest: 'fixture', + truncated: false + } + } + }, + { hostName: null, agentName: 'Codex' } + ) + expect(String(notice.props.children)).toContain('le modèle sélectionné') + expect(String(notice.props.children)).not.toContain(diagnostic) + const details = () => + renderer!.root.findAll( + (node) => String(node.type) === 'Text' && String(node.props.children).includes(diagnostic) + ) + expect(details()).toHaveLength(0) + const disclosure = renderer!.root.find( + (node) => String(node.type) === 'Pressable' && node.props['aria-expanded'] === false + ) + act(() => disclosure.props.onPress()) + expect(details().length).toBeGreaterThan(0) + act(() => renderer?.unmount()) + const hostAdvice: unknown = { + kind: 'status', + text: 'Custom host advice: use the enterprise model.', + failure: agentSessionFailureFact('modelUnavailable') + } + if (!isAdmissibleAgentJournalItemBody(hostAdvice) || hostAdvice.kind !== 'status') { + throw new Error('Expected host status row') + } + const custom = renderNotice(hostAdvice, { hostName: null, agentName: 'Codex' }) + expect(custom.props.children).toBe('Custom host advice: use the enterprise model.') + }) it('links a CI result line to its pull request and commit through the link sheet', () => { const openLink = vi.fn() diff --git a/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx b/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx index 82d76d12e10..ac094b90491 100644 --- a/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx +++ b/mobile/src/session/native-chat/transcript/MobileNativeChatNoticeRow.tsx @@ -73,7 +73,15 @@ function noticeLineText( // Only reword text fully described by its fact; other host text stays as written. const context = { agentName: names.agentName } const surface = - failure?.kind === 'savedConversationMissing' || failure?.kind === 'pluginInputRequired' + failure && + [ + 'savedConversationMissing', + 'pluginInputRequired', + 'modelUnavailable', + 'providerUnavailable', + 'providerSafetyStopped', + 'providerResponseFailed' + ].includes(failure.kind) ? (['row', 'rejection'] as const).find( (candidate) => notice.text === agentSessionFailureSentence(failure, candidate, context) ) @@ -157,17 +165,21 @@ export function MobileNativeChatNoticeRow({ case 'settled-permission': { const agent = names.agentName ?? look.agent const summary = - look.decision === 'denied' - ? t('chat.notice.permissionDenied', '{{agent}} denied permission. View details.', { + look.decision === 'approved' + ? t('chat.notice.safetyReviewApproved', '{{agent}} approved this action. View details.', { agent }) - : t( - 'chat.notice.safetyReview', - '{{agent}} reported a safety review warning. View details.', - { + : look.decision === 'denied' + ? t('chat.notice.permissionDenied', '{{agent}} denied permission. View details.', { agent - } - ) + }) + : t( + 'chat.notice.safetyReview', + '{{agent}} reported a safety review warning. View details.', + { + agent + } + ) return ( unit.sources[0]!.id === members[0]!.id) - const unit = buildMobileNativeChatUnit(members, NO_IDS, kinds, held) + const unit = buildNativeChatFoldUnit( + members, + NO_IDS, + kinds, + held, + finishMobileNativeChatMessages + ) if (unit !== held && unit.orphans.length > 0) { return null } diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts deleted file mode 100644 index 51ac45b648d..00000000000 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts +++ /dev/null @@ -1,135 +0,0 @@ -import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' -import { - foldToolMessages, - type NativeChatToolFoldKind -} from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' -import { - orphanRowId, - type NativeChatOrphanOrigin -} from '../../../../../src/shared/native-chat/tools/native-chat-folded-tool-results' -import { finishMobileNativeChatMessages } from '../mobile-native-chat-render-data' - -export type Unit = { - sources: readonly NativeChatMessage[] - rows: NativeChatMessage[] - orphans: readonly NativeChatOrphanOrigin[] -} - -export function groupMobileNativeChatUnitMembers( - grouped: readonly NativeChatMessage[], - kinds: ReadonlyMap -): NativeChatMessage[][] { - const members: NativeChatMessage[][] = [] - let active = false - for (const source of grouped) { - const kind = kinds.get(source)! - if (active && (kind === 'tool' || kind === 'sidecar' || kind === 'pass')) { - members.at(-1)!.push(source) - } else { - members.push([source]) - active = source.role === 'assistant' && kind !== 'orphan' - } - } - return members -} - -export function buildMobileNativeChatUnit( - sources: readonly NativeChatMessage[], - ids: ReadonlySet, - kinds: ReadonlyMap, - before: Unit | undefined -): Unit { - if ( - before && - before.sources.length === sources.length && - before.sources.every((source, index) => source === sources[index]) - ) { - return before - } - const substituted = before && substituteProse(before, sources, kinds) - const orphans: NativeChatOrphanOrigin[] = [] - const rows = - substituted ?? - finishMobileNativeChatMessages( - foldToolMessages(sources, ids, kinds, (origin) => orphans.push(origin)) - ) - return { sources, rows, orphans: substituted ? before!.orphans : orphans } -} - -export function buildMobileNativeChatUnits( - grouped: readonly NativeChatMessage[], - kinds: ReadonlyMap, - previous?: { units: readonly Unit[] } -): Unit[] { - const ids = new Set(grouped.map((row) => row.id)) - const oldUnits = new Map(previous?.units.map((unit) => [unit.sources[0]!.id, unit])) - const units = groupMobileNativeChatUnitMembers(grouped, kinds).map((sources) => - buildMobileNativeChatUnit(sources, ids, kinds, oldUnits.get(sources[0]!.id)) - ) - const allocated = new Set(ids) - const occurrences = new Map() - return units.map((unit) => { - const renamed = new Map() - const orphans = unit.orphans.map((origin) => { - const id = orphanRowId(origin.sourceId, allocated, occurrences) - allocated.add(id) - if (id === origin.row.id) { - return origin - } - const row = { ...origin.row, id } - renamed.set(origin.row, row) - return { ...origin, row } - }) - return renamed.size === 0 - ? unit - : { - ...unit, - orphans, - rows: unit.rows.map((row) => renamed.get(row) ?? row) - } - }) -} - -function substituteProse( - before: Unit, - sources: readonly NativeChatMessage[], - kinds: ReadonlyMap -): NativeChatMessage[] | null { - if (before.sources.length !== sources.length) { - return null - } - const changed = sources.flatMap((source, index) => - source === before.sources[index] ? [] : [index] - ) - if (changed.length !== 1 || changed[0] !== 0) { - return null - } - const old = before.sources[0]!, - next = sources[0]! - if ( - old.role !== next.role || - (next.role !== 'assistant' && next.role !== 'reasoning') || - old.unpairedToolResults || - next.unpairedToolResults || - !old.blocks.every((block) => block.type === 'text' && !block.providerFrame) || - !next.blocks.every((block) => block.type === 'text' && !block.providerFrame) - ) { - return null - } - const target = before.rows.find((row) => row.id === old.id && row.role === old.role) - if (!target || !old.blocks.every((block, index) => block === target.blocks[index])) { - return null - } - const contribution = sources - .slice(1) - .findLast( - (source) => - source.journalPosition && (kinds.get(source) === 'tool' || kinds.get(source) === 'sidecar') - ) - const replacement: NativeChatMessage = { - ...next, - blocks: [...next.blocks, ...target.blocks.slice(old.blocks.length)], - ...(contribution ? { foldedJournalPosition: contribution.journalPosition } : {}) - } - return before.rows.map((row) => (row === target ? replacement : row)) -} diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts index d393b28d89a..e7b598ab6c2 100644 --- a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts @@ -9,13 +9,19 @@ import { nativeChatImageTranscriptUnits, normalizeImageTranscriptUnit } from '../../../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers' -import { foldMobileNativeChatMessages } from '../mobile-native-chat-render-data' +import { + finishMobileNativeChatMessages, + foldMobileNativeChatMessages +} from '../mobile-native-chat-render-data' import { prepareMobileNativeChatSources, type MobileNativeChatProjectionSource } from './mobile-native-chat-projection-sources' import { projectMobileNativeChatTail } from './mobile-native-chat-projection-tail' -import { buildMobileNativeChatUnits, type Unit } from './mobile-native-chat-projection-units' +import { + buildNativeChatFoldUnits, + type NativeChatFoldUnit as Unit +} from '../../../../../src/shared/native-chat/transcript/native-chat-fold-units' type ImageUnit = { sources: readonly NativeChatMessage[]; rows: NativeChatMessage[] } export type MobileNativeChatProjection = { @@ -75,7 +81,12 @@ export function projectMobileNativeChatMessages( const kinds = new Map( grouped.map((source) => [source, previous?.kinds.get(source) ?? nativeChatToolFoldKind(source)]) ) - const units = buildMobileNativeChatUnits(grouped, kinds, previous) + const units = buildNativeChatFoldUnits( + grouped, + kinds, + new Map(previous?.units.map((unit) => [unit.sources[0]!.id, unit])), + finishMobileNativeChatMessages + ) const unchanged = previous && units.length === previous.units.length && diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts index f817554b92f..8d9f0705af2 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session.test.ts @@ -3,7 +3,10 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' +import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub' +import { publishPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' import { mobileNativeChatTranscriptCache } from './mobile-native-chat-transcript-cache' +import { encodeStoredChatTranscript } from './mobile-native-chat-transcript-encode' import { useMobileNativeChatSession, type MobileNativeChatSession @@ -545,3 +548,62 @@ describe('useMobileNativeChatSession transcriptLoading', () => { expect(renders.at(-1)).toMatchObject({ status: 'loading', ids: ['a-1'] }) }) }) + +describe('useMobileNativeChatSession after a relaunch', () => { + let renderer: ReactTestRenderer | null = null + let stored: string | null = null + + beforeEach(() => { + publishPageDeviceStore({ + available: () => true, + read: async (_table, keys) => ({ + status: 'ok', + values: keys.map((key) => (key.startsWith('transcript:') ? stored : null)) + }), + write: async () => ({ written: true }) + }) + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + publishPageDeviceStore(null) + }) + + it('paints the stored rows and subscribes after the newest one', async () => { + // What an earlier launch's page saved when this chat's turn settled. + stored = await encodeStoredChatTranscript({ + kind: 'terminal', + savedAt: 1_700_000_000_000, + messages: [ + { ...message('m1'), transcriptOrder: 100 }, + { ...message('m2'), transcriptOrder: 200 } + ], + hasMore: false, + beforeOffset: null + }) + const subscribe = vi.fn(() => () => {}) + const client = stubRpcClient({ subscribe }) + const seen: { state: MobileNativeChatSession | null } = { state: null } + function Harness(): null { + seen.state = useMobileNativeChatSession({ + client, + sourceIdentity: 'host-a\0relaunched', + agent: 'claude', + sessionId: 'session', + transcriptPath: null + }) + return null + } + await act(async () => { + renderer = create(createElement(Harness)) + }) + + expect(subscribe).toHaveBeenCalledTimes(1) + expect(subscribe.mock.calls[0]?.[1]).toMatchObject({ + resumeAfter: { id: 'm2', transcriptOrder: 200, timestamp: 1 } + }) + expect(seen.state?.messages.map((entry) => entry.id)).toEqual(['m1', 'm2']) + expect(seen.state?.savedAt).toBe(1_700_000_000_000) + }) +}) diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts index c1952510c32..978f859a8f3 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts @@ -1,8 +1,5 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import { - EMPTY_NATIVE_CHAT_TRANSCRIPT, - encodeNativeChatTranscriptIdentity -} from '../../../../src/shared/native-chat/transcript/native-chat-transcript-retention' +import { EMPTY_NATIVE_CHAT_TRANSCRIPT } from '../../../../src/shared/native-chat/transcript/native-chat-transcript-retention' import { createNativeChatMerger, replaceList @@ -23,9 +20,13 @@ import { randomV4Uuid } from '../../platform/random-v4-uuid' import { useMobileOlderPageLoader, type OlderPagePhase } from '../use-mobile-older-page-loader' import { cacheMobileNativeChatTranscript, + heldMobileNativeChatTranscript, mobileNativeChatResumePoint, mobileNativeChatTranscriptCache } from './mobile-native-chat-transcript-cache' +import { terminalChatTranscriptIdentity } from './mobile-native-chat-transcript-store' +import { noteChatTranscript } from './mobile-native-chat-transcript-writer' +import { useStoredChatTranscript } from './use-stored-chat-transcript' import type { MobileNativeChatStatus } from './mobile-native-chat-session-status' export type { MobileNativeChatStatus } from './mobile-native-chat-session-status' @@ -48,6 +49,8 @@ export type MobileNativeChatSession = { loadEarlier: () => void /** Latest provider turn boundary from the transcript feed; absent from older hosts. */ transcriptLifecycle?: NativeChatTurnLifecycle + /** When the rows on screen were saved, while they are an earlier launch's copy no read has confirmed. */ + savedAt?: number | null } const INITIAL_LIMIT = 40 @@ -79,12 +82,7 @@ export function useMobileNativeChatSession(args: { }): MobileNativeChatSession { const { client, sourceIdentity, agent, sessionId, transcriptPath } = args const [messages, setMessages] = useState([]) - const identity = encodeNativeChatTranscriptIdentity([ - sourceIdentity, - agent, - sessionId, - transcriptPath - ]) + const identity = terminalChatTranscriptIdentity(sourceIdentity, agent, sessionId, transcriptPath) // Derive pre-read status from props now; a passive effect would lag one commit. const initialStatus: MobileNativeChatStatus = !client || !agent ? 'idle' : !sessionId ? 'waiting-session' : 'loading' @@ -123,13 +121,23 @@ export function useMobileNativeChatSession(args: { const settledReady = settled?.status === 'ready' useEffect(() => { if (settledReady) { - cacheMobileNativeChatTranscript(identity, { + const beforeOffset = beforeOffsetRef.current + cacheMobileNativeChatTranscript(identity, { messages, hasMore, beforeOffset }) + noteChatTranscript( + identity, messages, - hasMore, - beforeOffset: beforeOffsetRef.current - }) + () => client?.getState() === 'connected', + (savedAt) => ({ kind: 'terminal', savedAt, messages, hasMore, beforeOffset }) + ) } - }, [identity, messages, hasMore, settledReady]) + }, [client, identity, messages, hasMore, settledReady]) + const readingStore = useStoredChatTranscript({ + // A tab that names no session (or a structured one) has no copy of its own. + identity: agent && sessionId ? identity : null, + read: !mobileNativeChatTranscriptCache.has(identity), + turnSettled: + settledReady && (lifecycle?.identity !== identity || lifecycle.lifecycle?.state !== 'working') + }) const setList = useCallback((next: readonly NativeChatMessage[]) => { replaceList(mergerRef.current, next) @@ -142,14 +150,17 @@ export function useMobileNativeChatSession(args: { supersede() limitRef.current = INITIAL_LIMIT snapshotSeenRef.current = false - const cached = mobileNativeChatTranscriptCache.get(identity) + const cached = readingStore ? undefined : heldMobileNativeChatTranscript(identity) + if (cached && !mobileNativeChatTranscriptCache.has(identity)) { + cacheMobileNativeChatTranscript(identity, cached) + } const resumeAfter = cached ? mobileNativeChatResumePoint(cached.messages) : null const holdsCachedRows = Boolean(cached?.messages.length) setList(cached?.messages ?? EMPTY_NATIVE_CHAT_TRANSCRIPT) setError(undefined) setHasMore(cached?.hasMore ?? false) beforeOffsetRef.current = cached?.beforeOffset ?? null - if (!client || !agent) { + if (!client || !agent || readingStore) { return } if (!sessionId) { @@ -240,7 +251,7 @@ export function useMobileNativeChatSession(args: { supersede() unsubscribe() } - }, [client, agent, sessionId, transcriptPath, identity, setList, supersede]) + }, [client, agent, sessionId, transcriptPath, identity, readingStore, setList, supersede]) const loadEarlier = useCallback(() => { if (!client || !agent || !sessionId || !hasMore) { @@ -309,22 +320,25 @@ export function useMobileNativeChatSession(args: { }, [client, agent, sessionId, transcriptPath, hasMore, setList, loadOlderPages]) // Show the cached rows through any unsettled read: a reopen paints at once, and a disconnect or error can't blank the conversation. - const visibleMessages = settledReady - ? messages - : (mobileNativeChatTranscriptCache.get(identity)?.messages ?? EMPTY_NATIVE_CHAT_TRANSCRIPT) + const held = settledReady ? undefined : heldMobileNativeChatTranscript(identity) + const visibleMessages = settledReady ? messages : (held?.messages ?? EMPTY_NATIVE_CHAT_TRANSCRIPT) return { // Withhold rows until they belong to this identity; passive reset otherwise exposes previous-tab history for one commit. messages: visibleMessages, status, - // Rows left from an earlier visit can't answer "is this ask still open?" until a read confirms them. + // Rows left from an earlier visit or launch can't answer "is this ask still open?" until a read confirms them. transcriptLoading: - status === 'loading' || status === 'awaiting-transcript' || settled?.rowsUnconfirmed === true, + status === 'loading' || + status === 'awaiting-transcript' || + settled?.rowsUnconfirmed === true || + held?.savedAt !== undefined, error, hasMore, loadingEarlier: olderPages === 'loading', olderPages, loadEarlier, - transcriptLifecycle: lifecycle?.identity === identity ? lifecycle.lifecycle : undefined + transcriptLifecycle: lifecycle?.identity === identity ? lifecycle.lifecycle : undefined, + savedAt: held?.savedAt ?? null } } diff --git a/mobile/src/session/native-chat/use-stored-chat-transcript.ts b/mobile/src/session/native-chat/use-stored-chat-transcript.ts new file mode 100644 index 00000000000..a10fd5fb0f2 --- /dev/null +++ b/mobile/src/session/native-chat/use-stored-chat-transcript.ts @@ -0,0 +1,57 @@ +import { useEffect, useReducer, useState } from 'react' +import { + peekStoredChatTranscript, + readStoredChatTranscript +} from './mobile-native-chat-transcript-store' +import { flushChatTranscript } from './mobile-native-chat-transcript-writer' + +// The same cap the boot read has: past it, the chat reads live without its stored copy. +const STORE_READ_WAIT_MS = 150 + +/** + * A chat's link to the phone's stored copy. Returns true while the copy is still being read (a few ms, then + * one re-render), so the chat subscribes only once it can paint and resume from it. The copy the chat noted + * is written when its turn settles and when the chat closes; the store writes on hidden itself. + */ +export function useStoredChatTranscript(args: { + identity: string | null + // False when this page already holds the chat, so there is nothing to read. + read: boolean + turnSettled: boolean +}): boolean { + const { identity, turnSettled } = args + // A store that doesn't answer in time never holds the live read back; its late answer still fills the copy. + const [gaveUpOn, setGaveUpOn] = useState(null) + const reading = + args.read && + identity !== null && + gaveUpOn !== identity && + peekStoredChatTranscript(identity) === undefined + const [, answered] = useReducer((answers: number) => answers + 1, 0) + useEffect(() => { + if (!reading || identity === null) { + return + } + let current = true + const wait = setTimeout(() => current && setGaveUpOn(identity), STORE_READ_WAIT_MS) + void readStoredChatTranscript(identity).then(() => current && answered()) + return () => { + current = false + clearTimeout(wait) + } + }, [identity, reading]) + useEffect(() => { + if (turnSettled && identity !== null) { + flushChatTranscript(identity) + } + }, [identity, turnSettled]) + useEffect( + () => () => { + if (identity !== null) { + flushChatTranscript(identity) + } + }, + [identity] + ) + return reading +} diff --git a/mobile/src/session/tabs/active-session-tab.ts b/mobile/src/session/tabs/active-session-tab.ts index 0326b23dadd..674cb67abc1 100644 --- a/mobile/src/session/tabs/active-session-tab.ts +++ b/mobile/src/session/tabs/active-session-tab.ts @@ -16,6 +16,11 @@ export type ResolveActiveSessionTabResult = { retainSelectedSessionTabId: boolean } +/** The tab a strip marks active, else its first. */ +export function activeSessionTabOf(tabs: readonly T[]): T | null { + return tabs.find((tab) => tab.isActive) ?? tabs[0] ?? null +} + export function resolveActiveSessionTab( tabs: readonly T[], opts: { @@ -24,7 +29,7 @@ export function resolveActiveSessionTab( navigationIntent?: 'follow' } ): ResolveActiveSessionTabResult { - const snapshotActive = tabs.find((tab) => tab.isActive) ?? tabs[0] ?? null + const snapshotActive = activeSessionTabOf(tabs) const pendingActiveSessionTabId = opts.pendingActiveSessionTabId // Why: targeted follow is the only host action allowed to supersede phone-local intent. if (opts.navigationIntent === 'follow') { diff --git a/mobile/src/session/tabs/notification-pane-tab.ts b/mobile/src/session/tabs/notification-pane-tab.ts index 4a3c6e3ed90..ca3fcdad015 100644 --- a/mobile/src/session/tabs/notification-pane-tab.ts +++ b/mobile/src/session/tabs/notification-pane-tab.ts @@ -1,4 +1,4 @@ -import { parsePaneKey } from '../../../../src/shared/workspace-layout/stable-pane-id' +import { makePaneKey, parsePaneKey } from '../../../../src/shared/workspace-layout/stable-pane-id' import { structuredAgentSessionPaneKey, structuredAgentSessionTabId @@ -22,3 +22,21 @@ export function notificationPaneTab(tabs: readonly MobileSessionTab[], paneKey: ) === paneKey) ) } + +// The pane key that opens this tab again; notificationPaneTab finds the tab from it. +export function mobileSessionTabPaneKey( + tab: MobileSessionTab | null | undefined +): string | undefined { + if (tab?.type === 'agent-session') { + return structuredAgentSessionPaneKey(structuredAgentSessionTabId(tab.sessionId), tab.sessionId) + } + if (tab?.type !== 'terminal' || !tab.leafId) { + return undefined + } + try { + return makePaneKey(tab.parentTabId ?? tab.id, tab.leafId) + } catch { + // An id the pane key grammar refuses opens the session on its current tab instead. + return undefined + } +} diff --git a/mobile/src/session/use-mobile-session-controller.ts b/mobile/src/session/use-mobile-session-controller.ts index efd7d0a817e..fc11f3af02d 100644 --- a/mobile/src/session/use-mobile-session-controller.ts +++ b/mobile/src/session/use-mobile-session-controller.ts @@ -32,6 +32,7 @@ import { useMobileSessionContentCreateActions } from './use-mobile-session-conte import { useMobileSessionCloseActions } from './tabs/use-mobile-session-close-actions' import { useMobileSessionBulkClose } from './tabs/use-mobile-session-bulk-close' import { useMobileSessionPresentation } from './use-mobile-session-presentation' +import { useMobileSessionStoredChatTab } from './use-mobile-session-stored-chat-tab' import { useMobileSessionPanelRouteActions } from './use-mobile-session-panel-route-actions' export function useMobileSessionController() { @@ -94,6 +95,7 @@ export function useMobileSessionController() { const lifecycle = Object.assign(tabReconciliation, useMobileSessionLifecycle(tabReconciliation)) const keyboardState = Object.assign(lifecycle, useMobileSessionKeyboardState(lifecycle)) useMobileSessionStartup(keyboardState) + useMobileSessionStoredChatTab(keyboardState) const preferences = useMobileSessionPreferenceFocus(keyboardState) const tabSwitching = Object.assign(keyboardState, useMobileSessionTabSwitching(keyboardState)) const openNativeSession = useMobileStructuredSessionOpening(tabSwitching) diff --git a/mobile/src/session/use-mobile-session-dictation-setup.ts b/mobile/src/session/use-mobile-session-dictation-setup.ts new file mode 100644 index 00000000000..a1c46e002b8 --- /dev/null +++ b/mobile/src/session/use-mobile-session-dictation-setup.ts @@ -0,0 +1,77 @@ +import { useCallback, useRef, useState } from 'react' +import { AppState } from 'react-native' +import { useFocusEffect } from 'expo-router' +import { usePhoneDictationReady } from '../hooks/use-phone-dictation-ready' +import { + dictationMicHidden, + dictationNeedsSetup, + fetchDictationSetup +} from '../dictation/mobile-dictation-setup' +import type { MobileSessionFeedbackCapabilitiesModel } from './use-mobile-session-feedback-capabilities' +import type { DictationTerm } from '../../../src/shared/dictation-dictionary' + +// The computer's dictation settings as this session reads them: mic shown, mode, filler switch, and whether setup is needed first. +export function useMobileSessionDictationSetup(scope: MobileSessionFeedbackCapabilitiesModel) { + const { client, connState, worktreeId, setShowDictationSetup, setDictationMode } = scope + const { setDictationEnabled } = scope + // The phone's own recognizer needs no computer setup, and chat inserts its words on the phone. + const phoneDictation = usePhoneDictationReady() + // The host's filler switch and this worktree's terms, kept from its last setup read; fillers on until one says otherwise. + const [removeFillerWords, setRemoveFillerWords] = useState(true) + const [dictationTerms, setDictationTerms] = useState(undefined) + // Only a host setup read sets this; while false, the host's start refusal decides (older hosts, first tap before the read). + const dictationNeedsSetupRef = useRef(false) + + const dictationSettingsReadRef = useRef(0) + const refreshDictationMode = useCallback(async () => { + const read = ++dictationSettingsReadRef.current + void phoneDictation.refresh() + if (!client || connState !== 'connected') { + return + } + try { + const setup = await fetchDictationSetup(client, worktreeId) + if (read === dictationSettingsReadRef.current) { + setDictationMode(setup.dictationMode) + setRemoveFillerWords(setup.removeFillerWords !== false) + setDictationTerms(setup.dictationTerms) + setDictationEnabled(!dictationMicHidden(setup)) + dictationNeedsSetupRef.current = dictationNeedsSetup(setup) + } + } catch { + // Keep the last settings when an older host cannot report them. + } + }, [client, connState, phoneDictation.refresh, setDictationEnabled, setDictationMode, worktreeId]) + + // The sheet may have changed host setup: let the host judge taps until the fresh read lands. + const closeDictationSetup = useCallback(() => { + setShowDictationSetup(false) + dictationNeedsSetupRef.current = false + void refreshDictationMode() + }, [refreshDictationMode, setShowDictationSetup]) + + useFocusEffect( + useCallback(() => { + void refreshDictationMode() + const subscription = AppState.addEventListener('change', (state) => { + if (state === 'active') { + void refreshDictationMode() + } + }) + return () => { + // Late replies from a retired connection or focus must not rebind the mic. + dictationSettingsReadRef.current += 1 + subscription.remove() + } + }, [refreshDictationMode]) + ) + + return { + phoneDictation, + removeFillerWords, + dictationTerms, + dictationNeedsSetupRef, + closeDictationSetup, + refreshDictationMode + } +} diff --git a/mobile/src/session/use-mobile-session-dictation.ts b/mobile/src/session/use-mobile-session-dictation.ts new file mode 100644 index 00000000000..32159402a3c --- /dev/null +++ b/mobile/src/session/use-mobile-session-dictation.ts @@ -0,0 +1,317 @@ +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, + useSyncExternalStore +} from 'react' +import { useFocusEffect, useNavigation } from 'expo-router' +import { HOST_SESSION_ROUTE } from '../navigation/host-stack-navigation' +import { useMobileSessionDictationSetup } from './use-mobile-session-dictation-setup' +import { triggerError } from '../platform/haptics' +import { useClipboardWriter } from '../platform/clipboard' +import { + useMobileDictationDestination, + useMobileDictationPreviews +} from '../dictation/use-mobile-dictation-destination' +import { + dictationFailureMessage, + isDictationSetupRequiredError +} from '../dictation/mobile-dictation-setup' +import { useMobileDictationLeaveHold } from '../dictation/mobile-dictation-leave-hold' +import { useMobileDictationHost } from '../dictation/mobile-dictation-host' +import { mobileDictationShownOnScreen } from '../dictation/mobile-dictation-shown' +import { useDictationComputerName } from '../dictation/use-mobile-dictation-live' +import { nativeChatDictationCopy } from '../dictation/mobile-session-native-chat-dictation-copy' +import { dictationAnnounceCopy } from '../dictation/mobile-dictation-announce-copy' +import { + useWorkspaceExecutionHost, + workspaceRouteHref +} from '../navigation/workspace-execution-host' +import { mobileSessionTabPaneKey } from './tabs/notification-pane-tab' +import type { MobileSessionFeedbackCapabilitiesModel } from './use-mobile-session-feedback-capabilities' +import type { useMobileNativeChatController } from './native-chat/use-mobile-native-chat-controller' + +// The session screen's side of the page's one dictation: start it here, show it in place while this screen is in front, and insert where it started. +export function useMobileSessionDictation( + scope: MobileSessionFeedbackCapabilitiesModel, + nativeChatController: ReturnType, + sendLiveTerminalInput: (handle: string, bytes: string) => Promise +) { + const { + hostId, + worktreeId, + client, + connState, + activeHandle, + activeHandleRef, + activeSessionTab, + setShowDictationSetup, + dictationRouteContextRef, + flushPendingLiveInputBeforeExternalSend, + canSend, + showToast, + router + } = scope + const { showNativeChat, showNativeChatRef } = nativeChatController + const host = useMobileDictationHost() + const computerName = useDictationComputerName(hostId) + const { start: startHost } = host + const executionHost = useWorkspaceExecutionHost() + const sessionKey = JSON.stringify([hostId, executionHost ?? null, worktreeId]) + const [instance] = useState(() => ({})) + const [inFront, setInFront] = useState(true) + useFocusEffect( + useCallback(() => { + setInFront(true) + return () => setInFront(false) + }, []) + ) + const shown = mobileDictationShownOnScreen({ + ownedHere: host.owner?.sessionKey === sessionKey, + inFront + }) + // Only the screen showing the dictation re-renders on its every word; the rest see one idle object and whether it is busy. + const dictation = useSyncExternalStore( + host.subscribe, + shown ? host.getDictation : host.getIdleDictation + ) + const busyElsewhere = useSyncExternalStore(host.subscribe, host.getUnderway) && !shown + // The screen's own navigation: bringing it back pops what was pushed over it, never another session's screen. + const navigation = useNavigation() + + // Share dictation error handling for start rejection and live errors so disabled host setup always opens the setup sheet. + const reportDictationFailure = useCallback( + (err: unknown) => { + const message = err instanceof Error ? err.message : String(err) + if (isDictationSetupRequiredError(message)) { + setShowDictationSetup(true) + return + } + triggerError() + showToast(dictationFailureMessage(message)) + }, + [setShowDictationSetup, showToast] + ) + + const clipboard = useClipboardWriter() + // The screen's toast is not read on the page, so where the words went is also spoken. + const tell = (message: string) => { + showToast(message) + host.announce(message) + } + // A transcript its target refused must not vanish: keep it on the clipboard and say so. + const keepUndeliveredDictation = (text: string) => { + triggerError() + void clipboard.writeText(text).then( + () => tell(nativeChatDictationCopy.insertFailedCopied()), + () => tell(nativeChatDictationCopy.insertFailed()) + ) + } + + const destination = useMobileDictationDestination(nativeChatController) + // Chat dictation is inserted locally; a terminal's words are typed into it live, while it is the active one. + const insertHere = (text: string): boolean => { + if (destination.landsInChat(showNativeChatRef.current)) { + if (destination.insertInChat(text)) { + host.announce(dictationAnnounceCopy.inserted()) + } else { + keepUndeliveredDictation(text) + } + return true + } + const routeContext = dictationRouteContextRef.current + const insertHandle = routeContext?.handle ?? activeHandleRef.current + // Another terminal is in front: the host types the words into the one the dictation started in. + if (insertHandle === null || insertHandle !== activeHandleRef.current) { + return false + } + dictationRouteContextRef.current = null + void (async () => { + const sent = + (await flushPendingLiveInputBeforeExternalSend(insertHandle)) && + (await sendLiveTerminalInput(insertHandle, text)) + // Live input lands in a terminal the keyboard may cover, so say where the words went. + if (sent) { + tell(nativeChatDictationCopy.inserted()) + } else { + keepUndeliveredDictation(text) + } + })().catch(() => keepUndeliveredDictation(text)) + return true + } + + const navigationRef = useRef(navigation) + useLayoutEffect(() => { + navigationRef.current = navigation + }) + const screenRef = useRef({ + shown, + insert: insertHere, + reportFailure: reportDictationFailure, + showToast + }) + useLayoutEffect(() => { + screenRef.current = { + shown, + insert: insertHere, + reportFailure: reportDictationFailure, + showToast + } + }) + const { attach, refresh } = host + useEffect( + () => + attach({ + instance, + sessionKey, + shown: () => screenRef.current.shown, + insert: (text) => screenRef.current.insert(text), + reportFailure: (err) => { + dictationRouteContextRef.current = null + screenRef.current.reportFailure(err) + }, + toast: (message) => screenRef.current.showToast(message), + bringToFront: (paneKey) => { + const current = navigationRef.current + // From this screen POP_TO starts at this route (the dispatch's source), so it stops here; merge keeps its params and swaps the pane. + current?.dispatch({ + type: 'POP_TO', + payload: { + name: HOST_SESSION_ROUTE, + params: paneKey ? { paneKey } : undefined, + merge: true + }, + target: current.getState()?.key + }) + } + }), + [attach, dictationRouteContextRef, instance, sessionKey] + ) + // The pill reads shown() on the host's render. + useEffect(() => refresh(), [refresh, shown]) + + const { + phoneDictation, + removeFillerWords, + dictationTerms, + dictationNeedsSetupRef, + closeDictationSetup, + refreshDictationMode + } = useMobileSessionDictationSetup(scope) + // Starting needs the host (unless the phone hears chat itself), but a reconnect must not end a recording: the host keeps the session through it. + const dictationCanStart = showNativeChat + ? connState === 'connected' || phoneDictation.ready + : canSend + + const leaveKeepsPage = useCallback(() => router.canGoBack(), [router]) + const dictationLeaveHold = useMobileDictationLeaveHold(dictation, leaveKeepsPage) + const previews = useMobileDictationPreviews(destination, dictation, activeHandle) + + const startDictation = useCallback(() => { + if (busyElsewhere) { + // One dictation per phone: the pill for the other one is on screen. + triggerError() + return + } + if (!dictationCanStart) { + return + } + if (dictationNeedsSetupRef.current && !phoneDictation.readyRef.current) { + // Explain setup before the OS microphone prompt: mic access cannot help until the host can transcribe. + setShowDictationSetup(true) + return + } + const routeContext = activeHandle ? { handle: activeHandle } : null + dictationRouteContextRef.current = routeContext + const target = destination.captureDestination(showNativeChat, activeHandle) + const paneKey = mobileSessionTabPaneKey(activeSessionTab) + // A refused start comes back through this screen's reportFailure while it is shown, or the host's toast. + void startHost({ + instance, + sessionKey, + client, + target: + target?.field === 'chat' + ? target.scope === null + ? null + : { field: 'chat', scope: target.scope } + : target, + title: activeSessionTab?.title ?? '', + paneKey, + href: workspaceRouteHref( + `/h/${encodeURIComponent(hostId)}/session/${encodeURIComponent(worktreeId)}${paneKey ? `?paneKey=${encodeURIComponent(paneKey)}` : ''}`, + executionHost + ), + dictationMode: scope.dictationMode, + removeFillerWords, + dictationTerms, + worktreeId, + computerName + }) + }, [ + computerName, + activeHandle, + activeSessionTab, + busyElsewhere, + client, + destination.captureDestination, + dictationCanStart, + dictationRouteContextRef, + executionHost, + hostId, + startHost, + instance, + phoneDictation.readyRef, + removeFillerWords, + dictationTerms, + scope.dictationMode, + sessionKey, + setShowDictationSetup, + showNativeChat, + worktreeId + ]) + + const stopDictation = host.stop + const cancelDictation = useCallback(() => { + dictationRouteContextRef.current = null + void dictation.cancel() + }, [dictationRouteContextRef, dictation]) + + const handleDictationToggle = useCallback(() => { + if (dictation.isProcessing) { + // Ignore toggles until finish settles; a tap must not discard what was said. + } else if (dictation.isStarting || dictation.isRecording) { + stopDictation() + } else { + startDictation() + } + }, [dictation, startDictation, stopDictation]) + + const handleDictationPressIn = useCallback(() => { + if (!dictation.isStarting && !dictation.isRecording && !dictation.isProcessing) { + startDictation() + } + }, [dictation, startDictation]) + + const handleDictationPressOut = useCallback(() => { + // Speech is held from the press, so a release while starting finishes once the host answers. + if (dictation.isStarting || dictation.isRecording) { + stopDictation() + } + }, [dictation, stopDictation]) + + return { + dictation, + dictationLeaveHold, + ...previews, + startDictation, + cancelDictation, + handleDictationToggle, + handleDictationPressIn, + handleDictationPressOut, + closeDictationSetup, + refreshDictationMode + } +} diff --git a/mobile/src/session/use-mobile-session-lifecycle.ts b/mobile/src/session/use-mobile-session-lifecycle.ts index e7ea01a8e54..30dd15eb573 100644 --- a/mobile/src/session/use-mobile-session-lifecycle.ts +++ b/mobile/src/session/use-mobile-session-lifecycle.ts @@ -5,7 +5,10 @@ import { useEffect, useRef, useCallback, useState } from 'react' import { AppState, type AppStateStatus, Platform } from 'react-native' import { useFocusEffect } from 'expo-router' import { loadHosts } from '../transport/hosts/host-store' -import { loadTerminalAccessoryLayout } from '../terminal/terminal-accessory-layout' +import { + loadTerminalAccessoryLayout, + saveTerminalSmartRail +} from '../terminal/terminal-accessory-layout' import { recoverActiveTerminalAfterForeground, shouldRecoverTerminalOnAppStateChange @@ -25,6 +28,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM setCustomKeys, setVisibleBuiltInIds, setDirectionPadEnabled, + setSmartRailEnabled, setHostEndpoint, setHostName, connStateRef, @@ -101,6 +105,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM if (layout) { setVisibleBuiltInIds(layout.visibleBuiltInIds) setDirectionPadEnabled(layout.directionPadEnabled !== false) + setSmartRailEnabled(layout.smartRail === true) } setAccessoryLayoutLoaded(true) } @@ -112,6 +117,19 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM } }, [padAvailable, shellStorage]) + const handleSmartRailChange = useCallback( + (enabled: boolean) => { + // A read that started before the toggle must not flip it back. + layoutReadRevisionRef.current += 1 + setSmartRailEnabled(enabled) + saveTerminalSmartRail(enabled, padAvailable).catch((error: unknown) => { + console.warn('[terminal-keys] the store would not take the Smart rail setting', error) + setSmartRailEnabled(!enabled) + }) + }, + [padAvailable] + ) + useFocusEffect( useCallback(() => { const releaseKeys = refreshCustomKeys() @@ -195,6 +213,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM }, [connState, scheduleDelayedAction, subscribeToTerminal, terminalResume, unsubscribeTerminal]) return { accessoryPreferencesReady: customKeysLoaded && accessoryLayoutLoaded, + handleSmartRailChange, pendingForegroundRecoveryRef } } diff --git a/mobile/src/session/use-mobile-session-native-chat-dictation.ts b/mobile/src/session/use-mobile-session-native-chat-dictation.ts index aaafe9b0f95..d339e2a6c63 100644 --- a/mobile/src/session/use-mobile-session-native-chat-dictation.ts +++ b/mobile/src/session/use-mobile-session-native-chat-dictation.ts @@ -1,32 +1,12 @@ -import { useEffect, useCallback, useRef, useState } from 'react' -import { AppState } from 'react-native' -import { useFocusEffect } from 'expo-router' -import { useMobileDictation } from '../hooks/use-mobile-dictation' -import { usePhoneDictationReady } from '../hooks/use-phone-dictation-ready' -import { triggerError } from '../platform/haptics' -import { useClipboardWriter } from '../platform/clipboard' -import { - useMobileDictationDestination, - useMobileDictationPreviews -} from '../dictation/use-mobile-dictation-destination' -import { - dictationFailureMessage, - dictationMicHidden, - dictationNeedsSetup, - fetchDictationSetup, - isDictationSetupRequiredError -} from '../dictation/mobile-dictation-setup' +import { useEffect } from 'react' +import { useMobileSessionDictation } from './use-mobile-session-dictation' import { useMobileNativeChatController } from './native-chat/use-mobile-native-chat-controller' -import { useMobileDictationLeaveHold } from '../dictation/mobile-dictation-leave-hold' -import { useMobileDictationHaptics } from '../dictation/use-mobile-dictation-haptics' -import { useMobileDictationSilenceStop } from '../dictation/use-mobile-dictation-silence-stop' import { useMobileNativeChatReadability } from './native-chat/transcript/use-mobile-native-chat-readability' import { useMobileNativeChatInputLease } from './native-chat/use-mobile-native-chat-input-lease' import { useMobileNativeChatSendError } from './native-chat/use-mobile-native-chat-send-error' import { mobileNativeChatScopeKey } from './native-chat/mobile-native-chat-scope-key' import { mobileNativeChatOverlayInputLockReason } from './native-chat/mobile-native-chat-overlay-lock-reason' import { useMobileSendCompletionGeneration } from './use-mobile-send-completion-generation' -import { nativeChatDictationCopy } from '../dictation/mobile-session-native-chat-dictation-copy' import type { MobileSessionFeedbackCapabilitiesModel } from './use-mobile-session-feedback-capabilities' export function useMobileSessionNativeChatDictation( @@ -44,17 +24,9 @@ export function useMobileSessionNativeChatDictation( activeSessionTabId, diffComments, diffCommentsRef, - setShowDictationSetup, - setDictationMode, - dictationEnabled, - setDictationEnabled, deviceTokenRef, - dictationRouteContextRef, activeHandleRef, activeSessionTab, - flushPendingLiveInputBeforeExternalSend, - canSend, - canCompose, showToast, resetLiveInputFocus } = scope @@ -105,181 +77,10 @@ export function useMobileSessionNativeChatDictation( surfaceKey: JSON.stringify([routeKey, activeHandle, showNativeChat]) }) - // Share dictation error handling for start rejection and live errors so disabled host setup always opens the setup sheet. - const reportDictationFailure = useCallback( - (err: unknown) => { - const message = err instanceof Error ? err.message : String(err) - if (isDictationSetupRequiredError(message)) { - setShowDictationSetup(true) - return - } - triggerError() - showToast(dictationFailureMessage(message)) - }, - [setShowDictationSetup, showToast] - ) - - const clipboard = useClipboardWriter() - // A transcript its target refused must not vanish: keep it on the clipboard and say so. - const keepUndeliveredDictation = (text: string) => { - triggerError() - void clipboard.writeText(text).then( - () => showToast(nativeChatDictationCopy.insertFailedCopied()), - () => showToast(nativeChatDictationCopy.insertFailed()) - ) - } - - const destination = useMobileDictationDestination(nativeChatController) - // The phone's own recognizer needs no computer setup, and chat inserts its words on the phone. - const phoneDictation = usePhoneDictationReady() - // Starting needs the host (unless the phone hears chat itself), but a reconnect must not end a recording: the host keeps the session through it. - const dictationCanStart = showNativeChat - ? connState === 'connected' || phoneDictation.ready - : canSend - // The host's filler switch, kept from its last setup read; on until one says otherwise. - const [removeFillerWords, setRemoveFillerWords] = useState(true) - const dictation = useMobileDictation({ - client, - enabled: (showNativeChat || canCompose) && dictationEnabled, - removeFillerWords, - onTranscript: (text) => { - // Chat dictation is inserted locally; a terminal's words are typed into it live. - if (destination.landsInChat(showNativeChatRef.current)) { - if (!destination.insertInChat(text)) { - keepUndeliveredDictation(text) - } - return - } - const routeContext = dictationRouteContextRef.current - dictationRouteContextRef.current = null - const insertHandle = routeContext?.handle ?? activeHandleRef.current - void (async () => { - const sent = - insertHandle !== null && - (await flushPendingLiveInputBeforeExternalSend(insertHandle)) && - (await sendLiveTerminalInput(insertHandle, text)) - // Live input lands in a terminal the keyboard may cover, so say where the words went. - if (sent) { - showToast(nativeChatDictationCopy.inserted()) - } else { - keepUndeliveredDictation(text) - } - })().catch(() => keepUndeliveredDictation(text)) - }, - onError: (err) => { - dictationRouteContextRef.current = null - reportDictationFailure(err) - }, - onAudioLimitReached: () => showToast(nativeChatDictationCopy.stoppedAtCloudLimit()) - }) - - const dictationLeaveHold = useMobileDictationLeaveHold(dictation) - const previews = useMobileDictationPreviews(destination, dictation, activeHandle) - - // Only a host setup read sets this; while false, the host's start refusal decides (older hosts, first tap before the read). - const dictationNeedsSetupRef = useRef(false) - - const startDictation = useCallback(() => { - if (!dictationCanStart) { - return - } - if (dictationNeedsSetupRef.current && !phoneDictation.readyRef.current) { - // Explain setup before the OS microphone prompt: mic access cannot help until the host can transcribe. - setShowDictationSetup(true) - return - } - const routeContext = activeHandle ? { handle: activeHandle } : null - dictationRouteContextRef.current = routeContext - destination.captureDestination(showNativeChat, activeHandle) - void dictation.start().catch((err) => { - if (dictationRouteContextRef.current === routeContext) { - dictationRouteContextRef.current = null - } - reportDictationFailure(err) - }) - }, [ - activeHandle, - destination.captureDestination, - dictation, - dictationCanStart, - phoneDictation.readyRef, - reportDictationFailure, - setShowDictationSetup, - showNativeChat - ]) - - const stopDictation = useMobileDictationHaptics(dictation) - useMobileDictationSilenceStop(dictation, scope.dictationMode, stopDictation, showToast) - - const cancelDictation = useCallback(() => { - dictationRouteContextRef.current = null - void dictation.cancel() - }, [dictation]) - - const handleDictationToggle = useCallback(() => { - if (dictation.isProcessing) { - // Ignore toggles until finish settles; a tap must not discard what was said. - } else if (dictation.isStarting || dictation.isRecording) { - stopDictation() - } else { - startDictation() - } - }, [dictation, startDictation, stopDictation]) - - const handleDictationPressIn = useCallback(() => { - if (!dictation.isStarting && !dictation.isRecording && !dictation.isProcessing) { - startDictation() - } - }, [dictation, startDictation]) - - const handleDictationPressOut = useCallback(() => { - // Speech is held from the press, so a release while starting finishes once the host answers. - if (dictation.isStarting || dictation.isRecording) { - stopDictation() - } - }, [dictation, stopDictation]) - - const dictationSettingsReadRef = useRef(0) - const refreshDictationMode = useCallback(async () => { - const read = ++dictationSettingsReadRef.current - void phoneDictation.refresh() - if (!client || connState !== 'connected') { - return - } - try { - const setup = await fetchDictationSetup(client) - if (read === dictationSettingsReadRef.current) { - setDictationMode(setup.dictationMode) - setRemoveFillerWords(setup.removeFillerWords !== false) - setDictationEnabled(!dictationMicHidden(setup)) - dictationNeedsSetupRef.current = dictationNeedsSetup(setup) - } - } catch { - // Keep the last settings when an older host cannot report them. - } - }, [client, connState, phoneDictation.refresh, setDictationEnabled, setDictationMode]) - - // The sheet may have changed host setup: let the host judge taps until the fresh read lands. - const closeDictationSetup = useCallback(() => { - setShowDictationSetup(false) - dictationNeedsSetupRef.current = false - void refreshDictationMode() - }, [refreshDictationMode, setShowDictationSetup]) - - useFocusEffect( - useCallback(() => { - void refreshDictationMode() - const subscription = AppState.addEventListener('change', (state) => { - if (state === 'active') { - void refreshDictationMode() - } - }) - return () => { - // Late replies from a retired connection or focus must not rebind the mic. - dictationSettingsReadRef.current += 1 - subscription.remove() - } - }, [refreshDictationMode]) + const sessionDictation = useMobileSessionDictation( + scope, + nativeChatController, + sendLiveTerminalInput ) useEffect(() => { @@ -300,16 +101,7 @@ export function useMobileSessionNativeChatDictation( toggleTabChatView, showNativeChat, showNativeChatRef, - dictation, - dictationLeaveHold, - ...previews, - startDictation, - cancelDictation, - handleDictationToggle, - handleDictationPressIn, - handleDictationPressOut, - closeDictationSetup, - refreshDictationMode + ...sessionDictation } } diff --git a/mobile/src/session/use-mobile-session-screen-state.ts b/mobile/src/session/use-mobile-session-screen-state.ts index eb0f7d28b74..bde653c4045 100644 --- a/mobile/src/session/use-mobile-session-screen-state.ts +++ b/mobile/src/session/use-mobile-session-screen-state.ts @@ -82,6 +82,7 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) const [renameTarget, setRenameTarget] = useState(null) const [customKeys, setCustomKeys] = useState([]) const [directionPadEnabled, setDirectionPadEnabled] = useState(true) + const [smartRailEnabled, setSmartRailEnabled] = useState(false) const [visibleBuiltInIds, setVisibleBuiltInIds] = useState( getDefaultTerminalAccessoryBuiltInIds ) @@ -182,6 +183,8 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel) setCustomKeys, directionPadEnabled, setDirectionPadEnabled, + smartRailEnabled, + setSmartRailEnabled, visibleBuiltInIds, setVisibleBuiltInIds, showCustomKeyModal, diff --git a/mobile/src/session/use-mobile-session-stored-chat-tab.ts b/mobile/src/session/use-mobile-session-stored-chat-tab.ts new file mode 100644 index 00000000000..6a88579b9a2 --- /dev/null +++ b/mobile/src/session/use-mobile-session-stored-chat-tab.ts @@ -0,0 +1,89 @@ +import { useEffect, useState } from 'react' +import { useLocalSearchParams } from 'expo-router' +import { firstParam } from '../navigation/route-param-reader' +import { usePageBridgeClient } from '../transport/connection/client-context.web' +import { activeSessionTabOf } from './tabs/active-session-tab' +import { + peekStoredChatTranscript, + readStoredChatTranscript, + storedTabChatTranscriptIdentity +} from './native-chat/mobile-native-chat-transcript-store' +import type { MobileSessionKeyboardStateModel } from '../terminal/session/use-mobile-session-keyboard-state' + +/** + * A relaunch opens on the chat the stored strip had active when the phone holds a copy of it, until the + * host's first snapshot picks the tab. Other tabs wait for that snapshot, so the body says connecting or offline. + */ +export function useMobileSessionStoredChatTab(scope: MobileSessionKeyboardStateModel): void { + const { + hostId, + worktreeId, + sessionTabs, + activeSessionTabId, + activeSessionTabIdRef, + activeSessionTabTypeRef, + appliedSnapshotMarkerRef, + pendingSelectionRef, + setActiveSessionTabId, + nativeChatTranscriptIsLocalReadable, + nativeChatController: { sessionViewReady, isTabChatView } + } = scope + // A notification or agent-row tap names its own pane (use-notification-pane-navigation), which wins. + const client = usePageBridgeClient() + const urlPaneKey = firstParam(useLocalSearchParams<{ paneKey?: string | string[] }>().paneKey) + const [opensPane] = useState( + () => Boolean(client.getShellSession()?.route?.params?.paneKey) || Boolean(urlPaneKey) + ) + const storedActiveTab = + activeSessionTabId === null && sessionViewReady && !opensPane + ? activeSessionTabOf(sessionTabs) + : null + const storedChat = + storedActiveTab && + (storedActiveTab.type === 'agent-session' || isTabChatView(storedActiveTab.id)) + ? storedTabChatTranscriptIdentity( + hostId, + worktreeId, + storedActiveTab, + nativeChatTranscriptIsLocalReadable + ) + : null + const storedChatTabId = storedChat ? storedActiveTab?.id : undefined + const storedChatTabType = storedChat ? storedActiveTab?.type : undefined + useEffect(() => { + if (!storedChat || !storedChatTabId || !storedChatTabType) { + return + } + let current = true + const open = (held: unknown): void => { + if ( + current && + held && + appliedSnapshotMarkerRef.current.version === -1 && + pendingSelectionRef.current === null + ) { + activeSessionTabTypeRef.current = storedChatTabType + activeSessionTabIdRef.current = storedChatTabId + setActiveSessionTabId(storedChatTabId) + } + } + const held = peekStoredChatTranscript(storedChat) + if (held === undefined) { + void readStoredChatTranscript(storedChat).then(open) + } else { + open(held) + } + return () => { + current = false + } + }, [ + activeSessionTabIdRef, + activeSessionTabTypeRef, + appliedSnapshotMarkerRef, + pendingSelectionRef, + setActiveSessionTabId, + storedChat, + storedChatTabId, + storedChatTabType + ]) +} diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index f15182b48eb..62c4cd9d9cd 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -1,6 +1,6 @@ import { asyncQuestionSourceScope as questionSourceScope } from '../../../src/shared/native-chat/input/native-chat-ask' +import { structuredChatTranscriptIdentity } from './native-chat/mobile-native-chat-transcript-store' import { useMemo, useRef } from 'react' -import { encodeNativeChatTranscriptIdentity } from '../../../src/shared/native-chat/transcript/native-chat-transcript-retention' import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' import { isFinalAgentSessionReadRefusal } from '../../../src/shared/agent-session/failures/structured-agent-session-read-refusal' @@ -75,10 +75,10 @@ export function useMobileStructuredAgentSession( const commandsWait = queueCapable && hostSupport?.queuedCommands === true const queueFollowUps = useQueueFollowUps(client, connected && enabled, sessionId, paired, enabled) const hostStopsConversation = hostSupport?.conversationStop ?? null - const sessionKey = encodeNativeChatTranscriptIdentity([sourceIdentity, agent, sessionId]) + const sessionKey = structuredChatTranscriptIdentity(sourceIdentity, agent, sessionId) const commandPendingRef = useRef(false) const stateArgs = { client, sessionId, sessionKey, enabled, connected, onCommandsChanged } - const { state, stateRef, queuedMessages, queuePause, olderPages, loadEarlier } = + const { state, stateRef, queuedMessages, queuePause, olderPages, loadEarlier, savedAt } = useMobileStructuredAgentState(stateArgs) const mutate = useMobileStructuredAgentMutate({ @@ -268,14 +268,16 @@ export function useMobileStructuredAgentSession( session: { messages, status, - transcriptLoading: status === 'loading', + // A stored copy can't answer "is this ask still open?" until a live frame confirms it. + transcriptLoading: status === 'loading' || savedAt !== null, error: state.error, readFailedFinally: status === 'error' && isFinalAgentSessionReadRefusal(state.readRefusal), clearing, hasMore: state.hasOlder && olderPages !== 'unavailable' && !clearing, loadingEarlier: olderPages === 'loading', olderPages, - loadEarlier + loadEarlier, + savedAt }, isWorking: isWorking || queueSendsNext, canStop, diff --git a/mobile/src/session/use-mobile-structured-agent-state.ts b/mobile/src/session/use-mobile-structured-agent-state.ts index 2a9fc65a5d9..c2bcae0c88e 100644 --- a/mobile/src/session/use-mobile-structured-agent-state.ts +++ b/mobile/src/session/use-mobile-structured-agent-state.ts @@ -18,7 +18,6 @@ import { isFinalAgentSessionReadRefusal } from '../../../src/shared/agent-sessio import { EMPTY_STRUCTURED_AGENT_SESSION, oldestStructuredAgentSessionCursor, - reduceStructuredAgentSession, type StructuredAgentSessionAction, type StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' @@ -41,8 +40,18 @@ import { } from './mobile-structured-agent-session-rpc' import { subscribeTranscriptAfterHold } from './mobile-structured-transcript-subscription' import { useMobileOlderPageLoader, type OlderPagePhase } from './use-mobile-older-page-loader' +import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' +import { + reduceStructuredChatState, + noteChatTranscript, + storedStructuredSessionState, + storedStructuredCopy, + unconfirmedStructuredStateSavedAt +} from './native-chat/mobile-native-chat-transcript-writer' +import { useStoredChatTranscript } from './native-chat/use-stored-chat-transcript' const MAX_RETAINED_SESSION_STATES = 32 + /** The host already batches streamed text, so phones merge only within about a frame; desktop keeps the shared window. */ const STREAMED_TEXT_COALESCE_MS = 16 @@ -90,6 +99,8 @@ export function useMobileStructuredAgentState(args: { queuePause: AgentSessionQueuePause | null olderPages: OlderPagePhase loadEarlier: () => void + /** When the transcript on screen was saved, while it is an earlier launch's copy no read has confirmed. */ + savedAt: number | null } { const { client, connected, enabled, sessionId, sessionKey } = args const commandsChanged = useRef(args.onCommandsChanged) @@ -100,10 +111,23 @@ export function useMobileStructuredAgentState(args: { const [sessionStates, setSessionStates] = useState>( () => new Map() ) - const state = - enabled && sessionKey - ? (sessionStates.get(sessionKey) ?? EMPTY_STRUCTURED_AGENT_SESSION) - : EMPTY_STRUCTURED_AGENT_SESSION + const retained = enabled && sessionKey ? sessionStates.get(sessionKey) : undefined + const stored = + enabled && sessionKey && !retained ? storedStructuredSessionState(sessionKey) : null + const state = retained ?? stored ?? EMPTY_STRUCTURED_AGENT_SESSION + // The phone's copy is written when a turn settles, on hidden and when the chat closes; never per frame. + const liveRead = enabled && sessionKey !== null && state.status === 'ready' + useEffect(() => { + if (liveRead && sessionKey) { + const isLive = () => client?.getState() === 'connected' + noteChatTranscript(sessionKey, state, isLive, (at) => storedStructuredCopy(state, at)) + } + }, [client, liveRead, sessionKey, state]) + const readingStore = useStoredChatTranscript({ + identity: enabled && sessionId ? sessionKey : null, + read: !retained, + turnSettled: liveRead && !mobileStructuredAgentSessionWorking(state) + }) const { phase: olderPages, load: loadOlderPages, supersede } = useMobileOlderPageLoader() const stateRef = useRef(state) useLayoutEffect(() => { @@ -116,8 +140,11 @@ export function useMobileStructuredAgentState(args: { return } setSessionStates((current) => { - const previous = current.get(sessionKey) ?? EMPTY_STRUCTURED_AGENT_SESSION - const next = reduceStructuredAgentSession(previous, action, Date.now()) + const previous = + current.get(sessionKey) ?? + storedStructuredSessionState(sessionKey) ?? + EMPTY_STRUCTURED_AGENT_SESSION + const next = reduceStructuredChatState(previous, action, Date.now()) if (next === previous) { return current } @@ -141,7 +168,7 @@ export function useMobileStructuredAgentState(args: { if (!client || !sessionId || !enabled) { return } - if (!connected) { + if (!connected || readingStore) { return } apply({ type: 'loading' }) @@ -198,7 +225,7 @@ export function useMobileStructuredAgentState(args: { ) .catch(() => undefined) } - }, [apply, client, connected, enabled, sessionId, sessionKey, supersede]) + }, [apply, client, connected, enabled, readingStore, sessionId, sessionKey, supersede]) const loadEarlier = useCallback(() => { const start = oldestStructuredAgentSessionCursor(stateRef.current) @@ -282,6 +309,7 @@ export function useMobileStructuredAgentState(args: { queuedMessages: state.queuedMessages === undefined ? null : (state.queuedMessages ?? []), queuePause: state.queuePause ?? null, olderPages, - loadEarlier + loadEarlier, + savedAt: unconfirmedStructuredStateSavedAt(state) } } diff --git a/mobile/src/session/use-mobile-structured-transcript.ts b/mobile/src/session/use-mobile-structured-transcript.ts index f4fa032ca3c..4d1e1745023 100644 --- a/mobile/src/session/use-mobile-structured-transcript.ts +++ b/mobile/src/session/use-mobile-structured-transcript.ts @@ -5,7 +5,8 @@ import { latestAgentSessionContextClearSequence } from '../../../src/shared/agent-session/agent-session-context-clear' import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer' -import { projectStructuredAgentSessionMessages } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import type { StructuredAgentSessionOptimisticMessage } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import { createStructuredAgentSessionMessageProjection } from '../../../src/shared/agent-session/view/structured-agent-session-message-stream' import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names' import { withNativeChatCutTurnNotices } from '../../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' import { omitNativeChatThreadGoalRows } from '../../../src/shared/native-chat/transcript/native-chat-thread-goal-rows' @@ -22,7 +23,7 @@ const mobileStructuredTranscript = createStructuredQuestionProjection( export function useMobileStructuredTranscript( agent: string | null, state: Pick, - optimistic: Parameters[1], + optimistic: readonly StructuredAgentSessionOptimisticMessage[], sessionKey: string ) { const [clearSent, setClearSent] = useState<{ @@ -61,24 +62,22 @@ export function useMobileStructuredTranscript( }), [agent, floor, state.items] ) + const projectMessages = useMemo( + () => createStructuredAgentSessionMessageProjection(mobileStructuredTranscript.messages), + [] + ) + const questionTranscript = useMemo(() => mobileStructuredTranscript.stream(), []) const messages = useMemo( () => // The goal strip on the composer shows goal state, as on desktop. - omitNativeChatThreadGoalRows( - projectStructuredAgentSessionMessages( - transcriptItems, - optimistic, - state.submissions, - mobileStructuredTranscript.messages - ) - ), - [transcriptItems, optimistic, state.submissions] + omitNativeChatThreadGoalRows(projectMessages(transcriptItems, optimistic, state.submissions)), + [transcriptItems, optimistic, state.submissions, projectMessages] ) return { clearing, onClearSent, transcriptItems, messages, - receipts: mobileStructuredTranscript.transcript(transcriptItems).receipts + receipts: questionTranscript(transcriptItems).receipts } } diff --git a/mobile/src/source-control/MobileSourceControlNextStepBar.tsx b/mobile/src/source-control/MobileSourceControlNextStepBar.tsx index 97f854bd54a..6a524717c3e 100644 --- a/mobile/src/source-control/MobileSourceControlNextStepBar.tsx +++ b/mobile/src/source-control/MobileSourceControlNextStepBar.tsx @@ -30,6 +30,7 @@ import type { MobileNextStepTone } from './mobile-source-control-next-step' import { styles as sourceControlStyles } from './mobile-source-control-styles' +import { useMobileDictationClearance } from '../dictation/mobile-dictation-host-context' const ICONS: Record = { push: ArrowUp, @@ -84,13 +85,20 @@ export function MobileSourceControlNextStepBar({ const [composerFocused, setComposerFocused] = useState(false) // The bar rides the keyboard only for its own commit box; for any other field it steps aside. const lift = composerFocused && view.kind === 'composer' ? keyboardLift : 0 - if ((view.kind === 'hidden' && !notice) || (keyboardLift > 0 && lift === 0)) { + const hidden = (view.kind === 'hidden' && !notice) || (keyboardLift > 0 && lift === 0) + const [barHeight, setBarHeight] = useState(0) + // A dictation pill floats above this bar instead of over its buttons. + useMobileDictationClearance(hidden ? 0 : barHeight + lift) + if (hidden) { return null } const reason = view.kind === 'button' ? view.reason : null return ( onHeightChange(event.nativeEvent.layout.height)} + onLayout={(event) => { + setBarHeight(event.nativeEvent.layout.height) + onHeightChange(event.nativeEvent.layout.height) + }} style={[ styles.bar, { diff --git a/mobile/src/source-control/review/github-pr-rpc.ts b/mobile/src/source-control/review/github-pr-rpc.ts index 595d67de125..0b46be0adc6 100644 --- a/mobile/src/source-control/review/github-pr-rpc.ts +++ b/mobile/src/source-control/review/github-pr-rpc.ts @@ -100,7 +100,9 @@ export async function fetchPRForBranch( branch: string linkedPRNumber?: number | null fallbackPRNumber?: number | null + acceptMergedFallbackPR?: boolean currentHeadOid?: string | null + // An action's read: re-learn host status, and join no host lookup begun before it. refresh?: boolean } ): Promise> { @@ -131,7 +133,9 @@ export async function fetchPRForBranch( branch: args.branch, linkedPRNumber: args.linkedPRNumber ?? null, fallbackPRNumber: args.fallbackPRNumber ?? null, - currentHeadOid: args.currentHeadOid ?? null + ...(args.acceptMergedFallbackPR ? { acceptMergedFallbackPR: true } : {}), + currentHeadOid: args.currentHeadOid ?? null, + ...(args.refresh ? { userRefresh: true } : {}) }), contract.options ) @@ -222,7 +226,13 @@ export async function fetchWorkItemDetails( export function fetchPRChecks( client: RpcOperationSender, worktreeId: string, - args: { prNumber: number; headSha?: string | null; prRepo?: GitHubPrRepoSlug | null } + args: { + prNumber: number + headSha?: string | null + prRepo?: GitHubPrRepoSlug | null + // An action's read: past gh's response cache, joining no host read begun before it. + refresh?: boolean + } ): Promise> { return settleGithubPrRead(githubPrChecksRead, () => githubPrChecksRead.request( @@ -230,7 +240,10 @@ export function fetchPRChecks( githubPrRequestParams( githubPrChecksRead.operation.method, worktreeId, - { prNumber: args.prNumber }, + { + prNumber: args.prNumber, + ...(args.refresh ? { noCache: true, userRefresh: true } : {}) + }, { prRepo: args.prRepo, headSha: args.headSha } ) ) diff --git a/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts b/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts index 1a85fde8f6e..afa29ec9504 100644 --- a/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts +++ b/mobile/src/source-control/review/mobile-diff-review-branch-compare-cache.ts @@ -3,7 +3,10 @@ import { defineHostQuery, fetchHostQuery } from '../../query/host-query' import { hostQueryKey, type HostQueryTarget } from '../../query/host-query-key' import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import { gitStatusQuery } from '../mobile-git-status-query' -import type { BranchCompareLoadResult } from './mobile-diff-review-loaders' +import type { + BranchCompareLoadResult, + MobileBranchCompareCache +} from './mobile-diff-review-loaders' export type ReviewBranchCompareKey = { baseRef: string; head: string } @@ -14,29 +17,54 @@ const reviewBranchCompareQuery = defineHostQuery boolean + // A compare a git change marked as it landed: newer than the shown one, and being read again. + onStale: (loaded: BranchCompareLoadResult) => void + // The compare the build read, once it settles; until then the build reads it again itself after a git change. + onSettled: (key: ReviewBranchCompareKey) => void +} + +// The branch compare cache one Review build reads through. A superseded build's compare is never shown. +export function reviewBuildBranchCompareCache( queryClient: QueryClient, host: { hostId: string; client: RpcClient }, target: HostQueryTarget, - key: ReviewBranchCompareKey, - read: () => Promise -): Promise { - const loaded = await fetchHostQuery( - queryClient, - reviewBranchCompareQuery, - host, - target, - key, - read - ) - // Only a compare that landed for this head is worth reusing; cached status can trail a commit. - if (loaded.result?.summary.headOid !== key.head) { - queryClient.removeQueries({ - queryKey: hostQueryKey(host.hostId, reviewBranchCompareQuery.family, target, key), - exact: true - }) + build: ReviewBuild +): MobileBranchCompareCache { + const { isCurrent, onStale } = build + return async (key, read) => { + if (!isCurrent()) { + return { result: null } + } + try { + const loaded = await fetchHostQuery( + queryClient, + reviewBranchCompareQuery, + host, + target, + key, + { + read, + isCurrent, + onStale + } + ) + // Only a compare that landed for this head is worth reusing; cached status can trail a commit. + // A superseded build's answer may predate the entry a newer build is reading, so only the current one evicts. + if (isCurrent() && loaded.result?.summary.headOid !== key.head) { + queryClient.removeQueries({ + queryKey: hostQueryKey(host.hostId, reviewBranchCompareQuery.family, target, key), + exact: true + }) + } + return loaded + } finally { + if (isCurrent()) { + build.onSettled(key) + } + } } - return loaded } // Marked by a git change and not being read again, so only a new build brings the current compare. diff --git a/mobile/src/source-control/review/mobile-pr-queries.ts b/mobile/src/source-control/review/mobile-pr-queries.ts index d4279971f0e..adec08baecd 100644 --- a/mobile/src/source-control/review/mobile-pr-queries.ts +++ b/mobile/src/source-control/review/mobile-pr-queries.ts @@ -15,7 +15,9 @@ import { resolveGitHubWorkItemTarget } from '../../../../src/shared/github/work-item-target' import type { GitHubWorkItemDetails } from '../../../../src/shared/github/work-item-types' -import { defineHostQuery } from '../../query/host-query' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../src/shared/execution-host' +import { worktreeIdsEqual } from '../../../../src/shared/worktree/id' +import { defineHostQuery, type HostQuerySignal, type HostSignalEvent } from '../../query/host-query' import { hostQueryKey, type HostQueryParams, @@ -126,11 +128,27 @@ function keepCheckObservation( return pr ? { ...next, pr } : next } -// No desktop signal for PR changes reaches the phone, so it revalidates on focus and polls while shown. +// The desktop's own workspaces only: a relayed server's PR refreshes never reach this stream. +function namesThisCheckout(event: HostSignalEvent, target: HostQueryTarget): boolean { + return ( + event.type === 'pullRequestChanged' && + target.exec === LOCAL_EXECUTION_HOST_ID && + worktreeIdsEqual(event.worktreeId, target.worktree ?? '') + ) +} + +// Sent when a desktop PR refresh sees the PR change; changes no desktop refresh sees still wait for focus or the poll. +const pullRequestChangedSignal: HostQuerySignal = { + events: ['pullRequestChanged'], + floorMs: 1_000, + matches: namesThisCheckout +} + export const prBranchReviewQuery = defineHostQuery({ family: 'pr.forBranch', staleTime: 30_000, refetchOnWindowFocus: true, + signal: pullRequestChangedSignal, fetch: async (client, target, input: PrBranchInput, previous: PrBranchReview | undefined, read) => keepCheckObservation( await loadPrBranchReview( @@ -146,7 +164,8 @@ export const prBranchReviewQuery = defineHostQuery({ branch: input.branch, headSha: input.head, // Only an action's read re-learns host status; revalidations reuse what this connection knows. - refresh: read.live + refresh: read.live, + previous } ), previous @@ -157,12 +176,21 @@ export const prChecksQuery = defineHostQuery({ family: 'pr.checks', staleTime: 15_000, refetchOnWindowFocus: true, - fetch: async (client, target, input: PrChecksInput): Promise => { + // The event also fires when the checks rollup moves, which the summary alone can't list. + signal: pullRequestChangedSignal, + fetch: async ( + client, + target, + input: PrChecksInput, + _previous, + read + ): Promise => { const outcome = await fetchPRChecks(client, target.worktree ?? '', { prNumber: input.number, headSha: input.head, // Fork checks must use the PR's own repo identity. - prRepo: prRepoSlug(input) + prRepo: prRepoSlug(input), + refresh: read.live }) if (!outcome.ok) { throw new Error(outcome.error) diff --git a/mobile/src/source-control/review/mobile-pr-sidebar-state.ts b/mobile/src/source-control/review/mobile-pr-sidebar-state.ts index 34416229028..5038ee8801d 100644 --- a/mobile/src/source-control/review/mobile-pr-sidebar-state.ts +++ b/mobile/src/source-control/review/mobile-pr-sidebar-state.ts @@ -9,6 +9,11 @@ import type { GitHubWorkItemDetails } from '../../../../src/shared/github/work-i import type { HostedReviewInfo } from '../../../../src/shared/source-control/hosted-review/hosted-review-contracts' import type { GitHubPrReadOutcome } from './github-pr-rpc' import { isGitHubPRSuppressed } from '../../../../src/shared/worktree/github-pr-suppression' +import { + prBranchFallbackNeedsHint, + resolvePRBranchFallback, + shouldAcceptMergedFallbackPR +} from '../../../../src/shared/github/pr-branch-fallback-rule' import { shouldApplyBranchMismatchedLinkedPRClear, shouldApplyDivergedLinkedPRClear, @@ -72,6 +77,7 @@ export type PrSidebarLoadDeps = { branch: string linkedPRNumber?: number | null fallbackPRNumber?: number | null + acceptMergedFallbackPR?: boolean currentHeadOid?: string | null refresh?: boolean } @@ -109,12 +115,25 @@ function resolveStaleLink( return null } +/** The hosted-review hint a branch lookup fell back to, kept so a branch with no PR isn't asked twice per read. */ +export type PrBranchHint = { number: number | null; readAt: number } + /** The branch's GitHub review: its PR and the workspace's push target, or none. */ export type PrBranchReview = - | { kind: 'found'; pr: PRInfo; pushTarget: GitPushTarget | null } - | { kind: 'none' } + // linkedPRNumber: the link the PR was read with, so a later link change drops it as a fallback. + | { kind: 'found'; pr: PRInfo; pushTarget: GitPushTarget | null; linkedPRNumber: number | null } + | { kind: 'none'; hint?: PrBranchHint } + +// The host re-reads a selected branch's hosted review once a minute, so a younger hint is still its answer. +const BRANCH_HINT_STALE_MS = 60_000 + +function keptHint(previous: PrBranchReview | undefined): PrBranchHint | null { + const hint = previous?.kind === 'none' ? previous.hint : undefined + return hint && Date.now() - hint.readAt < BRANCH_HINT_STALE_MS ? hint : null +} // Parallel link resolution also retains closed/merged reviews. A failed read throws its message, classified when shown. +// Like desktop, the last PR result is the lookup's fallback, so the hint is read only for a branch with none. export async function loadPrBranchReview( deps: PrSidebarLoadDeps, args: { @@ -122,37 +141,68 @@ export async function loadPrBranchReview( branch: string headSha?: string | null refresh?: boolean + previous?: PrBranchReview } ): Promise { - const [hintOutcome, link] = await Promise.all([ - deps.fetchForBranch(args.worktreeId, { branch: args.branch }), - deps.fetchWorktreeGitHubPRLink(args.worktreeId) + const previousRead = args.previous?.kind === 'found' ? args.previous : null + // Desktop drops its last PR when the workspace's link changes; a result read under another link is no fallback. + const fallbackPR = (linkedPRNumber: number | null) => + previousRead && previousRead.linkedPRNumber === linkedPRNumber ? previousRead.pr : null + const kept = keptHint(args.previous) + // A failed hint read is no hint, and is not kept. + let hintRead: Promise | undefined + const readHint = () => + (hintRead ??= kept + ? Promise.resolve(kept) + : deps.fetchForBranch(args.worktreeId, { branch: args.branch }).then((outcome) => + outcome.ok + ? { + number: outcome.result?.provider === 'github' ? outcome.result.number : null, + readAt: Date.now() + } + : null + )) + // The link isn't known yet: with no PR read before, start the hint alongside it (a linked PR wastes it); + // a link that changed since the last read waits for the hint instead. + const [link] = await Promise.all([ + deps.fetchWorktreeGitHubPRLink(args.worktreeId), + prBranchFallbackNeedsHint({ linkedPRNumber: null, cachedPR: previousRead }) ? readHint() : null ]) - const branchHint = - hintOutcome.ok && hintOutcome.result?.provider === 'github' ? hintOutcome.result.number : null const requestHeadOid = args.headSha ?? null - // Same as desktop: the explicit link wins; the branch's review is only a fallback. - const fetchPR = (linkedPRNumber: number | null) => - deps.fetchPRForBranch(args.worktreeId, { + // Same as desktop: the explicit link wins; the last PR result, else the branch's review, is only a fallback. + const fetchPR = async (linkedPRNumber: number | null, cachedPR: PRInfo | null) => { + const fallback = resolvePRBranchFallback({ + linkedPRNumber, + cachedPR, + hintPRNumber: prBranchFallbackNeedsHint({ linkedPRNumber, cachedPR }) + ? ((await readHint())?.number ?? null) + : null, + currentHeadOid: requestHeadOid + }) + return deps.fetchPRForBranch(args.worktreeId, { branch: args.branch, linkedPRNumber, - fallbackPRNumber: linkedPRNumber === null ? branchHint : null, + fallbackPRNumber: fallback.fallbackPRNumber, + ...(shouldAcceptMergedFallbackPR({ linkedPRNumber, ...fallback }) + ? { acceptMergedFallbackPR: true } + : {}), currentHeadOid: requestHeadOid, ...(args.refresh ? { refresh: true } : {}) }) + } let linkedPR = link.linkedPR - let prOutcome = await fetchPR(linkedPR) + let prOutcome = await fetchPR(linkedPR, fallbackPR(linkedPR)) const staleLink = prOutcome.ok ? resolveStaleLink(prOutcome.result, link, args.branch, requestHeadOid) : null - // Desktop drops a link the branch has moved past, then resolves by branch. + // Desktop drops a link the branch has moved past, then resolves by branch with only the hint. if (staleLink) { linkedPR = null // The refetch sends no link, so it need not wait for the clear to land. ;[, prOutcome] = await Promise.all([ deps.clearWorktreeReviewLink(args.worktreeId, staleLink), - fetchPR(null) + fetchPR(null, null) ]) } if (!prOutcome.ok) { @@ -165,9 +215,15 @@ export async function loadPrBranchReview( prOutcome.result.number ) ) { - return { kind: 'none' } + const hint = await hintRead + return hint ? { kind: 'none', hint } : { kind: 'none' } + } + return { + kind: 'found', + pr: prOutcome.result, + pushTarget: link.pushTarget, + linkedPRNumber: linkedPR } - return { kind: 'found', pr: prOutcome.result, pushTarget: link.pushTarget } } // What the screen shows for a PR read that failed with nothing accepted to keep. diff --git a/mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts b/mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts index 8770531221a..a9d92e9dfd2 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts @@ -24,7 +24,7 @@ import { reviewDescriptorFromItem } from './mobile-diff-review-screen-model' import type { ReviewSheetIntents } from './mobile-diff-review-sheets' -import { useMobileDiffReviewNoteDraft } from './use-mobile-diff-review-note-draft' +import type { MobileDiffReviewNoteDraft } from './use-mobile-diff-review-note-draft' type CommentActionsInput = { client: RpcClient | null @@ -43,9 +43,12 @@ type CommentActionsInput = { navigationRef: { readonly current: number } /** GitHub's viewed mark for a PR file, or null when the file's viewed state lives on the phone. */ remoteViewed: (item: MobileDiffReviewQueueItem, viewed: boolean) => Promise | null - setComposerBody: Dispatch> + noteDraft: Pick< + MobileDiffReviewNoteDraft, + 'openNewNoteSheet' | 'openEditComposer' | 'clearSavedNote' + > setActionError: Dispatch> - sheets: Pick + sheets: Pick } export function useMobileDiffReviewCommentActions(input: CommentActionsInput) { @@ -64,11 +67,12 @@ export function useMobileDiffReviewCommentActions(input: CommentActionsInput) { selectIndex, navigationRef, remoteViewed, - setComposerBody, + noteDraft, setActionError, sheets } = input - const { openSheet, openSheetWhenIdle, closeSheet } = sheets + const { openSheetWhenIdle, closeSheet } = sheets + const { openNewNoteSheet, openEditComposer, clearSavedNote } = noteDraft const persistMetadata = useCallback( async ( @@ -147,12 +151,6 @@ export function useMobileDiffReviewCommentActions(input: CommentActionsInput) { [persistMetadata, screenState, setActionError, setScreenState, updateReadyState, worktreeId] ) - const { openNewNoteSheet, openEditComposer, clearSavedNote } = useMobileDiffReviewNoteDraft({ - composerBody, - setComposerBody, - openSheet - }) - const openComposer = useCallback( (lineNumber: number) => openNewNoteSheet({ kind: 'composer', composer: { mode: 'create', lineNumber } }), diff --git a/mobile/src/source-control/review/use-mobile-diff-review-controller.test.ts b/mobile/src/source-control/review/use-mobile-diff-review-controller.test.ts index 4b951d0b466..7bcd5c31744 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-controller.test.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-controller.test.ts @@ -6,6 +6,9 @@ import { createFakeRpcClient } from '../../mobile-web-shell/bridge-host-test-fak import type { ReviewScreenState } from './mobile-diff-review-screen-model' import { useMobileDiffReviewController } from './use-mobile-diff-review-controller' import { documentQueryClient } from '../../test-support/rpc-recording/hook-mount' +import { publishPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store' +import { resetDurableDraftFieldsForTests } from '../../drafts/durable-draft-fields' +import { publishInMemoryDeviceStore } from '../../drafts/in-memory-device-store.test-support' const loadSnapshot = vi.hoisted(() => vi.fn()) // Each build's notes-and-files read; status comes from the shared git.status query, held pending here. @@ -92,6 +95,8 @@ describe('useMobileDiffReviewController', () => { afterEach(() => { act(() => renderer?.unmount()) renderer = null + resetDurableDraftFieldsForTests() + publishPageDeviceStore(null) }) describe('Stage · next file', () => { @@ -204,5 +209,44 @@ describe('useMobileDiffReviewController', () => { act(() => controller?.openComposer(3)) expect(controller?.composerBody).toBe('') }) + + it('brings an unsaved new note back after the app is killed, not the text of an edit', async () => { + // The shell's draft table outlives the page; nothing else does. + const table = new Map() + publishInMemoryDeviceStore(table) + const openReview = async () => { + loadSnapshot.mockResolvedValueOnce(unstaged(['c.ts'])) + await act(async () => { + renderer = create(queries.wrap(createElement(StageProbe))) + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + } + await openReview() + act(() => controller?.openComposer(3)) + act(() => controller?.setComposerBody('rename this')) + act(() => controller?.closeComposer()) + act(() => + controller?.openEditComposer({ + id: 'saved', + worktreeId: 'wt-1', + filePath: 'c.ts', + lineNumber: 1, + side: 'modified', + body: 'older note', + createdAt: 1 + }) + ) + act(() => controller?.setComposerBody('older note, edited')) + // The draft row saves once typing settles. + await act(async () => { + await vi.waitFor(() => expect(table.size).toBe(1)) + }) + act(() => renderer?.unmount()) + resetDurableDraftFieldsForTests() + + await openReview() + act(() => controller?.openComposer(3)) + expect(controller?.composerBody).toBe('rename this') + }) }) }) diff --git a/mobile/src/source-control/review/use-mobile-diff-review-controller.ts b/mobile/src/source-control/review/use-mobile-diff-review-controller.ts index 6b7e9501774..8ee31adcf5d 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-controller.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-controller.ts @@ -27,6 +27,9 @@ import { useMobilePrSidebarController } from './use-mobile-pr-sidebar-controller import { useMobileDiffReviewGitHub } from './use-mobile-diff-review-github' import { mobileDiffReviewThreadsForItem } from './mobile-diff-review-github' import { mobileDiffReviewNotesForItem } from './mobile-diff-comments' +import { useMobileDiffReviewNoteDraft } from './use-mobile-diff-review-note-draft' +import { workspaceDraftRowKey } from '../../drafts/durable-draft-rows' +import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host' const NO_COMMENTS: readonly DiffComment[] = [] @@ -74,7 +77,12 @@ export function useMobileDiffReviewController(input: ControllerInput) { const [sheets, dispatchSheets] = useReducer(reduceReviewSheets, NO_REVIEW_SHEETS) const sheetIntents = useMemo(() => reviewSheetIntents(dispatchSheets), []) const composer = reviewComposer(sheets) - const [composerBody, setComposerBody] = useState('') + const executionHost = useWorkspaceExecutionHost() + const noteDraft = useMobileDiffReviewNoteDraft({ + draftKey: workspaceDraftRowKey('reviewNote', { hostId, executionHost, worktreeId }, ''), + openSheet: sheetIntents.openSheet + }) + const { composerBody, setComposerBody } = noteDraft const [actionError, setActionError] = useState(null) const [busyAction, setBusyAction] = useState(null) const worktreeLabel = getWorktreeLabel(name, worktreeId) @@ -182,7 +190,7 @@ export function useMobileDiffReviewController(input: ControllerInput) { selectKey, moveSelection, remoteViewed: setRemoteViewed, - setComposerBody, + noteDraft, setActionError, setBusyAction, sheets: sheetIntents, diff --git a/mobile/src/source-control/review/use-mobile-diff-review-interactions.ts b/mobile/src/source-control/review/use-mobile-diff-review-interactions.ts index 6176651f97d..10bbfc7a0d6 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-interactions.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-interactions.ts @@ -6,6 +6,7 @@ import type { MobileDiffReviewQueueItem } from './mobile-diff-review-queue' import type { ComposerState, ReviewScreenState } from './mobile-diff-review-screen-model' import type { ReviewSheet, ReviewSheetIntents } from './mobile-diff-review-sheets' import type { MobileReviewTerminalTab } from './review-terminal-reply-schema' +import type { MobileDiffReviewNoteDraft } from './use-mobile-diff-review-note-draft' import { sourceFileDiffOpenRun } from '../mobile-source-file-open-operations' import { refusedRpcMessageOrFallback } from '../../transport/rpc/rpc-refusal-message' import { useMobileDiffReviewCommentActions } from './use-mobile-diff-review-comment-actions' @@ -33,7 +34,7 @@ type InteractionInput = { selectKey: (key: string) => void moveSelection: (direction: 'next' | 'previous') => void remoteViewed: (item: MobileDiffReviewQueueItem, viewed: boolean) => Promise | null - setComposerBody: Dispatch> + noteDraft: MobileDiffReviewNoteDraft setActionError: Dispatch> setBusyAction: Dispatch> sheets: ReviewSheetIntents @@ -61,7 +62,7 @@ export function useMobileDiffReviewInteractions(input: InteractionInput) { selectKey, moveSelection, remoteViewed, - setComposerBody, + noteDraft, setActionError, setBusyAction, sheets, @@ -99,7 +100,7 @@ export function useMobileDiffReviewInteractions(input: InteractionInput) { selectIndex, navigationRef, remoteViewed, - setComposerBody, + noteDraft, setActionError, sheets }) diff --git a/mobile/src/source-control/review/use-mobile-diff-review-note-draft.ts b/mobile/src/source-control/review/use-mobile-diff-review-note-draft.ts index 2a04dc98a06..cb50996f0ca 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-note-draft.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-note-draft.ts @@ -1,10 +1,11 @@ -import { useCallback, useRef, type Dispatch, type SetStateAction } from 'react' +import { useCallback, useState, type SetStateAction } from 'react' import type { DiffComment } from '../../../../src/shared/diff-comment-types' +import { useDurableDraftField } from '../../drafts/durable-draft-fields' import type { ReviewSheet, ReviewSheetIntents } from './mobile-diff-review-sheets' type NoteDraftInput = { - composerBody: string - setComposerBody: Dispatch> + // Where the new note waits through leaving the review and the app being killed. + draftKey: string openSheet: ReviewSheetIntents['openSheet'] } @@ -13,45 +14,46 @@ type NewNoteSheet = | { kind: 'composer'; composer: { mode: 'create'; lineNumber: number } } /** The review's unsaved new note: kept across Cancel, reopen and picking other lines, cleared only once saved. */ -export function useMobileDiffReviewNoteDraft({ - composerBody, - setComposerBody, - openSheet -}: NoteDraftInput) { - // Set while an edit borrows the text field; the new note comes back when a new-note sheet opens. - const setAsideNoteRef = useRef(null) +export function useMobileDiffReviewNoteDraft({ draftKey, openSheet }: NoteDraftInput) { + const [newNote, setNewNote] = useDurableDraftField(draftKey, 'note') + // An edit borrows the text field with its own text, until a new-note sheet opens; the new note is untouched + // underneath. Kept past the edit sheet closing, so its text stays while it slides away. + const [editBody, setEditBody] = useState(null) + const setEditText = useCallback( + (next: SetStateAction) => + setEditBody((current) => (typeof next === 'function' ? next(current ?? '') : next)), + [] + ) + const openNewNoteSheet = useCallback( (sheet: NewNoteSheet) => { - if (setAsideNoteRef.current !== null) { - setComposerBody(setAsideNoteRef.current) - setAsideNoteRef.current = null - } + setEditBody(null) openSheet(sheet) }, - [openSheet, setComposerBody] + [openSheet] ) // The user may have moved on while a note was saving; drop only the text that was saved. const clearSavedNote = useCallback( - (saved: string) => { - const isSaved = (text: string) => text.trim() === saved.trim() - if (setAsideNoteRef.current === null) { - setComposerBody((current) => (isSaved(current) ? '' : current)) - } else if (isSaved(setAsideNoteRef.current)) { - setAsideNoteRef.current = '' - } - }, - [setComposerBody] + (saved: string) => setNewNote((current) => (current.trim() === saved.trim() ? '' : current)), + [setNewNote] ) const openEditComposer = useCallback( (comment: DiffComment) => { - setAsideNoteRef.current ??= composerBody openSheet({ kind: 'composer', composer: { mode: 'edit', comment } }) - setComposerBody(comment.body) + setEditBody(comment.body) }, - [composerBody, openSheet, setComposerBody] + [openSheet] ) - return { openNewNoteSheet, openEditComposer, clearSavedNote } + return { + composerBody: editBody ?? newNote, + setComposerBody: editBody === null ? setNewNote : setEditText, + openNewNoteSheet, + openEditComposer, + clearSavedNote + } } + +export type MobileDiffReviewNoteDraft = ReturnType diff --git a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts index 10fe03182a0..8122c702baf 100644 --- a/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts +++ b/mobile/src/source-control/review/use-mobile-diff-review-snapshot.ts @@ -9,10 +9,10 @@ import { useMobileSourceControlSettings } from '../mobile-source-control-setting import type { RpcClient } from '../../transport/rpc/rpc-client-contract' import type { ConnectionState } from '../../transport/connection/connection-state' import { loadMobileDiffReviewCommitSnapshot } from './mobile-diff-review-commit-loader' -import type { MobileBranchCompareCache } from './mobile-diff-review-loaders' +import type { BranchCompareLoadResult } from './mobile-diff-review-loaders' import { - readCachedReviewBranchCompare, reviewBranchCompareNeedsRead, + reviewBuildBranchCompareCache, type ReviewBranchCompareKey } from './mobile-diff-review-branch-compare-cache' import type { MobileDiffReviewQueueFilter } from './mobile-diff-review-queue' @@ -73,7 +73,7 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { ) // The status read the shown snapshot was built from; AWAITING while a build waits for its first read. const builtFromRef = useRef(undefined) - // The compare the current build read, so a git change that marked it stale rebuilds even when status held. + // The compare the current build has read, so a git change that marked it stale rebuilds even when status held. const builtCompareRef = useRef(null) // Reloads after a write wait for the rebuild they cause, so the screen's buttons match the new files. const buildWaitersRef = useRef<(() => void)[]>([]) @@ -170,14 +170,45 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { throw err } ) - const cacheBranchCompare: MobileBranchCompareCache = async (key, read) => { - // A superseded build's compare is never shown. - if (!isCurrent()) { - return { result: null } + // Once this build's files show, a later compare goes onto the screen, keeping note edits made since. + // Without a compare (null) the shown one holds until the new one lands. + let shownBuild = false + const showBuilt = (state: ReviewScreenState, loaded: BranchCompareLoadResult | null) => { + const onShown = shownBuild + shownBuild = true + if (!sameStatus && !onShown) { + setStatusRevision(queryClient.getQueryState(statusKey)?.dataUpdatedAt ?? 0) } - builtCompareRef.current = key - return readCachedReviewBranchCompare(queryClient, { hostId, client }, target, key, read) + setScreenState((prev) => { + const held = + prev.kind === 'ready' ? { result: prev.branchCompare, error: prev.branchError } : null + const compare = loaded ?? held + const base = onShown && prev.kind === 'ready' ? prev : state + return compare ? withMobileDiffReviewBranch(base, compare, worktreeId) : base + }) + if (loaded) { + setActionError(loaded.error ?? null) + } + settleWaiters() } + // A compare a git change marked as it landed is newer than the shown one, so it shows while read again. + const showStaleCompare = (loaded: BranchCompareLoadResult) => + void snapshot.then( + (state) => isCurrent() && showBuilt(state, loaded), + () => {} + ) + const cacheBranchCompare = reviewBuildBranchCompareCache( + queryClient, + { hostId, client }, + target, + { + isCurrent, + onStale: showStaleCompare, + onSettled: (key) => { + builtCompareRef.current = key + } + } + ) const { snapshot, branch } = startMobileDiffReviewSnapshot(client, worktreeId, { status: statusInput, compareAgainstUpstream, @@ -191,30 +222,13 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { if (!isCurrent()) { return } - if (!sameStatus) { - setStatusRevision(queryClient.getQueryState(statusKey)?.dataUpdatedAt ?? 0) - } - if (loaded) { - setScreenState(withMobileDiffReviewBranch(state, loaded, worktreeId)) - setActionError(loaded.error ?? null) - return - } - // Hold the shown compare until the new one lands. - setScreenState((prev) => - prev.kind === 'ready' - ? withMobileDiffReviewBranch( - state, - { result: prev.branchCompare, error: prev.branchError }, - worktreeId - ) - : state - ) // A write waits for the files it changed, not for the branch compare. - settleWaiters() - const settled = await branch - if (isCurrent()) { - setScreenState((prev) => withMobileDiffReviewBranch(prev, settled, worktreeId)) - setActionError(settled.error ?? null) + showBuilt(state, loaded) + if (!loaded) { + const settled = await branch + if (isCurrent()) { + showBuilt(state, settled) + } } } catch (err) { fail(err) @@ -233,9 +247,18 @@ export function useMobileDiffReviewSnapshot(input: SnapshotInput) { ) }, [client, commitOid, connState, queryClient, reloadNonce, statusKey, worktreeReview]) + // Closing Review ends its build, so a compare it is still reading is not read again for later git changes. + useEffect( + () => () => { + loadGenerationRef.current += 1 + settleWaiters() + }, + [] + ) + // A status read that changed what Changes shows rebuilds the snapshot; one in flight already brings its own. // A read that lands unchanged rebuilds too once a git change marked the shown compare stale; a compare - // still out is read again by its own build when it lands marked. + // its build has not settled yet is read again by that build. const rebuildOnStatusRead = useEffectEvent((read: GitStatusRead) => { const built = builtFromRef.current if (built === AWAITING) { diff --git a/mobile/src/source-control/review/use-mobile-pr-comment-actions.ts b/mobile/src/source-control/review/use-mobile-pr-comment-actions.ts index 6df40877f65..d1f83cd1e96 100644 --- a/mobile/src/source-control/review/use-mobile-pr-comment-actions.ts +++ b/mobile/src/source-control/review/use-mobile-pr-comment-actions.ts @@ -15,6 +15,8 @@ import { } from './pr-comment-actions' import { prCommentTarget, prCommentWrite, type PrCommentWrite } from './pr-comment-writes' import type { PrQueryScope } from './mobile-pr-queries' +import { workspaceDraftRowKey } from '../../drafts/durable-draft-rows' +import { useWorkspaceExecutionHost } from '../../navigation/workspace-execution-host' export type PrCommentActionsInput = { hostId: string @@ -52,6 +54,22 @@ export function useMobilePrCommentActions(input: PrCommentActionsInput) { const { mutate, blockedOffline } = useHostMutation(prCommentWrite, { hostId, client }) const ready = client !== null && connState === 'connected' && !blockedOffline const target = useMemo(() => prCommentTarget(queries), [queries]) + const executionHost = useWorkspaceExecutionHost() + // A fork's #N and upstream #N keep separate drafts; null is a new root comment. + const draftKey = useCallback( + (replyTo: number | null): string | null => { + if (prNumber <= 0) { + return null + } + const repo = prRepo ? `${prRepo.host ?? ''}/${prRepo.owner}/${prRepo.repo}` : '' + return workspaceDraftRowKey( + 'prComment', + { hostId, executionHost, worktreeId }, + `${repo}#${prNumber}#${replyTo ?? 'new'}` + ) + }, + [executionHost, hostId, prNumber, prRepo, worktreeId] + ) const setBusy = useCallback((key: string, busy: boolean) => { setBusyKeys((prev) => { @@ -160,6 +178,7 @@ export function useMobilePrCommentActions(input: PrCommentActionsInput) { [busyKeys] ), isRootBusy: busyKeys.has(ROOT_KEY), + draftKey, reply, toggleResolve, addRootComment, diff --git a/mobile/src/source-control/use-mobile-source-control-commit-runners.ts b/mobile/src/source-control/use-mobile-source-control-commit-runners.ts index 5a9b6fbcc05..48bcfadf5bd 100644 --- a/mobile/src/source-control/use-mobile-source-control-commit-runners.ts +++ b/mobile/src/source-control/use-mobile-source-control-commit-runners.ts @@ -1,4 +1,4 @@ -import { useCallback, type MutableRefObject } from 'react' +import { useCallback, type Dispatch, type MutableRefObject, type SetStateAction } from 'react' import { translate } from '../i18n/mobile-i18n' import { triggerError, triggerSuccess } from '../platform/haptics' import type { LoadStatusOptions } from './mobile-source-control-screen-state' @@ -12,7 +12,8 @@ type SendGitRequest = (method: string, params?: Record) => P type RunGitWorkflow = ( actionId: string, runner: () => Promise, - options?: { clearCommitMessage?: boolean } + // The committed message; the field is cleared only while it still holds that text. + options?: { clearCommitMessage?: string } ) => Promise type Params = { @@ -28,7 +29,7 @@ type Params = { busyActionRef: MutableRefObject setBusyAction: (next: string | null) => void setActionError: (next: string | null) => void - setCommitMessage: (next: string) => void + setCommitMessage: Dispatch> recordCommitFailure: RecordMobileCommitFailure } @@ -80,7 +81,7 @@ export function useMobileSourceControlCommitRunners(params: Params) { throw err } }, - { clearCommitMessage: true } + { clearCommitMessage: message } ) }, [commitMessage, recordCommitFailure, runGitWorkflow, sendCommitRequest, stagedEntries]) @@ -101,11 +102,12 @@ export function useMobileSourceControlCommitRunners(params: Params) { try { await sendCommitRequest(message) didCommit = true + // The commit landed: a kill during the push must not bring its message back, and text typed since stays. + setCommitMessage((current) => (current.trim() === message ? '' : current)) await afterCommit() if (!mountedRef.current) { return false } - setCommitMessage('') triggerSuccess() await loadStatus({ force: true }) return true @@ -122,7 +124,6 @@ export function useMobileSourceControlCommitRunners(params: Params) { recordCommitFailure({ error: errorMessage, commitMessage: message, stagedEntries }) } if (didCommit) { - setCommitMessage('') await loadStatus({ clearActionErrorOnSuccess: false, force: true diff --git a/mobile/src/source-control/use-mobile-source-control-runners.ts b/mobile/src/source-control/use-mobile-source-control-runners.ts index 4fc63f59aba..956899af2a6 100644 --- a/mobile/src/source-control/use-mobile-source-control-runners.ts +++ b/mobile/src/source-control/use-mobile-source-control-runners.ts @@ -83,7 +83,7 @@ export function useMobileSourceControlRunners(params: Params) { async ( actionId: string, runner: () => Promise, - options?: { clearCommitMessage?: boolean; refreshOnError?: boolean } + options?: { clearCommitMessage?: string; refreshOnError?: boolean } ) => { if (busyActionRef.current) { return false @@ -94,12 +94,14 @@ export function useMobileSourceControlRunners(params: Params) { recordCommitFailure(null) try { await runner() + // The commit landed, so its message must not come back, even when the screen has left. + const committed = options?.clearCommitMessage + if (committed !== undefined) { + setCommitMessage((current) => (current.trim() === committed ? '' : current)) + } if (!mountedRef.current) { return false } - if (options?.clearCommitMessage) { - setCommitMessage('') - } triggerSuccess() await loadStatus({ force: true }) return true @@ -148,7 +150,7 @@ export function useMobileSourceControlRunners(params: Params) { ) const runGitSequence = useCallback( - async (actionId: string, steps: GitStep[], options?: { clearCommitMessage?: boolean }) => { + async (actionId: string, steps: GitStep[], options?: { clearCommitMessage?: string }) => { return await runGitWorkflow( actionId, async () => { diff --git a/mobile/src/source-control/use-mobile-source-control-state.ts b/mobile/src/source-control/use-mobile-source-control-state.ts index 168fa193856..7b1a96b3edd 100644 --- a/mobile/src/source-control/use-mobile-source-control-state.ts +++ b/mobile/src/source-control/use-mobile-source-control-state.ts @@ -4,6 +4,9 @@ import { useSafeAreaInsets } from 'react-native-safe-area-context' import { useForceReconnect } from '../transport/connection/host-client-hooks' import { useWorkspaceClient } from '../worktree/use-workspace-client' import { getWorktreeLabel } from '../worktree/worktree-label' +import { workspaceDraftRowKey } from '../drafts/durable-draft-rows' +import { useDurableDraftField } from '../drafts/durable-draft-fields' +import { useWorkspaceExecutionHost } from '../navigation/workspace-execution-host' import { useMobileGitRequests } from './use-mobile-git-requests' import { useMobileSourceControlLoaders } from './use-mobile-source-control-loaders' import { useMobileSourceControlOpeners } from './use-mobile-source-control-openers' @@ -48,7 +51,12 @@ export function useMobileSourceControlState(params: MobileSourceControlStatePara const { client, state: connState } = useWorkspaceClient(hostId) const forceReconnect = useForceReconnect() const [busyAction, setBusyAction] = useState(null) - const [commitMessage, setCommitMessage] = useState('') + const executionHost = useWorkspaceExecutionHost() + // The message waits through leaving the screen and the app being killed; a commit clears it. + const [commitMessage, setCommitMessage] = useDurableDraftField( + workspaceDraftRowKey('commit', { hostId, executionHost, worktreeId }, ''), + 'message' + ) const [generatingMessage, setGeneratingMessage] = useState(false) const [showBranchPicker, setShowBranchPicker] = useState(false) const [localBranches, setLocalBranches] = useState(null) diff --git a/mobile/src/stats/home-stats-summary-read.ts b/mobile/src/stats/home-stats-summary-read.ts index 365bb32b0bb..e1ee4807167 100644 --- a/mobile/src/stats/home-stats-summary-read.ts +++ b/mobile/src/stats/home-stats-summary-read.ts @@ -1,6 +1,8 @@ import { z } from 'zod' import { salvagedOptional } from '../../../src/shared/zod-salvage' -import type { RpcClient } from '../transport/rpc/rpc-client-contract' +import { HOST_LIST_TARGET, NO_HOST_LIST_INPUT } from '../host-screen/host-list-queries' +import { defineHostQuery } from '../query/host-query' +import { hostQueryKey } from '../query/host-query-key' import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/rpc-operation' import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader' import type { HomeStatsRow } from './home-stats-total' @@ -15,7 +17,6 @@ const homeStatsSummarySchema = z .nullish() .catch(undefined) -// Decorative totals: a refusal keeps the last shown reply. const homeStatsSummaryRead = bindDeferredRpcOperation( defineRpcOperation({ name: 'stats.home-summary-or-skip', @@ -26,23 +27,35 @@ const homeStatsSummaryRead = bindDeferredRpcOperation( }) ) -export type HomeStatsSetter = ( - updater: (previous: Record) => Record -) => void +type HomeStats = Exclude -export function fetchHomeHostStats( - client: RpcClient, - hostId: string, - setStats: HomeStatsSetter, - disposed: () => boolean -): void { - homeStatsSummaryRead - .requestSingleFlight(client, hostId) - .then((reply) => { - const summary = homeStatsSummaryRead.interpret(reply) - if (!disposed() && summary.accepted) { - setStats((previous) => ({ ...previous, [hostId]: summary.value })) - } - }) - .catch(() => {}) -} +export const homeStatsQuery = defineHostQuery({ + family: 'stats.summary', + fetch: async (client, _target, _input, previous, read) => { + const summary = homeStatsSummaryRead.interpret(await homeStatsSummaryRead.request(client)) + if (summary.accepted) { + return summary.value ?? null + } + // Decorative totals: a refusal keeps the last reply this launch read, never re-dates a stored one. + if (previous !== undefined && !read.previousFromStore) { + return previous + } + throw new Error('stats.summary unavailable') + }, + // Re-read each time Home comes back, as before; nothing on the desktop signals new totals. + staleTime: 0, + gcTime: Infinity, + persist: { + version: 1, + dataSchema: z + .looseObject({ + totalAgentsSpawned: z.number().optional(), + totalPRsCreated: z.number().optional(), + totalAgentTimeMs: z.number().optional() + }) + .nullable() + } +}) + +export const homeStatsKey = (hostId: string) => + hostQueryKey(hostId, homeStatsQuery.family, HOST_LIST_TARGET, NO_HOST_LIST_INPUT) diff --git a/mobile/src/tasks/github-review-publication.test.tsx b/mobile/src/tasks/github-review-publication.test.tsx index 6b8eecf228c..27ef19d09c3 100644 --- a/mobile/src/tasks/github-review-publication.test.tsx +++ b/mobile/src/tasks/github-review-publication.test.tsx @@ -11,6 +11,7 @@ import type { TaskItem } from './mobile-tasks-project-workspace-types' import { useMobileTasksHostedCommentReviewActions } from './use-mobile-tasks-hosted-comment-review-actions' import { useMobileTasksMutation } from './use-mobile-tasks-workspace-and-project-state' import { useMobileTasksItemState } from './use-mobile-tasks-item-state' +import { useTaskCommentDraft } from './task-draft-rows' import { useMobileTasksItemDetailLoading } from './use-mobile-tasks-item-detail-loading' vi.mock('./mobile-tasks-dependencies', async () => ({ @@ -60,6 +61,7 @@ async function mount(loadDetails = false) { itemState.readDetailPayload, itemState.reconcilePrFileConnection ) + const [itemCommentDraft, setItemCommentDraft] = useTaskCommentDraft(selection.actionItem) const mutation = useMobileTasksMutation() const [items, setItems] = useState([selected]) const [error, setError] = useState('') @@ -70,6 +72,8 @@ async function mount(loadDetails = false) { ...selection, ...mutation, ...itemState, + itemCommentDraft, + setItemCommentDraft, client, tasksSupported: true, setError, diff --git a/mobile/src/tasks/mobile-tasks-dependencies.ts b/mobile/src/tasks/mobile-tasks-dependencies.ts index 3ebbcbc47da..6ec046746c3 100644 --- a/mobile/src/tasks/mobile-tasks-dependencies.ts +++ b/mobile/src/tasks/mobile-tasks-dependencies.ts @@ -145,5 +145,6 @@ export type { SshConnectionState } from '../../../src/shared/ssh-types' export { githubProjectHost, - githubProjectIdentityKey as githubProjectKey + githubProjectIdentityKey as githubProjectKey, + toGitHubProjectIdentity } from '../../../src/shared/github/project-identity' diff --git a/mobile/src/tasks/mobile-tasks-github-project-pickers.tsx b/mobile/src/tasks/mobile-tasks-github-project-pickers.tsx index 00972f482c6..56b373428bb 100644 --- a/mobile/src/tasks/mobile-tasks-github-project-pickers.tsx +++ b/mobile/src/tasks/mobile-tasks-github-project-pickers.tsx @@ -13,6 +13,7 @@ import { ActivityIndicator, githubProjectKey, PickerModal, + toGitHubProjectIdentity, type GitHubProjectRef } from './mobile-tasks-dependencies' import { ListGroup, SectionHeader, ListRow } from '../components/list/ListGroup' @@ -253,11 +254,7 @@ export function renderMobileTasksGitHubProjectPicker(model: ConnectionPresentati ...githubProjectSettings, pinned: [ ...githubProjectSettings.pinned, - { - owner: project.owner, - ownerType: project.ownerType, - number: project.number - } + toGitHubProjectIdentity(project) ].slice(0, 20) }) ) @@ -284,7 +281,7 @@ export function renderMobileTasksGitHubProjectPicker(model: ConnectionPresentati ) : ( {browseGitHubProjects.map((project) => - projectRow(project.id, project, project.title, undefined) + projectRow(`browse:${githubProjectKey(project)}`, project, project.title, undefined) )} )} @@ -295,20 +292,21 @@ export function renderMobileTasksGitHubProjectPicker(model: ConnectionPresentati } export function renderMobileTasksGitHubProjectViewPicker(model: ConnectionPresentationModel) { + const pending = model.pendingGitHubProjectViewSelection return ( { - const view = model.githubProjectViews.find((candidate) => candidate.id === viewId) + const view = (pending?.views ?? model.githubProjectViews).find( + (candidate) => candidate.id === viewId + ) if (view && view.layout !== 'TABLE_LAYOUT') { model.setGithubProjectError( translate( @@ -318,8 +316,8 @@ export function renderMobileTasksGitHubProjectViewPicker(model: ConnectionPresen ) return } - if (model.pendingGitHubProjectViewSelection) { - model.commitGitHubProjectView(model.pendingGitHubProjectViewSelection, viewId) + if (pending) { + model.commitGitHubProjectView(pending.project, viewId, pending.views) model.setPendingGitHubProjectViewSelection(null) return } @@ -330,7 +328,7 @@ export function renderMobileTasksGitHubProjectViewPicker(model: ConnectionPresen }} onClose={() => { model.setShowGitHubProjectViewPicker(false) - if (model.pendingGitHubProjectViewSelection) { + if (pending) { model.setPendingGitHubProjectViewSelection(null) } }} diff --git a/mobile/src/tasks/task-draft-rows.ts b/mobile/src/tasks/task-draft-rows.ts new file mode 100644 index 00000000000..9a9d25f0d89 --- /dev/null +++ b/mobile/src/tasks/task-draft-rows.ts @@ -0,0 +1,35 @@ +import { durableDraftRowKey } from '../drafts/durable-draft-rows' +import { useDurableDraftField } from '../drafts/durable-draft-fields' +import { githubTaskKey } from './github-task-identity' +import type { ActionableTaskItem } from './mobile-tasks-project-workspace-types' +import type { GitHubProjectRow } from './mobile-tasks-view-state-types' + +/** The item a status edit or refresh hands over as a new object is still the same item. */ +export function taskItemIdentity(item: ActionableTaskItem): string { + return item.provider === 'github' ? `github:${githubTaskKey(item.source)}` : item.key +} + +// Tasks rows are host-scoped (`''` worktree part); the shell binds the host. +function taskCommentDraftKey(id: string | null): string | null { + return id === null ? null : durableDraftRowKey('taskComment', '', id) +} + +const TASK_CREATE_DRAFT_KEY = durableDraftRowKey('taskCreate', '', '') + +/** The open item's comment box, kept per item. */ +export function useTaskCommentDraft(item: ActionableTaskItem | null) { + return useDurableDraftField(taskCommentDraftKey(item && taskItemIdentity(item)), 'text') +} + +/** A GitHub project row's comment box, kept per row. */ +export function useProjectRowCommentDraft(row: GitHubProjectRow | null) { + return useDurableDraftField(taskCommentDraftKey(row && `githubProject:${row.id}`), 'text') +} + +/** The New issue sheet's title and body, kept until a create succeeds and read only once the sheet opens. */ +export function useTaskCreateDraft(open: boolean) { + const key = open ? TASK_CREATE_DRAFT_KEY : null + const [createTitle, setCreateTitle] = useDurableDraftField(key, 'title') + const [createBody, setCreateBody] = useDurableDraftField(key, 'body') + return { createTitle, setCreateTitle, createBody, setCreateBody } +} diff --git a/mobile/src/tasks/use-mobile-task-comment-send-outcome.ts b/mobile/src/tasks/use-mobile-task-comment-send-outcome.ts index f0225f11fe1..ac847f9fc26 100644 --- a/mobile/src/tasks/use-mobile-task-comment-send-outcome.ts +++ b/mobile/src/tasks/use-mobile-task-comment-send-outcome.ts @@ -5,7 +5,7 @@ import { useRef, useState } from './mobile-tasks-dependencies' -import { githubTaskKey } from './github-task-identity' +import { taskItemIdentity } from './task-draft-rows' import type { ActionableTaskItem } from './mobile-tasks-project-workspace-types' import type { DetailPayload } from './mobile-tasks-provider-detail-types' import { isRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity' @@ -33,7 +33,7 @@ type CommentSendOutcome = { } function itemIdentity(item: ActionableTaskItem | null): string | null { - return item?.provider === 'github' ? githubTaskKey(item.source) : (item?.key ?? null) + return item && taskItemIdentity(item) } function sameCommentText(a: string, b: string): boolean { diff --git a/mobile/src/tasks/use-mobile-tasks-hosted-comment-review-actions.tsx b/mobile/src/tasks/use-mobile-tasks-hosted-comment-review-actions.tsx index b2399a1c5ee..21908343735 100644 --- a/mobile/src/tasks/use-mobile-tasks-hosted-comment-review-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-hosted-comment-review-actions.tsx @@ -160,7 +160,7 @@ export function useMobileTasksHostedCommentReviewActions< finish() } }, - [claimPublication, client, itemCommentDraft, tryBeginMutation] + [claimPublication, client, itemCommentDraft, setItemCommentDraft, tryBeginMutation] ) const copyTaskLink = useCallback( diff --git a/mobile/src/tasks/use-mobile-tasks-item-state.tsx b/mobile/src/tasks/use-mobile-tasks-item-state.tsx index 09470fdf41a..c20f71c2f7c 100644 --- a/mobile/src/tasks/use-mobile-tasks-item-state.tsx +++ b/mobile/src/tasks/use-mobile-tasks-item-state.tsx @@ -27,7 +27,6 @@ export function useMobileTasksItemState() { }, []) const [itemTitleDraft, setItemTitleDraft] = useState('') const [itemBodyDraft, setItemBodyDraft] = useState('') - const [itemCommentDraft, setItemCommentDraft] = useState('') const [itemAddLabelsDraft, setItemAddLabelsDraft] = useState('') const [itemRemoveLabelsDraft, setItemRemoveLabelsDraft] = useState('') const [itemAddAssigneesDraft, setItemAddAssigneesDraft] = useState('') @@ -110,8 +109,6 @@ export function useMobileTasksItemState() { setItemTitleDraft, itemBodyDraft, setItemBodyDraft, - itemCommentDraft, - setItemCommentDraft, itemAddLabelsDraft, setItemAddLabelsDraft, itemRemoveLabelsDraft, diff --git a/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx b/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx index b1ff0216e05..c5c85a0ee1a 100644 --- a/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-linear-item-actions.tsx @@ -81,7 +81,7 @@ export function useMobileTasksLinearItemActions< finish() } }, - [client, linearCommentDraft, tryBeginMutation] + [client, linearCommentDraft, setLinearCommentDraft, tryBeginMutation] ) const openLinearSubIssue = useCallback( diff --git a/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx b/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx index da5a090f2fa..1c5aaeccc21 100644 --- a/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx +++ b/mobile/src/tasks/use-mobile-tasks-list-and-detail-effects.tsx @@ -1,4 +1,5 @@ import { githubTaskKey } from './github-task-identity' +import { taskItemIdentity } from './task-draft-rows' import { translate } from '../i18n/mobile-i18n' import type { ProjectLoadingActionsModel } from './use-mobile-tasks-project-loading-actions' import { @@ -52,7 +53,6 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM setError, setGithubProjectError, setGithubRepoSlugCache, - setLinearCommentDraft, setLinearStates, setLinearStatesError, setLinearStatesLoading, @@ -246,7 +246,6 @@ export function useMobileTasksListAndDetailEffects(model: ProjectLoadingActionsM const linearMetadataKey = linearMetadataItem?.key ?? null useEffect(() => { - setLinearCommentDraft('') setLinearSubIssueTitle('') }, [linearMetadataKey]) @@ -315,7 +314,6 @@ export function useMobileTasksItemSelectionEffects( | 'setItemAddAssigneesDraft' | 'setItemAddLabelsDraft' | 'setItemBodyDraft' - | 'setItemCommentDraft' | 'setItemRemoveAssigneesDraft' | 'setItemRemoveLabelsDraft' | 'setItemReplyDrafts' @@ -333,7 +331,6 @@ export function useMobileTasksItemSelectionEffects( setItemAddAssigneesDraft, setItemAddLabelsDraft, setItemBodyDraft, - setItemCommentDraft, setItemRemoveAssigneesDraft, setItemRemoveLabelsDraft, setItemReplyDrafts, @@ -341,8 +338,7 @@ export function useMobileTasksItemSelectionEffects( setItemTitleDraft, setPrFileCommentDrafts } = model - const actionIdentity = - actionItem?.provider === 'github' ? githubTaskKey(actionItem.source) : actionItem?.key + const actionIdentity = actionItem && taskItemIdentity(actionItem) const fileRevision = model.detailPayload?.provider === 'github' @@ -357,10 +353,10 @@ export function useMobileTasksItemSelectionEffects( }, [actionIdentity, client, fileRevision, resetPrFiles]) // Keyed on identity: status edits, refreshes and reconnects hand over a new object for the same item. + // The comment box is not reset: it is kept per item in its draft row. useEffect(() => { setItemTitleDraft(actionItem?.title ?? '') setItemBodyDraft('') - setItemCommentDraft('') setItemAddLabelsDraft('') setItemRemoveLabelsDraft('') setItemAddAssigneesDraft('') diff --git a/mobile/src/tasks/use-mobile-tasks-picker-projection.tsx b/mobile/src/tasks/use-mobile-tasks-picker-projection.tsx index c8015b4ea9b..19040fb2808 100644 --- a/mobile/src/tasks/use-mobile-tasks-picker-projection.tsx +++ b/mobile/src/tasks/use-mobile-tasks-picker-projection.tsx @@ -49,6 +49,7 @@ export function useMobileTasksPickerProjection(model: DetailCommentRenderersMode items, jiraConnection, linearTeams, + pendingGitHubProjectViewSelection, provider, reposById, selectedHostedRepos, @@ -223,7 +224,7 @@ export function useMobileTasksPickerProjection(model: DetailCommentRenderersMode ) const githubProjectViewOptions = useMemo[]>( () => - githubProjectViews.map((view) => ({ + (pendingGitHubProjectViewSelection?.views ?? githubProjectViews).map((view) => ({ value: view.id, label: view.name, subtitle: @@ -232,7 +233,7 @@ export function useMobileTasksPickerProjection(model: DetailCommentRenderersMode : t('tasks.pickerProjection.unsupportedLayout', 'Unsupported layout on mobile'), disabled: view.layout !== 'TABLE_LAYOUT' })), - [githubProjectViews, t] + [githubProjectViews, pendingGitHubProjectViewSelection, t] ) return Object.assign(model, { createTargetOptions, diff --git a/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx b/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx index 35fbe3e4e86..c7a950ce7c4 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-detail-loading.tsx @@ -20,7 +20,6 @@ export function useMobileTasksProjectDetailLoading< | 'setPrFileCommentDrafts' | 'resetPrFiles' | 'setProjectBodyDraft' - | 'setProjectCommentDraft' | 'setProjectEditingCommentDraft' | 'setProjectEditingCommentId' | 'setProjectFieldDrafts' @@ -42,7 +41,6 @@ export function useMobileTasksProjectDetailLoading< setPrFileCommentDrafts, resetPrFiles, setProjectBodyDraft, - setProjectCommentDraft, setProjectEditingCommentDraft, setProjectEditingCommentId, setProjectFieldDrafts, @@ -57,11 +55,11 @@ export function useMobileTasksProjectDetailLoading< resetPrFiles() }, [projectRowItem, client, projectRowDetailRefreshSeq, resetPrFiles]) // Keyed on row id: field edits, merges and reconnects hand over a new object for the same row. + // The comment box is not reset: it is kept per row in its draft row. const projectRowId = projectRowItem?.id ?? null useEffect(() => { setProjectTitleDraft(projectRowItem?.content.title ?? '') setProjectBodyDraft(projectRowItem?.content.body ?? '') - setProjectCommentDraft('') setProjectEditingCommentId(null) setProjectEditingCommentDraft('') setProjectReviewersDraft('') diff --git a/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx index 3d2d11b60e5..f3555c5400b 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-loading-actions.tsx @@ -8,7 +8,9 @@ import { githubProjectHost, githubProjectKey, parseProjectInput, - useCallback + toGitHubProjectIdentity, + useCallback, + useRef } from './mobile-tasks-dependencies' import type { GitHubProjectTable } from './mobile-tasks-legacy-foundation' import { @@ -47,6 +49,8 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions taskStateHydrated, tasksSupported } = model + // Each pick bumps this, so a late views reply for an earlier pick cannot overwrite a newer one. + const projectSelectionRef = useRef(0) const loadGitHubProjects = useCallback(async (): Promise => { if (!client || connState !== 'connected' || !tasksSupported) { return @@ -80,9 +84,7 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions throw new Error(result.error.message) } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the schema requires the `id` a view is selected by and types `number`/`name`/`layout` without requiring them, because a layout arm this build has not heard of must reach the "no supported views" test rather than drop the row. - const views = result.views as GitHubProjectViewSummary[] - setGithubProjectViews(views) - return views + return result.views as GitHubProjectViewSummary[] }, [client, connState, taskStateHydrated, tasksSupported] ) @@ -153,19 +155,23 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions ) const commitGitHubProjectView = useCallback( - (project: GitHubProjectRef, viewId: string): void => { - const projectKey = githubProjectKey(project) + (project: GitHubProjectRef, viewId: string, views?: GitHubProjectViewSummary[]): void => { + const ref = toGitHubProjectIdentity(project) + const projectKey = githubProjectKey(ref) const nextSettings: GitHubProjectSettings = { ...githubProjectSettings, recent: [ - { ...project, lastOpenedAt: new Date().toISOString() }, + { ...ref, lastOpenedAt: new Date().toISOString() }, ...githubProjectSettings.recent.filter((entry) => githubProjectKey(entry) !== projectKey) ].slice(0, 10), lastViewByProject: { ...githubProjectSettings.lastViewByProject, [projectKey]: { viewId } }, - activeProject: project + activeProject: ref + } + if (views) { + setGithubProjectViews(views) } persistGitHubProjectSettings(nextSettings) setAppliedGithubProjectSearch(undefined) @@ -180,51 +186,47 @@ export function useMobileTasksProjectLoadingActions(model: TaskPaginationActions if (!tasksSupported || !taskStateHydrated) { return } + const selection = ++projectSelectionRef.current setGithubProjectLoading(true) setGithubProjectError('') try { const views = await loadGitHubProjectViews(project) - const projectKey = githubProjectKey(project) - const rememberedView = githubProjectSettings.lastViewByProject[projectKey]?.viewId + if (selection !== projectSelectionRef.current) { + return + } const explicitView = typeof options.viewNumber === 'number' ? views.find((view) => view.number === options.viewNumber) : undefined - if (options.viewNumber !== undefined && !explicitView) { - // Stale view URLs prompt for a replacement view, matching desktop. - const supportedViews = views.filter((view) => view.layout === 'TABLE_LAYOUT') - if (supportedViews.length === 0) { - throw new Error('This project has no supported views.') - } - setPendingGitHubProjectViewSelection(project) - setShowGitHubProjectViewPicker(true) - return - } if (explicitView && explicitView.layout !== 'TABLE_LAYOUT') { throw new Error("Orca doesn't support this GitHub Project layout yet.") } - if (!explicitView && !rememberedView) { - // Ask for the first Project view; do not silently choose the first table. - const supportedViews = views.filter((view) => view.layout === 'TABLE_LAYOUT') - if (supportedViews.length === 0) { - throw new Error('This project has no supported views.') - } - setPendingGitHubProjectViewSelection(project) - setShowGitHubProjectViewPicker(true) - return - } + // A remembered Board or Roadmap view (desktop renders those) cannot open here. + const rememberedViewId = + options.viewNumber === undefined + ? githubProjectSettings.lastViewByProject[githubProjectKey(project)]?.viewId + : undefined const selectedView = explicitView ?? - views.find((view) => view.id === rememberedView && view.layout === 'TABLE_LAYOUT') ?? - undefined - if (!selectedView) { + views.find((view) => view.id === rememberedViewId && view.layout === 'TABLE_LAYOUT') + if (selectedView) { + commitGitHubProjectView(project, selectedView.id, views) + return + } + if (!views.some((view) => view.layout === 'TABLE_LAYOUT')) { throw new Error('This project has no supported views.') } - commitGitHubProjectView(project, selectedView.id) + // Ask for a view, matching desktop: never silently choose the first table. + setPendingGitHubProjectViewSelection({ project, views }) + setShowGitHubProjectViewPicker(true) } catch (err) { - setGithubProjectError(err instanceof Error ? err.message : 'Failed to select project') + if (selection === projectSelectionRef.current) { + setGithubProjectError(err instanceof Error ? err.message : 'Failed to select project') + } } finally { - setGithubProjectLoading(false) + if (selection === projectSelectionRef.current) { + setGithubProjectLoading(false) + } } }, [ diff --git a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx index f606200946d..3640476072c 100644 --- a/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-project-workspace-comment-actions.tsx @@ -233,7 +233,7 @@ export function useMobileTasksProjectWorkspaceCommentActions(model: WorkspaceCre setProjectMutating(false) } }, - [activeGitHubProjectHost, client, projectCommentDraft, projectMutating] + [activeGitHubProjectHost, client, projectCommentDraft, projectMutating, setProjectCommentDraft] ) const updateProjectRowComment = useCallback( diff --git a/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx b/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx index 2d4e4b8e826..70aaa0eb0a9 100644 --- a/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx +++ b/mobile/src/tasks/use-mobile-tasks-route-and-item-state.tsx @@ -50,6 +50,7 @@ import { } from './mobile-tasks-legacy-foundation' import { getTaskPresetQuery } from '../../../src/shared/work-items/task-preset-query' import { useMobileTasksItemState } from './use-mobile-tasks-item-state' +import { useTaskCommentDraft, useTaskCreateDraft } from './task-draft-rows' import { useMobileJiraConnectionState } from './use-mobile-jira-connection-state' import type { JiraIssueFilter } from '../../../src/shared/jira/jira-types' @@ -165,8 +166,8 @@ export function useMobileTasksRouteAndItemState() { const [showGitHubPagePicker, setShowGitHubPagePicker] = useState(false) const [showCreateTask, setShowCreateTask] = useState(false) const [showCreateTargetPicker, setShowCreateTargetPicker] = useState(false) - const [createTitle, setCreateTitle] = useState('') - const [createBody, setCreateBody] = useState('') + const { createTitle, setCreateTitle, createBody, setCreateBody } = + useTaskCreateDraft(showCreateTask) const [createRepoId, setCreateRepoId] = useState(null) const [createTeamId, setCreateTeamId] = useState(null) const [linearTeams, setLinearTeams] = useState([]) @@ -186,6 +187,7 @@ export function useMobileTasksRouteAndItemState() { itemState.readDetailPayload, itemState.reconcilePrFileConnection ) + const [itemCommentDraft, setItemCommentDraft] = useTaskCommentDraft(itemSelection.actionItem) const [mergeMethodTaskItem, setMergeMethodTaskItem] = useState< Extract | Extract | null >(null) @@ -360,7 +362,9 @@ export function useMobileTasksRouteAndItemState() { setPendingProjectGitHubMerge, pendingHostedStateChange, setPendingHostedStateChange, - ...itemState + ...itemState, + itemCommentDraft, + setItemCommentDraft } } diff --git a/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx b/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx index 59e08b80ce2..d794ab4f4f1 100644 --- a/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx +++ b/mobile/src/tasks/use-mobile-tasks-task-create-actions.tsx @@ -141,8 +141,9 @@ export function useMobileTasksTaskCreateActions(model: LinearItemActionsModel) { ) } setShowCreateTask(false) - setCreateTitle('') - setCreateBody('') + // Text typed while the create ran, here or in a reopened sheet, is not what it sent. + setCreateTitle((current) => (current === createTitle ? '' : current)) + setCreateBody((current) => (current === createBody ? '' : current)) await loadTasks({ silent: true }) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to create task') diff --git a/mobile/src/tasks/use-mobile-tasks-workspace-and-project-state.tsx b/mobile/src/tasks/use-mobile-tasks-workspace-and-project-state.tsx index 6f9ba1e71d5..2faf539fc36 100644 --- a/mobile/src/tasks/use-mobile-tasks-workspace-and-project-state.tsx +++ b/mobile/src/tasks/use-mobile-tasks-workspace-and-project-state.tsx @@ -2,6 +2,7 @@ import { useRef, useCallback } from 'react' import { useBottomDrawerFollowUp } from '../components/bottom-drawer/use-bottom-drawer-follow-up' import type { RouteAndItemStateModel } from './use-mobile-tasks-route-and-item-state' import type { WorkspaceSshRecord } from './workspace-ssh-gate' +import { useProjectRowCommentDraft, useTaskCommentDraft } from './task-draft-rows' import { type BaseRefSearchResult, type GitHubProjectPartialFailure, @@ -86,7 +87,9 @@ export function useMobileTasksWorkspaceAndProjectState(model: RouteAndItemStateM const [linearStates, setLinearStates] = useState([]) const [linearStatesLoading, setLinearStatesLoading] = useState(false) const [linearStatesError, setLinearStatesError] = useState('') - const [linearCommentDraft, setLinearCommentDraft] = useState('') + const [linearCommentDraft, setLinearCommentDraft] = useTaskCommentDraft( + model.actionItem?.provider === 'linear' ? model.actionItem : null + ) const [linearSubIssueTitle, setLinearSubIssueTitle] = useState('') const [taskStateHydrated, setTaskStateHydrated] = useState(false) const [runtimeTaskSettings, setRuntimeTaskSettings] = useState({}) @@ -122,8 +125,11 @@ export function useMobileTasksWorkspaceAndProjectState(model: RouteAndItemStateM const [showGitHubProjectPicker, setShowGitHubProjectPicker] = useState(false) const [showGitHubProjectViewPicker, setShowGitHubProjectViewPicker] = useState(false) const [showGitHubProjectFieldsPicker, setShowGitHubProjectFieldsPicker] = useState(false) - const [pendingGitHubProjectViewSelection, setPendingGitHubProjectViewSelection] = - useState(null) + // The project being picked keeps its own views, so cancelling leaves the active project's list intact. + const [pendingGitHubProjectViewSelection, setPendingGitHubProjectViewSelection] = useState<{ + project: GitHubProjectRef + views: GitHubProjectViewSummary[] + } | null>(null) const [projectRowItem, setProjectRowItem] = useState(null) const [projectRowDetail, setProjectRowDetail] = useState(null) const [projectRowDetailLoading, setProjectRowDetailLoading] = useState(false) @@ -131,7 +137,7 @@ export function useMobileTasksWorkspaceAndProjectState(model: RouteAndItemStateM const [projectRowDetailRefreshSeq, setProjectRowDetailRefreshSeq] = useState(0) const [projectTitleDraft, setProjectTitleDraft] = useState('') const [projectBodyDraft, setProjectBodyDraft] = useState('') - const [projectCommentDraft, setProjectCommentDraft] = useState('') + const [projectCommentDraft, setProjectCommentDraft] = useProjectRowCommentDraft(projectRowItem) const [projectEditingCommentId, setProjectEditingCommentId] = useState(null) const [projectEditingCommentDraft, setProjectEditingCommentDraft] = useState('') const [projectReviewersDraft, setProjectReviewersDraft] = useState('') diff --git a/mobile/src/terminal/session/MobileSessionAccessoryKeys.tsx b/mobile/src/terminal/session/MobileSessionAccessoryKeys.tsx index f88d4d336c7..737327fab48 100644 --- a/mobile/src/terminal/session/MobileSessionAccessoryKeys.tsx +++ b/mobile/src/terminal/session/MobileSessionAccessoryKeys.tsx @@ -21,6 +21,17 @@ import { styles as sessionStyles } from '../../session/mobile-session-styles' import { useKeyboardPersistingTaps } from '../../platform/keyboard-persisting-taps' import type { MobileSessionController } from '../../session/use-mobile-session-controller' import { useMobileSessionKeyboardLift } from './use-mobile-session-keyboard-lift' +import { + AGENT_SMART_KEY_STEP_MS, + type AgentSmartKey +} from '../../../../src/shared/terminal/input/agent-smart-keys' +import type { TerminalAccessoryKey } from '../terminal-accessory-keys' +import { resolveMobileTerminalTabSmartKeys } from './mobile-terminal-tab-agent' +import { MobileSessionSmartKeys } from './MobileSessionSmartKeys' +import { MobileSessionLatchKeys } from './MobileSessionLatchKeys' +import { isAccessibilityClick, useTerminalKeyRowTouch } from './use-terminal-key-row-touch' + +type PreparedPress = ReturnType // The terminal's key row above the live input; every key goes straight to the terminal. export function MobileSessionAccessoryKeys({ @@ -46,10 +57,26 @@ export function MobileSessionAccessoryKeys({ stopAccessoryRepeat, cancelAccessoryRepeat, prepareAccessoryPress, - handlePaste + handlePaste, + dockKeys, + activeSessionTab, + terminals, + smartRailEnabled } = controller const keyboardLift = useMobileSessionKeyboardLift(controller.dockBottomInset) - const accessoryPresses = useRef(new Map>()) + const accessoryPresses = useRef(new Map()) + const scrollRef = useRef(null) + const latestSmartKeys = useMemo( + () => + smartRailEnabled ? resolveMobileTerminalTabSmartKeys(activeSessionTab, terminals) : null, + [smartRailEnabled, activeSessionTab, terminals] + ) + const touch = useTerminalKeyRowTouch({ + scrollRef, + latest: latestSmartKeys, + cancelAccessoryRepeat + }) + const smartKeys = touch.shown const keepsKeyboard = useKeyboardPersistingTaps('always') // An unmounting Pressable never fires onPressOut, so a held key would outlive its row. useEffect(() => cancelAccessoryRepeat, [cancelAccessoryRepeat]) @@ -70,8 +97,57 @@ export function MobileSessionAccessoryKeys({ ] const sendKeyLabel = (label: string) => t('session.accessoryKeys.sendKey', 'Send {{label}}', { label }) + // Held Shift, Ctrl or Alt turn a key into its combo and are used up when it sends; keys that take none send as they are. + const prepareBuiltInPress = (key: TerminalAccessoryKey): PreparedPress => { + const chord = dockKeys.chordInput(key.id) + const press = prepareAccessoryPress(chord ?? createTerminalLiveAccessoryInput(key)) + const takeChord = () => { + if (chord) { + dockKeys.takeModifiers() + } + } + return { + tap: () => { + takeChord() + return press.tap() + }, + hold: (firstRepeatDelayMs) => { + takeChord() + press.hold(firstRepeatDelayMs) + } + } + } + // Later writes belong to the same press, so a scroll after release mustn't drop them; a tab switch does. + const sendSmartKey = (key: AgentSmartKey) => { + const handle = controller.activeHandleRef.current + void (async () => { + for (const [index, bytes] of key.writes.entries()) { + if (index > 0) { + await new Promise((resolve) => setTimeout(resolve, AGENT_SMART_KEY_STEP_MS)) + } + if (controller.activeHandleRef.current !== handle) { + return + } + if (!(await prepareAccessoryPress({ bytes }).tap())) { + return + } + } + })() + } + const latchIndex = builtInKeys.findIndex((key) => key.id === 'tab') + 1 + const latchKeys = ( + touch.arm('latch')} + onPress={(modifier, event) => + touch.fire('latch', event, () => dockKeys.tapModifier(modifier)) + } + /> + ) return ( - + {/* Why: fixed keyboard escape hatch; outside the ScrollView so it can't scroll away (#5106). */} {keyboardLift > 0 && ( + {smartKeys ? ( + touch.arm(`smart:${key.id}`)} + onPress={(key, event) => touch.fire(`smart:${key.id}`, event, () => sendSmartKey(key))} + /> + ) : null} { - if (activeHandle) { - void toggleDisplayMode(activeHandle) - } - }} + onPressIn={() => touch.arm('displayMode')} + onPress={(event) => + touch.fire('displayMode', event, () => { + if (activeHandle) { + void toggleDisplayMode(activeHandle) + } + }) + } accessibilityRole="button" accessibilityLabel={ phoneDisplay @@ -133,7 +222,8 @@ export function MobileSessionAccessoryKeys({ style={keyStyle} disabled={!canSend} hitSlop={TERMINAL_KEY_HIT_SLOP} - onPress={() => void handlePaste()} + onPressIn={() => touch.arm('paste')} + onPress={(event) => touch.fire('paste', event, () => void handlePaste())} accessibilityRole="button" accessibilityLabel={t( 'session.accessoryKeys.pasteFromClipboard', @@ -143,20 +233,22 @@ export function MobileSessionAccessoryKeys({ {t('session.accessoryKeys.paste', 'Paste')} )} - {builtInKeys.map((key) => ( + {latchIndex === 0 ? latchKeys : null} + {builtInKeys.flatMap((key, index) => [ { + touch.arm(key.id) if (!key.repeatable) { return } - const press = prepareAccessoryPress(createTerminalLiveAccessoryInput(key)) - accessoryPresses.current.set(key.id, press) + const prepared = prepareBuiltInPress(key) + accessoryPresses.current.set(key.id, prepared) if (event.type === 'keydown') { - press.hold(TERMINAL_ACCESSORY_REPEAT_DELAY_MS) + prepared.hold(TERMINAL_ACCESSORY_REPEAT_DELAY_MS) } }} onPressOut={() => { @@ -165,23 +257,23 @@ export function MobileSessionAccessoryKeys({ } }} onPress={(event) => { - if (key.repeatable) { - // Accessibility clicks have no touch-down to prepare a sender. - const accessibilityClick = - event.type === 'click' && - 'detail' in event.nativeEvent && - event.nativeEvent.detail === 0 - const press = - (!accessibilityClick && accessoryPresses.current.get(key.id)) || - prepareAccessoryPress(createTerminalLiveAccessoryInput(key)) - accessoryPresses.current.delete(key.id) - void press.tap() - return - } - void handleAccessoryKey(createTerminalLiveAccessoryInput(key)) + // Accessibility clicks have no touch-down to prepare a sender. + const prepared = + (key.repeatable && + !isAccessibilityClick(event) && + accessoryPresses.current.get(key.id)) || + prepareBuiltInPress(key) + accessoryPresses.current.delete(key.id) + touch.fire(key.id, event, () => void prepared.tap()) }} onLongPress={ - key.repeatable ? () => accessoryPresses.current.get(key.id)?.hold() : undefined + key.repeatable + ? () => { + if (touch.stillArmed(key.id)) { + accessoryPresses.current.get(key.id)?.hold() + } + } + : undefined } delayLongPress={TERMINAL_ACCESSORY_REPEAT_DELAY_MS} // A web - ))} + , + index + 1 === latchIndex ? latchKeys : null + ])} {customKeys.map((key) => ( [...keyStyle({ pressed }), styles.customKey]} disabled={!canSend} hitSlop={TERMINAL_KEY_HIT_SLOP} - onPress={() => void handleAccessoryKey({ bytes: key.bytes })} + onPressIn={() => touch.arm(key.id)} + onPress={(event) => + touch.fire(key.id, event, () => void handleAccessoryKey({ bytes: key.bytes })) + } onLongPress={() => { triggerMediumImpact() setDeleteKeyTarget(key) @@ -216,7 +312,8 @@ export function MobileSessionAccessoryKeys({ [styles.key, pressed && styles.keyPressed]} hitSlop={TERMINAL_KEY_HIT_SLOP} - onPress={() => setShowCustomKeyModal(true)} + onPressIn={() => touch.arm('addKey')} + onPress={(event) => touch.fire('addKey', event, () => setShowCustomKeyModal(true))} accessibilityRole="button" accessibilityLabel={t('session.accessoryKeys.addCustomShortcut', 'Add custom shortcut')} > diff --git a/mobile/src/terminal/session/MobileSessionLatchKeys.tsx b/mobile/src/terminal/session/MobileSessionLatchKeys.tsx new file mode 100644 index 00000000000..234f96e4f72 --- /dev/null +++ b/mobile/src/terminal/session/MobileSessionLatchKeys.tsx @@ -0,0 +1,58 @@ +import { Pressable, Text, type GestureResponderEvent } from 'react-native' +import type { TerminalShortcutModifier } from '../terminal-accessory-keys' +import type { StickyModifiers } from '../terminal-sticky-modifiers' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import { TERMINAL_KEY_HIT_SLOP, terminalDockStyles as styles } from './terminal-dock-styles' + +const LATCHES: readonly { id: TerminalShortcutModifier; label: string }[] = [ + { id: 'shift', label: 'Shift' }, + { id: 'ctrl', label: 'Ctrl' }, + { id: 'alt', label: 'Alt' } +] + +/** Shift, Ctrl and Alt on the key row: a tap holds one for the next key, a double tap locks it. */ +export function MobileSessionLatchKeys({ + modifiers, + disabled, + onPressIn, + onPress +}: { + modifiers: StickyModifiers + disabled: boolean + onPressIn: () => void + onPress: (modifier: TerminalShortcutModifier, event: GestureResponderEvent) => void +}) { + useMobileColorScheme() + const t = useMobileTranslation() + const names: Record = { + shift: t('session.accessoryKeys.shift', 'Shift'), + ctrl: t('session.accessoryKeys.control', 'Control'), + alt: t('session.accessoryKeys.alt', 'Alt') + } + return LATCHES.map(({ id, label }) => { + const latch = modifiers[id] + return ( + [ + styles.key, + styles.keyLatch, + latch === 'once' && styles.keyLatched, + latch === 'locked' && styles.keyLocked, + pressed && styles.keyPressed, + disabled && styles.disabled + ]} + disabled={disabled} + hitSlop={TERMINAL_KEY_HIT_SLOP} + onPressIn={onPressIn} + onPress={(event) => onPress(id, event)} + accessibilityRole="button" + accessibilityLabel={names[id]} + accessibilityState={{ selected: latch !== 'off' }} + > + {label} + + ) + }) +} diff --git a/mobile/src/terminal/session/MobileSessionSmartKeys.tsx b/mobile/src/terminal/session/MobileSessionSmartKeys.tsx new file mode 100644 index 00000000000..fdc0f612d85 --- /dev/null +++ b/mobile/src/terminal/session/MobileSessionSmartKeys.tsx @@ -0,0 +1,112 @@ +import { Pressable, Text, View, type GestureResponderEvent } from 'react-native' +import type { + AgentSmartKey, + AgentSmartKeyName, + AgentSmartKeySet +} from '../../../../src/shared/terminal/input/agent-smart-keys' +import { MobileAgentIcon } from '../../components/MobileAgentIcon' +import type { Translate } from '../../i18n/mobile-i18n' +import { useMobileTranslation } from '../../i18n/use-mobile-translation' +import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' +import { TERMINAL_KEY_HIT_SLOP, terminalDockStyles as styles } from './terminal-dock-styles' + +function smartKeyWord(t: Translate, name: AgentSmartKeyName): string { + switch (name) { + case 'stop': + return t('session.smartKeys.stop', 'Stop') + case 'sendNow': + return t('session.smartKeys.sendNow', 'Send now') + case 'background': + return t('session.smartKeys.background', 'Background') + case 'mode': + return t('session.smartKeys.mode', 'Mode') + case 'yes': + return t('session.smartKeys.yes', 'Yes') + case 'always': + return t('session.smartKeys.always', 'Always') + case 'no': + return t('session.smartKeys.no', 'No') + case 'cancel': + return t('session.smartKeys.cancel', 'Cancel') + case 'history': + return t('session.smartKeys.history', 'History') + case 'rewind': + return t('session.smartKeys.rewind', 'Rewind') + case 'queue': + return t('session.smartKeys.queue', 'Queue') + case 'edit': + return t('session.smartKeys.edit', 'Edit') + case 'answer': + return t('session.smartKeys.answer', 'Answer') + case 'skip': + return t('session.smartKeys.skip', 'Skip') + case 'confirm': + return t('session.smartKeys.confirm', 'Confirm') + case 'reject': + return t('session.smartKeys.reject', 'Reject') + } +} + +/** The agent's keys for its current state, in a capsule at the front of the key row. */ +export function MobileSessionSmartKeys({ + keySet, + disabled, + onPressIn, + onPress +}: { + keySet: AgentSmartKeySet + disabled: boolean + onPressIn: (key: AgentSmartKey) => void + onPress: (key: AgentSmartKey, event: GestureResponderEvent) => void +}) { + useMobileColorScheme() + const t = useMobileTranslation() + return ( + <> + + + {keySet.keys.map((key) => { + const word = key.name ? smartKeyWord(t, key.name) : null + return ( + [ + styles.key, + key.primary && styles.smartKeyPrimary, + pressed && styles.keyPressed, + disabled && styles.disabled + ]} + disabled={disabled} + hitSlop={TERMINAL_KEY_HIT_SLOP} + onPressIn={() => onPressIn(key)} + onPress={(event) => onPress(key, event)} + accessibilityRole="button" + accessibilityLabel={ + word + ? t('session.smartKeys.keyLabel', '{{word}}, sends {{combo}}', { + word, + combo: key.combo + }) + : t('session.accessoryKeys.sendKey', 'Send {{label}}', { label: key.combo }) + } + > + {word ? ( + + + {word} + + + {key.combo} + + + ) : ( + {key.combo} + )} + + ) + })} + + + + ) +} diff --git a/mobile/src/terminal/session/MobileTerminalInputActions.tsx b/mobile/src/terminal/session/MobileTerminalInputActions.tsx index ca3a69e4ef2..3730693bdad 100644 --- a/mobile/src/terminal/session/MobileTerminalInputActions.tsx +++ b/mobile/src/terminal/session/MobileTerminalInputActions.tsx @@ -1,4 +1,4 @@ -import type { RefObject } from 'react' +import { useContext, type RefObject } from 'react' import { ActivityIndicator, Pressable, @@ -17,7 +17,11 @@ import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import { keepHeldPressThroughLongPress } from '../../platform/held-press-long-press' import { dictationControlsCopy } from '../../dictation/mobile-dictation-controls-copy' import { useMobileDictationCancelDrop } from '../../dictation/use-mobile-dictation-cancel-drop' -import { MobileDictationMicIcon } from '../../dictation/MobileDictationLiveControls' +import { + MobileDictationMicIcon, + MobileDictationRetryButton +} from '../../dictation/MobileDictationLiveControls' +import { MobileDictationLiveContext } from '../../dictation/mobile-dictation-live-context' type DictationState = { readonly isStarting: boolean @@ -54,11 +58,20 @@ type MobileTerminalInputActionsProps = MobileTerminalDictationButtonProps & export function MobileTerminalInputActions(props: MobileTerminalInputActionsProps) { const { isStarting, isRecording, isProcessing } = props.dictation - // Attach steps aside while dictating so the words get the field's room. + const live = useContext(MobileDictationLiveContext) + // A kept failure is cleared by every start and Retry, so it never shows while dictating. + const failureReason = live?.failureReason ?? null + // Attach steps aside while dictating or holding a failed recording, so the field gets the room. return ( <> - {isStarting || isRecording || isProcessing ? null : } - + {isStarting || isRecording || isProcessing || failureReason !== null ? null : ( + + )} + {failureReason !== null && live ? ( + + ) : ( + + )} ) } diff --git a/mobile/src/terminal/session/MobileTerminalLiveInputStatus.tsx b/mobile/src/terminal/session/MobileTerminalLiveInputStatus.tsx index a60cf7965ba..45d018b21eb 100644 --- a/mobile/src/terminal/session/MobileTerminalLiveInputStatus.tsx +++ b/mobile/src/terminal/session/MobileTerminalLiveInputStatus.tsx @@ -12,6 +12,7 @@ import { import { MobileDictationLiveContext } from '../../dictation/mobile-dictation-live-context' import { MobileDictationCancelButton, + MobileDictationFailureNote, MobileDictationFinishingNote, MobileDictationRecordingMeter } from '../../dictation/MobileDictationLiveControls' @@ -37,6 +38,16 @@ export function MobileTerminalLiveInputStatus({ const t = useMobileTranslation() const live = useContext(MobileDictationLiveContext) const dictationTitle = mobileDictationStatusTitle(dictation) + if (live?.failureReason != null) { + return ( + + + + + + + ) + } if (!dictationTitle) { return isAttaching ? ( diff --git a/mobile/src/terminal/session/TerminalPaneView.tsx b/mobile/src/terminal/session/TerminalPaneView.tsx index b6c4d54013c..5cacb727223 100644 --- a/mobile/src/terminal/session/TerminalPaneView.tsx +++ b/mobile/src/terminal/session/TerminalPaneView.tsx @@ -31,6 +31,8 @@ type TerminalPaneViewProps = { terminalTheme?: RuntimeMobileTerminalTheme textScale: number onRef: (handle: string, ref: TerminalWebViewHandle | null) => void + // Must keep one identity: the pane reports its document gone when it unmounts. + onDocumentReleased: (handle: string) => void onWebReady: (handle: string) => void onSelectionMode: (handle: string, active: boolean) => void onSelectionCopy: (handle: string, text: string) => void @@ -63,6 +65,7 @@ export function TerminalPaneView({ terminalTheme, textScale, onRef, + onDocumentReleased, onWebReady, onSelectionMode, onSelectionCopy, @@ -82,10 +85,7 @@ export function TerminalPaneView({ }: TerminalPaneViewProps) { useMobileColorScheme() const t = useMobileTranslation() - const [visited, setVisited] = useState(visible) - if (visible && !visited) { - setVisited(true) - } + useEffect(() => () => onDocumentReleased(handle), [handle, onDocumentReleased]) const [routeFocused, setRouteFocused] = useState(false) useFocusEffect( useCallback(() => { @@ -113,13 +113,9 @@ export function TerminalPaneView({ ? terminalPaneKeyboardLayout(splitFrame, splitDirection, splitIndex, keyboardInset) : null - if (!visible && !visited) { - return null - } - return ( ${path}` ) @@ -168,8 +166,7 @@ beforeAll(async () => { ORCA_BACKGROUND_LAUNCH: '1', ORCA_POPUP_FIXTURE_ORIGIN: origin, ORCA_POPUP_FIXTURE_STATUS: statusPath, - ORCA_POPUP_FIXTURE_NATIVE_CONTROLS: nativeControls ? '1' : '0', - ORCA_POPUP_FIXTURE_ADAPTER_PROBE: adapterProbe ? '1' : '0' + ORCA_POPUP_FIXTURE_NATIVE_CONTROLS: nativeControls ? '1' : '0' }, stdio: ['ignore', 'pipe', 'pipe'] }) @@ -190,12 +187,7 @@ beforeAll(async () => { return current.ready === true }) expect(status()).toMatchObject({ ready: true, windowsHidden: true }) - const names = [ - 'local', - 'route', - ...(nativeControls ? ['local-control', 'route-control'] : []), - ...(adapterProbe ? ['probe-one', 'probe-two'] : []) - ] + const names = ['local', 'route', ...(nativeControls ? ['local-control', 'route-control'] : [])] for (const name of names) { await waitForFixture(() => Boolean( @@ -283,10 +275,6 @@ export async function closeChildren(page: Page): Promise { let evidenceName = 'electron-evidence.json' let nativeControls = false -let adapterProbe = false -export function enablePopupAdapterProbe(): void { - adapterProbe = true -} export function enablePopupFixtureNativeControls(): void { nativeControls = true } diff --git a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts index 4f8a7f81e70..bfd564a762f 100644 --- a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-electron-fixture.ts @@ -21,7 +21,6 @@ import type { BrowserRouteGuestLifecycleClaim, BrowserRoutePageGuestIdentity } from '../../../routing/guest-authority/browser-route-page-authority' -import { BrowserPopupAdapterProbeFixture } from './browser-popup-adapter-probe-fixture' const origin = process.env.ORCA_POPUP_FIXTURE_ORIGIN const statusPath = process.env.ORCA_POPUP_FIXTURE_STATUS @@ -50,10 +49,6 @@ let fixtureAuthority: symbol | null = authority let fixtureAuthorityThrows = false let revision = 0 let failure: string | undefined -const adapterProbe = - process.env.ORCA_POPUP_FIXTURE_ADAPTER_PROBE === '1' - ? new BrowserPopupAdapterProbeFixture(() => writeStatus()) - : null const native = new BrowserPopupNativeFixture({ routeSession: () => fixtureRouteSession, failAuthority: (throwOnRead) => { @@ -91,7 +86,6 @@ function writeStatus(error?: string): void { blocked, inputs, electronVersion: process.versions.electron, - adapterProbe: adapterProbe?.events, windowsHidden: BaseWindow.getAllWindows().every((window) => !window.isVisible()), guestIds: Object.fromEntries([...guests].map(([name, guest]) => [name, guest.id])) }) @@ -127,11 +121,7 @@ async function createHost(name: string, partition: string, nativeControl = false writeStatus() }) if (nativeControl) { - if (adapterProbe) { - adapterProbe.install(guest) - } else { - native.installControlHandler(guest) - } + native.installControlHandler(guest) await guest.loadURL(`${fixtureOrigin}/${name}`) resolve() return @@ -265,10 +255,6 @@ async function run(): Promise { await createHost('local-control', localPartition, true) await createHost('route-control', routePartition, true) } - if (adapterProbe) { - await createHost('probe-one', localPartition, true) - await createHost('probe-two', localPartition, true) - } ready = true writeStatus() } diff --git a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-status.ts b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-status.ts index 446732becea..5d42166dc50 100644 --- a/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-status.ts +++ b/src/main/browser/guest-lifecycle/popups/compatibility/browser-popup-compatibility-status.ts @@ -6,7 +6,6 @@ type PopupFixtureSecurity = { export type PopupCompatibilityStatus = { electronVersion: string - adapterProbe?: Record[] revision: number ready?: boolean error?: string diff --git a/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts b/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts index e3d42272402..567a3ad3c39 100644 --- a/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts +++ b/src/main/browser/identity/wire-probes/browser-session-ua-wire-identity.electron.test.ts @@ -43,13 +43,12 @@ afterAll(() => { } }) -type ProbeArm = 'clean' | 'late-session-setter' | 'mobile' | 'mixed-mobile' | 'native' +type ProbeArm = 'clean' type ProbeResult = Readonly<{ arm: ProbeArm rawUserAgent: string cleanUserAgent: string - mobileUserAgent: string sessionUserAgent: string navigatorUserAgent: string fallbackAfterReadyNameChange: string @@ -96,24 +95,6 @@ describe('browser session wire identity under Electron', () => { expect(distinctUserAgents(result.cdpRequests)).toEqual([result.cleanUserAgent]) expect(distinctJavaScriptUserAgents(result.identities)).toEqual([result.cleanUserAgent]) }, 40_000) - - it('keeps the process-native identity across documents, frames, and workers', async () => { - const result = await runProbe('native') - assertCoverage(result) - expect(identityForContext(result.identities, 'document').userAgent).toBe(result.rawUserAgent) - expect(identityForContext(result.identities, 'blob').userAgent).toBe(result.rawUserAgent) - expect(identityForContext(result.identities, 'shared-worker').userAgent).toBe( - result.rawUserAgent - ) - expect(identityForContext(result.identities, 'service-worker').userAgent).toBe( - result.rawUserAgent - ) - expect(userAgentForPath(result.receipts, '/')).toBe(result.rawUserAgent) - expect(userAgentForPath(result.receipts, '/blob-fetch')).toBe(result.rawUserAgent) - expect(userAgentForPath(result.receipts, '/shared-worker-fetch-a')).toBe(result.rawUserAgent) - expect(userAgentForPath(result.receipts, '/service-worker-fetch')).toBe(result.rawUserAgent) - expect(userAgentForPath(result.receipts, '/no-header-fill')).toBe(result.rawUserAgent) - }, 40_000) }) async function runProbe(arm: ProbeArm): Promise { @@ -238,11 +219,8 @@ const arm = ${JSON.stringify(options.arm)} const startupMarks = [] app.setName('OrcaWireIdentityFixture') const preReadyNativeUserAgent = app.userAgentFallback -let identity -if (arm !== 'late-session-setter') { - identity = processIdentity.initializeBrowserProcessUserAgent(arm === 'native' ? 'native' : 'clean') - startupMarks.push('fallback') -} +processIdentity.initializeBrowserProcessUserAgent('clean') +startupMarks.push('fallback') const waitForBarrier = async () => { const deadline = Date.now() + 15000 while (!existsSync(${JSON.stringify(options.barrierPath)})) { @@ -265,47 +243,22 @@ async function run() { await waitForBarrier() const sess = session.fromPartition('persist:wire-identity-test') startupMarks.push('session') - const rawUserAgent = arm === 'clean' ? preReadyNativeUserAgent : app.userAgentFallback - const cleanUserAgent = identity?.cleanUserAgent ?? cleanElectronUserAgent(rawUserAgent) - if (arm === 'late-session-setter') sess.setUserAgent(cleanUserAgent) + const rawUserAgent = preReadyNativeUserAgent + const cleanUserAgent = cleanElectronUserAgent(rawUserAgent) sess.setCertificateVerifyProc((_request, callback) => callback(0)) - const chromeVersion = cleanUserAgent.match(/Chrome\/([\d.]+)/)?.[1] || process.versions.chrome - const major = chromeVersion.split('.')[0] - const mobileUserAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/' + chromeVersion + ' Mobile/15E148 Safari/604.1' - let mainWebContentsId - if (arm === 'clean' || arm === 'mobile' || arm === 'mixed-mobile') { - sess.webRequest.onBeforeSendHeaders( - { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] }, - (details, callback) => { - const userAgentKey = Object.keys(details.requestHeaders).find( - key => key.toLowerCase() === 'user-agent' - ) || 'User-Agent' - if (arm !== 'mobile' && arm !== 'mixed-mobile') { - callback({ requestHeaders: details.requestHeaders }) - return - } - // Shared/service workers lack a guest id and keep their session identity. - if (details.webContentsId !== mainWebContentsId) { - callback({ requestHeaders: details.requestHeaders }) - return - } - details.requestHeaders[userAgentKey] = mobileUserAgent - callback({ requestHeaders: details.requestHeaders }) - } - ) - } + sess.webRequest.onBeforeSendHeaders( + { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] }, + (details, callback) => callback({ requestHeaders: details.requestHeaders }) + ) const windows = [] const window = new BrowserWindow({ show: false, webPreferences: { partition: 'persist:wire-identity-test', sandbox: true } }) windows.push(window) startupMarks.push('webContents') - mainWebContentsId = window.webContents.id - const pageIdentity = arm === 'native' ? rawUserAgent : arm === 'mobile' || arm === 'mixed-mobile' ? mobileUserAgent : cleanUserAgent - if (arm === 'native' || arm === 'mobile' || arm === 'mixed-mobile') window.webContents.setUserAgent(pageIdentity) window.webContents.setWindowOpenHandler(() => ({ action: 'allow', createWindow: options => { const popup = new BrowserWindow({ ...options, show: false }) - popup.webContents.setUserAgent(arm === 'native' ? rawUserAgent : cleanUserAgent) + popup.webContents.setUserAgent(cleanUserAgent) windows.push(popup) return popup.webContents } @@ -316,12 +269,6 @@ async function run() { window.webContents.executeJavaScript('window.probePromise'), requestWithoutUserAgent(sess, ${JSON.stringify(options.httpOrigin)} + '/no-header-fill') ]) - if (arm === 'mixed-mobile') { - const peer = new BrowserWindow({ show: false, webPreferences: { partition: 'persist:wire-identity-test', sandbox: true } }) - windows.push(peer) - await peer.loadURL(${JSON.stringify(options.httpOrigin)} + '/desktop-peer') - await peer.webContents.executeJavaScript('window.peerProbePromise') - } const defaultWindow = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }) windows.push(defaultWindow) await defaultWindow.loadURL(${JSON.stringify(options.httpOrigin)} + '/default-window') @@ -334,7 +281,7 @@ async function run() { ]) await new Promise(resolve => setTimeout(resolve, 250)) clearTimeout(timeout) - writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ arm, rawUserAgent, cleanUserAgent, mobileUserAgent, sessionUserAgent: sess.getUserAgent(), navigatorUserAgent, fallbackAfterReadyNameChange, startupMarks })) + writeFileSync(${JSON.stringify(options.resultPath)}, JSON.stringify({ arm, rawUserAgent, cleanUserAgent, sessionUserAgent: sess.getUserAgent(), navigatorUserAgent, fallbackAfterReadyNameChange, startupMarks })) for (const candidate of windows) if (!candidate.isDestroyed()) candidate.destroy() app.exit(0) } @@ -356,9 +303,6 @@ function assertCoverage(result: ProbeResult): void { true ) const expectedContexts = ['blob', 'document', 'frame', 'popup', 'service-worker', 'shared-worker'] - if (result.arm === 'mixed-mobile') { - expectedContexts.push('desktop-peer', 'shared-worker') - } expect(result.identities.map(({ context }) => context).sort()).toEqual(expectedContexts.sort()) } @@ -370,21 +314,6 @@ function distinctJavaScriptUserAgents(records: readonly WireProbeJavaScriptIdent return [...new Set(records.map(({ userAgent }) => userAgent))].sort() } -function userAgentForPath(receipts: readonly WireProbeReceipt[], path: string): string | null { - const values = distinctUserAgents(receipts.filter((receipt) => receipt.path === path)) - expect(values, path).toHaveLength(1) - return values[0] ?? null -} - -function identityForContext( - identities: readonly WireProbeJavaScriptIdentity[], - context: string -): WireProbeJavaScriptIdentity { - const matches = identities.filter((identity) => identity.context === context) - expect(matches, context).toHaveLength(1) - return matches[0]! -} - async function reservePort(): Promise { const server = createServer() await new Promise((resolve, reject) => { diff --git a/src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts b/src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts deleted file mode 100644 index 2e5bc3ae600..00000000000 --- a/src/main/browser/sessions/profiles/browser-session-registry-identity.persistence.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - createFsState, - IDENTITY_RECORD_PATH, - installModuleMocks, - seedMeta -} from './browser-session-registry-persistence-test-fixture' - -describe('BrowserSessionRegistry retired identity data', () => { - beforeEach(() => { - vi.resetModules() - vi.restoreAllMocks() - }) - - it('does not re-arm the retired-choice notice on the launch after an explicit choice', async () => { - const profileId = '11111111-1111-4111-8111-111111111111' - const fsState = createFsState() - seedMeta(fsState, { - defaultSource: null, - profiles: [ - { - id: profileId, - scope: 'isolated', - partition: `persist:orca-browser-session-${profileId}`, - label: 'Existing', - source: null, - userAgentMode: 'native' - } - ] - }) - - installModuleMocks(fsState) - const { browserSessionRegistry } = await import('./browser-session-registry') - const identity = await import('../../identity/mode/browser-identity-mode-store') - - browserSessionRegistry.initializeBrowserSessionsFromPersistedState() - expect(identity.getBrowserIdentityMigrationNotice()).toEqual({ degraded: false }) - - await identity.setBrowserIdentityMode('native') - expect(identity.getBrowserIdentityMigrationNotice()).toBeNull() - - identity.resetBrowserIdentityModeStoreForTests() - browserSessionRegistry.initializeBrowserSessionsFromPersistedState() - - expect(identity.getBrowserIdentityMigrationNotice()).toBeNull() - expect(JSON.parse(fsState.files.get(IDENTITY_RECORD_PATH) ?? '{}')).toMatchObject({ - explicitSelection: true, - migrationNoticePending: false - }) - }) -}) diff --git a/src/main/browser/sessions/profiles/browser-session-registry-persistence-test-fixture.ts b/src/main/browser/sessions/profiles/browser-session-registry-persistence-test-fixture.ts deleted file mode 100644 index 077d59bbfad..00000000000 --- a/src/main/browser/sessions/profiles/browser-session-registry-persistence-test-fixture.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { vi } from 'vitest' - -type RegistryMock = ReturnType - -export const USER_DATA = '/user-data' -export const META_PATH = `${USER_DATA}/browser-session-meta.json` -export const IDENTITY_RECORD_PATH = `${USER_DATA}/browser-identity-mode.json` -export const SITE_PERMISSIONS_PATH = `${USER_DATA}/browser-site-permissions.json` -export const CLEAN_USER_AGENT = - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.7871.224 Safari/537.36' - -export type FsState = { - files: Map - present: Set -} - -const fsKey = (pathValue: string): string => pathValue.replaceAll('\\', '/') - -export const createFsState = (): FsState => ({ files: new Map(), present: new Set() }) - -export function seedMeta(fsState: FsState, meta: unknown): void { - const raw = JSON.stringify(meta) - fsState.files.set(META_PATH, raw) - fsState.present.add(META_PATH) -} - -export function seedSitePermissions(fsState: FsState, profiles: unknown): void { - fsState.files.set(SITE_PERMISSIONS_PATH, JSON.stringify({ version: 1, profiles })) - fsState.present.add(SITE_PERMISSIONS_PATH) -} - -export type BrowserSessionRegistryMocks = { - sessionFromPartitionMock: RegistryMock - installBrowserSessionUserAgentPolicyMock: RegistryMock - browserManagerHandleGuestWillDownloadMock: RegistryMock - browserManagerNotifyPermissionDeniedMock: RegistryMock - requestSystemMediaAccessMock: RegistryMock -} - -export function installModuleMocks( - fsState: FsState, - copyFailures = new Set(), - failIdentityWrite = false -): BrowserSessionRegistryMocks { - const sessionFromPartitionMock: ReturnType = vi.fn((partition: string) => ({ - partition, - setUserAgent: vi.fn(), - getUserAgent: vi.fn(() => CLEAN_USER_AGENT), - setPermissionRequestHandler: vi.fn(), - setPermissionCheckHandler: vi.fn(), - setDevicePermissionHandler: vi.fn(), - setDisplayMediaRequestHandler: vi.fn(), - on: vi.fn(), - removeListener: vi.fn(), - clearStorageData: vi.fn().mockResolvedValue(undefined), - clearCache: vi.fn().mockResolvedValue(undefined) - })) - const installBrowserSessionUserAgentPolicyMock: RegistryMock = vi.fn(() => vi.fn()) - const browserManagerHandleGuestWillDownloadMock: RegistryMock = vi.fn() - const browserManagerNotifyPermissionDeniedMock: RegistryMock = vi.fn() - const requestSystemMediaAccessMock: RegistryMock = vi.fn().mockResolvedValue(true) - - vi.doMock('electron', () => ({ - app: { getPath: vi.fn(() => USER_DATA) }, - session: { fromPartition: sessionFromPartitionMock }, - systemPreferences: { - askForMediaAccess: vi.fn().mockResolvedValue(true), - getMediaAccessStatus: vi.fn(() => 'granted') - } - })) - - vi.doMock('node:fs', () => ({ - // Identity persistence uses the durable writer's fsync/rename path. - closeSync: vi.fn(), - fsyncSync: vi.fn(), - openSync: vi.fn(() => 1), - rmSync: vi.fn((p: string) => { - const key = fsKey(p) - fsState.present.delete(key) - fsState.files.delete(key) - }), - copyFileSync: vi.fn((src: string, dst: string) => { - const sourceKey = fsKey(src) - const destinationKey = fsKey(dst) - if (copyFailures.has(sourceKey)) { - throw new Error(`copy fail for ${src}`) - } - fsState.present.add(destinationKey) - const value = fsState.files.get(sourceKey) - if (value !== undefined) { - fsState.files.set(destinationKey, value) - } - }), - existsSync: vi.fn((p: string) => fsState.present.has(fsKey(p))), - mkdirSync: vi.fn(), - statSync: vi.fn(() => ({ mtimeMs: 0 })), - readFileSync: vi.fn((p: string) => { - const v = fsState.files.get(fsKey(p)) - if (v === undefined) { - // A missing error code would mark the file unreadable and block writes. - throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }) - } - return v - }), - renameSync: vi.fn((from: string, to: string) => { - const sourceKey = fsKey(from) - const destinationKey = fsKey(to) - const v = fsState.files.get(sourceKey) - if (v === undefined) { - throw new Error('ENOENT') - } - fsState.files.set(destinationKey, v) - fsState.present.add(destinationKey) - fsState.files.delete(sourceKey) - fsState.present.delete(sourceKey) - }), - unlinkSync: vi.fn((p: string) => { - const key = fsKey(p) - fsState.present.delete(key) - fsState.files.delete(key) - }), - writeFileSync: vi.fn((p: string, data: string | Uint8Array) => { - if (failIdentityWrite && fsKey(p).includes('browser-identity-mode.json')) { - throw new Error('read-only userData') - } - const value = typeof data === 'string' ? data : Buffer.from(data).toString('utf-8') - const key = fsKey(p) - fsState.files.set(key, value) - fsState.present.add(key) - }) - })) - - vi.doMock('../../guest-lifecycle/manager/browser-manager', () => ({ - browserManager: { - notifyPermissionDenied: browserManagerNotifyPermissionDeniedMock, - handleGuestWillDownload: browserManagerHandleGuestWillDownloadMock, - installCertificateRequestGuard: vi.fn(), - removeCertificateRequestGuard: vi.fn(), - resolvePagePromptTarget: vi.fn(() => null) - } - })) - vi.doMock('../../site-settings/permissions/browser-media-access', () => ({ - hasSystemMediaAccess: vi.fn(() => true), - requestSystemMediaAccess: requestSystemMediaAccessMock - })) - vi.doMock('../../identity/requests/browser-session-ua', () => ({ - installBrowserSessionUserAgentPolicy: installBrowserSessionUserAgentPolicyMock - })) - vi.doMock('../../identity/browser-process-user-agent', () => ({ - getBrowserProcessUserAgentIdentity: () => ({ - mode: 'clean', - userAgent: CLEAN_USER_AGENT - }) - })) - vi.doMock('../../../persistence/loading-store/user-data-path', () => ({ - getCanonicalUserDataPath: () => USER_DATA - })) - // Model legacy unmarked stages; real SQLite merges have separate file-backed coverage. - vi.doMock('../../cookies/staging/browser-cookie-staged-import', () => ({ - SCOPED_COOKIE_IMPORT_FORMAT: 'scoped-v1', - InvalidStagedCookieImportError: class extends Error {}, - isPermanentStagedCookieImportFailure: vi.fn(() => false), - applyScopedStagedCookieImport: vi.fn(() => false), - isScopedStagedCookieImport: vi.fn(() => false), - removeCookieImportScopeMarker: vi.fn() - })) - const renameFileWithWindowsRetryMock = vi.fn((source: string, target: string) => { - const sourceKey = fsKey(source) - const targetKey = fsKey(target) - if (!fsState.present.has(sourceKey)) { - throw new Error('ENOENT') - } - const value = fsState.files.get(sourceKey) - fsState.present.delete(sourceKey) - fsState.files.delete(sourceKey) - fsState.present.add(targetKey) - if (value !== undefined) { - fsState.files.set(targetKey, value) - } - }) - vi.doMock('../../../../shared/windows-retry-file-operations', async (importOriginal) => ({ - ...(await importOriginal>()), - renameFileWithWindowsRetry: renameFileWithWindowsRetryMock - })) - vi.doMock('../../../filesystem/atomic-file-publication', () => ({ - writeFileAtomically: vi.fn((pathValue: string, data: string) => { - const key = fsKey(pathValue) - fsState.files.set(key, data) - fsState.present.add(key) - }) - })) - - return { - sessionFromPartitionMock, - installBrowserSessionUserAgentPolicyMock, - browserManagerHandleGuestWillDownloadMock, - browserManagerNotifyPermissionDeniedMock, - requestSystemMediaAccessMock - } -} diff --git a/src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts b/src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts deleted file mode 100644 index 5d8abc958d8..00000000000 --- a/src/main/browser/sessions/profiles/browser-session-registry-startup-metadata.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { - DEFAULT_LOCAL_ORCA_PROFILE_ID, - getOrcaProfileBrowserSessionPartition -} from '../../../../shared/orca-profiles' -import { - createFsState, - installModuleMocks, - META_PATH, - seedMeta -} from './browser-session-registry-persistence-test-fixture' - -describe('browser profile startup metadata reads', () => { - beforeEach(() => { - vi.resetModules() - vi.restoreAllMocks() - }) - - it.each([10, 100])( - 'reads one snapshot when restoring %i profiles and keeps extension assignments current', - async (count) => { - const fsState = createFsState() - const profiles = Array.from({ length: count }, (_, index) => { - const id = `00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}` - return { - id, - scope: 'isolated', - partition: getOrcaProfileBrowserSessionPartition(DEFAULT_LOCAL_ORCA_PROFILE_ID, id), - label: `Browser ${index}`, - source: null - } - }) - const enabledExtensionIdsByProfileId = Object.fromEntries([ - ['default', ['default-extension']], - ...profiles.map((profile, index) => [profile.id, [`extension-${index}`]]) - ]) - seedMeta(fsState, { profiles, enabledExtensionIdsByProfileId }) - installModuleMocks(fsState) - const attachExtensions = vi.fn() - vi.doMock('../../extensions/profile-sessions/browser-extension-session-loader', () => ({ - attachBrowserExtensionsToProfileSession: attachExtensions - })) - const { browserSessionRegistry } = await import('./browser-session-registry') - const { readFileSync } = await import('node:fs') - vi.mocked(readFileSync).mockClear() - - browserSessionRegistry.initializeBrowserSessionsFromPersistedState() - - expect( - vi.mocked(readFileSync).mock.calls.filter(([path]) => path === META_PATH) - ).toHaveLength(1) - expect(browserSessionRegistry.listProfiles()).toHaveLength(count + 1) - expect(attachExtensions).toHaveBeenCalledTimes(count + 1) - for (const profile of browserSessionRegistry.listProfiles()) { - expect(attachExtensions).toHaveBeenCalledWith( - profile, - enabledExtensionIdsByProfileId[profile.id] - ) - } - - seedMeta(fsState, { - profiles, - enabledExtensionIdsByProfileId: { default: ['new-extension'] } - }) - attachExtensions.mockClear() - vi.mocked(readFileSync).mockClear() - - browserSessionRegistry.initializeBrowserSessionsFromPersistedState() - - expect( - vi.mocked(readFileSync).mock.calls.filter(([path]) => path === META_PATH) - ).toHaveLength(1) - expect(attachExtensions).toHaveBeenCalledWith(browserSessionRegistry.getDefaultProfile(), [ - 'new-extension' - ]) - for (const profile of profiles) { - expect(attachExtensions).toHaveBeenCalledWith(profile, []) - } - } - ) -}) diff --git a/src/main/browser/sessions/profiles/browser-session-registry.test.ts b/src/main/browser/sessions/profiles/browser-session-registry.test.ts index 23c38b85923..eabc72c18b7 100644 --- a/src/main/browser/sessions/profiles/browser-session-registry.test.ts +++ b/src/main/browser/sessions/profiles/browser-session-registry.test.ts @@ -64,11 +64,6 @@ import { deleteManagedBrowserProfile, ensureManagedBrowserProfile } from './browser-managed-session-profiles' -import { - configureBrowserSitePermissionStore, - listBrowserSitePermissions, - setBrowserSitePermissionDecisions -} from '../../site-settings/permissions/browser-site-permission-store' import { setBrowserNetworkProxySettingsResolver } from '../proxy/browser-session-proxy' import { handleElectronProxyLogin } from '../../../network/electron-proxy-credentials' import { applyProxySettingsToSession } from '../../../network/proxy-settings' @@ -208,19 +203,6 @@ describe('BrowserSessionRegistry', () => { ).rejects.toThrow('retired') }) - it('deletes a non-default profile and its remembered site answers', async () => { - configureBrowserSitePermissionStore(mkdtempSync(join(tmpdir(), 'orca-site-permissions-'))) - const profile = await browserSessionRegistry.createProfile('isolated', 'Delete Test') - expect(profile).not.toBeNull() - expect(browserSessionRegistry.isAllowedPartition(profile!.partition)).toBe(true) - setBrowserSitePermissionDecisions(profile!.id, 'https://example.com', ['camera'], 'allow') - const deleted = await browserSessionRegistry.deleteProfile(profile!.id) - expect(deleted).toBe(true) - expect(browserSessionRegistry.isAllowedPartition(profile!.partition)).toBe(false) - expect(browserSessionRegistry.getProfile(profile!.id)).toBeNull() - expect(listBrowserSitePermissions(profile!.id)).toEqual([]) - }) - // Electron Sessions outlive deleted profiles; their header hooks must be retired. it('creates one managed profile per owner and a fresh one after its owner is removed', async () => { @@ -245,32 +227,4 @@ describe('BrowserSessionRegistry', () => { const recreated = await ensureManagedBrowserProfile(owner, 'Workspace: feature') expect(recreated?.partition).not.toBe(first.partition) }) - - it('announces each profile change after the list reflects it', async () => { - const seen: string[][] = [] - browserSessionRegistry.onProfilesChanged = () => - seen.push(browserSessionRegistry.listProfiles().map((profile) => profile.label)) - try { - const made = await browserSessionRegistry.createProfile('isolated', 'Made by CLI') - const managed = await ensureManagedBrowserProfile({ kind: 'repo', id: 'announce' }, 'Repo') - if (!made || !managed) { - throw new Error('Expected created profiles') - } - browserSessionRegistry.updateProfileSource(made.id, { - browserFamily: 'manual', - importedAt: 1 - }) - await browserSessionRegistry.deleteProfile(made.id) - await browserSessionRegistry.deleteProfile('default') - await browserSessionRegistry.createProfile('default', 'Refused') - - expect(seen).toHaveLength(4) - expect(seen[0]).toContain('Made by CLI') - expect(seen[1]).toContain('Repo') - expect(seen[2]).toContain('Made by CLI') - expect(seen[3]).not.toContain('Made by CLI') - } finally { - browserSessionRegistry.onProfilesChanged = null - } - }) }) diff --git a/src/main/browser/sessions/proxy/browser-session-proxy.test.ts b/src/main/browser/sessions/proxy/browser-session-proxy.test.ts index 7f5a406d072..ff182459a9d 100644 --- a/src/main/browser/sessions/proxy/browser-session-proxy.test.ts +++ b/src/main/browser/sessions/proxy/browser-session-proxy.test.ts @@ -28,33 +28,11 @@ vi.mock('electron', () => ({ import { applyBrowserSessionProxies, - awaitBrowserSessionProxies, applyProxyToBrowserSession, invalidateBrowserSessionProxyApplication, setBrowserNetworkProxySettingsResolver } from './browser-session-proxy' -import { - applyProxySettingsToSession, - releaseProxySessionApplication -} from '../../../network/proxy-settings' -import type { NetworkProxySettings } from '../../../../shared/network-proxy' - -const PROFILES = [ - { - id: 'default', - scope: 'default' as const, - partition: 'persist:orca-browser', - label: 'Default', - source: null - }, - { - id: 'iso', - scope: 'isolated' as const, - partition: 'persist:orca-browser-session-iso', - label: 'Isolated', - source: null - } -] +import { releaseProxySessionApplication } from '../../../network/proxy-settings' describe('browser session proxy', () => { beforeEach(() => { @@ -112,129 +90,4 @@ describe('browser session proxy', () => { [{ mode: 'system' }] ]) }) - - describe('startup readiness', () => { - beforeEach(() => { - for (const key of [ - 'http_proxy', - 'https_proxy', - 'all_proxy', - 'HTTP_PROXY', - 'HTTPS_PROXY', - 'ALL_PROXY' - ]) { - vi.stubEnv(key, '') - } - setBrowserNetworkProxySettingsResolver(() => ({})) - }) - - afterEach(() => vi.unstubAllEnvs()) - - it('awaits installed policies without reapplying them and keeps later system probes fresh', async () => { - const sessions = PROFILES.map((profile) => fromPartition(profile.partition)) - const finishResolutions: (() => void)[] = [] - for (const sess of sessions) { - sess.resolveProxy.mockImplementationOnce( - () => - new Promise((resolve) => { - finishResolutions.push(() => resolve('DIRECT')) - }) - ) - } - const installations = sessions.map((sess) => applyProxySettingsToSession(sess, {})) - let settled = false - const startup = awaitBrowserSessionProxies(PROFILES).then(() => (settled = true)) - - await vi.waitFor(() => expect(finishResolutions).toHaveLength(PROFILES.length)) - expect(settled).toBe(false) - for (const finish of finishResolutions) { - finish() - } - await Promise.all([...installations, startup]) - await awaitBrowserSessionProxies(PROFILES) - - for (const sess of sessions) { - expect(sess.resolveProxy).toHaveBeenCalledOnce() - expect(sess.setProxy).not.toHaveBeenCalled() - sess.resolveProxy.mockResolvedValue('PROXY changed-system.example:8080') - } - await applyBrowserSessionProxies(PROFILES, {}) - for (const sess of sessions) { - expect(sess.resolveProxy).toHaveBeenCalledTimes(2) - } - }) - - it('awaits every installation and preserves failed-partition warnings and retry budget', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const failed = fromPartition('persist:orca-browser') - failed.resolveProxy.mockRejectedValue(new Error('native proxy failure')) - await expect(applyProxySettingsToSession(failed, {})).rejects.toThrow('native proxy failure') - const healthy = fromPartition('persist:orca-browser-session-iso') - let finishHealthy: (() => void) | undefined - healthy.resolveProxy.mockImplementationOnce( - () => new Promise((resolve) => (finishHealthy = () => resolve('DIRECT'))) - ) - const installation = applyProxySettingsToSession(healthy, {}) - let settled = false - const startup = awaitBrowserSessionProxies(PROFILES).finally(() => (settled = true)) - const failure = expect(startup).rejects.toThrow('persist:orca-browser') - - await vi.waitFor(() => expect(failed.resolveProxy).toHaveBeenCalledTimes(6)) - expect(settled).toBe(false) - finishHealthy?.() - await Promise.all([installation, failure]) - - expect(healthy.resolveProxy).toHaveBeenCalledOnce() - expect(warn).toHaveBeenCalledExactlyOnceWith( - '[proxy] Failed to apply proxy to browser partition', - 'persist:orca-browser' - ) - }) - - it.each([false, true])( - 'awaits the newest settings write when the initial policy fails=%s', - async (initialFails) => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) - const profiles = PROFILES.slice(0, 1) - const sess = fromPartition('persist:orca-browser') - let settings: NetworkProxySettings = {} - setBrowserNetworkProxySettingsResolver(() => settings) - let finishInitial: (() => void) | undefined - sess.resolveProxy.mockImplementationOnce( - () => - new Promise((resolve, reject) => { - finishInitial = () => - initialFails ? reject(new Error('native proxy failure')) : resolve('DIRECT') - }) - ) - if (initialFails) { - sess.resolveProxy.mockRejectedValueOnce(new Error('native proxy failure')) - sess.resolveProxy.mockRejectedValueOnce(new Error('native proxy failure')) - } - let finishWrite: (() => void) | undefined - sess.setProxy.mockImplementationOnce( - () => new Promise((resolve) => (finishWrite = resolve)) - ) - const installation = applyProxySettingsToSession(sess, {}).catch((error: unknown) => error) - let settled = false - const startup = awaitBrowserSessionProxies(profiles).then(() => (settled = true)) - await vi.waitFor(() => expect(sess.resolveProxy).toHaveBeenCalledOnce()) - settings = { httpProxyUrl: 'http://fresh.example:8080' } - const sweep = applyBrowserSessionProxies(profiles, settings) - finishInitial?.() - - await vi.waitFor(() => expect(sess.setProxy).toHaveBeenCalledOnce()) - expect(settled).toBe(false) - finishWrite?.() - await Promise.all([installation, startup, sweep]) - - expect(sess.resolveProxy).toHaveBeenCalledTimes(initialFails ? 3 : 1) - expect(sess.setProxy).toHaveBeenCalledExactlyOnceWith({ - mode: 'fixed_servers', - proxyRules: 'http://fresh.example:8080' - }) - expect(warn).not.toHaveBeenCalled() - } - ) - }) }) diff --git a/src/main/browser/site-settings/display/browser-site-display-controller.test.ts b/src/main/browser/site-settings/display/browser-site-display-controller.test.ts index 9f304231229..8ef505bf2d9 100644 --- a/src/main/browser/site-settings/display/browser-site-display-controller.test.ts +++ b/src/main/browser/site-settings/display/browser-site-display-controller.test.ts @@ -178,9 +178,7 @@ describe('BrowserSiteDisplayController color scheme', () => { it.each([ { order: 'read-first', profileId: 'work', colorScheme: 'light', saved: 'dark' }, - { order: 'registration-first', profileId: 'work', colorScheme: 'light', saved: 'dark' }, - { order: 'read-first', profileId: 'default', colorScheme: 'dark', saved: 'light' }, - { order: 'registration-first', profileId: 'default', colorScheme: 'dark', saved: 'light' } + { order: 'registration-first', profileId: 'work', colorScheme: 'light', saved: 'dark' } ] as const)( 'keeps actual $profileId precedence across $order, reload and debugger loss', ({ order, profileId, colorScheme, saved }) => { diff --git a/src/main/claude/__fixtures__/claude-parent-task-stop-2.1.319.jsonl b/src/main/claude/__fixtures__/claude-parent-task-stop-2.1.319.jsonl new file mode 100644 index 00000000000..f61bb00f483 --- /dev/null +++ b/src/main/claude/__fixtures__/claude-parent-task-stop-2.1.319.jsonl @@ -0,0 +1,10 @@ +{"at":4444,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","task_type":"local_agent","subagent_type":"general-purpose","description":"Parent ownership probe"}],"uuid":"parent-task-frame-1","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":4446,"frame":{"type":"system","subtype":"task_started","task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","tool_use_id":"toolu_parent","description":"Parent ownership probe","subagent_type":"general-purpose","is_backgrounded":true,"spawn_depth":1,"task_type":"local_agent","prompt":"First use Bash with run_in_background true to run `sleep 100`. Then use Bash in the foreground to run `sleep 100`. Do not run any other commands. When both are done, briefly report that you finished.","uuid":"parent-task-frame-2","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7437,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","task_type":"local_agent","subagent_type":"general-purpose","description":"Parent ownership probe"},{"task_id":"shell-child","run_id":"0mw894jxj-fd21549d","task_type":"local_bash","description":"Sleep 100 seconds in background","parent_task_id":"agent-parent"}],"uuid":"parent-task-frame-3","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7439,"frame":{"type":"system","subtype":"task_started","task_id":"shell-child","run_id":"0mw894jxj-fd21549d","owned_by_subagent":true,"tool_use_id":"toolu_shell","description":"Sleep 100 seconds in background","is_backgrounded":true,"parent_task_id":"agent-parent","task_type":"local_bash","uuid":"parent-task-frame-4","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7446,"frame":{"type":"system","subtype":"task_updated","task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","patch":{"status":"killed","end_time":1794167703280},"uuid":"parent-task-frame-5","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7446,"frame":{"type":"system","subtype":"task_notification","task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","tool_use_id":"toolu_parent","status":"stopped","output_file":"/tmp/claude/tasks/agent-parent.output","summary":"Parent ownership probe","uuid":"parent-task-frame-6","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7446,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"shell-child","run_id":"0mw894jxj-fd21549d","task_type":"local_bash","description":"Sleep 100 seconds in background","parent_task_id":"agent-parent"}],"uuid":"parent-task-frame-7","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7449,"frame":{"type":"system","subtype":"task_updated","task_id":"shell-child","run_id":"0mw894jxj-fd21549d","patch":{"status":"killed","end_time":1794167703284},"uuid":"parent-task-frame-8","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7450,"frame":{"type":"system","subtype":"task_notification","task_id":"shell-child","run_id":"0mw894jxj-fd21549d","tool_use_id":"toolu_shell","status":"stopped","output_file":"/tmp/claude/tasks/shell-child.output","summary":"Sleep 100 seconds in background","uuid":"parent-task-frame-9","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} +{"at":7450,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[],"uuid":"parent-task-frame-10","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}} diff --git a/src/main/claude/claude-agent-sdk-control-requests.test.ts b/src/main/claude/claude-agent-sdk-control-requests.test.ts index f2e7f19fff6..ccec589542b 100644 --- a/src/main/claude/claude-agent-sdk-control-requests.test.ts +++ b/src/main/claude/claude-agent-sdk-control-requests.test.ts @@ -6,6 +6,21 @@ afterEach(() => { vi.useRealTimers() }) +it('bounds the optional persisted title request and ignores its late response', async () => { + vi.useFakeTimers() + const pending = Promise.withResolvers() + const generateSessionTitle = vi.fn(() => pending.promise) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the feature-detected method is called. + const controls = createClaudeControlSurface({ generateSessionTitle } as unknown as Query) + const result = controls.generateSessionTitle!('Repair login') + const expired = expect(result).rejects.toThrow('claude generate_session_title request timed out') + await vi.advanceTimersByTimeAsync(30_000) + await expired + pending.resolve('Late title') + await expect(result).rejects.toThrow('timed out') + expect(generateSessionTitle).toHaveBeenCalledWith('Repair login', { persist: true }) +}) + describe('createClaudeControlSurface stopTask', () => { it('bounds a lost reply and permits a later stop request', async () => { vi.useFakeTimers() diff --git a/src/main/claude/claude-agent-sdk-control-requests.ts b/src/main/claude/claude-agent-sdk-control-requests.ts index 980093a4e9c..addeba66e28 100644 --- a/src/main/claude/claude-agent-sdk-control-requests.ts +++ b/src/main/claude/claude-agent-sdk-control-requests.ts @@ -114,6 +114,7 @@ export type ClaudeControlSurface = { getContextUsage: (options?: ClaudeControlOptions) => Promise /** Names `sessionId` as the user's rename; refused once the CLI has moved to another session. */ renameSession: (title: string, sessionId: string, options?: ClaudeControlOptions) => Promise + generateSessionTitle?: (description: string) => Promise } type InterruptingQuery = { @@ -123,7 +124,16 @@ type InterruptingQuery = { } export function createClaudeControlSurface(query: Query): ClaudeControlSurface { + const title = 'generateSessionTitle' in query ? query.generateSessionTitle : null return { + ...(typeof title === 'function' + ? { + generateSessionTitle: (description: string) => + runClaudeControl('generate_session_title', () => + Promise.resolve(title.call(query, description, { persist: true })) + ) + } + : {}), interrupt: (options) => runClaudeControl( 'interrupt', diff --git a/src/main/claude/claude-background-stop-records.test.ts b/src/main/claude/claude-background-stop-records.test.ts index 31e7a477a0c..6d9e034bfd3 100644 --- a/src/main/claude/claude-background-stop-records.test.ts +++ b/src/main/claude/claude-background-stop-records.test.ts @@ -8,6 +8,7 @@ import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/ag import { agentChildWorkLiveness } from '../../shared/agent-status/child-work/agent-status-child-work-liveness' import { conversationCommandBlocked } from '../native-chat/agent-session-wire/operations/structured-conversation-command-admission' import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' +import { PARENT_TASK_STOP } from './claude-parent-task-frames.test-fixture' import { RESUMED_BY_MESSAGE } from './claude-captured-task-frames.test-fixture' import { hostWithParent, parent, producer } from './claude-child-work-producer-harness.test-fixture' @@ -54,7 +55,6 @@ async function droppedFromRoster() { expect(records()).toMatchObject([ { membership: 'live', stoppable: true, providerId: 'agent-1', kind: 'agent' } ]) - expect(run.adapter.backgroundTaskState('session-1')).toBeNull() expect(blocked()?.message).toBe('Stop background tasks before using this command.') // Snapshot stop targets before dispatch; settle only acknowledged records. const stop = async (taskId?: string) => { @@ -78,6 +78,46 @@ async function droppedFromRoster() { } describe('a background Stop acts on the host child records', () => { + it('keeps a stopped owner and its independently stoppable shell attached from real task frames', async () => { + const host = hostWithParent() + const run = await producer(host) + run.replay(PARENT_TASK_STOP.slice(0, 7)) + const owner = run.records().find((record) => record.kind === 'agent') + expect(owner).toMatchObject({ membership: 'settled', outcome: 'cancelled' }) + expect(run.records().find((record) => record.kind === 'command')).toMatchObject({ + membership: 'live', + stoppable: true, + parentChildWorkId: owner?.childWorkId + }) + const targets = agentChildWorkStopTargets( + host.getStructuredChildWorkViews(parent), + 'shell-child' + ) + expect(targets.map((target) => target.providerId)).toEqual(['shell-child']) + await run.adapter.stopBackgroundTasks({ + sessionId: 'session-1', + fence: 7, + taskIds: targets.map((target) => target.providerId) + }) + expect(run.claude.connections[0]!.calls.filter((call) => call.subtype === 'stop_task')).toEqual( + [{ subtype: 'stop_task', params: { taskId: 'shell-child' } }] + ) + run.replay(PARENT_TASK_STOP.slice(7)) + expect(run.records().find((record) => record.kind === 'command')).toMatchObject({ + membership: 'settled', + outcome: 'cancelled' + }) + + // Start-only delivery in reverse owner order must converge too; no original tool traffic is replayed. + const childFirst = await producer() + childFirst.replay([PARENT_TASK_STOP[3]!, PARENT_TASK_STOP[1]!]) + const resolvedOwner = childFirst.records().find((record) => record.kind === 'agent') + expect(childFirst.records().find((record) => record.kind === 'command')).toMatchObject({ + membership: 'live', + parentChildWorkId: resolvedOwner?.childWorkId + }) + }) + it("stops the row's own task, which the records keep after the roster dropped it", async () => { const { records, blocked, stopCalls, stop, basis } = await droppedFromRoster() diff --git a/src/main/claude/claude-background-task-frames.ts b/src/main/claude/claude-background-task-frames.ts index 5b776d6af04..c2948a166e9 100644 --- a/src/main/claude/claude-background-task-frames.ts +++ b/src/main/claude/claude-background-task-frames.ts @@ -88,3 +88,15 @@ export function liveClaudeTaskRunState(status: unknown): AgentSessionBackgroundT return null } } + +export const CLAUDE_BACKGROUND_TASK_ROW_SUBTYPES: ReadonlySet = new Set([ + 'task_started', + 'task_updated', + 'task_progress', + 'task_notification' +]) + +export const CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES: ReadonlySet = new Set([ + 'task_progress', + 'background_tasks_changed' +]) diff --git a/src/main/claude/claude-background-task-identity.ts b/src/main/claude/claude-background-task-identity.ts new file mode 100644 index 00000000000..2d19b843dde --- /dev/null +++ b/src/main/claude/claude-background-task-identity.ts @@ -0,0 +1,107 @@ +import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity' +import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' +import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types' +import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' + +export type ClaudeBackgroundTaskDescriptor = { + identity: AgentJournalItemIdentity + generation: number + toolUseId?: string + linkage: AgentJournalProducerLinkage +} + +export type ClaudeBackgroundTaskIndex = { + latest?: ClaudeBackgroundTaskDescriptor + unresolved?: ClaudeBackgroundTaskDescriptor + aliases: Map +} + +export function claudeBackgroundTaskIdentity( + taskId: string, + generation = 1 +): AgentJournalItemIdentity { + return { + provider: 'orca', + clientMessageId: `claude-background-task:${taskId}${generation > 1 ? `#${generation}` : ''}` + } +} + +export function indexClaudeBackgroundTask( + index: ClaudeBackgroundTaskIndex, + itemId: string, + taskId: string, + toolUseId: string | undefined, + linkage: AgentJournalProducerLinkage +): void { + const identity = parseAgentJournalItemKey(itemId) + if (identity?.provider !== 'orca') { + return + } + const base = `claude-background-task:${taskId}` + const generation = + identity.clientMessageId === base + ? 1 + : identity.clientMessageId.startsWith(`${base}#`) + ? Number(identity.clientMessageId.slice(base.length + 1)) + : Number.NaN + if (!Number.isSafeInteger(generation) || generation < 1) { + return + } + const descriptor = { identity, generation, toolUseId, linkage } + if (!index.latest || generation >= index.latest.generation) { + index.latest = descriptor + } + if (toolUseId === undefined) { + if (!index.unresolved || generation >= index.unresolved.generation) { + index.unresolved = descriptor + } + } else { + const prior = index.aliases.get(toolUseId) + if (!prior || generation >= prior.generation) { + index.aliases.set(toolUseId, descriptor) + } + } +} + +export function selectClaudeBackgroundTask( + index: ClaudeBackgroundTaskIndex | undefined, + toolUseId?: string +): ClaudeBackgroundTaskDescriptor | undefined { + return toolUseId === undefined + ? index?.latest + : (index?.aliases.get(toolUseId) ?? index?.unresolved) +} + +export function resolveClaudeBackgroundTaskDescriptor( + journal: StructuredAgentSessionLifecycleJournal, + id: string, + toolUseId?: string +): ClaudeBackgroundTaskDescriptor { + const index: ClaudeBackgroundTaskIndex = { aliases: new Map() } + journal.visitItems((itemId, _sequence, body) => { + if (body.kind !== 'message') { + return + } + const block = body.blocks.find(isBackgroundTaskBlock) + if (block?.taskId === id) { + indexClaudeBackgroundTask(index, itemId, id, block.parentToolUseId, {}) + } + }) + return ( + selectClaudeBackgroundTask(index, toolUseId) ?? { + identity: claudeBackgroundTaskIdentity(id, (index.latest?.generation ?? 0) + 1), + generation: (index.latest?.generation ?? 0) + 1, + toolUseId, + linkage: {} + } + ) +} + +export function resolveClaudeBackgroundTaskIdentity( + journal: StructuredAgentSessionLifecycleJournal, + id: string, + toolUseId: string | undefined +): AgentJournalItemIdentity { + return resolveClaudeBackgroundTaskDescriptor(journal, id, toolUseId).identity +} diff --git a/src/main/claude/claude-background-task-roster.ts b/src/main/claude/claude-background-task-roster.ts index 422ec533fca..80e89a514e6 100644 --- a/src/main/claude/claude-background-task-roster.ts +++ b/src/main/claude/claude-background-task-roster.ts @@ -1,3 +1,4 @@ +import type { ClaudeTaskInvocations } from './claude-task-invocations' import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row' import { classifyClaudeBackgroundTaskKind, @@ -15,16 +16,23 @@ import type { export function observeClaudeBackgroundTaskRoster( tasks: unknown[], rows: Map, - revise: (id: string, change: ClaudeBackgroundTaskChange) => void + revise: (id: string, change: ClaudeBackgroundTaskChange) => void, + admitOwned?: (id: string, task: Record) => boolean | void ): void { for (const entry of tasks) { const task = record(entry) const id = task === null ? null : taskId(task) + if (task && id && task.ambient !== true && task.skip_transcript !== true) { + if (admitOwned?.(id, task) === false) { + continue + } + } const row = id === null ? undefined : rows.get(id) if ( task === null || id === null || task.ambient === true || + task.skip_transcript === true || !row || isSettledBackgroundTaskState(row.block.state) ) { @@ -37,3 +45,26 @@ export function observeClaudeBackgroundTaskRoster( }) } } + +export function observeOwnedClaudeBackgroundTaskRoster(input: { + tasks: unknown[] + rows: Map + invocations: ClaudeTaskInvocations + revise: (id: string, change: ClaudeBackgroundTaskChange) => void + attribute: (id: string, row: ClaudeBackgroundTaskRow) => void + admit: (id: string, task: Record) => void +}): void { + observeClaudeBackgroundTaskRoster(input.tasks, input.rows, input.revise, (id, task) => { + const selected = input.invocations.selection(task, id) + if (!selected?.acceptsStart || selected.invocation.excluded || selected.invocation.monitor) { + return false + } + const row = input.rows.get(id) + if (row) { + input.attribute(id, row) + } else if (selected.invocation.parentTaskId !== undefined) { + input.admit(id, task) + } + return true + }) +} diff --git a/src/main/claude/claude-background-task-row-journal.ts b/src/main/claude/claude-background-task-row-journal.ts index e78bf4f0c09..3ea4197ff06 100644 --- a/src/main/claude/claude-background-task-row-journal.ts +++ b/src/main/claude/claude-background-task-row-journal.ts @@ -8,60 +8,22 @@ import type { } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle' -import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate' +import { + claudeBackgroundTaskIdentity, + resolveClaudeBackgroundTaskIdentity +} from './claude-background-task-identity' +export { + claudeBackgroundTaskIdentity, + resolveClaudeBackgroundTaskIdentity +} from './claude-background-task-identity' const MAX_RESOLVED_TASK_IDENTITIES = 512 const ADMITTED: StructuredAgentSessionSinkAdmission = { accepted: true } -/** Generation suffixes preserve restarted runs; generation 1 retains the legacy journal key. */ -export function claudeBackgroundTaskIdentity( - taskId: string, - generation = 1 -): AgentJournalItemIdentity { - const key = - generation > 1 - ? `claude-background-task:${taskId}#${generation}` - : `claude-background-task:${taskId}` - return { provider: 'orca', clientMessageId: key } -} - export const claudeBackgroundTaskBody = backgroundTaskJournalBody -export function resolveClaudeBackgroundTaskIdentity( - journal: StructuredAgentSessionLifecycleJournal, - id: string, - toolUseId: string | undefined -): AgentJournalItemIdentity { - let maxGeneration = 0 - let matchingGeneration: number | undefined - let parentlessGeneration: number | undefined - journal.visitItems((itemId, _sequence, body) => { - const identity = parseAgentJournalItemKey(itemId) - if (!identity || identity.provider !== 'orca') { - return - } - const taskBlock = body.kind === 'message' ? body.blocks.find(isBackgroundTaskBlock) : undefined - if (!taskBlock || taskBlock.taskId !== id) { - return - } - const generation = persistedTaskGeneration(identity.clientMessageId, id) - if (generation === null) { - return - } - maxGeneration = Math.max(maxGeneration, generation) - if (taskBlock.parentToolUseId === toolUseId) { - matchingGeneration = Math.max(matchingGeneration ?? 0, generation) - } else if (taskBlock.parentToolUseId === undefined) { - parentlessGeneration = Math.max(parentlessGeneration ?? 0, generation) - } - }) - // A prior parentless row cannot be proved distinct from the later aliased outcome. - return claudeBackgroundTaskIdentity( - id, - matchingGeneration ?? parentlessGeneration ?? (maxGeneration === 0 ? 1 : maxGeneration + 1) - ) -} - export class ClaudeBackgroundTaskIdentityResolver { private journal: StructuredAgentSessionLifecycleJournal | null = null private epoch: string | null = null @@ -102,19 +64,6 @@ export class ClaudeBackgroundTaskIdentityResolver { } } -function persistedTaskGeneration(clientMessageId: string, taskId: string): number | null { - const base = `claude-background-task:${taskId}` - if (clientMessageId === base) { - return 1 - } - const prefix = `${base}#` - if (!clientMessageId.startsWith(prefix)) { - return null - } - const generation = Number(clientMessageId.slice(prefix.length)) - return Number.isSafeInteger(generation) && generation > 1 ? generation : null -} - export function writeClaudeBackgroundTaskRow( sink: StructuredAgentSessionEventSink, identities: ClaudeBackgroundTaskIdentityResolver, @@ -127,7 +76,7 @@ export function writeClaudeBackgroundTaskRow( lifecycle = false ): StructuredAgentSessionSinkAdmission { const body = claudeBackgroundTaskBody(row.block) - const serialized = JSON.stringify(body) + const serialized = JSON.stringify([body, row.linkage]) if (serialized === row.lastSerialized) { return ADMITTED } @@ -135,16 +84,42 @@ export function writeClaudeBackgroundTaskRow( const identity = claudeBackgroundTaskIdentity(id, row.generation) // A reused row belongs to the current run, so it must count as executing. const appendOptions = { + ...row.linkage, turnScope: turnScope(), executes: true as const, ...(lifecycle ? { lifecycle: true } : {}) } const publishOptions = lifecycle ? { lifecycle: true } : {} + const toolUseId = row.block.parentToolUseId const resolveIdentity = (journal: StructuredAgentSessionLifecycleJournal) => - identities.resolve(journal, id, row.toolUseId) + identities.resolve(journal, id, toolUseId) const appendAndPublish = sink.tryAppendResolvedItemAndPublish let admission: StructuredAgentSessionSinkAdmission - if (appendAndPublish) { + if (sink.tryReviseResolvedItemAndPublish) { + const identitySizeBound = claudeBackgroundTaskIdentity(id, Number.MAX_SAFE_INTEGER) + // A saved alias is at most512 characters, each at most6 JSON bytes. + const reservedBytes = + estimateStructuredAgentSessionItemBytes(identitySizeBound, body) + 512 * 6 + 64 + admission = sink.tryReviseResolvedItemAndPublish( + reservedBytes, + (journal) => { + const resolved = resolveIdentity(journal) + const saved = journal.itemBody(agentJournalItemKey(resolved)) + const savedBlock = + saved?.kind === 'message' ? saved.blocks.find(isBackgroundTaskBlock) : undefined + const block = body.kind === 'message' ? body.blocks.find(isBackgroundTaskBlock) : undefined + const alias = block?.parentToolUseId ?? savedBlock?.parentToolUseId + return { + identity: resolved, + body: + block && alias && block.parentToolUseId === undefined + ? claudeBackgroundTaskBody({ ...block, parentToolUseId: alias }) + : body + } + }, + appendOptions + ) + } else if (appendAndPublish) { // Budget for any safe generation suffix before the deferred sink resolves its durable identity. const identitySizeBound = claudeBackgroundTaskIdentity(id, Number.MAX_SAFE_INTEGER) admission = appendAndPublish(identitySizeBound, body, resolveIdentity, appendOptions) diff --git a/src/main/claude/claude-background-task-row-lifecycle.ts b/src/main/claude/claude-background-task-row-lifecycle.ts index e612b26ffa2..112157ec7d7 100644 --- a/src/main/claude/claude-background-task-row-lifecycle.ts +++ b/src/main/claude/claude-background-task-row-lifecycle.ts @@ -1,3 +1,5 @@ +import type { ClaudeTaskInvocation } from './claude-task-invocations' +import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' import { canReplaceBackgroundTaskState, isSettledBackgroundTaskState @@ -19,6 +21,8 @@ import { export type ClaudeBackgroundTaskRow = { block: NativeChatBackgroundTaskBlock + linkage?: AgentJournalProducerLinkage + invocation?: ClaudeTaskInvocation lastSerialized: string | null /** Immutable alias for persistence/coalescing; the final frame may enrich the block's parent. */ toolUseId?: string @@ -208,3 +212,20 @@ export function reviseClaudeBackgroundTaskRow( } row.block = next } + +export function attributeClaudeBackgroundTaskRow(id: string, row: ClaudeBackgroundTaskRow): void { + const invocation = row.invocation + const toolUseId = invocation?.toolUseId + if (toolUseId && row.block.parentToolUseId === undefined) { + row.block = { ...row.block, parentToolUseId: toolUseId } + } + const parent = invocation?.reportedParentTaskId + if (parent) { + row.linkage = { + agentId: id, + parentAgentId: parent, + producerKind: 'background', + ...(toolUseId ? { providerParentRef: toolUseId } : {}) + } + } +} diff --git a/src/main/claude/claude-background-task-row-writer.ts b/src/main/claude/claude-background-task-row-writer.ts index d1f71279e70..b4551e1e480 100644 --- a/src/main/claude/claude-background-task-row-writer.ts +++ b/src/main/claude/claude-background-task-row-writer.ts @@ -1,3 +1,6 @@ +import { CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES } from './claude-background-task-frames' +import type { ClaudeTaskInvocations } from './claude-task-invocations' +import { claudeBackgroundTaskToolUseId } from './claude-background-task-row-lifecycle' import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' import type { StructuredAgentSessionEventSink, @@ -94,3 +97,36 @@ export class ClaudeBackgroundTaskRowWriter { this.identities.clear() } } + +export function createClaudeBackgroundTaskTurnOpener( + openOutputTurn: ((frame: Record, observedAt: number) => void) | undefined, + invocations: ClaudeTaskInvocations +) { + return ( + journaling: { frame: Record; observedAt: number } | null, + open: boolean, + id: string | null, + row?: ClaudeBackgroundTaskRow + ): (() => void) => { + const frame = journaling?.frame + const invocation = + row?.invocation ?? + (frame && id !== null + ? (invocations.selection(frame, id)?.invocation ?? + invocations.get(id, claudeBackgroundTaskToolUseId(frame))) + : undefined) + return () => { + // Task inventory from a known child cannot assert execution of the root. + const subtype = frame?.subtype + if ( + journaling && + open && + invocation?.parentTaskId === undefined && + (typeof subtype !== 'string' || + !CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES.has(subtype)) + ) { + openOutputTurn?.(journaling.frame, journaling.observedAt) + } + } + } +} diff --git a/src/main/claude/claude-background-task-rows.ts b/src/main/claude/claude-background-task-rows.ts index be03348a337..bc5dca47ebc 100644 --- a/src/main/claude/claude-background-task-rows.ts +++ b/src/main/claude/claude-background-task-rows.ts @@ -1,9 +1,15 @@ +import { ClaudeTaskInvocations } from './claude-task-invocations' import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import { BoundedMap } from '../../shared/bounded-map' -import { record, taskAliasId } from './claude-background-task-frames' import { + record, + taskAliasId, + CLAUDE_BACKGROUND_TASK_ROW_SUBTYPES +} from './claude-background-task-frames' +import { + attributeClaudeBackgroundTaskRow, claudeBackgroundTaskPatchChange, claudeBackgroundTaskToolUseId, canonicalClaudeBackgroundTaskId, @@ -19,31 +25,23 @@ import { ensureClaudeBackgroundTaskRowSlot, type ClaudeBackgroundTaskLedgerSizes } from './claude-background-task-memory' -import { ClaudeBackgroundTaskRowWriter } from './claude-background-task-row-writer' +import { + ClaudeBackgroundTaskRowWriter, + createClaudeBackgroundTaskTurnOpener +} from './claude-background-task-row-writer' import { observeClaudeBackgroundTaskStart } from './claude-background-task-start' -import { observeClaudeBackgroundTaskRoster } from './claude-background-task-roster' +import { observeOwnedClaudeBackgroundTaskRoster } from './claude-background-task-roster' import { ClaudeSubagentIds } from './claude-subagent-id-aliases' import { ClaudeOverflowTerminalRows } from './claude-overflow-terminal-rows' const MAX_TASK_ROWS = 64 -const TASK_SUBTYPES: ReadonlySet = new Set([ - 'task_started', - 'task_updated', - 'task_progress', - 'task_notification' -]) - -const SILENT_ROW_REFRESH_SUBTYPES: ReadonlySet = new Set([ - 'task_progress', - 'background_tasks_changed' -]) - export type ClaudeBackgroundTaskRowsDeps = { sink: StructuredAgentSessionEventSink /** Require a forwarded top-level invocation on first admission to exclude nested children. */ isForwardedParentTool: (toolUseId: string) => boolean /** Recover earlier-run subagent ownership when Claude does not repeat its announcement. */ + taskInvocations?: ClaudeTaskInvocations rosteredByEarlierRun?: (taskId: string) => boolean /** Reopen provider-resumed turns before journaling output so the session reports working. */ openOutputTurn?: (frame: Record, observedAt: number) => void @@ -56,13 +54,17 @@ export type ClaudeBackgroundTaskRowsDeps = { export class ClaudeBackgroundTaskRows { private readonly rows = new Map() private readonly writer: ClaudeBackgroundTaskRowWriter + private readonly openTurn: ReturnType private readonly overflowTerminalRows: ClaudeOverflowTerminalRows private readonly ledgers = new ClaudeBackgroundTaskLedgers() private readonly ids = new ClaudeSubagentIds() private readonly now: () => number + private readonly taskInvocations: ClaudeTaskInvocations constructor(private readonly deps: ClaudeBackgroundTaskRowsDeps) { + this.taskInvocations = deps.taskInvocations ?? new ClaudeTaskInvocations() this.now = deps.now ?? (() => Date.now()) + this.openTurn = createClaudeBackgroundTaskTurnOpener(deps.openOutputTurn, this.taskInvocations) this.writer = new ClaudeBackgroundTaskRowWriter( deps.sink, deps.turnScope, @@ -87,6 +89,7 @@ export class ClaudeBackgroundTaskRows { private journaling: { frame: Record; observedAt: number } | null = null observe(message: Record, observedAt: number = this.now()): boolean { + this.taskInvocations.observe(message) this.journaling = { frame: message, observedAt } // Claude wakes the lead for any task the lead launched, rowless subagents included; open that turn at the notification, once per frame. const toolUseId = @@ -101,7 +104,8 @@ export class ClaudeBackgroundTaskRows { if (frameId) { this.wakeFrames.set(frameId, true) } - this.deps.openOutputTurn?.(message, observedAt) + const id = canonicalClaudeBackgroundTaskId(message, this.ids) + this.openTurn(this.journaling, true, id)() } try { return this.observeFrame(message) @@ -111,10 +115,10 @@ export class ClaudeBackgroundTaskRows { } /** Monitor results may precede announcements; their notifications belong to the tool call. */ - observeMonitorToolResult(taskId: unknown): void { + observeMonitorToolResult(taskId: unknown, toolUseId?: string): void { const id = taskAliasId(taskId) if (id !== undefined) { - this.ledgers.rememberForeign(id, 'ambient') + this.taskInvocations.excludeMonitor(id, toolUseId) } } @@ -126,28 +130,46 @@ export class ClaudeBackgroundTaskRows { if (!Array.isArray(message.tasks)) { return false } - observeClaudeBackgroundTaskRoster(message.tasks, this.rows, (id, change) => - this.revise(id, change) - ) + observeOwnedClaudeBackgroundTaskRoster({ + tasks: message.tasks, + rows: this.rows, + invocations: this.taskInvocations, + revise: (id, change) => this.revise(id, change), + attribute: attributeClaudeBackgroundTaskRow, + admit: (id, task) => { + if (!this.ledgers.terminalTaskIds.has(id)) { + this.observeStart(id, task, true) + } + } + }) return true } - if (typeof message.subtype !== 'string' || !TASK_SUBTYPES.has(message.subtype)) { + if ( + typeof message.subtype !== 'string' || + !CLAUDE_BACKGROUND_TASK_ROW_SUBTYPES.has(message.subtype) + ) { return false } const id = canonicalClaudeBackgroundTaskId(message, this.ids) if (id === null) { return false } + const selected = this.taskInvocations.selection(message, id) + if (selected?.invocation.excluded || selected?.invocation.monitor) { + return true + } + if (selected?.current === false) { + if (message.subtype !== 'task_notification') { + return true + } + const generation = this.ledgers.generations.next(id) + const row = newClaudeBackgroundTaskRowFromNotification(id, message, this.now(), generation) + row.invocation = selected.invocation + this.writeRow(id, row) + return true + } if (message.subtype === 'task_started') { - return observeClaudeBackgroundTaskStart({ - id, - message, - rows: this.rows, - ledgers: this.ledgers, - isForwardedParentTool: this.deps.isForwardedParentTool, - openRow: (taskId, frame) => this.openRow(taskId, frame), - maxRows: MAX_TASK_ROWS - }) + return this.observeStart(id, message) } if (this.ledgers.foreign.has(id)) { return true @@ -162,6 +184,28 @@ export class ClaudeBackgroundTaskRows { return this.observePatch(id, message) } + private observeStart(id: string, message: Record, roster = false): boolean { + const selected = this.taskInvocations.selection(message, id) + if (!selected?.acceptsStart || selected.invocation.excluded || selected.invocation.monitor) { + return true + } + return observeClaudeBackgroundTaskStart({ + id, + message: { + ...message, + ...(roster ? { is_backgrounded: true } : {}), + tool_use_id: selected.invocation.toolUseId + }, + owned: selected.invocation.parentTaskId !== undefined, + rows: this.rows, + ledgers: this.ledgers, + isForwardedParentTool: this.deps.isForwardedParentTool, + openRow: (taskId, frame) => this.openRow(taskId, frame), + refresh: (id) => this.write(id), + maxRows: MAX_TASK_ROWS + }) + } + settleSession(): void { for (const [id, row] of this.rows) { if (!isSettledBackgroundTaskState(row.block.state)) { @@ -180,13 +224,13 @@ export class ClaudeBackgroundTaskRows { this.ids.clear() } - retryPendingWrites() { - return this.writer.retryPendingWrites() - } + retryPendingWrites = () => this.writer.retryPendingWrites() private openRow(id: string, message: Record): void { const generation = this.ledgers.generations.next(id) - this.rows.set(id, newClaudeBackgroundTaskRow(id, message, this.now(), generation)) + const row = newClaudeBackgroundTaskRow(id, message, this.now(), generation) + row.invocation = this.taskInvocations.get(id, claudeBackgroundTaskToolUseId(message)) + this.rows.set(id, row) this.write(id) } @@ -218,10 +262,9 @@ export class ClaudeBackgroundTaskRows { return true } const generation = this.ledgers.generations.next(id) - this.rows.set( - id, - newClaudeBackgroundTaskRowFromNotification(id, message, this.now(), generation) - ) + const row = newClaudeBackgroundTaskRowFromNotification(id, message, this.now(), generation) + row.invocation = this.taskInvocations.get(id, claudeBackgroundTaskToolUseId(message)) + this.rows.set(id, row) this.write(id) return true } @@ -230,6 +273,7 @@ export class ClaudeBackgroundTaskRows { if (this.ledgers.fallbackTaskIds.has(id)) { const change = claudeBackgroundTaskPatchChange(message) if (change.state && isSettledBackgroundTaskState(change.state)) { + this.taskInvocations.settleFrame(id, message) this.ledgers.rememberTerminal(this.rows, id, claudeBackgroundTaskToolUseId(message)) this.overflowTerminalRows.observePatch(id, message, change) return true @@ -248,6 +292,7 @@ export class ClaudeBackgroundTaskRows { } const change = claudeBackgroundTaskPatchChange(message) if (change.state && isSettledBackgroundTaskState(change.state)) { + this.taskInvocations.settleFrame(id, message) this.ledgers.rememberTerminal(this.rows, id, claudeBackgroundTaskToolUseId(message)) } if (row) { @@ -280,23 +325,7 @@ export class ClaudeBackgroundTaskRows { openOutputTurn = true, lifecycle = false ): void { - const journaling = this.journaling - this.writer.write( - id, - row, - () => { - // Why: progress and roster ticks refresh the row only. Opening a turn - // here flips an idle chat back to working. - const subtype = journaling?.frame.subtype - if ( - journaling && - openOutputTurn && - (typeof subtype !== 'string' || !SILENT_ROW_REFRESH_SUBTYPES.has(subtype)) - ) { - this.deps.openOutputTurn?.(journaling.frame, journaling.observedAt) - } - }, - lifecycle - ) + attributeClaudeBackgroundTaskRow(id, row) + this.writer.write(id, row, this.openTurn(this.journaling, openOutputTurn, id, row), lifecycle) } } diff --git a/src/main/claude/claude-background-task-start.ts b/src/main/claude/claude-background-task-start.ts index ed70d1b2da3..76f6ad07b1b 100644 --- a/src/main/claude/claude-background-task-start.ts +++ b/src/main/claude/claude-background-task-start.ts @@ -12,7 +12,7 @@ import { } from './claude-background-task-memory' import { isClaudeSubagentTask } from './claude-subagent-task-frames' -export function observeClaudeBackgroundTaskStart(input: { +type ClaudeBackgroundTaskStartInput = { id: string message: Record rows: Map @@ -20,7 +20,14 @@ export function observeClaudeBackgroundTaskStart(input: { isForwardedParentTool: (toolUseId: string) => boolean openRow: (id: string, message: Record) => void maxRows: number -}): boolean { +} + +export function observeClaudeBackgroundTaskStart( + input: ClaudeBackgroundTaskStartInput & { + owned: boolean + refresh: (id: string, row: ClaudeBackgroundTaskRow) => void + } +): boolean { const { id, message, rows, ledgers } = input if (ledgers.fallbackTaskIds.has(id)) { if (ledgers.terminalTaskIds.has(id)) { @@ -39,10 +46,6 @@ export function observeClaudeBackgroundTaskStart(input: { return false } } - if (message.ambient === true || message.skip_transcript === true) { - ledgers.rememberForeign(id, 'ambient') - return true - } if (isClaudeSubagentTask(message)) { ledgers.rememberForeign(id, 'roster') return true @@ -57,6 +60,7 @@ export function observeClaudeBackgroundTaskStart(input: { ledgers.foreign.delete(id) // A live task's duplicate announcement is redelivery, not a new run. if (!isSettledBackgroundTaskState(existing.block.state)) { + input.refresh(id, existing) return true } if (shouldRestartClaudeBackgroundTaskRow(existing, message)) { @@ -81,7 +85,7 @@ export function observeClaudeBackgroundTaskStart(input: { ledgers.foreign.delete(id) const toolUseId = claudeBackgroundTaskToolUseId(message) // Absence of a parent is not evidence of an unforwarded parent. - if (toolUseId !== undefined && !input.isForwardedParentTool(toolUseId)) { + if (toolUseId !== undefined && !input.owned && !input.isForwardedParentTool(toolUseId)) { ledgers.rememberForeign(id, 'sidechain') return true } diff --git a/src/main/claude/claude-background-task-turn-resumption.test.ts b/src/main/claude/claude-background-task-turn-resumption.test.ts index 9ae77f35372..13a2d59ba17 100644 --- a/src/main/claude/claude-background-task-turn-resumption.test.ts +++ b/src/main/claude/claude-background-task-turn-resumption.test.ts @@ -161,3 +161,78 @@ describe('a typed background-task row opens the turn it resumes', () => { expect(projected(items())).toBe('idle') }) }) + +it('keeps an alias-only owned notification idle even when its alias was forwarded at the root', () => { + const { translator, items } = harness() + spawnToolCall(translator) + translator.handle( + systemFrame('owned-start', { + subtype: 'task_started', + task_id: 'owned', + tool_use_id: TOOL, + parent_task_id: 'owner', + task_type: 'local_bash', + is_backgrounded: true + }) + ) + settleTurn(translator) + translator.handle( + systemFrame('owned-terminal', { + subtype: 'task_notification', + tool_use_id: TOOL, + status: 'completed', + summary: 'Finished child' + }) + ) + expect(items().find((item) => item.itemId.includes('owned'))?.body).toMatchObject({ + kind: 'message', + blocks: expect.arrayContaining([ + expect.objectContaining({ type: 'background-task', taskId: 'owned', state: 'done' }) + ]) + }) + expect(projected(items())).toBe('idle') + translator.dispose() +}) + +it('keeps owned terminal overflow writes idle without a retained row invocation', () => { + const { translator, items } = harness() + for (let index = 0; index < 65; index += 1) { + translator.handle( + systemFrame(`owned-start-${index}`, { + subtype: 'task_started', + task_id: `owned-${index}`, + parent_task_id: 'owner', + task_type: 'local_bash', + is_backgrounded: true + }) + ) + } + settleTurn(translator) + translator.handle( + systemFrame('overflow-owned-patch', { + subtype: 'task_updated', + task_id: 'owned-64', + patch: { status: 'failed' } + }) + ) + translator.handle( + systemFrame('overflow-owned-orphan', { + subtype: 'task_notification', + task_id: 'owned-terminal-only', + parent_task_id: 'owner', + status: 'completed' + }) + ) + const terminal = items().filter( + (item) => + item.body.kind === 'message' && + item.body.blocks.some( + (block) => + block.type === 'background-task' && + ['owned-64', 'owned-terminal-only'].includes(block.taskId) + ) + ) + expect(terminal).toHaveLength(2) + expect(projected(items())).toBe('idle') + translator.dispose() +}) diff --git a/src/main/claude/claude-child-work-decoder.ts b/src/main/claude/claude-child-work-decoder.ts index 67dd220f3fa..d155db75b49 100644 --- a/src/main/claude/claude-child-work-decoder.ts +++ b/src/main/claude/claude-child-work-decoder.ts @@ -1,14 +1,7 @@ // Roster changes, turn endings and spawn results cannot settle a child. -import type { - AgentChildWorkKind, - AgentChildWorkOperation, - AgentChildWorkOutcome -} from '../../shared/agent-status/child-work/agent-status-child-work' -import type { - AgentChildWorkEvidence, - AgentChildWorkLiveObservation -} from '../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { ClaudeTaskInvocations } from './claude-task-invocations' +import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' import { classifyClaudeBackgroundTaskKind, liveClaudeTaskRunState, @@ -21,83 +14,34 @@ import { taskUsageTotalTokens, terminalClaudeTaskRunState } from './claude-background-task-frames' -import { isClaudeSubagentTask } from './claude-subagent-task-frames' +import { claudeStartedTaskKind } from './claude-subagent-task-frames' import { ClaudeAgentWaitCalls } from './claude-agent-wait-calls' -import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../shared/orca-cli-invocations' import { claudeChildWorkOutcome, + claudeChildWorkObservation, + type DecodedClaudeTask, + type EndedClaudeTask, claudeTaskProgressFacts, type ClaudeTaskFacts } from './claude-child-work-evidence' -type DecodedClaudeTask = { - kind: AgentChildWorkKind - backgrounded: boolean - /** Monitors stay monitoring until the provider reports them running. */ - running: boolean - name?: string - description?: string - toolUseId?: string - /** Runs `orca orchestration check --wait`: waiting on worker agents, so agent work. */ - awaitsAgents?: true -} - type ClaudeToolOwner = (toolUseId: string) => string | null type PendingEdge = (observedAt: number) => AgentChildWorkEvidence -function observation( - id: string, - task: DecodedClaudeTask, - facts: ClaudeTaskFacts, - observedAt: number, - waiting: boolean -): AgentChildWorkLiveObservation { - const operation: AgentChildWorkOperation | undefined = facts.toolName - ? { toolName: facts.toolName, basis: 'reported', observedAt } - : task.awaitsAgents - ? { - toolName: 'Bash', - input: ORCA_ORCHESTRATION_WAIT_COMMAND, - basis: 'reported', - observedAt - } - : undefined - return { - handle: { - idKind: 'task_id', - id, - ...(task.toolUseId !== undefined ? { runId: task.toolUseId } : {}) - }, - kind: task.kind, - residency: task.backgrounded ? 'background' : 'foreground', - state: waiting ? 'waiting' : task.running || task.kind !== 'monitor' ? 'working' : 'monitoring', - ...(task.name ? { name: task.name, agentType: task.name } : {}), - ...(task.description ? { description: task.description } : {}), - ...(facts.totalTokens !== undefined ? { totalTokens: facts.totalTokens } : {}), - ...(operation ? { operation } : {}), - ...(facts.lastMessage ? { lastMessage: facts.lastMessage } : {}), - // Only background tasks expose a stop target. - stoppable: task.backgrounded - } -} - export class ClaudeChildWorkDecoder { private readonly live = new Map() /** Retain ended runs for the session to distinguish wakes from late starts. */ - private readonly ended = new Map< - string, - { - run: string | undefined - outcome: AgentChildWorkOutcome - task?: DecodedClaudeTask - } - >() + private readonly ended = new Map() + private readonly childrenByOwner = new Map>() private waiting: ReadonlySet = new Set() private pending: PendingEdge[] = [] private readonly agentWaits = new ClaudeAgentWaitCalls() /** `ownerOf` names the subagent that made a child tool call; an ending task wakes it. */ + constructor(readonly taskInvocations = new ClaudeTaskInvocations()) {} + observe(message: Record, ownerOf?: ClaudeToolOwner): void { + this.taskInvocations.observe(message) if (message.type === 'assistant') { this.agentWaits.observe(message) return @@ -105,10 +49,31 @@ export class ClaudeChildWorkDecoder { if (message.type !== 'system') { return } + if (message.subtype === 'background_tasks_changed') { + if (Array.isArray(message.tasks)) { + for (const entry of message.tasks) { + const task = record(entry) + const id = task && taskId(task) + if ( + task && + id && + !this.ended.has(id) && + this.taskInvocations.parentOf(id, taskAliasId(task.tool_use_id)) + ) { + this.started(id, task, true) + } + } + } + return + } const id = taskId(message) if (!id) { return } + const selected = this.taskInvocations.selection(message, id) + if (selected && (!selected.current || selected.invocation.excluded)) { + return + } switch (message.subtype) { case 'task_started': this.started(id, message) @@ -145,8 +110,10 @@ export class ClaudeChildWorkDecoder { } clear(): void { + this.taskInvocations.clear() this.live.clear() this.ended.clear() + this.childrenByOwner.clear() this.agentWaits.clear() this.waiting = new Set() this.pending.push((observedAt) => ({ type: 'session-ended', observedAt })) @@ -158,12 +125,14 @@ export class ClaudeChildWorkDecoder { return pending.map((edge) => edge(observedAt)) } - private started(id: string, message: Record): void { - const toolUseId = taskAliasId(message.tool_use_id) - const awaitsAgents = this.agentWaits.take(toolUseId) - if (message.ambient === true || message.skip_transcript === true) { + private started(id: string, message: Record, roster = false): void { + const selection = this.taskInvocations.selection(message, id) + if (!selection?.acceptsStart || selection.invocation.excluded) { return } + const invocation = selection.invocation + const toolUseId = invocation.toolUseId + const awaitsAgents = this.agentWaits.take(toolUseId) const existing = this.live.get(id) const ended = existing ? undefined : this.ended.get(id) const restart = ended !== undefined @@ -171,12 +140,13 @@ export class ClaudeChildWorkDecoder { if (ended?.run !== undefined && ended.run === toolUseId && ended.outcome !== 'succeeded') { return } - const kind = startedTaskKind(message) + const kind = claudeStartedTaskKind(message) this.upsert( id, { kind: kind !== 'unknown' ? kind : (existing?.kind ?? 'unknown'), backgrounded: + roster || message.is_backgrounded === true || kind === 'workflow' || kind === 'monitor' || @@ -185,16 +155,22 @@ export class ClaudeChildWorkDecoder { name: taskName(message) ?? existing?.name, description: taskDescription(message.description) ?? existing?.description, toolUseId: toolUseId ?? existing?.toolUseId, + parentTaskId: invocation.parentTaskId, ...(awaitsAgents || existing?.awaitsAgents ? { awaitsAgents: true as const } : {}) }, {}, - restart + restart, + roster ) } /** Claude resumes a finished subagent when a task it launched notifies; show it working from that frame, not its restart a moment later. */ - private wakeOwner(toolUseId: string | undefined, ownerOf: ClaudeToolOwner | undefined): void { - const ownerId = toolUseId ? ownerOf?.(toolUseId) : null + private wakeOwner( + toolUseId: string | undefined, + ownerOf: ClaudeToolOwner | undefined, + parentTaskId?: string + ): void { + const ownerId = parentTaskId ?? (toolUseId ? ownerOf?.(toolUseId) : null) const owner = ownerId ? this.ended.get(ownerId) : undefined if (ownerId && owner?.outcome === 'succeeded' && owner.task?.kind === 'agent') { this.upsert(ownerId, { ...owner.task, running: true }, {}, true) @@ -207,11 +183,8 @@ export class ClaudeChildWorkDecoder { return } // Progress descriptions describe the current activity, not the task. - this.upsert( - id, - { ...task, name: task.name ?? taskName(message) }, - claudeTaskProgressFacts(message) - ) + const name = task.name ?? taskName(message) + this.upsert(id, { ...task, name }, claudeTaskProgressFacts(message)) } private updated( @@ -230,7 +203,6 @@ export class ClaudeChildWorkDecoder { } return } - // Late updates cannot reopen an ended task. if (!existing && this.ended.has(id)) { return } @@ -251,6 +223,7 @@ export class ClaudeChildWorkDecoder { name: name ?? existing?.name, description: description ?? existing?.description, toolUseId: existing?.toolUseId, + parentTaskId: existing?.parentTaskId, ...(existing?.awaitsAgents ? { awaitsAgents: true as const } : {}) }, {}, @@ -262,11 +235,44 @@ export class ClaudeChildWorkDecoder { id: string, task: DecodedClaudeTask, facts: ClaudeTaskFacts, - restart = false + restart = false, + unchangedRoster = false ): void { + if (unchangedRoster && JSON.stringify(task) === JSON.stringify(this.live.get(id))) { + return + } + const ownerBecameLive = !this.live.has(id) || restart this.ended.delete(id) + this.removeOwnerIndex(id) this.live.set(id, task) + if (task.parentTaskId) { + const children = this.childrenByOwner.get(task.parentTaskId) ?? new Set() + children.add(id) + this.childrenByOwner.set(task.parentTaskId, children) + } this.report(id, task, facts, restart) + // Admission can resolve a child's raw owner only after that owner's live edge. + if (!ownerBecameLive) { + return + } + for (const childId of this.childrenByOwner.get(id) ?? []) { + const child = this.live.get(childId) + if (child && childId !== id) { + this.report(childId, child, {}) + } + } + } + + private removeOwnerIndex(id: string): void { + const parent = this.live.get(id)?.parentTaskId + if (parent === undefined) { + return + } + const children = this.childrenByOwner.get(parent) + children?.delete(id) + if (children?.size === 0) { + this.childrenByOwner.delete(parent) + } } /** Read waiting state at drain so all queued live edges agree. */ @@ -274,7 +280,7 @@ export class ClaudeChildWorkDecoder { this.pending.push((observedAt) => ({ type: 'live', observedAt, - child: observation(id, task, facts, observedAt, this.waiting.has(id)), + child: claudeChildWorkObservation(id, task, facts, observedAt, this.waiting.has(id)), ...(restart ? { restart: true } : {}) })) } @@ -290,6 +296,8 @@ export class ClaudeChildWorkDecoder { ownerOf?: ClaudeToolOwner ): void { const task = this.live.get(id) + this.taskInvocations.settle(id, status, reported.runId ?? task?.toolUseId) + this.removeOwnerIndex(id) this.live.delete(id) const outcome = claudeChildWorkOutcome(status) this.ended.set(id, { @@ -300,7 +308,7 @@ export class ClaudeChildWorkDecoder { }) // Every ending but a stop notifies, which wakes the subagent that launched the task. if (outcome !== 'cancelled') { - this.wakeOwner(reported.runId ?? task?.toolUseId, ownerOf) + this.wakeOwner(reported.runId ?? task?.toolUseId, ownerOf, task?.parentTaskId) } this.pending.push((observedAt) => ({ type: 'ended', @@ -316,10 +324,3 @@ export class ClaudeChildWorkDecoder { })) } } - -/** Releases predating `task_type` still name an agent in `subagent_type`. */ -function startedTaskKind(message: Record): AgentChildWorkKind { - return isClaudeSubagentTask(message) - ? 'agent' - : classifyClaudeBackgroundTaskKind(message.task_type) -} diff --git a/src/main/claude/claude-child-work-evidence.ts b/src/main/claude/claude-child-work-evidence.ts index 33ff92e4267..7110cd50489 100644 --- a/src/main/claude/claude-child-work-evidence.ts +++ b/src/main/claude/claude-child-work-evidence.ts @@ -1,4 +1,9 @@ -import type { AgentChildWorkOutcome } from '../../shared/agent-status/child-work/agent-status-child-work' +import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../shared/orca-cli-invocations' +import type { + AgentChildWorkKind, + AgentChildWorkOperation, + AgentChildWorkOutcome +} from '../../shared/agent-status/child-work/agent-status-child-work' import type { AgentChildWorkEvidence, AgentChildWorkLiveObservation @@ -17,6 +22,62 @@ import { type ClaudeToolUse } from './structured/journal/claude-structured-item-translation' +export type EndedClaudeTask = { + run: string | undefined + outcome: AgentChildWorkOutcome + task?: DecodedClaudeTask +} + +export type DecodedClaudeTask = { + kind: AgentChildWorkKind + backgrounded: boolean + /** Monitors stay monitoring until the provider reports them running. */ + running: boolean + name?: string + description?: string + toolUseId?: string + parentTaskId?: string + /** Runs `orca orchestration check --wait`: waiting on worker agents, so agent work. */ + awaitsAgents?: true +} + +export function claudeChildWorkObservation( + id: string, + task: DecodedClaudeTask, + facts: ClaudeTaskFacts, + observedAt: number, + waiting: boolean +): AgentChildWorkLiveObservation { + const operation: AgentChildWorkOperation | undefined = facts.toolName + ? { toolName: facts.toolName, basis: 'reported', observedAt } + : task.awaitsAgents + ? { + toolName: 'Bash', + input: ORCA_ORCHESTRATION_WAIT_COMMAND, + basis: 'reported', + observedAt + } + : undefined + return { + handle: { + idKind: 'task_id', + id, + ...(task.toolUseId !== undefined ? { runId: task.toolUseId } : {}) + }, + ...(task.parentTaskId ? { ownerId: task.parentTaskId } : {}), + kind: task.kind, + residency: task.backgrounded ? 'background' : 'foreground', + state: waiting ? 'waiting' : task.running || task.kind !== 'monitor' ? 'working' : 'monitoring', + ...(task.name ? { name: task.name, agentType: task.name } : {}), + ...(task.description ? { description: task.description } : {}), + ...(facts.totalTokens !== undefined ? { totalTokens: facts.totalTokens } : {}), + ...(operation ? { operation } : {}), + ...(facts.lastMessage ? { lastMessage: facts.lastMessage } : {}), + // Only background tasks expose a stop target. + stoppable: task.backgrounded + } +} + export type ClaudeTaskFacts = { toolName?: string lastMessage?: string @@ -57,6 +118,9 @@ export function withClaudeChildWorkOwners( return evidence } const owned = (child: AgentChildWorkLiveObservation): AgentChildWorkLiveObservation => { + if (child.ownerId !== undefined) { + return child + } const ownerId = child.handle.runId === undefined ? null : ownerOf(child.handle.runId) return ownerId !== null && ownerId !== child.handle.id ? { ...child, ownerId } : child } diff --git a/src/main/claude/claude-child-work-roster-performance.test.ts b/src/main/claude/claude-child-work-roster-performance.test.ts new file mode 100644 index 00000000000..36f68abfa97 --- /dev/null +++ b/src/main/claude/claude-child-work-roster-performance.test.ts @@ -0,0 +1,89 @@ +import { expect, it } from 'vitest' +import { ClaudeChildWorkDecoder } from './claude-child-work-decoder' +import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store' +import { createAgentChildWorkAdmission } from '../../shared/agent-status/child-work/agent-status-child-work-admission' +import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-reconciliation' +import { parent } from './claude-child-work-producer-harness.test-fixture' + +it('emits only new or changed roster facts at10 and100 live tasks', () => { + for (const count of [10, 100]) { + const decoder = new ClaudeChildWorkDecoder() + const store = createAgentStatusStore({ epoch: 'roster-perf', mode: 'authority' }) + store.applyMutation({ parent: { subject: parent } }) + let minted = 0 + const admission = createAgentChildWorkAdmission(store, { + mintChildWorkId: () => `child-${++minted}` + }) + let clock = 1_700_000_000_000 + let rosterEdges = 0 + let rosterWrites = 0 + const feed = (message: Record, rosterBound = 0) => { + decoder.observe({ type: 'system', ...message }) + const evidence = decoder.drain(++clock) + const before = store.getSnapshot().revision + reconcileAgentChildWorkEvidence({ store, admission, parent, provider: 'claude', evidence }) + const writes = store.getSnapshot().revision - before + if (message.subtype === 'background_tasks_changed') { + const live = evidence.filter((edge) => edge.type === 'live').length + expect(live).toBeLessThanOrEqual(rosterBound) + expect(writes).toBeLessThanOrEqual(rosterBound) + rosterEdges += live + rosterWrites += writes + } + } + const owner = { + task_id: 'owner', + task_type: 'local_agent', + tool_use_id: 'tool-owner', + is_backgrounded: true + } + feed({ subtype: 'task_started', ...owner }) + let shellOwner = 'owner' + const shell = (id: number) => ({ + task_id: `shell-${id}`, + task_type: 'local_bash', + description: `shell${id}`, + parent_task_id: shellOwner + }) + const live: number[] = [] + for (let id = 0; id < count; id++) { + live.push(id) + const roster = { subtype: 'background_tasks_changed', tasks: [owner, ...live.map(shell)] } + // Only one task is newly present; unchanged replacement rosters need no host writes. + feed(roster, 1) + feed({ + subtype: 'task_started', + ...shell(id), + tool_use_id: `tool-${id}`, + is_backgrounded: true + }) + feed(roster) + } + // The introductions above need at most one edge/write each, independent of full-roster size. + expect(rosterEdges).toBeLessThanOrEqual(count) + expect(rosterWrites).toBeLessThanOrEqual(count) + rosterEdges = 0 + rosterWrites = 0 + feed({ subtype: 'task_started', ...owner, task_id: 'owner-second', tool_use_id: 'tool-second' }) + shellOwner = 'owner-second' + // A real owner change invalidates exactly the affected children, then its duplicate invalidates none. + feed({ subtype: 'background_tasks_changed', tasks: live.map(shell) }, count) + feed({ subtype: 'background_tasks_changed', tasks: live.map(shell) }) + for (let id = 0; id < count; id++) { + feed({ + subtype: 'task_notification', + task_id: `shell-${id}`, + tool_use_id: `tool-${id}`, + status: 'completed' + }) + live.shift() + feed({ subtype: 'background_tasks_changed', tasks: [owner, ...live.map(shell)] }) + } + // N introductions require at most N live edges and N store writes, independent of roster size. + expect(rosterEdges).toBeLessThanOrEqual(count) + expect(rosterWrites).toBeLessThanOrEqual(count) + expect(store.getChildren(parent).filter((child) => child.kind === 'command')).toHaveLength( + count + ) + } +}) diff --git a/src/main/claude/claude-journal-bound-delivery.test.ts b/src/main/claude/claude-journal-bound-delivery.test.ts new file mode 100644 index 00000000000..6c14507c9cf --- /dev/null +++ b/src/main/claude/claude-journal-bound-delivery.test.ts @@ -0,0 +1,112 @@ +import { expect, it, vi } from 'vitest' +import { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' +import { bindClaudeJournalReadingControl } from './structured/journal/claude-structured-session-journal-control' +import type { + StructuredAgentSessionEventSink, + StructuredAgentSessionReadingControl +} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' + +function unboundSink() { + let notify: (() => void) | undefined + let control: StructuredAgentSessionReadingControl | undefined + let bound = false + const sink: StructuredAgentSessionEventSink = { + appendItem: () => {}, + appendTombstone: () => {}, + publish: () => {}, + onJournalBound: (listener) => { + notify = listener + return () => { + notify = undefined + } + }, + journalLinkage: () => + bound + ? { + epoch: 'test', + visitItemsWithLinkage: () => {}, + threadGoal: () => null, + threadGoalSource: () => ({ goal: null, row: null }) + } + : null, + bindReadingControl: (next) => { + control = next + return () => {} + } + } + return { + sink, + bind: () => { + bound = true + notify?.() + }, + pressure: (paused: boolean) => control?.[paused ? 'pauseReading' : 'resumeReading']() + } +} + +it('holds ordered interpretation until binding while preserving independent sink pressure', () => { + const state = unboundSink() + let published = false + const delivery = new ClaudeJournalBoundDelivery(state.sink, () => published) + const connection = { pauseReading: vi.fn(), resumeReading: vi.fn() } + bindClaudeJournalReadingControl(state.sink, connection, null, delivery) + const observed: string[] = [] + delivery.deliver(() => { + observed.push('start') + delivery.deliver(() => observed.push('later')) + }) + delivery.deliver(() => observed.push('terminal')) + published = true + delivery.flush() + state.pressure(true) + expect(observed).toEqual([]) + state.bind() + expect(observed).toEqual(['start', 'terminal', 'later']) + expect(connection.resumeReading).not.toHaveBeenCalled() + state.pressure(false) + expect(connection.resumeReading).toHaveBeenCalledOnce() +}) + +it('terminates the uncommitted prefix on disposal and ignores a late binding', () => { + const state = unboundSink() + const delivery = new ClaudeJournalBoundDelivery(state.sink) + const interpret = vi.fn() + delivery.deliver(interpret) + delivery.dispose() + state.bind() + delivery.deliver(interpret) + expect(interpret).not.toHaveBeenCalled() +}) + +it('fails a bounded unbound prefix instead of silently losing or replaying observations', () => { + const state = unboundSink() + const delivery = new ClaudeJournalBoundDelivery(state.sink) + const failure = vi.fn() + const interpret = vi.fn() + delivery.onFailure = failure + const payload = 'x'.repeat(1024 * 1024) + expect(() => { + for (let index = 0; index < 33; index++) { + delivery.deliver(interpret, payload) + } + }).toThrow('capacity exceeded') + state.bind() + expect(failure).toHaveBeenCalledOnce() + expect(interpret).not.toHaveBeenCalled() +}) + +it('reports binding interpretation failure through its owning failure path', () => { + const state = unboundSink() + const delivery = new ClaudeJournalBoundDelivery(state.sink) + const failure = vi.fn() + delivery.onFailure = failure + const error = new Error('invalid saved identity') + delivery.deliver(() => { + throw error + }) + const later = vi.fn() + delivery.deliver(later) + expect(() => state.bind()).not.toThrow() + expect(failure).toHaveBeenCalledWith(error) + expect(later).not.toHaveBeenCalled() +}) diff --git a/src/main/claude/claude-journal-bound-delivery.ts b/src/main/claude/claude-journal-bound-delivery.ts new file mode 100644 index 00000000000..f095cc7576d --- /dev/null +++ b/src/main/claude/claude-journal-bound-delivery.ts @@ -0,0 +1,135 @@ +import type { + StructuredAgentSessionEventSink, + StructuredAgentSessionReadingControl +} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' + +/** Own provider observations until their saved identity input is available. */ +export class ClaudeJournalBoundDelivery { + private pending: ({ run: () => void; bytes: number } | undefined)[] = [] + private entries = 0 + private bytes = 0 + private draining = false + private closed = false + private unsubscribe?: () => void + private control?: StructuredAgentSessionReadingControl + private paused = false + onFailure?: (error: Error) => void + + constructor( + private sink?: StructuredAgentSessionEventSink, + private readonly published: () => boolean = () => true + ) { + this.bind(sink) + } + + bind(sink: StructuredAgentSessionEventSink | undefined): void { + this.unsubscribe?.() + this.sink = sink + this.unsubscribe = sink?.onJournalBound?.(() => this.flush()) + } + + get ready(): boolean { + return ( + !this.closed && + this.published() && + (!this.sink?.onJournalBound || this.sink.journalLinkage?.() !== null) + ) + } + + bindReadingControl(control: StructuredAgentSessionReadingControl): () => void { + this.control = control + if (this.paused) { + control.pauseReading() + } + return () => { + if (this.control === control) { + this.control = undefined + } + } + } + + deliver(run: () => void, payload?: unknown): void { + if (this.closed) { + return + } + if (this.ready && !this.draining) { + run() + return + } + const bytes = Buffer.byteLength(JSON.stringify(payload ?? null), 'utf8') + 64 + if (this.entries >= 1_024 || this.bytes + bytes > 32 * 1024 * 1024) { + const error = new Error('Claude event delivery capacity exceeded before journal binding') + this.dispose() + this.onFailure?.(error) + throw error + } + this.pending.push({ run, bytes }) + this.entries++ + this.bytes += bytes + this.updateReading() + } + + interpret(event: T, handle: (event: T) => void): void { + if (event.type === 'ended' || event.type === 'retiring') { + this.dispose() + handle(event) + } else if (this.ready) { + handle(event) + } else { + this.deliver(() => handle(event), event) + } + } + + flush(): void { + if (!this.ready || this.draining) { + this.updateReading() + return + } + this.draining = true + try { + while (this.pending.length && !this.closed) { + const prefix = this.pending + this.pending = [] + for (let index = 0; index < prefix.length; index++) { + if (this.closed) { + break + } + const entry = prefix[index]! + prefix[index] = undefined + this.entries-- + this.bytes -= entry.bytes + entry.run() + } + } + } catch (cause) { + this.dispose() + const error = cause instanceof Error ? cause : new Error(String(cause)) + if (!this.onFailure) { + throw error + } + this.onFailure(error) + } finally { + this.draining = false + this.updateReading() + } + } + + /** Retirement ends uncommitted delivery; it must never replay into a disposed translator. */ + dispose(): void { + this.closed = true + this.pending = [] + this.entries = 0 + this.bytes = 0 + this.unsubscribe?.() + this.unsubscribe = undefined + this.updateReading() + } + + private updateReading(): void { + const paused = !this.closed && this.published() && !this.ready + if (paused !== this.paused) { + this.paused = paused + this.control?.[paused ? 'pauseReading' : 'resumeReading']() + } + } +} diff --git a/src/main/claude/claude-journal-translator-contract.ts b/src/main/claude/claude-journal-translator-contract.ts index 96af6b7a240..21f4057ca02 100644 --- a/src/main/claude/claude-journal-translator-contract.ts +++ b/src/main/claude/claude-journal-translator-contract.ts @@ -1,3 +1,5 @@ +import type { ClaudeTaskInvocations } from './claude-task-invocations' +import type { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery' import type { AgentSessionContextReport } from '../../shared/agent-session/agent-session-context-usage' import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope' import type { @@ -16,6 +18,7 @@ import type { AgentSessionAccountKind } from '../../shared/agent-session/agent-s export type ClaudeJournalTranslatorDeps = { sink: StructuredAgentSessionEventSink + delivery?: ClaudeJournalBoundDelivery bindPromptItemId?: (journalItemId: string, promptKey: string) => void coalesceMs?: number schedule?: AgentSessionDeltaCoalescerDeps['schedule'] @@ -29,6 +32,7 @@ export type ClaudeJournalTranslatorDeps = { } export type ClaudeJournalTranslator = { + readonly taskInvocations: ClaudeTaskInvocations handle: (event: ClaudeStructuredSessionEvent) => void journalPrompts: Pick< ClaudeJournalPrompts, @@ -45,6 +49,7 @@ export type ClaudeJournalTranslator = { readonly openTurnInLiveProviderCycle: boolean readonly openTurnHasInputWork: boolean flush: () => void + childTaskParent?: (taskId: string, run?: string) => string | undefined childToolOwner?: ClaudeChildToolQueries['childToolOwner'] childActivity?: ClaudeChildToolQueries['childActivity'] retryPendingTaskRows?: () => StructuredAgentSessionSinkAdmission diff --git a/src/main/claude/claude-message-journaling.ts b/src/main/claude/claude-message-journaling.ts index 86c36ee9394..b25929a818a 100644 --- a/src/main/claude/claude-message-journaling.ts +++ b/src/main/claude/claude-message-journaling.ts @@ -196,7 +196,10 @@ export function journalClaudeMessage( tool.name === 'Monitor' && ctx.toolOrigins.has(result.toolUseId) ) { - ctx.backgroundTasks.observeMonitorToolResult(claudeRecord(message.tool_use_result)?.taskId) + ctx.backgroundTasks.observeMonitorToolResult( + claudeRecord(message.tool_use_result)?.taskId, + result.toolUseId + ) } ctx.tools.delete(result.toolUseId) changed = true diff --git a/src/main/claude/claude-parent-task-frames.test-fixture.ts b/src/main/claude/claude-parent-task-frames.test-fixture.ts new file mode 100644 index 00000000000..a90897291da --- /dev/null +++ b/src/main/claude/claude-parent-task-frames.test-fixture.ts @@ -0,0 +1,11 @@ +// CLI 2.1.319, isolated real run: parent Stop, live child roster, then separate child Stop; IDs/paths sanitized. +import { readFileSync } from 'node:fs' +import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' + +export const PARENT_TASK_STOP: CapturedFrame[] = readFileSync( + new URL('./__fixtures__/claude-parent-task-stop-2.1.319.jsonl', import.meta.url), + 'utf8' +) + .trim() + .split('\n') + .map((line) => JSON.parse(line)) diff --git a/src/main/claude/claude-parent-task-recovery.test.ts b/src/main/claude/claude-parent-task-recovery.test.ts new file mode 100644 index 00000000000..c5812f98b32 --- /dev/null +++ b/src/main/claude/claude-parent-task-recovery.test.ts @@ -0,0 +1,785 @@ +import { afterEach, expect, it } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { + producer, + frame, + system, + toolUse, + toolResult +} from './claude-child-work-producer-harness.test-fixture' +import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' +import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' +import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation' +import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support' +import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import { + claudeBackgroundTaskBody, + claudeBackgroundTaskIdentity +} from './claude-background-task-row-journal' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types' +import { + adapterAtPublishFor, + fakeClaude, + identityFor +} from './structured/claude-structured-session-test-support' +import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { ClaudeSubagentIdentities } from './claude-subagent-identities' +import { ClaudeJournaledSubagents } from './claude-subagent-journaled-identities' + +const journals = createTrackedJournalOpener() +const cleanup: string[] = [] +afterEach(async () => { + await journals.closeAll() + for (const path of cleanup.splice(0)) { + await rm(path, { recursive: true, force: true }) + } +}) + +it('retains explicit ambient and skip-transcript exclusion when roster omits those optional flags', async () => { + for (const flag of ['ambient', 'skip_transcript']) { + const run = await producer() + run.send( + system('task_started', { + task_id: 'excluded', + task_type: 'local_bash', + parent_task_id: 'owner', + is_backgrounded: true, + tool_use_id: 'tool-old', + [flag]: true + }) + ) + run.send( + system('background_tasks_changed', { + tasks: [{ task_id: 'excluded', task_type: 'local_bash', parent_task_id: 'owner' }] + }) + ) + run.send( + system('task_updated', { + task_id: 'excluded', + patch: { status: 'running', is_backgrounded: true, description: 'Excluded shell' } + }) + ) + expect.soft(run.records(), flag).toEqual([]) + expect + .soft( + [...run.journalItems.values()].filter( + (row) => + row.body.kind === 'message' && + row.body.blocks.some((block) => block.type === 'background-task') + ), + flag + ) + .toEqual([]) + run.send( + system('task_notification', { + task_id: 'excluded', + tool_use_id: 'tool-old', + status: 'stopped' + }) + ) + run.send(toolUse('tool-new', 'Bash', { command: 'sleep 1', run_in_background: true })) + run.send( + system('task_started', { + task_id: 'excluded', + task_type: 'local_bash', + tool_use_id: 'tool-new', + is_backgrounded: true + }) + ) + expect(run.records().find((row) => row.kind === 'command')).toMatchObject({ + membership: 'live' + }) + run.send( + system('task_progress', { + task_id: 'excluded', + tool_use_id: 'tool-pending', + parent_task_id: 'pending-owner', + [flag]: true + }) + ) + run.send( + system('task_notification', { + task_id: 'excluded', + tool_use_id: 'tool-new', + status: 'stopped' + }) + ) + run.send( + system('task_started', { + task_id: 'excluded', + task_type: 'local_bash', + tool_use_id: 'tool-pending', + is_backgrounded: true + }) + ) + expect(run.records().filter((row) => row.membership === 'live')).toEqual([]) + expect( + [...run.journalItems.values()].some( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.parentToolUseId === 'tool-pending' + ) + ) + ).toBe(false) + } +}) + +it('uses the matching durable generation ownership when an earlier run receives a terminal revision', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-parent-review-codex-')) + cleanup.push(root) + const journal = await journals.open({ + identity: { + sessionId: 'orca-session', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('claude-session', null) + }, + now: () => 9000, + stateDirectory: root + }) + for (const [generation, tool, owner] of [ + [1, 'tool-first', 'owner-first'], + [2, 'tool-second', 'owner-second'], + [3, 'tool-root', undefined] + ] as const) { + await journal.appendItem( + claudeBackgroundTaskIdentity('reused', generation), + claudeBackgroundTaskBody({ + type: 'background-task', + taskId: 'reused', + kind: 'command', + label: 'sleep', + parentToolUseId: tool, + state: 'unverifiable', + startedAt: 1 + }), + { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE, + ...(owner + ? { + agentId: 'reused', + parentAgentId: owner, + producerKind: 'background' as const, + providerParentRef: tool + } + : {}) + } + ) + } + const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + deferred.bind({ journal, fence: 1, publish: () => {} }) + const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 }) + translator.handle({ + type: 'message', + sessionId: 'orca-session', + message: { + type: 'system', + subtype: 'task_notification', + task_id: 'reused', + tool_use_id: 'tool-first', + session_id: 'claude-session', + uuid: 'historical-owned-completion', + status: 'completed' + } + }) + expect(await deferred.drained()).toEqual({ ok: true }) + expect(journal.runningTurn()).toBeNull() + const prior = journal + .snapshot() + .items.find( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.parentToolUseId === 'tool-first' + ) + ) + translator.handle({ + type: 'message', + sessionId: 'orca-session', + message: { + type: 'system', + subtype: 'task_notification', + task_id: 'reused', + status: 'completed' + } + }) + expect(await deferred.drained()).toEqual({ ok: true }) + const rootRow = journal + .snapshot() + .items.find( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.parentToolUseId === 'tool-root' + ) + ) + expect(rootRow?.agentId).toBeUndefined() + expect(rootRow?.body.kind === 'message' ? rootRow.body.blocks : []).toContainEqual( + expect.objectContaining({ taskId: 'reused', parentToolUseId: 'tool-root', state: 'done' }) + ) + translator.handle({ + type: 'message', + sessionId: 'orca-session', + message: system('task_started', { + task_id: 'reused', + task_type: 'local_bash', + tool_use_id: 'tool-first', + parent_task_id: 'owner-first', + is_backgrounded: true + }) + }) + expect(await deferred.drained()).toEqual({ ok: true }) + const oldBody = journal + .snapshot() + .items.find((row) => row.providerParentRef === 'tool-first')?.body + expect(oldBody?.kind === 'message' ? oldBody.blocks : []).toContainEqual( + expect.objectContaining({ parentToolUseId: 'tool-first', state: 'done' }) + ) + translator.dispose() + deferred.close() + const queued = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + const pending = createClaudeJournalTranslator({ sink: queued.sink, coalesceMs: 0 }) + const feed = (subtype: string, fields: Record) => + pending.handle({ + type: 'message', + sessionId: 'orca-session', + message: system(subtype, fields) + }) + feed('task_started', { + task_id: 'queued', + task_type: 'local_bash', + tool_use_id: 'queued-old', + parent_task_id: 'owner-first', + is_backgrounded: true + }) + feed('task_notification', { task_id: 'queued', tool_use_id: 'queued-old', status: 'stopped' }) + feed('task_progress', { + task_id: 'queued', + tool_use_id: 'queued-new', + description: 'New operation before announcement' + }) + feed('task_started', { + task_id: 'queued', + task_type: 'local_bash', + tool_use_id: 'queued-new', + parent_task_id: 'owner-second', + is_backgrounded: true + }) + feed('task_updated', { + task_id: 'queued', + tool_use_id: 'queued-old', + patch: { status: 'completed' } + }) + feed('task_progress', { + task_id: 'queued', + tool_use_id: 'queued-old', + description: 'Old operation' + }) + queued.bind({ journal, fence: 1, publish: () => {} }) + expect(await queued.drained()).toEqual({ ok: true }) + const queuedRows = journal + .snapshot() + .items.filter( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.taskId === 'queued' + ) + ) + expect(queuedRows).toHaveLength(2) + const current = queuedRows.find((row) => row.providerParentRef === 'queued-new') + expect(current).toMatchObject({ parentAgentId: 'owner-second' }) + expect(current?.body.kind === 'message' ? current.body.blocks : []).toContainEqual( + expect.objectContaining({ parentToolUseId: 'queued-new', state: 'working' }) + ) + pending.dispose() + queued.close() + expect(prior).toMatchObject({ parentAgentId: 'owner-first', providerParentRef: 'tool-first' }) +}) + +it('advances a journaled nested agent attempt rather than replacing it with the parent placeholder', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-nested-parent-recovery-')) + cleanup.push(root) + const journal = await journals.open({ + identity: { + sessionId: 'orca-session', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'claude', + providerHandle: claudeProviderHandle('claude-session', null) + }, + now: () => 9000, + stateDirectory: root + }) + await journal.appendItem( + { provider: 'claude', sessionId: 'claude-session', uuid: 'saved-attempt' }, + { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'previous attempt' }] }, + { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE, + agentId: 'nested', + parentAgentId: 'owner', + producerKind: 'agent', + providerParentRef: 'tool-second', + attempt: 2 + } + ) + const journaled = new ClaudeJournaledSubagents(() => journal) + const identities = new ClaudeSubagentIdentities({ journaled }) + identities.observeSystemFrame({ + type: 'system', + subtype: 'background_tasks_changed', + tasks: [{ task_id: 'nested', task_type: 'local_agent', parent_task_id: 'owner' }] + }) + identities.observeSystemFrame({ + type: 'system', + subtype: 'task_started', + task_id: 'nested', + tool_use_id: 'tool-third', + task_type: 'local_agent', + parent_task_id: 'owner' + }) + expect(identities.linkage.settledLinkageFor('tool-third')).toMatchObject({ + kind: 'linked', + linkage: { attempt: 3 } + }) +}) + +it.each(['notification', 'killed', 'failed'])( + 'keeps distinct shell invocations isolated after %s', + async (ending) => { + const run = await producer() + run.send( + system('task_started', { + task_id: 'owner', + task_type: 'local_agent', + tool_use_id: 'spawn-owner', + is_backgrounded: true + }) + ) + run.send( + system('task_started', { + task_id: 'reused', + task_type: 'local_bash', + tool_use_id: 'tool-first', + parent_task_id: 'owner', + is_backgrounded: true + }) + ) + run.send( + ending === 'notification' + ? system('task_notification', { + task_id: 'reused', + tool_use_id: 'tool-first', + status: 'stopped' + }) + : system('task_updated', { task_id: 'reused', patch: { status: ending } }) + ) + run.send( + system('task_progress', { + task_id: 'reused', + tool_use_id: 'tool-root', + description: 'New operation before announcement' + }) + ) + expect(run.records().find((row) => row.kind === 'command')).toMatchObject({ + membership: 'settled', + stoppable: false + }) + expect( + [...run.journalItems.values()].filter( + (row) => + row.body.kind === 'message' && + row.body.blocks.some((block) => block.type === 'background-task') + ) + ).toHaveLength(1) + run.send(toolUse('tool-root', 'Bash', { command: 'sleep 1', run_in_background: true })) + run.send( + system('task_started', { + task_id: 'reused', + task_type: 'local_bash', + tool_use_id: 'tool-root', + is_backgrounded: true + }) + ) + run.send( + system('task_updated', { + task_id: 'reused', + tool_use_id: 'tool-first', + patch: { status: 'completed' } + }) + ) + run.send( + system('task_progress', { + task_id: 'reused', + tool_use_id: 'tool-first', + description: 'Old operation' + }) + ) + const newer = [...run.journalItems.values()].find( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.parentToolUseId === 'tool-root' + ) + ) + expect.soft(newer).toBeDefined() + expect.soft(newer?.agentId).toBeUndefined() + const owner = run.records().find((row) => row.kind === 'agent') + const child = run.records().find((row) => row.kind === 'command') + expect(child?.parentChildWorkId).not.toBe(owner?.childWorkId) + expect(child).toMatchObject({ membership: 'live', stoppable: true }) + expect(JSON.stringify(child)).not.toContain('Old operation') + expect(newer?.body.kind === 'message' ? newer.body.blocks : []).toContainEqual( + expect.objectContaining({ parentToolUseId: 'tool-root', state: 'working' }) + ) + } +) + +it.each([false, true])( + 'keeps Monitor invocation reports out of the transcript, reused ID: %s', + async (reused) => { + const run = await producer() + if (reused) { + run.send(toolUse('tool-old', 'Bash', { command: 'sleep 1', run_in_background: true })) + run.send( + system('task_started', { + task_id: 'monitor-task', + task_type: 'local_bash', + tool_use_id: 'tool-old', + is_backgrounded: true + }) + ) + run.send( + system('task_notification', { + task_id: 'monitor-task', + tool_use_id: 'tool-old', + status: 'completed' + }) + ) + } + run.send(toolUse('tool-monitor', 'Monitor', { command: 'watch' })) + run.send({ + ...toolResult('tool-monitor', 'Started'), + tool_use_result: { taskId: 'monitor-task' } + }) + run.send( + system('task_started', { + task_id: 'monitor-task', + task_type: 'local_bash', + tool_use_id: 'tool-monitor', + is_backgrounded: true + }) + ) + run.send( + system('background_tasks_changed', { + tasks: [{ task_id: 'monitor-task', task_type: 'local_bash', parent_task_id: 'owner' }] + }) + ) + expect( + [...run.journalItems.values()].filter( + (row) => + row.body.kind === 'message' && + row.body.blocks.some((block) => block.type === 'background-task') + ) + ).toHaveLength(reused ? 1 : 0) + expect(run.records().some((row) => row.membership === 'live')).toBe(true) + } +) + +it('retains pending ownership and terminal evidence without granting a partial frame live authority', async () => { + const run = await producer() + run.send( + system('task_started', { + task_id: 'reused', + task_type: 'local_bash', + tool_use_id: 'tool-old', + is_backgrounded: true + }) + ) + run.send( + system('task_progress', { + task_id: 'reused', + tool_use_id: 'tool-owned', + parent_task_id: 'owner' + }) + ) + run.send( + system('task_notification', { + task_id: 'reused', + tool_use_id: 'tool-old', + status: 'stopped' + }) + ) + run.send( + system('task_started', { + task_id: 'reused', + task_type: 'local_bash', + tool_use_id: 'tool-owned', + is_backgrounded: true + }) + ) + expect(run.records().find((row) => row.kind === 'command')).toMatchObject({ + membership: 'live', + stoppable: true + }) + expect( + [...run.journalItems.values()].find( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.parentToolUseId === 'tool-owned' + ) + ) + ).toMatchObject({ agentId: 'reused' }) + run.send( + system('task_notification', { + task_id: 'reused', + tool_use_id: 'tool-stopped-before-start', + status: 'stopped' + }) + ) + run.send( + system('task_notification', { + task_id: 'reused', + tool_use_id: 'tool-owned', + status: 'stopped' + }) + ) + run.send( + system('task_started', { + task_id: 'reused', + task_type: 'local_bash', + tool_use_id: 'tool-stopped-before-start', + is_backgrounded: true + }) + ) + expect(run.records().filter((row) => row.membership === 'live')).toEqual([]) + const stoppedBody = [...run.journalItems.values()].find( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => + block.type === 'background-task' && block.parentToolUseId === 'tool-stopped-before-start' + ) + )?.body + expect(stoppedBody?.kind === 'message' ? stoppedBody.blocks : []).toContainEqual( + expect.objectContaining({ parentToolUseId: 'tool-stopped-before-start', state: 'idle' }) + ) +}) + +it.each(['alias', 'no-alias', 'partial-alias', 'known-terminal'])( + 'admits a resumed agent only when the terminal did not identify that invocation: %s', + async (shape) => { + const run = await producer() + run.send( + system('task_notification', { + task_id: 'owner', + status: 'stopped', + ...(shape === 'known-terminal' ? { tool_use_id: 'spawn-owner' } : {}) + }) + ) + if (shape === 'partial-alias') { + run.send(system('task_progress', { task_id: 'owner', tool_use_id: 'spawn-owner' })) + } + run.send( + system('task_started', { + task_id: 'owner', + task_type: 'local_agent', + is_backgrounded: true, + ...(shape === 'no-alias' ? {} : { tool_use_id: 'spawn-owner' }) + }) + ) + run.send( + system('task_started', { + task_id: 'shell', + task_type: 'local_bash', + tool_use_id: 'shell-tool', + parent_task_id: 'owner', + is_backgrounded: true + }) + ) + const owner = run.records().find((row) => row.kind === 'agent') + const shell = run.records().find((row) => row.kind === 'command') + if (shape === 'known-terminal') { + expect(owner?.membership).not.toBe('live') + } else { + expect(owner).toMatchObject({ membership: 'live', stoppable: true }) + expect(shell).toMatchObject({ + membership: 'live', + stoppable: true, + parentChildWorkId: owner?.childWorkId + }) + } + } +) + +it('releases an alias-less roster against reopened ownership on binding without another provider frame', async () => { + const root = await mkdtemp(join(tmpdir(), 'orca-parent-binding-')) + cleanup.push(root) + const identity = identityFor() + const open = () => journals.open({ identity, now: () => 9000, stateDirectory: root }) + let journal = await open() + for (const id of ['saved-shell', 'saved-only']) { + await journal.appendItem( + claudeBackgroundTaskIdentity(id, 1), + claudeBackgroundTaskBody({ + type: 'background-task', + taskId: id, + kind: 'command', + label: 'sleep', + parentToolUseId: 'saved-tool', + state: 'unverifiable', + startedAt: 1 + }), + { + fence: 1, + turnScope: AGENT_JOURNAL_THREAD_SCOPE, + agentId: id, + parentAgentId: 'saved-owner', + producerKind: 'background', + providerParentRef: 'saved-tool' + } + ) + } + const originalId = journal.snapshot().items[0]!.itemId + await journals.closeAll() + journal = await open() + const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + deferred.sink.appendItem( + { provider: 'claude', sessionId: 'saved-session', uuid: 'before-bind' }, + { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Earlier queued write' }] }, + { turnScope: AGENT_JOURNAL_THREAD_SCOPE } + ) + const claude = fakeClaude() + const evidence: AgentChildWorkEvidence[] = [] + const adapter = adapterAtPublishFor( + claude, + {}, + [], + [], + undefined, + undefined, + (_sessionId, batch) => evidence.push(...batch) + ) + await adapter.acquire({ identity, fence: 1, spawnToken: 'binding-test', events: deferred.sink }) + const roster = () => + claude.connections[0]!.handlers.onMessage?.( + system('background_tasks_changed', { + tasks: [{ task_id: 'saved-shell', task_type: 'local_bash' }] + }) + ) + roster() + claude.connections[0]!.handlers.onMessage?.( + frame({ + type: 'assistant', + message: { + id: 'held-assistant', + role: 'assistant', + content: [{ type: 'text', text: 'Later provider write' }] + } + }) + ) + expect(evidence.filter((edge) => edge.type === 'live')).toEqual([]) + deferred.bind({ journal, fence: 1, publish: () => {} }) + expect(await deferred.drained()).toEqual({ ok: true }) + expect(evidence).toContainEqual( + expect.objectContaining({ + type: 'live', + child: expect.objectContaining({ + ownerId: 'saved-owner', + stoppable: true + }) + }) + ) + const liveIds = evidence + .filter((edge) => edge.type === 'live') + .map((edge) => edge.child.handle.id) + expect(liveIds).toContain('saved-shell') + expect(liveIds).not.toContain('saved-only') + const queuedMessages = journal + .snapshot() + .items.filter( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => + block.type === 'text' && + (block.text === 'Earlier queued write' || block.text === 'Later provider write') + ) + ) + expect(queuedMessages.map((row) => row.body)).toMatchObject([ + { kind: 'message', blocks: [{ type: 'text', text: 'Earlier queued write' }] }, + { kind: 'message', blocks: [{ type: 'text', text: 'Later provider write' }] } + ]) + expect(queuedMessages[0]!.sequence).toBeLessThan(queuedMessages[1]!.sequence) + expect(journal.item(originalId)).toMatchObject({ + agentId: 'saved-shell', + parentAgentId: 'saved-owner', + providerParentRef: 'saved-tool' + }) + expect(journal.item(originalId)?.body).toMatchObject({ + kind: 'message', + blocks: expect.arrayContaining([ + expect.objectContaining({ + taskId: 'saved-shell', + parentToolUseId: 'saved-tool', + state: 'working' + }) + ]) + }) + roster() + expect(await deferred.drained()).toEqual({ ok: true }) + expect( + journal + .snapshot() + .items.filter( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.taskId === 'saved-shell' + ) + ) + ).toHaveLength(1) + expect(journal.snapshot().items.find((row) => row.agentId === 'saved-only')?.body).toMatchObject({ + kind: 'message', + blocks: expect.arrayContaining([expect.objectContaining({ state: 'unverifiable' })]) + }) + const retired = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) + const replacement = adapterAtPublishFor(claude) + await replacement.acquire({ + identity, + fence: 1, + spawnToken: 'retired-test', + events: retired.sink + }) + claude.connections[1]!.handlers.onMessage?.( + system('task_started', { + task_id: 'retired-shell', + task_type: 'local_bash', + is_backgrounded: true + }) + ) + await replacement.releaseAcquisition({ sessionId: identity.sessionId }) + retired.bind({ journal, fence: 1, publish: () => {} }) + expect(await retired.drained()).toEqual({ ok: true }) + expect( + journal + .snapshot() + .items.some( + (row) => + row.body.kind === 'message' && + row.body.blocks.some( + (block) => block.type === 'background-task' && block.taskId === 'retired-shell' + ) + ) + ).toBe(false) + retired.close() + await adapter.releaseAcquisition({ sessionId: identity.sessionId }) + deferred.close() +}) diff --git a/src/main/claude/claude-stream-json-connection.test.ts b/src/main/claude/claude-stream-json-connection.test.ts index 17b63de60f7..95c7ec08f6a 100644 --- a/src/main/claude/claude-stream-json-connection.test.ts +++ b/src/main/claude/claude-stream-json-connection.test.ts @@ -147,6 +147,20 @@ function processState(pid: number): 'running' | 'exited' { } describe('Claude stream-json connection', () => { + it('completes task Stop through the real SDK while semantic reading is paused', async () => { + const scenario = scriptScenario([HOLD_OPEN]) + const connection = await open(launchFor(scenario)) + await connection.initializationResult() + connection.pauseReading?.() + await connection.stopTask('owned-shell') + expect(scenario.readReport().controlRequests).toContainEqual( + expect.objectContaining({ + request: expect.objectContaining({ subtype: 'stop_task', task_id: 'owned-shell' }) + }) + ) + connection.resumeReading?.() + }) + it('settles a send only once the frame reached the child, and replays reach onMessage', async () => { const replay = { type: 'user', diff --git a/src/main/claude/claude-subagent-identities.ts b/src/main/claude/claude-subagent-identities.ts index 7cdd45d5c6c..ebafff0d1da 100644 --- a/src/main/claude/claude-subagent-identities.ts +++ b/src/main/claude/claude-subagent-identities.ts @@ -1,3 +1,4 @@ +import { ClaudeTaskInvocations } from './claude-task-invocations' import { BoundedMap } from '../../shared/bounded-map' import { ClaudeSubagentIds } from './claude-subagent-id-aliases' import type { ClaudeJournaledSubagents } from './claude-subagent-journaled-identities' @@ -19,6 +20,7 @@ export type ClaudeSubagentIdentitiesDeps = { /** Resolve grandchildren through the child that journaled their spawn call. */ childOwnerRefOf?: (toolUseId: string) => string | null journaled?: ClaudeJournaledSubagents + taskInvocations?: ClaudeTaskInvocations } export class ClaudeSubagentIdentities { @@ -26,9 +28,11 @@ export class ClaudeSubagentIdentities { private readonly known = new BoundedMap({ maxEntries: MAX_KNOWN_SUBAGENTS }) + readonly taskInvocations: ClaudeTaskInvocations readonly linkage: ClaudeSubagentLinkageSource & ClaudeAgentLinkageSource constructor(private readonly deps: ClaudeSubagentIdentitiesDeps) { + this.taskInvocations = deps.taskInvocations ?? new ClaudeTaskInvocations(deps.journaled) this.ids = new ClaudeSubagentIds(deps.journaled?.canonical) this.linkage = new ClaudeSubagentLinkage({ ids: this.ids, @@ -39,11 +43,16 @@ export class ClaudeSubagentIdentities { }, isForwardedParentTool: deps.isForwardedParentTool, childOwnerRefOf: deps.childOwnerRefOf, + parentTaskOf: this.parentOf, spawnRefOf: (canonicalId) => this.known.get(canonicalId)?.run ?? null }) } + parentOf = (id: string, run?: string): string | undefined => + this.taskInvocations.parentOf(id, run) + observeSystemFrame(message: Record): boolean { + this.taskInvocations.observe(message) const frame = readClaudeSubagentTaskFrame(message) if (!frame) { return false @@ -62,7 +71,10 @@ export class ClaudeSubagentIdentities { if (frame.toolUseId) { this.ids.alias(frame.toolUseId, frame.taskId) } - if (frame.announcesSubagent) { + if ( + frame.announcesSubagent && + this.taskInvocations.selection(message, frame.taskId)?.acceptsStart !== false + ) { this.announce(frame.taskId, frame.toolUseId) } return true diff --git a/src/main/claude/claude-subagent-journaled-identities.ts b/src/main/claude/claude-subagent-journaled-identities.ts index 7094a9b49c5..82b51b7d0f3 100644 --- a/src/main/claude/claude-subagent-journaled-identities.ts +++ b/src/main/claude/claude-subagent-journaled-identities.ts @@ -1,3 +1,10 @@ +import { + indexClaudeBackgroundTask, + selectClaudeBackgroundTask, + type ClaudeBackgroundTaskIndex, + type ClaudeBackgroundTaskDescriptor +} from './claude-background-task-identity' +import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types' import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types' import { namedSubagents } from '../../shared/native-chat/transcript/native-chat-subagent-items' import type { StructuredAgentSessionLinkageJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views' @@ -6,6 +13,8 @@ import { isBoundedClaudeTaskId } from './claude-background-task-tracker' type Reading = { canonicalByToolUse: Map attemptByAgent: Map + parents: Map> + backgrounds: Map subagents: Set } @@ -23,6 +32,15 @@ export class ClaudeJournaledSubagents { /** Zero means no journaled attempt. */ attempt = (agentId: string): number => this.current()?.attemptByAgent.get(agentId) ?? 0 + parent = (taskId: string, run?: string): string | undefined => + (run === undefined + ? [...(this.current()?.parents.get(taskId)?.values() ?? [])].at(-1) + : this.current()?.parents.get(taskId)?.get(run) + )?.parentAgentId + + background = (taskId: string, run?: string): ClaudeBackgroundTaskDescriptor | undefined => + selectClaudeBackgroundTask(this.current()?.backgrounds.get(taskId), run) + isSubagent = (taskId: string): boolean => this.current()?.subagents.has(taskId) === true private current(): Reading | null { @@ -43,9 +61,24 @@ function read(journal: StructuredAgentSessionLinkageJournal): Reading { const reading: Reading = { canonicalByToolUse: new Map(), attemptByAgent: new Map(), + parents: new Map(), + backgrounds: new Map(), subagents: new Set() } - journal.visitItemsWithLinkage((_itemId, _sequence, body, linkage) => { + journal.visitItemsWithLinkage((itemId, _sequence, body, linkage) => { + if (linkage.agentId !== undefined && linkage.producerKind === 'agent') { + const parents = reading.parents.get(linkage.agentId) ?? new Map() + parents.delete(linkage.providerParentRef) + parents.set(linkage.providerParentRef, linkage) + reading.parents.set(linkage.agentId, parents) + } + if (body.kind === 'message') { + for (const block of body.blocks.filter(isBackgroundTaskBlock)) { + const index = reading.backgrounds.get(block.taskId) ?? { aliases: new Map() } + indexClaudeBackgroundTask(index, itemId, block.taskId, block.parentToolUseId, linkage) + reading.backgrounds.set(block.taskId, index) + } + } readAgentRow(reading, linkage) if (body.kind === 'message' && linkage.agentId === undefined) { for (const entry of body.blocks.flatMap(namedSubagents)) { diff --git a/src/main/claude/claude-subagent-linkage.ts b/src/main/claude/claude-subagent-linkage.ts index 8d6b221959d..ba8eed43498 100644 --- a/src/main/claude/claude-subagent-linkage.ts +++ b/src/main/claude/claude-subagent-linkage.ts @@ -31,6 +31,7 @@ export type ClaudeSubagentLinkageDeps = { isForwardedParentTool?: (toolUseId: string) => boolean /** Map sidechain tool calls to their child owner to identify grandchildren's parents. */ childOwnerRefOf?: (toolUseId: string) => string | null + parentTaskOf?: (canonicalId: string) => string | undefined spawnRefOf?: (canonicalId: string) => string | null } @@ -62,14 +63,16 @@ export class ClaudeSubagentLinkage linkageForAgent = (agentId: string): AgentJournalProducerLinkage => { const spawnRef = this.deps.spawnRefOf?.(agentId) ?? null if (spawnRef === null) { - return { agentId, producerKind: 'agent' } + const parentAgentId = this.deps.parentTaskOf?.(agentId) + return { agentId, producerKind: 'agent', ...(parentAgentId ? { parentAgentId } : {}) } } const { linkage } = this.settledLinkageFor(spawnRef) const { parentAgentId, ...rest } = linkage + const parent = this.deps.parentTaskOf?.(agentId) ?? parentAgentId return { ...rest, agentId, - ...(parentAgentId === undefined || parentAgentId === agentId ? {} : { parentAgentId }) + ...(parent === undefined || parent === agentId ? {} : { parentAgentId: parent }) } } @@ -125,6 +128,10 @@ export class ClaudeSubagentLinkage settled: boolean, depth: number ): ParentAgentVerdict { + const explicit = this.deps.parentTaskOf?.(this.deps.ids.canonical(parentToolUseId)) + if (explicit !== undefined) { + return { kind: 'known', agentId: explicit } + } const ownerRef = this.deps.childOwnerRefOf?.(parentToolUseId) ?? null if (ownerRef === null || depth >= MAX_PARENT_RESOLUTION_DEPTH) { return { kind: 'known' } diff --git a/src/main/claude/claude-subagent-resume-after-restart.test.ts b/src/main/claude/claude-subagent-resume-after-restart.test.ts index d2cc875ba42..049cc308d76 100644 --- a/src/main/claude/claude-subagent-resume-after-restart.test.ts +++ b/src/main/claude/claude-subagent-resume-after-restart.test.ts @@ -1,3 +1,5 @@ +import { PARENT_TASK_STOP } from './claude-parent-task-frames.test-fixture' +import { blockOf } from './claude-background-task-row-test-support' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -102,10 +104,13 @@ async function openJournal(): Promise { }) } -function acquire(journal: AgentSessionJournal) { +function acquire(journal: AgentSessionJournal, delayed = false) { const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging()) const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 }) - deferred.bind({ journal, fence: 1, publish: () => {} }) + const bind = () => deferred.bind({ journal, fence: 1, publish: () => {} }) + if (!delayed) { + bind() + } const settle = async (): Promise => { await expect(deferred.drained()).resolves.toEqual({ ok: true }) } @@ -115,7 +120,7 @@ function acquire(journal: AgentSessionJournal) { translator.dispose() deferred.close() } - return { translator, settle, exit } + return { translator, settle, exit, bind } } const proseRow = (journal: AgentSessionJournal, text: string): AgentJournalRenderItem | undefined => @@ -128,6 +133,85 @@ const proseRow = (journal: AgentSessionJournal, text: string): AgentJournalRende ) describe('a Claude subagent resumed after its provider restarted', () => { + it.each(['terminal-only', 'roster-first', 'unbound-roster-first', 'parent-omitting-roster'])( + 'retains one owned shell across close/reopen: %s', + async (order) => { + let journal = await openJournal() + const first = acquire(journal) + first.translator.handle(userTurn('parent-task-turn')) + // Contract: a parentless admission can learn ownership from a later roster without a body change. + first.translator.handle( + frame({ ...PARENT_TASK_STOP[3]!.frame, parent_task_id: undefined, tool_use_id: undefined }) + ) + await first.settle() + const beforeOwnership = journal + .snapshot() + .items.find((item) => blockOf(item.body)?.taskId === 'shell-child') + expect(beforeOwnership?.agentId).toBeUndefined() + first.translator.handle(frame(PARENT_TASK_STOP[2]!.frame)) + await first.settle() + expect(journal.item(beforeOwnership!.itemId)).toMatchObject({ + agentId: 'shell-child', + parentAgentId: 'agent-parent' + }) + first.translator.handle(frame(PARENT_TASK_STOP[3]!.frame)) + await first.settle() + const shell = journal + .snapshot() + .items.find((item) => blockOf(item.body)?.taskId === 'shell-child') + expect(shell).toMatchObject({ + agentId: 'shell-child', + parentAgentId: 'agent-parent', + producerKind: 'background', + providerParentRef: 'toolu_shell' + }) + await first.exit() + expect(blockOf(journal.item(shell!.itemId)?.body)?.state).toBe('unverifiable') + await journals.closeAll() + + journal = await openJournal() + const delayed = order === 'unbound-roster-first' + const resumed = acquire(journal, delayed) + if (!delayed) { + expect(resumed.translator.childTaskParent?.('shell-child')).toBe('agent-parent') + } + if (order === 'parent-omitting-roster') { + resumed.translator.handle( + frame({ + type: 'system', + subtype: 'background_tasks_changed', + tasks: [{ task_id: 'shell-child', task_type: 'local_bash' }] + }) + ) + await resumed.settle() + expect(journal.item(shell!.itemId)).toMatchObject({ parentAgentId: 'agent-parent' }) + expect(blockOf(journal.item(shell!.itemId)?.body)?.state).toBe('working') + } else if (order !== 'terminal-only') { + resumed.translator.handle(frame(PARENT_TASK_STOP[2]!.frame)) + resumed.translator.handle(frame(PARENT_TASK_STOP[3]!.frame)) + } + if (delayed) { + resumed.bind() + } + // Contract: a terminal revision must retain saved ownership even without a repeated start. + resumed.translator.handle(frame(PARENT_TASK_STOP[8]!.frame)) + await resumed.settle() + const shells = journal + .snapshot() + .items.filter((item) => blockOf(item.body)?.taskId === 'shell-child') + expect(shells).toHaveLength(1) + expect(shells[0]).toMatchObject({ + itemId: shell!.itemId, + agentId: 'shell-child', + parentAgentId: 'agent-parent', + producerKind: 'background', + providerParentRef: 'toolu_shell' + }) + expect(blockOf(shells[0]?.body)?.state).toBe('idle') + await resumed.exit() + } + ) + it('keeps the canonical id its first run was given, so one child stays one child', async () => { const journal = await openJournal() diff --git a/src/main/claude/claude-subagent-task-frames.ts b/src/main/claude/claude-subagent-task-frames.ts index 487756f83c4..89602d480ce 100644 --- a/src/main/claude/claude-subagent-task-frames.ts +++ b/src/main/claude/claude-subagent-task-frames.ts @@ -1,3 +1,4 @@ +import type { AgentChildWorkKind } from '../../shared/agent-status/child-work/agent-status-child-work' // Task IDs alone cannot distinguish agents from shells or workflows; task_type identifies the kind. import { @@ -63,3 +64,10 @@ export function readClaudeSubagentTaskFrame( excluded: announcement && !subagent } } + +/** Releases predating `task_type` still name an agent in `subagent_type`. */ +export function claudeStartedTaskKind(message: Record): AgentChildWorkKind { + return isClaudeSubagentTask(message) + ? 'agent' + : classifyClaudeBackgroundTaskKind(message.task_type) +} diff --git a/src/main/claude/claude-task-invocations.ts b/src/main/claude/claude-task-invocations.ts new file mode 100644 index 00000000000..fd417cb0f32 --- /dev/null +++ b/src/main/claude/claude-task-invocations.ts @@ -0,0 +1,165 @@ +import { record, taskAliasId, taskId } from './claude-background-task-frames' +import type { ClaudeBackgroundTaskDescriptor } from './claude-background-task-identity' + +export type ClaudeTaskInvocation = { + toolUseId?: string + parentTaskId?: string + /** Only current provider evidence may correct durable producer attribution. */ + reportedParentTaskId?: string + excluded: boolean + monitor: boolean + ended?: { status: string; toolUseId?: string } + /** Only accepted current evidence proves an alias is historical after replacement. */ + observed: boolean +} + +type Selection = { invocation: ClaudeTaskInvocation; current: boolean; acceptsStart: boolean } +type Task = { current: ClaudeTaskInvocation; aliases: Map } + +/** Acquisition-local provider facts; saved ownership never establishes a live task. */ +export class ClaudeTaskInvocations { + private readonly tasks = new Map() + private readonly observations = new WeakMap>() + + constructor( + private readonly saved?: { + background: (id: string, run?: string) => ClaudeBackgroundTaskDescriptor | undefined + parent: (id: string, run?: string) => string | undefined + } + ) {} + + observe(message: Record): void { + if (message.type !== 'system' || this.observations.has(message)) { + return + } + const selections = new Map() + this.observations.set(message, selections) + const roster = message.subtype === 'background_tasks_changed' + const entries = roster && Array.isArray(message.tasks) ? message.tasks : [message] + for (const entry of entries) { + const frame = record(entry) + const id = frame && taskId(frame) + if (!frame || !id) { + continue + } + const run = taskAliasId(frame.tool_use_id) ?? taskAliasId(record(frame.patch)?.tool_use_id) + const start = message.subtype === 'task_started' + const selection = this.select(id, run, start) + const { invocation, acceptsStart } = selection + if ((!start && !roster) || acceptsStart) { + invocation.observed ||= selection.current + invocation.toolUseId ??= run + invocation.reportedParentTaskId = + taskAliasId(frame.parent_task_id) ?? invocation.reportedParentTaskId + invocation.parentTaskId = invocation.reportedParentTaskId ?? invocation.parentTaskId + invocation.excluded ||= frame.ambient === true || frame.skip_transcript === true + if (start && acceptsStart) { + invocation.ended = undefined + } + } + if (message.subtype === 'task_notification') { + invocation.ended = { status: String(frame.status), toolUseId: invocation.toolUseId } + } + if (invocation.toolUseId) { + this.tasks.get(id)!.aliases.set(invocation.toolUseId, invocation) + } + selections.set(id, selection) + if (roster) { + this.observations.set(frame, new Map([[id, selection]])) + } + } + } + + selection(message: Record, id: string): Selection | undefined { + this.observe(message) + return this.observations.get(message)?.get(id) + } + + get(id: string, run?: string): ClaudeTaskInvocation | undefined { + const task = this.tasks.get(id) + return run === undefined + ? task?.current + : (task?.aliases.get(run) ?? + (task?.current.toolUseId === undefined ? task?.current : undefined)) + } + + parentOf = (id: string, run?: string): string | undefined => { + const task = this.tasks.get(id) + const invocation = run === undefined ? task?.current : task?.aliases.get(run) + return invocation + ? invocation.parentTaskId + : (this.saved?.background(id, run)?.linkage.parentAgentId ?? this.saved?.parent(id, run)) + } + + excludeMonitor(id: string, run?: string): void { + this.select(id, taskAliasId(run), true).invocation.monitor = true + } + + settle(id: string, status: unknown, run?: string): void { + const invocation = this.get(id, run) + if (invocation) { + invocation.ended = { status: String(status), toolUseId: invocation.toolUseId } + } + } + + settleFrame(id: string, message: Record): void { + this.settle( + id, + record(message.patch)?.status ?? message.status, + taskAliasId(message.tool_use_id) ?? taskAliasId(record(message.patch)?.tool_use_id) + ) + } + + clear(): void { + this.tasks.clear() + } + + private select(id: string, run: string | undefined, start: boolean): Selection { + let task = this.tasks.get(id) + if (!task) { + const latest = this.saved?.background(id) + const current = this.recover(id, latest ? undefined : run) + task = { current, aliases: new Map() } + if (current.toolUseId) { + task.aliases.set(current.toolUseId, current) + } + this.tasks.set(id, task) + } + let invocation = task.current + if (run !== undefined && invocation.toolUseId !== undefined && invocation.toolUseId !== run) { + const saved = this.saved?.background(id, run) + invocation = task.aliases.get(run) ?? this.recover(id, run) + // A known historical alias cannot replace the current invocation; a pending tool result can. + if ( + start && + !invocation.observed && + saved?.toolUseId !== run && + (task.current.ended !== undefined || !task.current.observed) + ) { + task.current = invocation + } + task.aliases.set(run, invocation) + } + const current = task.current === invocation + return { + invocation, + current, + acceptsStart: + current && + (invocation.ended === undefined || + (start && + (invocation.ended.status === 'completed' || invocation.ended.toolUseId === undefined))) + } + } + + private recover(id: string, run?: string): ClaudeTaskInvocation { + const descriptor = this.saved?.background(id, run) + return { + toolUseId: run ?? descriptor?.toolUseId, + parentTaskId: descriptor?.linkage.parentAgentId ?? this.saved?.parent(id, run), + observed: false, + excluded: false, + monitor: false + } + } +} diff --git a/src/main/claude/structured/claude-conversation-title-owner.test.ts b/src/main/claude/structured/claude-conversation-title-owner.test.ts new file mode 100644 index 00000000000..5a31653bbd5 --- /dev/null +++ b/src/main/claude/structured/claude-conversation-title-owner.test.ts @@ -0,0 +1,111 @@ +import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router' +import * as installedRouter from '../../claude-accounts/claude-profile-installed-router' +import { afterEach, expect, it, vi } from 'vitest' +import { acquired, fakeClaude, PROVIDER_SESSION_ID } from './claude-structured-session-test-support' +import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' + +afterEach(() => vi.restoreAllMocks()) + +it('reads only cached support and rejects a retired acquisition or changed account/context', async () => { + const cliFlag = vi.fn(async () => 'supported' as const) + const cli = fakeClaude() + const router = new ClaudeProfileRouter({ + getSettings: () => ({ + claudeManagedAccounts: [], + activeClaudeManagedAccountId: null, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + }), + dataRoot: '/isolated', + userHome: '/users/test', + env: {} + }) + const preparation = vi.spyOn(router, 'preparation') + vi.spyOn(installedRouter, 'getClaudeProfileRouter').mockReturnValue(router) + const adapter = await acquired(cli, { + cliFlag, + account: 'system', + claudeConfigDir: '/accounts/claude', + accountRecipe: { route: 'system', home: '/accounts/claude', configDir: '/accounts/claude' } + }) + try { + const record = agentSessionRecordFixture() + record.sessionId = 'session-1' + record.accountHome = { variable: 'CLAUDE_CONFIG_DIR', path: '/accounts/claude' } + record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID + const generate = vi.fn(async () => 'Broken chat title') + cli.connections[0]!.generateSessionTitle = generate + const owner = adapter.captureConversationTitleOwner(record)! + expect(owner.isCurrent(record)).toBe(true) + expect(await owner.generate('Repair login', () => owner.isCurrent(record))).toBe( + 'Broken chat title' + ) + expect(cliFlag).toHaveBeenLastCalledWith( + { option: 'generate_session_title', firstVersion: '2.1.310' }, + 250, + false + ) + expect( + owner.isCurrent({ ...record, accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/other' } }) + ).toBe(false) + expect( + owner.isCurrent({ + ...record, + providerContextBoundary: { operationId: 'clear-1', afterFence: 7, clearedAt: 1 } + }) + ).toBe(false) + const system = router.preparation() + preparation.mockReturnValue({ + ...system, + provenance: 'profile:other', + configDir: '/accounts/other' + }) + expect(owner.isCurrent(record)).toBe(false) + preparation.mockReturnValue(system) + expect(owner.isCurrent(record)).toBe(true) + await adapter.closeAll() + expect(owner.isCurrent(record)).toBe(false) + } finally { + await adapter.closeAll() + cli.dispose() + } +}) + +it.each(['unknown', 'unsupported'] as const)( + 'keeps %s CLIs on the existing generator path', + async (support) => { + const cli = fakeClaude() + const adapter = await acquired(cli, { cliFlag: async () => support }) + try { + const record = agentSessionRecordFixture() + record.sessionId = 'session-1' + record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID + const generate = vi.fn(async () => 'Do not use') + cli.connections[0]!.generateSessionTitle = generate + const owner = adapter.captureConversationTitleOwner(record)! + expect(await owner.generate('Repair login', () => true)).toBeNull() + expect(generate).not.toHaveBeenCalled() + } finally { + await adapter.closeAll() + cli.dispose() + } + } +) + +it('retains retirement knowledge when the optional title method is missing', async () => { + const cli = fakeClaude() + const adapter = await acquired(cli) + try { + const record = agentSessionRecordFixture() + record.sessionId = 'session-1' + record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID + const owner = adapter.captureConversationTitleOwner(record)! + expect(owner.isCurrent(record)).toBe(true) + expect(await owner.generate('Repair login', () => owner.isCurrent(record))).toBeNull() + await adapter.closeAll() + expect(owner.isCurrent(record)).toBe(false) + } finally { + await adapter.closeAll() + cli.dispose() + } +}) diff --git a/src/main/claude/structured/claude-conversation-title-owner.ts b/src/main/claude/structured/claude-conversation-title-owner.ts new file mode 100644 index 00000000000..640b72c668c --- /dev/null +++ b/src/main/claude/structured/claude-conversation-title-owner.ts @@ -0,0 +1,88 @@ +import { resolve } from 'node:path' +import { getClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router' +import { agentSessionAccountHomesEqual } from '../../../shared/agent-session/lifecycle/agent-session-account-home' +import { claudeNamingContextId } from '../claude-conversation-naming' +import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS } from '../claude-cli-flag-support' +import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter' +import type { ClaudeSession } from './claude-structured-session-state' + +export const captureClaudeConversationTitleOwner = + ( + sessions: Map + ): NonNullable => + (record) => { + const session = sessions.get(record.sessionId) + if (!session) { + return null + } + const { connection, acquisitionGeneration, fence, providerSessionId, initialization } = session + const boundary = record.providerContextBoundary?.operationId + const account = () => { + try { + const policy = getClaudeProfileRouter()?.preparation() + const recipe = initialization.accountRecipe + if (policy) { + if ((recipe?.route ?? initialization.account) === 'managed') { + if ( + !policy.provenance.startsWith('profile:') || + (recipe?.route === 'managed' && + policy.provenance !== `profile:${recipe.accountId}`) || + resolve(initialization.cwd, policy.configDir) !== initialization.claudeConfigDir + ) { + return null + } + } else if (policy.provenance !== 'system') { + return null + } + } + return JSON.stringify([ + policy?.provenance, + policy?.provenance.startsWith('profile:') ? policy.configDir : null + ]) + } catch { + return null + } + } + const selectedAccount = account() + const isCurrent: NonNullable< + ReturnType> + >['isCurrent'] = (current) => + sessions.get(record.sessionId) === session && + session.connection === connection && + !connection.closed && + !session.closeFinalization && + session.acquisitionGeneration === acquisitionGeneration && + session.fence === fence && + current.lease.runtimeFence === fence && + current.provider === 'claude' && + session.providerSessionId === providerSessionId && + claudeNamingContextId(current) === providerSessionId && + current.providerContextBoundary?.operationId === boundary && + agentSessionAccountHomesEqual(current.accountHome, record.accountHome) && + current.location.workspaceId === record.location.workspaceId && + current.location.executionHostId === record.location.executionHostId && + session.initialization === initialization && + selectedAccount !== null && + account() === selectedAccount + return { + isCurrent, + generate: async (firstPrompt, shouldExecute) => { + if ( + !session.initialization.startup.opened() || + !connection.generateSessionTitle || + !shouldExecute() + ) { + return null + } + // Verified support floor, not the request's introduction version; never start a probe here. + const supported = await session.cliFlag?.( + { option: 'generate_session_title', firstVersion: '2.1.310' }, + CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS, + false + ) + return supported === 'supported' && shouldExecute() + ? connection.generateSessionTitle?.(firstPrompt) + : null + } + } + } diff --git a/src/main/claude/structured/claude-kill-delivered-exit-receipt.ts b/src/main/claude/structured/claude-kill-delivered-exit-receipt.ts new file mode 100644 index 00000000000..4fa1bbb75ef --- /dev/null +++ b/src/main/claude/structured/claude-kill-delivered-exit-receipt.ts @@ -0,0 +1,10 @@ +import { AgentSessionAcquisitionRootExitObservedError } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' + +export function isKillDeliveredExitReceipt( + receipt: Error | undefined +): receipt is AgentSessionAcquisitionRootExitObservedError { + return ( + receipt instanceof AgentSessionAcquisitionRootExitObservedError && + receipt.deathEvidenceKind === 'kill-delivered' + ) +} diff --git a/src/main/claude/structured/claude-owned-task-send.test.ts b/src/main/claude/structured/claude-owned-task-send.test.ts new file mode 100644 index 00000000000..1f842127849 --- /dev/null +++ b/src/main/claude/structured/claude-owned-task-send.test.ts @@ -0,0 +1,116 @@ +import { expect, it } from 'vitest' +import { + adapterFor, + claudeFrame, + fakeClaude, + identityFor +} from './claude-structured-session-test-support' +import { PARENT_TASK_STOP } from '../claude-parent-task-frames.test-fixture' +import { createQueuedMessageTestRig } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture' +import { eventually } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture' +import { HOST_TEST_SESSION as SESSION } from '../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' +import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' + +it('delivers an ordinary send after an owned roster/start refresh without inventing root work', async () => { + const claude = fakeClaude() + const evidence: AgentChildWorkEvidence[] = [] + const rig = await createQueuedMessageTestRig({ agent: 'claude' }) + const adapter = adapterFor( + claude, + {}, + [], + [], + undefined, + undefined, + (_sessionId, batch) => evidence.push(...batch), + (outcome) => { + void rig.host.settleLateDispatch({ ...outcome, sessionId: SESSION }) + } + ) + let acquired = false + try { + rig.dispatch.mockImplementation(async (input) => { + if (!acquired) { + await adapter.acquire({ + identity: identityFor(SESSION), + fence: 1, + spawnToken: 'spawn-1', + events: rig.providerEvents() + }) + acquired = true + } + return adapter.dispatch({ ...input, sessionId: SESSION, fence: 1 }) + }) + const first = rig.send('start the work') + expect(await first.result).toMatchObject({ ok: true }) + await eventually(async () => + expect((await rig.submission(first.id))?.dispatchState).toBe('accepted') + ) + const connection = claude.connections[0]! + claudeFrame(connection, { + type: 'assistant', + uuid: 'root-answer', + parent_tool_use_id: null, + message: { role: 'assistant', content: [{ type: 'text', text: 'Started.' }] } + }) + claudeFrame(connection, { + type: 'result', + subtype: 'success', + uuid: 'root-result', + parent_tool_use_id: null, + duration_ms: 1000 + }) + await rig.host.collaboratorsForTests().runtimeState.flushAllEventSinks() + expect(rig.host.currentWork(SESSION)!.working()).toBe(false) + + // Recorded CLI roster has no tool alias; the following start enriches that same task. + const roster = PARENT_TASK_STOP[2]!.frame + claudeFrame(connection, { + ...roster, + tasks: Array.isArray(roster.tasks) ? roster.tasks.slice(1) : [] + }) + claudeFrame(connection, PARENT_TASK_STOP[3]!.frame) + await rig.host.collaboratorsForTests().runtimeState.flushAllEventSinks() + const snapshot = await rig.host.journalSnapshot(SESSION) + const children = snapshot.items.filter( + (item) => + item.body.kind === 'message' && + item.body.blocks.some( + (block) => block.type === 'background-task' && block.taskId === 'shell-child' + ) + ) + expect(children).toHaveLength(1) + expect(children[0]).toMatchObject({ agentId: 'shell-child', parentAgentId: 'agent-parent' }) + expect(evidence).toContainEqual( + expect.objectContaining({ + type: 'live', + child: expect.objectContaining({ + handle: expect.objectContaining({ id: 'shell-child' }), + ownerId: 'agent-parent', + stoppable: true + }) + }) + ) + const rootAfterChild = rig.host + .collaboratorsForTests() + .sessions.get(SESSION)! + .journal.runningTurn() + + const followup = rig.send('continue normally') + expect(await followup.result).toMatchObject({ ok: true }) + await eventually(async () => + expect((await rig.submission(followup.id))?.handedOverAt).toBeDefined() + ) + expect(rootAfterChild).toBeNull() + expect(connection.sent).toHaveLength(2) + expect(connection.sent[1]).toMatchObject({ + message: { + content: [{ type: 'text', text: 'continue normally' }] + } + }) + } finally { + await adapter.closeAll() + await rig.dispose() + claude.dispose() + } +}) diff --git a/src/main/claude/structured/claude-structured-dispatch-test-support.ts b/src/main/claude/structured/claude-structured-dispatch-test-support.ts index 63850f38e96..28964e3371a 100644 --- a/src/main/claude/structured/claude-structured-dispatch-test-support.ts +++ b/src/main/claude/structured/claude-structured-dispatch-test-support.ts @@ -1,3 +1,4 @@ +import { ClaudeJournalBoundDelivery } from '../claude-journal-bound-delivery' import { vi, type Mock } from 'vitest' import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' import { retireClaudeDispatchWaiters } from './claude-structured-dispatch' @@ -21,6 +22,7 @@ export function sessionFor(send: Mock = vi.fn().mockResolvedValue(undefined)): C dispatchWaiters: [], retiredDispatchWaiters: [], replayContentFallbackBlocked: false, + delivery: new ClaudeJournalBoundDelivery(), backgroundTasks: new ClaudeBackgroundTaskTracker(), childWork: new ClaudeChildWorkDecoder(), commands: new ClaudeSlashCommandCatalog(), diff --git a/src/main/claude/structured/claude-structured-event-delivery.ts b/src/main/claude/structured/claude-structured-event-delivery.ts index bf79ece6d23..0bd7e9189bf 100644 --- a/src/main/claude/structured/claude-structured-event-delivery.ts +++ b/src/main/claude/structured/claude-structured-event-delivery.ts @@ -30,6 +30,7 @@ export function emitClaudeStructuredSessionEvent({ deps.onEvent?.(event) } if (event.type === 'ended' || event.type === 'retiring') { + session?.delivery.dispose() session?.childWork.clear() session?.backgroundTasks.clear() } else if (event.type === 'message') { @@ -56,19 +57,18 @@ export function deliverClaudeConnectionEvent( exits: ReadonlyMap, attempt: ClaudeAcquisitionAttempt, sessionId: string, - event: () => void + event: () => void, + payload?: unknown ): void { - if (!attempt.published) { - attempt.buffered.push(event) - return - } - if (exits.get(sessionId)?.error instanceof ClaudePluginInputError) { - return - } - if ( - sessions.get(sessionId)?.connection === attempt.connection || - exits.get(sessionId)?.connection === attempt.connection - ) { - event() - } + attempt.delivery.deliver(() => { + if (attempt.cancelled || exits.get(sessionId)?.error instanceof ClaudePluginInputError) { + return + } + if ( + sessions.get(sessionId)?.connection === attempt.connection || + exits.get(sessionId)?.connection === attempt.connection + ) { + event() + } + }, payload) } diff --git a/src/main/claude/structured/claude-structured-session-acquisition.ts b/src/main/claude/structured/claude-structured-session-acquisition.ts index 47bb00a664d..68dc786dbb0 100644 --- a/src/main/claude/structured/claude-structured-session-acquisition.ts +++ b/src/main/claude/structured/claude-structured-session-acquisition.ts @@ -27,10 +27,7 @@ import { readClaudeTranscriptEntryUuid } from '../claude-transcript-entry-uuid' import { claudeTurnResumePointWriter } from './claude-structured-resume-point' import { withAgentSessionCreatePhase } from '../../observability/agent-session-instrumentation' import { resolveClaudeAcquisitionLaunch } from './launch/claude-structured-acquisition-launch' -import { - bindClaudeConnectionJournalControls, - createClaudeSessionJournalTranslator -} from './journal/claude-structured-session-journal-control' +import * as journal from './journal/claude-structured-session-journal-control' import { isRootClaudeFrame } from '../claude-turn-opening' import { createClaudeStartupOutcome, endsClaudeStartup } from './claude-structured-startup-outcome' import { claudeStartupResultError } from '../claude-stream-json-exit-error' @@ -70,7 +67,7 @@ export async function acquireClaudeSession({ initProof.reject(error) } const delivery = { attempt, initProof, callbacks, sessionId, sessions } - const translator = createClaudeSessionJournalTranslator( + const translator = journal.createClaudeSessionJournalTranslator( input.events, String(input.fence), delivery, @@ -81,6 +78,8 @@ export async function acquireClaudeSession({ const recordTurnEnd = claudeTurnResumePointWriter(sessionId, sessions, deps) const observedOptions: sessionState.ClaudeSession['reportedOptions'] = {} const handlePluginUi = claudePluginUiRecovery(delivery, () => liveSession) + const deliver = (payload: unknown, run: () => void): void => + callbacks.deliver(attempt, sessionId, run, payload) const onMessage = (message: Record): void => { if ( ignoresClaudeRetiredConnection(liveSession, sessions.get(sessionId), exits.get(sessionId)) @@ -144,7 +143,7 @@ export async function acquireClaudeSession({ liveSession, settlements, () => - callbacks.deliver(attempt, sessionId, () => { + deliver(message, () => { if (liveSession && (modelReport || permissionChanged)) { callbacks.emit(liveSession, input.events, { type: 'options-reported', @@ -175,7 +174,7 @@ export async function acquireClaudeSession({ ) } const emit = (event: Parameters[2]): void => - callbacks.deliver(attempt, sessionId, () => callbacks.emit(liveSession, input.events, event)) + deliver(event, () => callbacks.emit(liveSession, input.events, event)) try { const launch = await resolveClaudeAcquisitionLaunch({ @@ -230,11 +229,12 @@ export async function acquireClaudeSession({ ) attempt.connection = connection naming?.attach(connection) - unbindReadingControl = bindClaudeConnectionJournalControls( + unbindReadingControl = journal.bindClaudeConnectionJournalControls( input.events, connection, translator, - deps.now ? { now: deps.now } : {} + deps.now ? { now: deps.now } : {}, + attempt.delivery ) acquisitions.assertCurrent(sessionId, attempt) if (connection.pid === undefined) { @@ -262,6 +262,7 @@ export async function acquireClaudeSession({ leafUuid: observedLeafUuid, prompts, translator, + delivery: attempt.delivery, ...(unbindReadingControl ? { unbindReadingControl } : {}), process, initialization: { @@ -293,6 +294,7 @@ export async function acquireClaudeSession({ }) return acquisition } catch (error) { + attempt.delivery.dispose() unbindReadingControl?.() throw await resolveClaudeAcquisitionError({ error: await claudeStartupError(error, attempt.connection), diff --git a/src/main/claude/structured/claude-structured-session-adapter.ts b/src/main/claude/structured/claude-structured-session-adapter.ts index c72b025529e..01c999c9dee 100644 --- a/src/main/claude/structured/claude-structured-session-adapter.ts +++ b/src/main/claude/structured/claude-structured-session-adapter.ts @@ -1,5 +1,5 @@ import { dispatchClaudeCommand } from './claude-structured-command-dispatch' -import { AgentSessionAcquisitionRootExitObservedError } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' +import { isKillDeliveredExitReceipt } from './claude-kill-delivered-exit-receipt' import { claudeAcquireFailure } from '../claude-startup-failure' import { claudeStartPublication, openClaudeStart } from './claude-structured-start-ending' import { AgentSessionStartEndings } from '../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' @@ -34,7 +34,6 @@ import { settleClaudeUnexpectedExit, type ClaudeExitLifecycle } from './claude-structured-session-exit-lifecycle' -import type { AgentSessionBackgroundTaskState } from '../../../shared/agent-session/agent-session-background-task-wire' import { drainClaudeChildWork } from '../claude-child-work-evidence' import { deliverClaudeConnectionEvent, @@ -50,9 +49,11 @@ import { claudePromptCancelRoute } from './journal/claude-structured-prompt-repl import { claudeForkForRewind } from '../claude-rewind-fork' import { copyClaudeConversation } from '../claude-conversation-copy' import { ClaudeConversationNaming } from '../claude-conversation-naming' +import { captureClaudeConversationTitleOwner } from './claude-conversation-title-owner' export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAdapter { private readonly sessions = new Map() + captureConversationTitleOwner = captureClaudeConversationTitleOwner(this.sessions) private readonly acquisitions = new ClaudeAcquisitionRegistry() private readonly exits = new Map() private readonly settledExitErrors = new Map() @@ -91,8 +92,15 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda ...(naming ? { naming } : {}), callbacks: { publish: start.publish, - deliver: (attempt, sessionId, event) => - deliverClaudeConnectionEvent(this.sessions, this.exits, attempt, sessionId, event), + deliver: (attempt, sessionId, event, payload) => + deliverClaudeConnectionEvent( + this.sessions, + this.exits, + attempt, + sessionId, + event, + payload + ), emit: (session, _events, event) => this.emit(session, event), handleExit: (sessionId, attempt, error) => observeClaudeSessionExit(this.exitLifecycle, sessionId, attempt, error), @@ -183,12 +191,6 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda session: this.session(input.sessionId), timeoutMs: this.deps.requestTimeoutMs }) - /** Test-only roster; production ownership and Stop routing use host child records. */ - backgroundTaskState = (sessionId: string): AgentSessionBackgroundTaskState | null | undefined => { - const session = this.sessions.get(sessionId) - const state = session?.backgroundTasks.state - return session && (state ? { ...state, supportsTaskStop: true } : null) - } backgroundTaskStops = (sessionId: string) => this.sessions.has(sessionId) ? { supportsTaskStop: true, supportsStopAll: true } : undefined readCommands: NonNullable = (sessionId) => @@ -250,11 +252,7 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda try { const closed = await close() const receipt = this.settledExitErrors.get(sessionId) - if ( - closed && - receipt instanceof AgentSessionAcquisitionRootExitObservedError && - receipt.deathEvidenceKind === 'kill-delivered' - ) { + if (closed && isKillDeliveredExitReceipt(receipt)) { throw receipt } return closed @@ -281,13 +279,7 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda options ) => this.releaseAcquisition({ sessionId, closeOptions: options }).finally(() => { - const receipt = this.settledExitErrors.get(sessionId) - if ( - !( - receipt instanceof AgentSessionAcquisitionRootExitObservedError && - receipt.deathEvidenceKind === 'kill-delivered' - ) - ) { + if (!isKillDeliveredExitReceipt(this.settledExitErrors.get(sessionId))) { this.settledExitErrors.delete(sessionId) } }) diff --git a/src/main/claude/structured/claude-structured-session-close.ts b/src/main/claude/structured/claude-structured-session-close.ts index 4eb98131f6d..ff1154cdca3 100644 --- a/src/main/claude/structured/claude-structured-session-close.ts +++ b/src/main/claude/structured/claude-structured-session-close.ts @@ -86,6 +86,7 @@ export async function resolveClaudeAcquisitionError(input: { } export function settleClaudeExitedSession(session: ClaudeSession): void { + session.delivery.dispose() retireClaudeDispatchWaiters(session) settleClaudeTurnEndWaiters(session) for (const prompt of session.prompts.clear()) { @@ -113,6 +114,7 @@ async function finalizeClaudePublishedSession( input: CloseClaudePublishedSessionInput, session: ClaudeSession ): Promise { + session.delivery.dispose() settleClaudeTurnEndWaiters(session) // Null settles callbacks without writing responses during SDK cleanup. for (const prompt of session.prompts.clear()) { diff --git a/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts b/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts index f25a3e8465a..f8ca501b502 100644 --- a/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts +++ b/src/main/claude/structured/claude-structured-session-exit-lifecycle.ts @@ -58,6 +58,7 @@ export function observeClaudeSessionExit( return } const observedAt = lifecycle.deps.now?.() ?? Date.now() + session.delivery.dispose() session.events?.observeExit?.(claudeHeldSends(session), observedAt) lifecycle.endings.record(sessionId, session.acquisitionGeneration, claudeExitEnding(error)) lifecycle.sessions.delete(sessionId) diff --git a/src/main/claude/structured/claude-structured-session-publication.ts b/src/main/claude/structured/claude-structured-session-publication.ts index b45af38b353..30aac7965ca 100644 --- a/src/main/claude/structured/claude-structured-session-publication.ts +++ b/src/main/claude/structured/claude-structured-session-publication.ts @@ -93,6 +93,7 @@ export function createClaudeSessionPublication(input: { leafUuid: string | null prompts: ClaudePromptRegistry translator: ClaudeJournalTranslator | null + delivery: ClaudeAcquisitionAttempt['delivery'] unbindReadingControl?: () => void process: AgentSessionAcquisition['process'] initialization: Omit< @@ -130,7 +131,7 @@ export function createClaudeSessionPublication(input: { retiredDispatchWaiters: [], replayContentFallbackBlocked: false, backgroundTasks: new ClaudeBackgroundTaskTracker(), - childWork: new ClaudeChildWorkDecoder(), + childWork: new ClaudeChildWorkDecoder(input.translator?.taskInvocations), // An unread catalog is unavailable, not empty. commands: new ClaudeSlashCommandCatalog(), dispatchSequence: 0, @@ -148,6 +149,7 @@ export function createClaudeSessionPublication(input: { ), fastModeAtStart: false, translator: input.translator, + delivery: input.delivery, events: input.request.events, ...(input.unbindReadingControl ? { unbindReadingControl: input.unbindReadingControl } : {}), link, @@ -208,9 +210,7 @@ export async function publishClaudeSessionAttempt({ await withAgentSessionCreatePhase('publish', recordPhase, async () => { callbacks.publish(session) attempt.published = true - for (const event of attempt.buffered.splice(0)) { - event() - } + attempt.delivery.flush() }) // Buffered exit delivery can remove the session during publication. if (sessions.get(sessionId) !== session) { diff --git a/src/main/claude/structured/claude-structured-session-state.ts b/src/main/claude/structured/claude-structured-session-state.ts index 5ced67286d1..c0fb4d1f620 100644 --- a/src/main/claude/structured/claude-structured-session-state.ts +++ b/src/main/claude/structured/claude-structured-session-state.ts @@ -13,6 +13,7 @@ import type { ClaudeStructuredLaunch } from './launch/claude-structured-launch-r import type { StructuredLaunchRequest } from '../../runtime/agent-session/launch/structured-agent-launch-composition' import type { ClaudeJournalTranslator } from '../claude-journal-translator-contract' import type { ClaudePromptRegistry } from '../claude-prompt-registry' +import { ClaudeJournalBoundDelivery } from '../claude-journal-bound-delivery' import { cancelProcessAcquisition } from '@orca/process-host/cancel-process-acquisition' import type { AgentSessionFastModeState } from '../../../shared/agent-session/agent-session-wire' import type { AgentChildWorkEvidence } from '../../../shared/agent-status/child-work/agent-status-child-work-evidence' @@ -172,6 +173,7 @@ export type ClaudeSession = { closeEnded?: boolean translator: ClaudeJournalTranslator | null events: StructuredAgentSessionEventSink | undefined + delivery: ClaudeJournalBoundDelivery unbindReadingControl?: () => void /** Provider identity and initialize proof retained for the host-awaited open. */ link: AgentSessionProviderHandleLink @@ -207,7 +209,7 @@ export type ClaudeSessionExit = { export type ClaudeAcquisitionAttempt = { connection: ClaudeStreamJsonConnection | null prompts: ClaudePromptRegistry - buffered: (() => void)[] + delivery: ClaudeJournalBoundDelivery published: boolean cancelled: boolean exitProven: boolean @@ -224,16 +226,17 @@ export function createClaudeAcquisitionAttempt( const finished = new Promise((resolve) => { finish = resolve }) - return { + const attempt: ClaudeAcquisitionAttempt = { connection: null, prompts, - buffered: [], + delivery: new ClaudeJournalBoundDelivery(undefined, () => attempt.published), published: false, cancelled: false, exitProven: false, finished, finish } + return attempt } export class ClaudeAcquisitionRegistry { @@ -304,6 +307,7 @@ export async function cancelClaudeAcquisitionAttempt( return cancelProcessAcquisition({ cancel: () => { attempt.cancelled = true + attempt.delivery.dispose() }, connection: () => attempt.connection, exitProven: () => attempt.exitProven, @@ -314,7 +318,12 @@ export async function cancelClaudeAcquisitionAttempt( export type ClaudeAcquireCallbacks = { /** Publishes the session, its start ending admitted first so its exit is never missed. */ publish: (session: ClaudeSession) => void - deliver: (attempt: ClaudeAcquisitionAttempt, sessionId: string, event: () => void) => void + deliver: ( + attempt: ClaudeAcquisitionAttempt, + sessionId: string, + event: () => void, + payload?: unknown + ) => void emit: ( session: ClaudeSession | null, events: StructuredAgentSessionEventSink | undefined, diff --git a/src/main/claude/structured/journal/claude-structured-journal-translation.ts b/src/main/claude/structured/journal/claude-structured-journal-translation.ts index 5fa4f06cf27..b9a7cd8de4e 100644 --- a/src/main/claude/structured/journal/claude-structured-journal-translation.ts +++ b/src/main/claude/structured/journal/claude-structured-journal-translation.ts @@ -1,7 +1,6 @@ -import type { - ClaudeJournalTranslator, - ClaudeJournalTranslatorDeps -} from '../../claude-journal-translator-contract' +import { ClaudeTaskInvocations } from '../../claude-task-invocations' +import { ClaudeJournalBoundDelivery } from '../../claude-journal-bound-delivery' +import type * as contract from '../../claude-journal-translator-contract' import { claudeStreamingMessageBody, type ClaudeToolUse @@ -46,10 +45,11 @@ import { } from '../../claude-plugin-input-failure-journal' export function createClaudeJournalTranslator( - deps: ClaudeJournalTranslatorDeps -): ClaudeJournalTranslator { + deps: contract.ClaudeJournalTranslatorDeps +): contract.ClaudeJournalTranslator { const coverage = createClaudeFinalOutputCoverage(deps.sink) deps = { ...deps, sink: coverage.sink } + const delivery = deps.delivery ?? new ClaudeJournalBoundDelivery(deps.sink) const tools = new Map() const turnScope = () => turn.turnScope const prompts = new ClaudeJournalPrompts({ @@ -70,7 +70,9 @@ export function createClaudeJournalTranslator( const providerFallback = createClaudeProviderFrameFallback(deps.sink, fallbackId, turnScope) const toolOrigins = new ClaudeToolOriginRegistry() const journaled = new ClaudeJournaledSubagents(() => deps.sink.journalLinkage?.() ?? null) + const taskInvocations = new ClaudeTaskInvocations(journaled) const subagents = new ClaudeSubagentIdentities({ + taskInvocations, isForwardedParentTool: (toolUseId) => toolOrigins.has(toolUseId), childOwnerRefOf: (toolUseId) => toolOrigins.childOwnerRef(toolUseId), journaled @@ -94,6 +96,7 @@ export function createClaudeJournalTranslator( sink: deps.sink, isForwardedParentTool: (toolUseId) => toolOrigins.has(toolUseId), rosteredByEarlierRun: journaled.isSubagent, + taskInvocations, // Task output must open a resumed turn so the session does not appear idle while producing rows. openOutputTurn: (frame, observedAt) => turn.ensureOpen(frame, claudeStreamTurnSource(frame), observedAt), @@ -158,99 +161,100 @@ export function createClaudeJournalTranslator( backgroundTasks.settleSession() settleClaudeInterruptedTurn(turn, observedAt, failed) } - return { - handle: withClaudeConversationContent((event) => { - if (event.type === 'retiring') { - journalClaudePluginInputFailure({ event, turn, sink: deps.sink, finish }) - return - } - if (event.type === 'ended') { - finish(event.observedAt ?? Date.now(), event.failure?.kind === 'pluginInputRequired') - return - } - turn.observeStartedSend(event.type === 'message' ? (event.startedSend ?? null) : null) - if (event.type === 'message') { - context.observe(event.message, event.observedAt ?? Date.now()) - // Root init starts a cycle; replays after root work fold into it, while task frames do not mark cycle work. - if (isRootClaudeFrame(event.message)) { - if (event.message.type === 'system' && event.message.subtype === 'init') { - turn.observeProviderCycleStart() - } else if ( - event.startsTurn === true || - event.message.type === 'assistant' || - event.message.type === 'stream_event' - ) { - turn.observeProviderCycleWork() - turn.inputChoiceWorkObserved ||= - event.message.type !== 'assistant' || - event.message.is_api_error_message !== true || - event.startedSend != null - } - } - } - if (event.type === 'message' && absorbClaudeCommandFrame(messageContext, event.message)) { - return - } - if ( - event.type === 'message' && - journalClaudeStream(messageContext, event.message, event.observedAt ?? Date.now()) - ) { - return - } - // Observe announcements before flushing so buffered rows receive their resolved producer stamp. - const announced = event.type === 'message' && subagents.observeSystemFrame(event.message) - // Only ahead of a frame that can write a row: one per thinking token rewrote the whole row. - if (!(event.type === 'message' && isClaudeProgressFrame(event.message))) { - flush() - } - if (announced) { - corrections.retry() - streamedText.reattribute() - streamedThinking.reattribute() - } - if (event.type === 'prompt') { - prompts.handle(event) - } else if (event.type === 'prompt-cancelled') { - prompts.retryPendingCancellations() - prompts.cancel(event.promptKey) - } else if (event.type === 'message' && event.message.type === 'result') { - journalClaudeResult(resultContext, event.message, event.observedAt ?? Date.now()) - } else if (event.type === 'message') { - backgroundTasks.observe(event.message, event.observedAt ?? Date.now()) - messageContext.usageLimits.observe(event.message, turn.command?.rejections) - const kind = claudeProviderFrameKind(event.message) - if ( - !journalClaudeMessage( - messageContext, - event.message, - event.startsTurn === true, - event.observedAt ?? Date.now(), - event.requestedAt, - event.clientMessageId - ) + const handle = withClaudeConversationContent((event) => { + if (event.type === 'retiring') { + journalClaudePluginInputFailure({ event, turn, sink: deps.sink, finish }) + return + } + if (event.type === 'ended') { + finish(event.observedAt ?? Date.now(), event.failure?.kind === 'pluginInputRequired') + return + } + turn.observeStartedSend(event.type === 'message' ? (event.startedSend ?? null) : null) + if (event.type === 'message') { + context.observe(event.message, event.observedAt ?? Date.now()) + // Root init starts a cycle; replays after root work fold into it, while task frames do not mark cycle work. + if (isRootClaudeFrame(event.message)) { + if (event.message.type === 'system' && event.message.subtype === 'init') { + turn.observeProviderCycleStart() + } else if ( + event.startsTurn === true || + event.message.type === 'assistant' || + event.message.type === 'stream_event' ) { - providerFallback.append( - kind, - event.message, - undefined, - undefined, - undefined, - corrections.stampFor(claudeFrameParentRef(event.message)) - ) + turn.observeProviderCycleWork() + turn.inputChoiceWorkObserved ||= + event.message.type !== 'assistant' || + event.message.is_api_error_message !== true || + event.startedSend != null } - context.observeResponse(event.message, event.observedAt ?? Date.now()) - publishClaudeTurnActivity(turn, deps.sink, event) - // Idle also closes faults without a result; the live cause decides failed reopening. - if (claudeSessionStateEndsTurn(event.message)) { - corrections.abandon() - // No verdict: the CLI said the turn is over, not how it ended. - turn.settle({ state: 'completed', completedAt: event.observedAt ?? Date.now() }) - } - } else if (event.type === 'provider-frame') { - providerFallback.append(event.kind, event.payload) - publishClaudeTurnActivity(turn, deps.sink, event) } - }), + } + if (event.type === 'message' && absorbClaudeCommandFrame(messageContext, event.message)) { + return + } + if ( + event.type === 'message' && + journalClaudeStream(messageContext, event.message, event.observedAt ?? Date.now()) + ) { + return + } + // Observe announcements before flushing so buffered rows receive their resolved producer stamp. + const announced = event.type === 'message' && subagents.observeSystemFrame(event.message) + // Only ahead of a frame that can write a row: one per thinking token rewrote the whole row. + if (!(event.type === 'message' && isClaudeProgressFrame(event.message))) { + flush() + } + if (announced) { + corrections.retry() + streamedText.reattribute() + streamedThinking.reattribute() + } + if (event.type === 'prompt') { + prompts.handle(event) + } else if (event.type === 'prompt-cancelled') { + prompts.retryPendingCancellations() + prompts.cancel(event.promptKey) + } else if (event.type === 'message' && event.message.type === 'result') { + journalClaudeResult(resultContext, event.message, event.observedAt ?? Date.now()) + } else if (event.type === 'message') { + backgroundTasks.observe(event.message, event.observedAt ?? Date.now()) + messageContext.usageLimits.observe(event.message, turn.command?.rejections) + const kind = claudeProviderFrameKind(event.message) + if ( + !journalClaudeMessage( + messageContext, + event.message, + event.startsTurn === true, + event.observedAt ?? Date.now(), + event.requestedAt, + event.clientMessageId + ) + ) { + providerFallback.append( + kind, + event.message, + undefined, + undefined, + undefined, + corrections.stampFor(claudeFrameParentRef(event.message)) + ) + } + context.observeResponse(event.message, event.observedAt ?? Date.now()) + publishClaudeTurnActivity(turn, deps.sink, event) + // Idle also closes faults without a result; the live cause decides failed reopening. + if (claudeSessionStateEndsTurn(event.message)) { + corrections.abandon() + // No verdict: the CLI said the turn is over, not how it ended. + turn.settle({ state: 'completed', completedAt: event.observedAt ?? Date.now() }) + } + } else if (event.type === 'provider-frame') { + providerFallback.append(event.kind, event.payload) + publishClaudeTurnActivity(turn, deps.sink, event) + } + }) + return { + handle: (event) => delivery.interpret(event, handle), journalPrompts: prompts, get currentTurnId() { return turn.id @@ -269,6 +273,8 @@ export function createClaudeJournalTranslator( return turn.isOpen && turn.inputChoiceWorkObserved }, flush, + taskInvocations, + childTaskParent: subagents.parentOf, childToolOwner: childQueries.childToolOwner, childActivity: childQueries.childActivity, retryPendingTaskRows: () => backgroundTasks.retryPendingWrites(), @@ -288,6 +294,7 @@ export function createClaudeJournalTranslator( modelMayHaveChanged: () => context.modelMayHaveChanged(), modelWritten: (model) => context.modelWritten(model), dispose: () => { + delivery.dispose() flush() context.dispose() streamedText.dispose() diff --git a/src/main/claude/structured/journal/claude-structured-prompt-items.test.ts b/src/main/claude/structured/journal/claude-structured-prompt-items.test.ts new file mode 100644 index 00000000000..0be0dd589c7 --- /dev/null +++ b/src/main/claude/structured/journal/claude-structured-prompt-items.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it, vi } from 'vitest' +import { claudeQuestionItems } from './claude-structured-prompt-items' + +const LAYOUT_A = '┌──────┬────────┐\n│ nav │ main │\n└──────┴────────┘' + +describe('claudeQuestionItems', () => { + it('keeps option previews on single-select questions only', () => { + const [item] = claudeQuestionItems({ + sessionId: 'session-1', + prompt: { + requestId: 'req-1', + promptKey: 'req-1', + toolUseId: 'toolu-1', + toolName: 'AskUserQuestion', + kind: 'question', + input: { + questions: [ + { + question: 'Which layout?', + header: 'Layout', + multiSelect: false, + options: [ + { label: 'Sidebar', description: 'Nav on the left', preview: LAYOUT_A }, + { label: 'Top bar', description: 'Nav on top', preview: ' \n ' } + ] + }, + { + question: 'Which panes?', + header: 'Panes', + multiSelect: true, + options: [ + { label: 'Files', description: 'File tree', preview: 'files' }, + { label: 'Git', description: 'Changes', preview: 'git' } + ] + } + ] + }, + suggestions: [], + questionIds: ['q1', 'q2'], + settle: vi.fn() + } + }) + const questions = item!.body.questions! + expect(questions[0]!.options.map((option) => option.preview)).toEqual([LAYOUT_A, undefined]) + expect(questions[1]!.options.map((option) => option.preview)).toEqual([undefined, undefined]) + }) +}) diff --git a/src/main/claude/structured/journal/claude-structured-prompt-items.ts b/src/main/claude/structured/journal/claude-structured-prompt-items.ts index ef669549d3b..adefb290d77 100644 --- a/src/main/claude/structured/journal/claude-structured-prompt-items.ts +++ b/src/main/claude/structured/journal/claude-structured-prompt-items.ts @@ -10,6 +10,7 @@ import { truncateToolDetail } from '../../../../shared/native-chat/tools/native-chat-tool-summary' import { isPlanApprovalSubject } from '../../../../shared/agent-session/agent-session-approval-subject' +import { askOptionPreview } from '../../../../shared/native-chat/input/native-chat-ask-option-preview' import { boundJournalPromptBody } from '../../../native-chat/agent-session-journal/item-lifecycle/journal-prompt-body-bounds' import { claudeRecord, claudeText } from './claude-structured-item-translation' import { encodeClaudeQuestionOptionId } from './claude-structured-prompt-replies' @@ -77,16 +78,20 @@ function questionOptions( if (!Array.isArray(question.options)) { return [] } + // Claude draws previews only on single-select questions. + const singleSelect = question.multiSelect !== true return question.options.flatMap((value, index) => { const option = claudeRecord(value) const label = claudeText(option?.label) const description = claudeText(option?.description) + const preview = singleSelect ? askOptionPreview(option) : null return label ? [ { id: encodeClaudeQuestionOptionId(questionAddress, `choice-${index + 1}`), label, - ...(description ? { description } : {}) + ...(description ? { description } : {}), + ...(preview ? { preview } : {}) } ] : [] diff --git a/src/main/claude/structured/journal/claude-structured-session-journal-control.ts b/src/main/claude/structured/journal/claude-structured-session-journal-control.ts index 06cd38da791..374e73737dc 100644 --- a/src/main/claude/structured/journal/claude-structured-session-journal-control.ts +++ b/src/main/claude/structured/journal/claude-structured-session-journal-control.ts @@ -10,6 +10,7 @@ import type { ClaudeStreamJsonConnection } from '../../claude-stream-json-connec import type { ClaudeJournalTranslator } from '../../claude-journal-translator-contract' import { createClaudeJournalTranslator } from './claude-structured-journal-translation' import type { ClaudeInitProof } from '../claude-structured-init-proof' +import type { ClaudeJournalBoundDelivery } from '../../claude-journal-bound-delivery' import type { ClaudeAcquisitionAttempt, ClaudeSession, @@ -24,9 +25,12 @@ export function createClaudeSessionJournalTranslator( acceptStartupFailure: (message: Record) => boolean ): ClaudeJournalTranslator | null { const { attempt } = failure + attempt.delivery.onFailure = createClaudeJournalFailureHandler(failure) + attempt.delivery.bind(sink) return sink ? createClaudeJournalTranslator({ sink, + delivery: attempt.delivery, account: () => attempt.account, model: () => { const session = currentSession() @@ -83,13 +87,30 @@ function retryOwedWritesOnDrain( export function bindClaudeJournalReadingControl( sink: StructuredAgentSessionEventSink | undefined, connection: Pick, - translator: ClaudeJournalTranslator | null + translator: ClaudeJournalTranslator | null, + delivery?: ClaudeJournalBoundDelivery ): (() => void) | undefined { if (!connection.pauseReading || !connection.resumeReading) { return undefined } let sinkPaused = false - return sink?.bindReadingControl?.({ + let journalPaused = false + const resume = () => { + if (!sinkPaused && !journalPaused) { + connection.resumeReading?.() + } + } + const unbindDelivery = delivery?.bindReadingControl({ + pauseReading: () => { + journalPaused = true + connection.pauseReading?.() + }, + resumeReading: () => { + journalPaused = false + resume() + } + }) + const unbindSink = sink?.bindReadingControl?.({ pauseReading: () => { sinkPaused = true connection.pauseReading?.() @@ -98,20 +119,25 @@ export function bindClaudeJournalReadingControl( sinkPaused = false const retried = retryOwedWritesOnDrain(translator) if (!sinkPaused && (retried.accepted || retried.reason !== 'backpressure')) { - connection.resumeReading?.() + resume() } } }) + return () => { + unbindDelivery?.() + unbindSink?.() + } } export function bindClaudeConnectionJournalControls( sink: StructuredAgentSessionEventSink | undefined, connection: ClaudeStreamJsonConnection, translator: ClaudeJournalTranslator | null, - capture: ClaudeContextUsageCaptureOptions + capture: ClaudeContextUsageCaptureOptions, + delivery?: ClaudeJournalBoundDelivery ): (() => void) | undefined { const unbinds = [ - bindClaudeJournalReadingControl(sink, connection, translator), + bindClaudeJournalReadingControl(sink, connection, translator, delivery), bindClaudeContextUsageCapture(connection, translator, capture) ].filter((unbind): unbind is () => void => unbind !== undefined) return unbinds.length === 0 diff --git a/src/main/claude/structured/launch/claude-structured-child-env.test.ts b/src/main/claude/structured/launch/claude-structured-child-env.test.ts index 18c73fc32e0..1db318f15ed 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.test.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.test.ts @@ -2,13 +2,18 @@ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' +import { runProcess } from '@orca/process-host' import { + claudeChildEnv, resolveClaudeChildEnvSources, withOrcaClaudeEntrypoint } from './claude-structured-child-env' import { resolveStructuredAgentCommand } from '../../../native-chat/structured-agent-command-resolution' -afterEach(() => vi.unstubAllEnvs()) +afterEach(() => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() +}) it('resolves a custom Claude command against the login shell PATH', async () => { const root = mkdtempSync(join(tmpdir(), 'orca-shell-only-cli-')) @@ -40,4 +45,59 @@ it('keeps a differently cased Windows launch value over the Orca default', () => PATH: 'C:\\bin', CLAUDE_CODE_ENTRYPOINT: 'orca' }) + expect( + withOrcaClaudeEntrypoint( + inherited, + { + CLAUDE_CODE_ENTRYPOINT: 'first', + claude_code_entrypoint: 'last' + }, + 'win32' + ) + ).toEqual({ PATH: 'C:\\bin', CLAUDE_CODE_ENTRYPOINT: 'last' }) }) + +it('uses configured Windows values for both Claude lookup and its final child', async () => { + vi.stubGlobal('process', { ...process, platform: 'win32' }) + const sources = await resolveClaudeChildEnvSources({ + resolveInheritedEnv: async () => ({ + PATH: '/inherited/bin', + TOKEN: 'inherited', + CLAUDE_CONFIG_DIR: '/ambient' + }), + resolveEnv: () => ({ + path: '/configured/bin', + tOKEN: 'configured', + claude_config_dir: '/configured/home' + }), + resolveCommand: (options) => { + expect(options?.pathEnv).toBe('/configured/bin') + return { command: '/configured/bin/claude.exe', prefixArgs: [] } + } + }) + expect(claudeChildEnv(sources, undefined, { runtimeOnPath: false })).toEqual({ + PATH: '/configured/bin', + TOKEN: 'configured', + CLAUDE_CONFIG_DIR: '/configured/home', + CLAUDE_CODE_ENTRYPOINT: 'orca' + }) +}) + +it.skipIf(process.platform !== 'win32')( + 'passes configured values through a real Windows child despite inherited casing', + async () => { + vi.stubEnv('ORCA_NATIVE_ENV_CASE_PROBE', 'inherited') + const sources = await resolveClaudeChildEnvSources({ + resolveEnv: () => ({ orca_native_env_case_probe: 'configured' }), + resolveCommand: () => ({ command: process.execPath, prefixArgs: [] }) + }) + const result = await runProcess({ + program: sources.command, + args: ['--eval', 'process.stdout.write(process.env.ORCA_NATIVE_ENV_CASE_PROBE ?? "")'], + env: claudeChildEnv(sources, undefined, { runtimeOnPath: false }), + timeoutMs: 30_000 + }) + expect(result.code).toBe(0) + expect(result.stdout).toBe('configured') + } +) diff --git a/src/main/claude/structured/launch/claude-structured-child-env.ts b/src/main/claude/structured/launch/claude-structured-child-env.ts index 7348c90c323..c63824523ba 100644 --- a/src/main/claude/structured/launch/claude-structured-child-env.ts +++ b/src/main/claude/structured/launch/claude-structured-child-env.ts @@ -12,6 +12,7 @@ import { withCliRuntimeOnPath } from '../../../../shared/node-cli-command-resolu import { applyClaudeEnvPatch } from '../../../claude-accounts/environment' import { resolveClaudeCommand } from '../../../codex-cli/command' import { withoutInheritedClaudeConfigDir } from '../../claude-config-dir-pin' +import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' function cloneDefinedEnv(env: NodeJS.ProcessEnv | Record): Record { const next: Record = {} @@ -54,7 +55,8 @@ export function resolveClaudeChildEnvSources(deps: ClaudeEnvDeps): Promise readClaudeChildEnvSources(deps), deps.refreshEnvironmentAfterMiss, { - env: ({ inheritedEnv, overlay }) => ({ ...inheritedEnv, ...overlay }), + env: ({ inheritedEnv, overlay }) => + overlayEnvironmentVariables(inheritedEnv, overlay, process.platform), cwd: deps.resolveWorkingDirectory, signal: deps.signal }, @@ -64,14 +66,20 @@ export function resolveClaudeChildEnvSources(deps: ClaudeEnvDeps): Promise { assertStructuredAgentResolutionCurrent(deps.operation) - const overlay = await waitForPromiseWithSignal(Promise.resolve(deps.resolveEnv?.()), deps.signal) + const configured = await waitForPromiseWithSignal( + Promise.resolve(deps.resolveEnv?.()), + deps.signal + ) + const overlay = configured + ? overlayEnvironmentVariables({}, cloneDefinedEnv(configured), process.platform) + : undefined assertStructuredAgentResolutionCurrent(deps.operation) const inheritedEnv = deps.resolveInheritedEnv ? await waitForPromiseWithSignal(deps.resolveInheritedEnv(), deps.signal) : cloneDefinedEnv(process.env) assertStructuredAgentResolutionCurrent(deps.operation) deps.signal?.throwIfAborted() - const effectiveEnv = { ...inheritedEnv, ...overlay } + const effectiveEnv = overlayEnvironmentVariables(inheritedEnv, overlay, process.platform) const options = { pathEnv: effectiveEnv.PATH ?? effectiveEnv.Path ?? null, homePath: effectiveEnv.HOME ?? effectiveEnv.USERPROFILE @@ -95,13 +103,12 @@ export function withOrcaClaudeEntrypoint( (platform === 'win32' ? key.toUpperCase() : key) === CLAUDE_ENTRYPOINT_ENV const withoutEntrypoint = (source: Record): Record => Object.fromEntries(Object.entries(source).filter(([key]) => !isEntrypointKey(key))) - const override = Object.entries(overlay ?? {}).find(([key]) => isEntrypointKey(key))?.[1] // The SDK reads only the exact name and otherwise adds its own default, which Windows would pick. - return { - ...withoutEntrypoint(inheritedEnv), - ...withoutEntrypoint(overlay ?? {}), - [CLAUDE_ENTRYPOINT_ENV]: override ?? 'orca' - } + return overlayEnvironmentVariables( + { ...withoutEntrypoint(inheritedEnv), [CLAUDE_ENTRYPOINT_ENV]: 'orca' }, + overlay, + platform + ) } // Merge onto the shell environment to retain PATH and ambient Anthropic auth. diff --git a/src/main/claude/structured/launch/claude-structured-options.test.ts b/src/main/claude/structured/launch/claude-structured-options.test.ts index e9954a2d159..0caf086fbf8 100644 --- a/src/main/claude/structured/launch/claude-structured-options.test.ts +++ b/src/main/claude/structured/launch/claude-structured-options.test.ts @@ -1,3 +1,4 @@ +import { ClaudeJournalBoundDelivery } from '../../claude-journal-bound-delivery' import { describe, expect, it, vi } from 'vitest' import { setClaudeStructuredOption } from './claude-structured-options' import type { ClaudeSession } from '../claude-structured-session-state' @@ -25,6 +26,7 @@ function sessionFor(setModel: ClaudeSession['connection']['setModel']): ClaudeSe dispatchWaiters: [], retiredDispatchWaiters: [], replayContentFallbackBlocked: false, + delivery: new ClaudeJournalBoundDelivery(), backgroundTasks: new ClaudeBackgroundTaskTracker(), childWork: new ClaudeChildWorkDecoder(), commands: new ClaudeSlashCommandCatalog(), diff --git a/src/main/codex/codex-conversation-copy.test.ts b/src/main/codex/codex-conversation-copy.test.ts index bafac8ca255..17938242104 100644 --- a/src/main/codex/codex-conversation-copy.test.ts +++ b/src/main/codex/codex-conversation-copy.test.ts @@ -10,15 +10,24 @@ import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' import { agentSessionRecordFixture } from '../native-chat/agent-session-record-test-fixture' -import { copyCodexConversation, codexForkHistory } from './codex-conversation-copy' +import { copyCodexConversation } from './codex-conversation-copy' +import { codexForkHistory } from './codex-fork-history' +import { CodexAppServerTimeoutError } from './app-server/codex-app-server-session' import type { CodexAppServerRpc } from './app-server/codex-app-server-session' -const state = vi.hoisted(() => ({ - home: '', - paths: new Map(), - request: vi.fn(), - initialize: vi.fn() -})) +const state = vi.hoisted(() => { + const session: { + run?: (body: (rpc: CodexAppServerRpc) => Promise) => Promise + transport?: 'native' | 'unsupported-read' + } = {} + return { + home: '', + paths: new Map(), + request: vi.fn(), + initialize: vi.fn(), + session + } +}) vi.mock('../native-chat/codex-local-history', async (importOriginal) => { const original = await importOriginal() return { ...original, readCodexLocalHistory: vi.fn(original.readCodexLocalHistory) } @@ -30,19 +39,58 @@ vi.mock('../native-chat/codex-rollout-history-stream', async (importOriginal) => vi.mock('../native-chat/session-file-resolver', () => ({ resolveSessionFilePath: async (_agent: string, id: string) => state.paths.get(id) ?? null })) -vi.mock('./app-server/codex-app-server-session', async (importOriginal) => ({ - ...(await importOriginal()), - runCodexAppServerSession: async ( - launch: unknown, - body: (rpc: CodexAppServerRpc) => Promise - ) => { - state.initialize(launch) - return body({ request: state.request, notify: () => {} }) +vi.mock('./app-server/codex-app-server-session', async (importOriginal) => { + const original = await importOriginal() + return { + ...original, + runCodexAppServerSession: async ( + launch: AppServerSession.CodexAppServerInvocation, + body: (rpc: CodexAppServerRpc) => Promise + ) => { + state.initialize(launch) + if (state.session.transport) { + const server = String.raw` + let experimental = false + require('node:readline').createInterface({ input: process.stdin }).on('line', line => { + const message = JSON.parse(line) + if (typeof message.id !== 'number') return + if (message.method === 'initialize') { + experimental = message.params.capabilities?.experimentalApi === true + } + const error = message.method === 'thread/read' && process.argv[1] === 'unsupported-read' + ? { code: -32601, message: 'thread/read is not supported yet' } + : message.method === 'thread/turns/list' && !experimental + ? { code: -32600, message: 'thread/turns/list requires experimentalApi capability' } + : null + process.stdout.write(JSON.stringify({ id: message.id, ...(error ? { error } : { result: {} }) }) + '\n') + }) + ` + return original.runCodexAppServerSession( + { + ...launch, + command: process.execPath, + args: ['-e', server, state.session.transport], + cliPath: null + }, + (rpc) => + body({ + ...rpc, + request: async (method, params) => { + await rpc.request(method, params) + return state.request(method, params) + } + }) + ) + } + return state.session.run + ? state.session.run(body) + : body({ request: state.request, notify: () => {} }) + } } -})) +}) -const SOURCE = '00000000-0000-4000-8000-000000000001' -const CHILD = '00000000-0000-4000-8000-000000000002' +const SOURCE = '01a1bdd2-6d33-7a21-9a1d-c14f0117bc8c' +const CHILD = '01a1bde0-5ded-7f03-a1bf-3dae1613d8c7' let root: string beforeEach(async () => { @@ -50,6 +98,8 @@ beforeEach(async () => { state.home = root state.paths.clear() state.request.mockReset() + state.session.run = undefined + state.session.transport = undefined state.initialize.mockReset() vi.mocked(readCodexLocalHistory).mockClear() vi.mocked(readCodexRolloutBytes).mockClear() @@ -85,7 +135,12 @@ async function history(id: string, records: object[]) { state.paths.set(id, path) return path } -function copy(selected = `${SOURCE}:a1`, settled = true, turnId?: string) { +function copy( + selected = `${SOURCE}:a1`, + settled = true, + turnId?: string, + options: { signal?: AbortSignal; selectedItemId?: string } = {} +) { return copyCodexConversation( { record: agentSessionRecordFixture({ @@ -102,15 +157,18 @@ function copy(selected = `${SOURCE}:a1`, settled = true, turnId?: string) { providerHandle: null }, providerSessionId: SOURCE, + signal: options.signal, title: 'Source fork', accountHome: { variable: 'CODEX_HOME', path: root }, checkpoint: { - selectedItemId: agentJournalItemKey({ - provider: 'legacy', - agent: 'codex', - sessionId: SOURCE, - recordId: selected - }), + selectedItemId: + options.selectedItemId ?? + agentJournalItemKey({ + provider: 'legacy', + agent: 'codex', + sessionId: SOURCE, + recordId: selected + }), settled, ...(turnId ? { turnId } : {}) } @@ -150,10 +208,12 @@ async function childPrefix(lines?: number) { return path } -it('uses a persisted terminal canonical boundary for an idle imported latest reply with no live owner', async () => { +it('keeps omitted-mode compatibility for a persisted terminal imported reply', async () => { await history(SOURCE, turn('canonical', 1)) await childPrefix() - state.request.mockResolvedValue({ thread: { id: CHILD } }) + state.request.mockImplementation(async (method) => ({ + thread: { id: method === 'thread/read' ? SOURCE : CHILD } + })) await expect(copy(undefined, false)).resolves.toEqual({ sessionId: CHILD, coverage: { unit: 'codex-turn', ids: ['canonical'] } @@ -168,9 +228,11 @@ it('uses beforeTurnId only for the immediate next effective root and opts into t await history(SOURCE, [...turn(undefined, 1), ...turn('canonical-next', 2)]) await childPrefix(3) state.request.mockImplementation(async (method) => - method === 'thread/fork' - ? { thread: { id: CHILD } } - : { data: [{ id: 'legacy-first' }, { id: 'canonical-next' }], nextCursor: null } + method === 'thread/read' + ? { thread: { id: SOURCE, historyMode: 'paginated' } } + : method === 'thread/fork' + ? { thread: { id: CHILD } } + : { data: [{ id: 'legacy-first' }, { id: 'canonical-next' }], nextCursor: null } ) await expect(copy()).resolves.toEqual({ sessionId: CHILD, @@ -196,6 +258,9 @@ it('forks and reverts only the child for legacy, legacy, canonical, counting aga state.paths.set(CHILD, path) let reverted = false state.request.mockImplementation(async (method) => { + if (method === 'thread/read') { + return { thread: { id: SOURCE, historyMode: 'paginated' } } + } if (method === 'thread/fork') { return { thread: { id: CHILD, historyMode: 'paginated' } } } @@ -249,7 +314,8 @@ it('uses exact physical identities across repeated prompts rather than a retaine expect(result.selected.id).toBe('second') }) -it('freezes all-unrecorded root IDs on the source, excluding child replacements and later source growth', async () => { +it('keeps method-not-found compatibility with frozen unrecorded IDs despite source growth and child replacements', async () => { + state.session.transport = 'unsupported-read' await history(SOURCE, [...turn(undefined, 1), ...turn(undefined, 2), ...turn(undefined, 3)]) let reverted = false state.request.mockImplementation(async (method, params) => { @@ -290,7 +356,7 @@ it('freezes all-unrecorded root IDs on the source, excluding child replacements }) }) -it('certifies recorded turns in a standalone copied rollout with no physical history base', async () => { +it('keeps legacy-mode compatibility for recorded turns in a standalone copied rollout', async () => { const rows = await recordedCodexRollout('c') const source = rows.find((row) => row.type === 'session_meta')! const started = rows.find( @@ -312,9 +378,221 @@ it('certifies recorded turns in a standalone copied rollout with no physical his .join('\n') await writeFile(path, `${serialized}\n`) } - state.request.mockResolvedValue({ thread: { id: CHILD } }) + state.request.mockImplementation(async (method) => ({ + thread: { id: method === 'thread/read' ? SOURCE : CHILD, historyMode: 'legacy' } + })) await expect(copy(undefined, true, String(started.payload.turn_id))).resolves.toEqual({ sessionId: CHILD, coverage: { unit: 'codex-turn', ids: ['01a1b0d7-ac1d-7e00-85b8-806a4d8d494b'] } }) }) + +it('forks the current paged native prefix after rewind without source or child rollout authority', async () => { + state.session.transport = 'native' + await history(SOURCE, [ + ...turn('01a1bdd2-6d5e-7960-8fbb-30c962a5eeaa', 1), + ...turn('01a1bdd3-1293-7bc2-b750-017ca47738f9', 2) + ]) + const selected = '01a1bdd4-2977-7f81-8495-eb160b46419a' + state.request.mockImplementation(async (method, params) => { + if (method === 'thread/read') { + return { thread: { id: SOURCE, historyMode: 'paginated', status: { type: 'notLoaded' } } } + } + if (method === 'thread/fork') { + return { thread: { id: CHILD, historyMode: 'paginated' } } + } + if (!params?.cursor) { + return { + data: [{ id: '01a1bdd2-6d5e-7960-8fbb-30c962a5eeaa', status: 'completed' }], + nextCursor: 'page-2' + } + } + return { + data: [ + { id: '01a1bdd2-b7a1-7c63-8b19-cc361c2baefb', status: 'completed' }, + { id: selected, status: 'completed' }, + ...(params.threadId === CHILD + ? [{ id: '01a1bde0-5e1e-7ad0-ab18-f9ed07fd00e7', status: 'completed' }] + : []) + ], + nextCursor: null + } + }) + await expect( + copy(undefined, false, selected, { selectedItemId: `codex:${SOURCE}:${selected}:1` }) + ).resolves.toEqual({ + sessionId: '01a1bde0-5ded-7f03-a1bf-3dae1613d8c7', + coverage: { + unit: 'codex-turn', + ids: [ + '01a1bdd2-6d5e-7960-8fbb-30c962a5eeaa', + '01a1bdd2-b7a1-7c63-8b19-cc361c2baefb', + '01a1bdd4-2977-7f81-8495-eb160b46419a' + ] + } + }) + expect(state.request).toHaveBeenCalledWith('thread/fork', { + threadId: SOURCE, + lastTurnId: '01a1bdd4-2977-7f81-8495-eb160b46419a', + excludeTurns: true, + cwd: root + }) +}) + +it('bridges a saved physical reply with an absent command candidate without restoring a removed native turn', async () => { + await history(SOURCE, [...turn('kept', 1), ...turn('removed', 2)]) + state.request.mockImplementation(async (method) => { + if (method === 'thread/read') { + return { thread: { id: SOURCE, historyMode: 'paginated' } } + } + if (method === 'thread/fork') { + return { thread: { id: CHILD } } + } + return { data: [{ id: 'kept', status: 'completed' }], nextCursor: null } + }) + await expect(copy(undefined, true, 'orca-command')).resolves.toEqual({ + sessionId: CHILD, + coverage: { unit: 'codex-turn', ids: ['kept'] } + }) + await expect(copy(`${SOURCE}:a2`, true, 'orca-command')).rejects.toMatchObject({ + refusal: { + code: 'agent_session_operation_invalid', + details: { reason: 'savedConversationMissing' }, + createAttemptRefusedBeforeCommit: true + } + }) + await expect(copy(undefined, true)).resolves.toEqual({ + sessionId: CHILD, + coverage: { unit: 'codex-turn', ids: ['kept'] } + }) + await expect( + copy(undefined, true, 'removed', { selectedItemId: `codex:${SOURCE}:removed:1` }) + ).rejects.toMatchObject({ + refusal: { + details: { reason: 'savedConversationMissing' }, + createAttemptRefusedBeforeCommit: true + } + }) +}) + +it('keeps read faults in preparation and a contradictory copied prefix uncertain', async () => { + const selected = '01a1bdd4-2977-7f81-8495-eb160b46419a' + await history(SOURCE, turn(selected, 1)) + await childPrefix() + const prepare = () => copy(undefined, true, selected) + state.request.mockRejectedValue(new Error('read failed')) + await expect(prepare()).rejects.toMatchObject({ + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'transcriptUnreadable' }, + createAttemptRefusedBeforeCommit: true + } + }) + state.request.mockResolvedValue({ thread: { id: CHILD, historyMode: 'paginated' } }) + await expect(prepare()).rejects.toMatchObject({ + refusal: { + code: 'agent_session_identity_required', + details: { reason: 'transcriptUnreadable' }, + createAttemptRefusedBeforeCommit: true + } + }) + state.request.mockImplementation(async (method, params) => { + if (method === 'thread/read') { + return { thread: { id: SOURCE, historyMode: 'paginated' } } + } + if (method === 'thread/fork') { + return { thread: { id: CHILD } } + } + return { + data: (params?.threadId === SOURCE + ? ['01a1bdd2-6d5e-7960-8fbb-30c962a5eeaa', selected] + : [selected, '01a1bdd2-6d5e-7960-8fbb-30c962a5eeaa'] + ).map((id) => ({ + id + })), + nextCursor: null + } + }) + await expect(prepare()).rejects.not.toHaveProperty('refusal') +}) + +it('refuses invalid and repeated source cursors before copying', async () => { + state.request.mockImplementation(async (method) => + method === 'thread/read' + ? { thread: { id: SOURCE, historyMode: 'paginated' } } + : { data: [{ id: 'first' }], nextCursor: 'same-page' } + ) + await expect(copy(undefined, true, 'missing')).rejects.toMatchObject({ + refusal: { details: { reason: 'transcriptUnreadable' }, createAttemptRefusedBeforeCommit: true } + }) + state.request.mockImplementation(async (method) => + method === 'thread/read' + ? { thread: { id: SOURCE, historyMode: 'paginated' } } + : { data: [], nextCursor: 17 } + ) + await expect(copy(undefined, true, 'missing')).rejects.toMatchObject({ + refusal: { details: { reason: 'transcriptUnreadable' }, createAttemptRefusedBeforeCommit: true } + }) +}) + +it('cannot dispatch an abandoned preparation after its lifetime ends, but keeps an invoked fork uncertain', async () => { + const listed = Promise.withResolvers() + const release = Promise.withResolvers() + const expired = Promise.withResolvers() + const lifetime = new AbortController() + let abandoned: Promise | undefined + let childCreated = false + state.request.mockImplementation(async (method) => { + if (method === 'thread/read') { + return { thread: { id: SOURCE, historyMode: 'paginated' } } + } + if (method === 'thread/fork') { + childCreated = true + return { thread: { id: CHILD } } + } + listed.resolve() + return release.promise + }) + state.session.run = async (body) => { + abandoned = body({ request: state.request, notify: () => {}, signal: lifetime.signal }) + return Promise.race([abandoned, expired.promise]) + } + const preparation = copy(undefined, true, 'selected') + await listed.promise + lifetime.abort(new CodexAppServerTimeoutError('session ended')) + expired.reject(lifetime.signal.reason) + await expect(preparation).rejects.toMatchObject({ + refusal: { createAttemptRefusedBeforeCommit: true } + }) + release.resolve({ data: [{ id: 'selected' }], nextCursor: null }) + await expect(abandoned).rejects.toBe(lifetime.signal.reason) + expect(childCreated).toBe(false) + const forked = Promise.withResolvers() + const lost = Promise.withResolvers() + const pending = Promise.withResolvers() + state.session.run = async (body) => + Promise.race([body({ request: state.request, notify: () => {} }), lost.promise]) + state.request.mockImplementation(async (method) => { + if (method === 'thread/read') { + return { thread: { id: SOURCE, historyMode: 'paginated' } } + } + if (method === 'thread/fork') { + forked.resolve() + return pending.promise + } + return { data: [{ id: 'selected' }], nextCursor: null } + }) + const invoked = copy(undefined, true, 'selected') + await forked.promise + const timeout = new CodexAppServerTimeoutError('reply lost') + lost.reject(timeout) + await expect(invoked).rejects.not.toHaveProperty('refusal') + pending.reject(timeout) + state.session.run = undefined + state.session.transport = undefined + const caller = new AbortController() + caller.abort(new Error('caller cancelled')) + await expect(copy(undefined, true, 'selected', { signal: caller.signal })).rejects.toBe( + caller.signal.reason + ) +}) diff --git a/src/main/codex/codex-conversation-copy.ts b/src/main/codex/codex-conversation-copy.ts index f0bc1e43c49..cb3b3a9adee 100644 --- a/src/main/codex/codex-conversation-copy.ts +++ b/src/main/codex/codex-conversation-copy.ts @@ -1,15 +1,19 @@ -import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' +import { TEXT_GENERATION_FAILURE_COPY } from '../../shared/text-generation-failure-copy' +import { codexForkHistory } from './codex-fork-history' +import { + AgentConversationCopyError, + AgentConversationCopyStartError, + agentConversationCopyRefusal +} from '../native-chat/agent-conversation-copy-error' +import { isAgentSessionRefusalError } from '../../shared/agent-session/failures/agent-session-wire-refusals' import { join } from 'node:path' import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { asRecord, parseJsonObject } from '../ai-vault/session-scanner-values' +import { asRecord } from '../ai-vault/session-scanner-values' import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/providers/structured-agent-session-adapter' -import { createLegacyIdentityTracker } from '../native-chat/agent-session-journal/history-import/journal-legacy-identity' -import { readCodexLocalHistory } from '../native-chat/codex-local-history' import { resolveSessionFilePath } from '../native-chat/session-file-resolver' -import { decodeCodexTranscriptLine } from '../native-chat/transcript-line-decoders-codex' import { - CodexAppServerTimeoutError, + isCodexAppServerUnsupportedError, type CodexAppServerRpc } from './app-server/codex-app-server-session' import { @@ -18,117 +22,28 @@ import { } from './structured/session-lifecycle/codex-provider-session-rename' type CopyInput = Parameters>[0] -type Root = { id?: string; terminal: boolean; prompt: boolean } function unavailable(): never { - throw new AgentConversationCopyError( - 'Codex could not locate an exact saved boundary in this older chat. Fork a response in a newer chat.' - ) -} - -/** Use the importer's physical lineage and identity accounting, including discarded window rows. */ -export async function codexForkHistory(input: { - path: string - roots: string[] - selectedItemId: string - turnId?: string - sessionId: string - signal?: AbortSignal - inheritedOnly?: boolean -}) { - const identity = parseAgentJournalItemKey(input.selectedItemId) - const tracker = createLegacyIdentityTracker({ - transcriptAgent: 'codex', - agent: 'codex', - sessionId: input.sessionId - }) - const roots: Root[] = [] - let selected: Root | undefined - let lineIndex = 0 - let referenceBacked = false - await readCodexLocalHistory({ - filePath: input.path, - roots: input.roots, - visitRecord: ({ record, selected }) => { - if (selected && record?.type === 'session_meta') { - referenceBacked = asRecord(record.payload)?.history_base != null - } - }, - visit: (line, fallbackId, selectedSegment, recordId) => { - if (input.inheritedOnly && referenceBacked && selectedSegment) { - return - } - input.signal?.throwIfAborted() - const tracked = tracker.identify(line, lineIndex++) - const raw = parseJsonObject(line) - const payload = asRecord(raw?.payload) - if ( - raw?.type === 'event_msg' && - payload?.type === 'thread_rolled_back' && - typeof payload.num_turns === 'number' - ) { - roots.splice(Math.max(0, roots.length - payload.num_turns)) - return - } - if (raw?.type === 'event_msg' && payload?.type === 'task_started') { - roots.push({ - id: typeof payload.turn_id === 'string' ? payload.turn_id : undefined, - terminal: false, - prompt: false - }) - } - const message = decodeCodexTranscriptLine(line, fallbackId, { historyImport: true }) - if (message?.role === 'user') { - const previous = roots.at(-1) - if (!previous || (previous.prompt && (!previous.id || previous.terminal))) { - roots.push({ terminal: false, prompt: true }) - } else { - previous.prompt = true - } - } - const root = roots.at(-1) - if ( - root && - raw?.type === 'event_msg' && - (payload?.type === 'task_complete' || payload?.type === 'turn_aborted') && - (!payload.turn_id || payload.turn_id === root.id) - ) { - root.terminal = true - } - const importedMatch = - identity?.provider === 'legacy' && - identity.recordId === - (recordId ?? (tracked.provider === 'legacy' ? tracked.recordId : undefined)) - if ( - root && - ((importedMatch && message?.role === 'assistant') || - (input.turnId && root.id === input.turnId)) - ) { - if (selected && selected !== root) { - return unavailable() - } - selected = root - } - } - }) - const index = selected ? roots.indexOf(selected) : -1 - if (index < 0) { - return unavailable() - } - return { roots, index, selected: roots[index] } + throw new AgentConversationCopyError('Codex could not verify the copied chat.') } async function turns( rpc: CodexAppServerRpc, threadId: string, - count: number -): Promise<{ id: string }[]> { - const all: { id: string }[] = [] + through: number | string +): Promise<{ id: string; status?: unknown }[]> { + const all: { id: string; status?: unknown }[] = [] let cursor: string | null = null const seen = new Set() do { const page = asRecord( - await rpc.request('thread/turns/list', { threadId, cursor, sortDirection: 'asc', limit: 100 }) + await rpc.request('thread/turns/list', { + threadId, + cursor, + sortDirection: 'asc', + limit: 100, + itemsView: 'summary' + }) ) if (!Array.isArray(page?.data)) { return unavailable() @@ -138,7 +53,13 @@ async function turns( if (typeof turn?.id !== 'string') { return unavailable() } - all.push({ id: turn.id }) + all.push({ id: turn.id, status: turn.status }) + if (turn.id === through) { + return all + } + } + if (page.nextCursor != null && (typeof page.nextCursor !== 'string' || !page.nextCursor)) { + return unavailable() } cursor = typeof page.nextCursor === 'string' ? page.nextCursor : null if (cursor && seen.has(cursor)) { @@ -147,7 +68,7 @@ async function turns( if (cursor) { seen.add(cursor) } - } while (cursor && all.length < count) + } while (cursor && (typeof through === 'string' || all.length < through)) return all } @@ -155,140 +76,226 @@ export async function copyCodexConversation( input: CopyInput, invocation: CodexProviderInvocationDeps | undefined ) { - if (!input.record || !input.checkpoint || !invocation) { - return unavailable() - } - const { record, checkpoint } = input - const signal = AbortSignal.any([ - AbortSignal.timeout(60_000), - ...(input.signal ? [input.signal] : []) - ]) - const home = requireLegacyAgentSessionAccountHome(record.accountHome).path - const stores = [join(home, 'sessions'), join(home, 'archived_sessions')] - const find = async (id: string) => - (await resolveSessionFilePath( - 'codex', - id, - { codexSessionsDirs: stores, strictErrors: true }, - signal - )) ?? unavailable() - const history = await codexForkHistory({ - path: await find(input.providerSessionId), - roots: stores, - selectedItemId: checkpoint.selectedItemId, - turnId: checkpoint.turnId, - sessionId: input.providerSessionId, - signal - }) - const beforeTurnId = history.roots[history.index + 1]?.id - const lastTurnId = history.selected.id - if (!checkpoint.settled && !history.selected.terminal && !beforeTurnId) { - throw new AgentConversationCopyError( - "Codex hasn't finished this response yet. Wait for it to finish, then try again." - ) - } - return runCodexProviderAppServer( - record, - { ...invocation, resolveLaunchArgs: () => record.launchArgs ?? invocation.resolveLaunchArgs() }, - { timeoutMs: 60_000, signal, experimentalApi: !lastTurnId && Boolean(beforeTurnId) }, - async (rpc, cwd) => { - const prefix = history.roots.slice(0, history.index + 1) - const sourceTurns = prefix.every((root) => root.id) - ? prefix.map((root) => ({ id: root.id! })) - : await turns(rpc, input.providerSessionId, history.roots.length) - if ( - sourceTurns.length < prefix.length || - prefix.some((root, index) => root.id && root.id !== sourceTurns[index]?.id) - ) { - return unavailable() - } - const coverage = { - unit: 'codex-turn' as const, - ids: sourceTurns.slice(0, prefix.length).map((turn) => turn.id) - } - const fork = asRecord( - await rpc.request('thread/fork', { - threadId: input.providerSessionId, - ...(lastTurnId ? { lastTurnId } : beforeTurnId ? { beforeTurnId } : {}), - excludeTurns: true, - cwd - }) - ) - const thread = asRecord(fork?.thread) - const id = thread?.id - if (typeof id !== 'string' || !id.trim() || id === input.providerSessionId) { - return unavailable() - } - const captured = await codexForkHistory({ - path: await find(id), + let starting = false + let dispatched = false + try { + if (!input.record || !input.checkpoint || !invocation) { + return unavailable() + } + const { record, checkpoint } = input + const signal = AbortSignal.any([ + AbortSignal.timeout(60_000), + ...(input.signal ? [input.signal] : []) + ]) + const home = requireLegacyAgentSessionAccountHome(record.accountHome).path + const stores = [join(home, 'sessions'), join(home, 'archived_sessions')] + const legacy = parseAgentJournalItemKey(checkpoint.selectedItemId)?.provider === 'legacy' + const find = async (id: string) => + (await resolveSessionFilePath( + 'codex', + id, + { codexSessionsDirs: stores, strictErrors: true }, + signal + )) ?? unavailable() + const physicalHistory = async (turnId: string | undefined) => { + const path = await find(input.providerSessionId) + return codexForkHistory({ + path, roots: stores, selectedItemId: checkpoint.selectedItemId, - turnId: checkpoint.turnId, - sessionId: id, - inheritedOnly: true, + turnId, + sessionId: input.providerSessionId, signal }) - if ( - captured.index !== history.index || - captured.roots.length < prefix.length || - captured.roots - .slice(0, prefix.length) - .some((root, index) => root.id && root.id !== coverage.ids[index]) - ) { - return unavailable() - } - if (lastTurnId || beforeTurnId) { - if (captured.roots.length !== prefix.length) { - return unavailable() - } - } else { - // Trim the actual capture; coverage identities were frozen on the source before fork. - if (thread?.historyMode !== 'paginated') { - return unavailable() - } - const childTurns = await turns(rpc, id, captured.roots.length + 1) - if (childTurns.length !== captured.roots.length) { - return unavailable() - } - for (const [index, root] of captured.roots.entries()) { - if (root.id && root.id !== childTurns[index]?.id) { - return unavailable() + } + const missing = (): never => { + throw agentConversationCopyRefusal( + 'agent_session_operation_invalid', + { reason: 'savedConversationMissing' }, + 'Codex could not find this response in the saved chat. Open the chat again, then fork a response still in its history.' + ) + } + let history = legacy && !checkpoint.turnId ? await physicalHistory(undefined) : undefined + starting = true + return await runCodexProviderAppServer( + record, + { + ...invocation, + resolveLaunchArgs: () => record.launchArgs ?? invocation.resolveLaunchArgs() + }, + { timeoutMs: 60_000, signal, experimentalApi: true }, + async (rpc, cwd) => { + starting = false + let metadata + try { + metadata = asRecord( + asRecord( + await rpc.request('thread/read', { + threadId: input.providerSessionId, + includeTurns: false + }) + )?.thread + ) + if ( + metadata?.id !== input.providerSessionId || + (metadata.historyMode != null && + metadata.historyMode !== 'legacy' && + metadata.historyMode !== 'paginated') + ) { + throw new Error('Invalid source metadata') + } + } catch (error) { + if (!isCodexAppServerUnsupportedError(error)) { + throw error } } - const firstRemoved = childTurns[captured.index + 1] - if (firstRemoved) { - await rpc.request('thread/revert', { threadId: id, beforeTurnId: firstRemoved.id }) - const kept = await turns(rpc, id, captured.index + 2) + let native = metadata?.historyMode === 'paginated' + let sourceTurns = + native && checkpoint.turnId + ? await turns(rpc, input.providerSessionId, checkpoint.turnId) + : undefined + if (!native || !sourceTurns || sourceTurns.at(-1)?.id !== checkpoint.turnId) { + if (native && !legacy) { + return missing() + } + history ??= await physicalHistory(native && legacy ? undefined : checkpoint.turnId) + if (native && history.selected.id) { + sourceTurns = await turns(rpc, input.providerSessionId, history.selected.id) + if (sourceTurns.at(-1)?.id !== history.selected.id) { + return missing() + } + } else { + native = false + } + } + const lastTurnId = native ? sourceTurns!.at(-1)!.id : history!.selected.id + const beforeTurnId = native ? undefined : history!.roots[history!.index + 1]?.id + const terminal = native + ? ['completed', 'failed', 'interrupted'].includes(String(sourceTurns!.at(-1)?.status)) + : history!.selected.terminal + if (!checkpoint.settled && !terminal && !beforeTurnId) { + throw agentConversationCopyRefusal( + 'agent_session_operation_invalid', + { reason: 'turnActive' }, + "Codex hasn't finished this response yet. Wait for it to finish, then try again." + ) + } + const prefix = native ? sourceTurns! : history!.roots.slice(0, history!.index + 1) + sourceTurns = native + ? sourceTurns! + : prefix.every((root) => root.id) + ? prefix.map((root) => ({ id: root.id! })) + : await turns(rpc, input.providerSessionId, history!.roots.length) + if ( + sourceTurns.length < prefix.length || + prefix.some((root, index) => root.id && root.id !== sourceTurns![index]?.id) + ) { + return missing() + } + const coverage = { + unit: 'codex-turn' as const, + ids: sourceTurns.slice(0, prefix.length).map((turn) => turn.id) + } + rpc.signal?.throwIfAborted() + signal.throwIfAborted() + dispatched = true + const fork = asRecord( + await rpc.request('thread/fork', { + threadId: input.providerSessionId, + ...(lastTurnId ? { lastTurnId } : beforeTurnId ? { beforeTurnId } : {}), + excludeTurns: true, + cwd + }) + ) + const thread = asRecord(fork?.thread) + const id = thread?.id + if (typeof id !== 'string' || !id.trim() || id === input.providerSessionId) { + return unavailable() + } + if (native) { + const captured = await turns(rpc, id, lastTurnId!) if ( - kept.length !== captured.index + 1 || - kept.at(-1)?.id !== childTurns[captured.index]?.id + captured.length !== coverage.ids.length || + captured.some((turn, index) => turn.id !== coverage.ids[index]) ) { return unavailable() } + return { sessionId: id, coverage } } + const captured = await codexForkHistory({ + path: await find(id), + roots: stores, + selectedItemId: checkpoint.selectedItemId, + turnId: checkpoint.turnId, + sessionId: id, + inheritedOnly: true, + signal + }) + if ( + captured.index !== history!.index || + captured.roots.length < prefix.length || + captured.roots + .slice(0, prefix.length) + .some((root, index) => root.id && root.id !== coverage.ids[index]) + ) { + return unavailable() + } + if (lastTurnId || beforeTurnId) { + if (captured.roots.length !== prefix.length) { + return unavailable() + } + } else { + // Trim the actual capture; coverage identities were frozen on the source before fork. + if (thread?.historyMode !== 'paginated') { + return unavailable() + } + const childTurns = await turns(rpc, id, captured.roots.length + 1) + if (childTurns.length !== captured.roots.length) { + return unavailable() + } + for (const [index, root] of captured.roots.entries()) { + if (root.id && root.id !== childTurns[index]?.id) { + return unavailable() + } + } + const firstRemoved = childTurns[captured.index + 1] + if (firstRemoved) { + await rpc.request('thread/revert', { threadId: id, beforeTurnId: firstRemoved.id }) + const kept = await turns(rpc, id, captured.index + 2) + if ( + kept.length !== captured.index + 1 || + kept.at(-1)?.id !== childTurns[captured.index]?.id + ) { + return unavailable() + } + } + } + return { sessionId: id, coverage } } - return { sessionId: id, coverage } + ) + } catch (error) { + input.signal?.throwIfAborted() + if (!dispatched) { + const refusal = isAgentSessionRefusalError(error) + ? error + : agentConversationCopyRefusal( + 'agent_session_identity_required', + { reason: 'transcriptUnreadable' }, + starting + ? TEXT_GENERATION_FAILURE_COPY.agentCouldNotStart.replace('{{label}}', 'Codex') + : 'Codex could not read the saved chat. Open it again, then try forking the response.' + ) + if (starting) { + refusal.cause = new AgentConversationCopyStartError(refusal.refusal.message) + } + refusal.refusal.createAttemptRefusedBeforeCommit = true + throw refusal } - ).catch((error: unknown) => { if (error instanceof AgentConversationCopyError) { throw error } - if (error instanceof CodexAppServerTimeoutError || signal.aborted) { - throw new AgentConversationCopyError('Codex took too long to copy this chat. Try again.', { - cause: error - }) - } - if ( - error instanceof Error && - /(?:in[- ]progress|active turn|turn.*running)/i.test(error.message) - ) { - throw new AgentConversationCopyError( - 'Codex could not copy this chat while a response was running. Wait for it to finish, then try again.', - { cause: error } - ) - } - throw new AgentConversationCopyError('Codex could not copy this chat. Try again.', { + throw new AgentConversationCopyError('Codex could not verify the copied chat.', { cause: error }) - }) + } } diff --git a/src/main/codex/codex-fork-history.ts b/src/main/codex/codex-fork-history.ts new file mode 100644 index 00000000000..26d345e2693 --- /dev/null +++ b/src/main/codex/codex-fork-history.ts @@ -0,0 +1,100 @@ +import { AgentConversationCopyError } from '../native-chat/agent-conversation-copy-error' +import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import { asRecord, parseJsonObject } from '../ai-vault/session-scanner-values' +import { createLegacyIdentityTracker } from '../native-chat/agent-session-journal/history-import/journal-legacy-identity' +import { readCodexLocalHistory } from '../native-chat/codex-local-history' +import { decodeCodexTranscriptLine } from '../native-chat/transcript-line-decoders-codex' + +type Root = { id?: string; terminal: boolean; prompt: boolean } + +/** Use the importer's physical lineage and identity accounting, including discarded window rows. */ +export async function codexForkHistory(input: { + path: string + roots: string[] + selectedItemId: string + turnId?: string + sessionId: string + signal?: AbortSignal + inheritedOnly?: boolean +}) { + const identity = parseAgentJournalItemKey(input.selectedItemId) + const tracker = createLegacyIdentityTracker({ + transcriptAgent: 'codex', + agent: 'codex', + sessionId: input.sessionId + }) + const roots: Root[] = [] + let selected: Root | undefined + let lineIndex = 0 + let referenceBacked = false + await readCodexLocalHistory({ + filePath: input.path, + roots: input.roots, + visitRecord: ({ record, selected }) => { + if (selected && record?.type === 'session_meta') { + referenceBacked = asRecord(record.payload)?.history_base != null + } + }, + visit: (line, fallbackId, selectedSegment, recordId) => { + if (input.inheritedOnly && referenceBacked && selectedSegment) { + return + } + input.signal?.throwIfAborted() + const tracked = tracker.identify(line, lineIndex++) + const raw = parseJsonObject(line) + const payload = asRecord(raw?.payload) + if ( + raw?.type === 'event_msg' && + payload?.type === 'thread_rolled_back' && + typeof payload.num_turns === 'number' + ) { + roots.splice(Math.max(0, roots.length - payload.num_turns)) + return + } + if (raw?.type === 'event_msg' && payload?.type === 'task_started') { + roots.push({ + id: typeof payload.turn_id === 'string' ? payload.turn_id : undefined, + terminal: false, + prompt: false + }) + } + const message = decodeCodexTranscriptLine(line, fallbackId, { historyImport: true }) + if (message?.role === 'user') { + const previous = roots.at(-1) + if (!previous || (previous.prompt && (!previous.id || previous.terminal))) { + roots.push({ terminal: false, prompt: true }) + } else { + previous.prompt = true + } + } + const root = roots.at(-1) + if ( + root && + raw?.type === 'event_msg' && + (payload?.type === 'task_complete' || payload?.type === 'turn_aborted') && + (!payload.turn_id || payload.turn_id === root.id) + ) { + root.terminal = true + } + const importedMatch = + identity?.provider === 'legacy' && + identity.recordId === + (recordId ?? (tracked.provider === 'legacy' ? tracked.recordId : undefined)) + if ( + root && + ((importedMatch && message?.role === 'assistant') || + (input.turnId && root.id === input.turnId)) + ) { + if (selected && selected !== root) { + throw new AgentConversationCopyError('Codex could not verify the copied chat.') + } + selected = root + } + } + }) + const index = selected ? roots.indexOf(selected) : -1 + if (index < 0) { + throw new AgentConversationCopyError('Codex could not verify the copied chat.') + } + return { roots, index, selected: roots[index] } +} diff --git a/src/main/codex/configuration/toml/config-toml-line-scan.ts b/src/main/codex/configuration/toml/config-toml-line-scan.ts index c065bb7aa1d..a76e3ad999f 100644 --- a/src/main/codex/configuration/toml/config-toml-line-scan.ts +++ b/src/main/codex/configuration/toml/config-toml-line-scan.ts @@ -33,18 +33,20 @@ export function updateTomlLineScanState(state: TomlLineScanState, line: string): index += 2 continue } - if (line.startsWith('"""', index)) { + const closing = getTomlMultilineCloserLength(line, index, '"') + if (closing !== null) { mode = null - index += 3 + index += closing continue } index += 1 continue } if (mode === 'literal') { - if (line.startsWith("'''", index)) { + const closing = getTomlMultilineCloserLength(line, index, "'") + if (closing !== null) { mode = null - index += 3 + index += closing continue } index += 1 @@ -199,6 +201,19 @@ export function parseTomlStringValue(source: string, offset: number): ParsedToml return null } +// Up to two content quotes may sit against the closer, so a run of 3-5 quotes ends the string. +function getTomlMultilineCloserLength( + line: string, + index: number, + quote: '"' | "'" +): number | null { + let run = 0 + while (line[index + run] === quote) { + run += 1 + } + return run < 3 ? null : Math.min(run, 5) +} + function skipTomlBasicString(line: string, startIndex: number): number { let index = startIndex while (index < line.length) { diff --git a/src/main/codex/structured/background-work/codex-background-command-tracker.ts b/src/main/codex/structured/background-work/codex-background-command-tracker.ts index 8a2ddfcc3c7..583f958aa0d 100644 --- a/src/main/codex/structured/background-work/codex-background-command-tracker.ts +++ b/src/main/codex/structured/background-work/codex-background-command-tracker.ts @@ -35,6 +35,7 @@ export type CodexBackgroundCommandChange = export class CodexBackgroundCommandTracker { private readonly commands = new Map() + private readonly byThread = new Map>() private readonly settled = new Set() constructor(private readonly primaryThreadId: string) {} @@ -52,13 +53,20 @@ export class CodexBackgroundCommandTracker { return null } this.commands.set(key, command) + const thread = this.byThread.get(command.threadId) ?? new Set() + thread.add(key) + this.byThread.set(command.threadId, thread) return this.liveChange(command) } /** A surviving process becomes background work when the turn that launched it ends. */ endTurn(threadId: string, turnId: string): CodexBackgroundCommandChange[] { const backgrounded: CodexBackgroundCommandChange[] = [] - for (const command of this.commands.values()) { + for (const key of this.byThread.get(threadId) ?? []) { + const command = this.commands.get(key) + if (!command) { + continue + } if ( command.threadId === threadId && (command.turnId === turnId || command.turnId === null) && @@ -86,9 +94,7 @@ export class CodexBackgroundCommandTracker { /** The thread closed: Codex stops its processes first, so none of them can report an exit. */ endThread(threadId: string): CodexBackgroundCommandChange[] { - return [...this.commands] - .filter(([, command]) => command.threadId === threadId) - .flatMap(([key]) => this.end(key) ?? []) + return [...(this.byThread.get(threadId) ?? [])].flatMap((key) => this.end(key) ?? []) } /** Its approval went unanswered until its turn ended, so its process never started. */ @@ -129,9 +135,10 @@ export class CodexBackgroundCommandTracker { /** Live processes, including foreground tools that are absent from the strip. */ threadCommands(threadId: string): CodexBackgroundCommandChange[] { - return [...this.commands.values()] - .filter((command) => command.threadId === threadId) - .map((command) => this.liveChange(command)) + return [...(this.byThread.get(threadId) ?? [])].flatMap((key) => { + const command = this.commands.get(key) + return command ? [this.liveChange(command)] : [] + }) } clear(): CodexBackgroundCommandChange[] { @@ -143,6 +150,7 @@ export class CodexBackgroundCommandTracker { }) ) this.commands.clear() + this.byThread.clear() this.settled.clear() return ended } @@ -152,6 +160,11 @@ export class CodexBackgroundCommandTracker { const existing = this.commands.get(key) if (existing) { this.commands.delete(key) + const thread = this.byThread.get(existing.threadId) + thread?.delete(key) + if (thread?.size === 0) { + this.byThread.delete(existing.threadId) + } } this.rememberSettled(key) return existing diff --git a/src/main/codex/structured/background-work/codex-background-task-tracker.ts b/src/main/codex/structured/background-work/codex-background-task-tracker.ts index 67a57591e53..cda46518af4 100644 --- a/src/main/codex/structured/background-work/codex-background-task-tracker.ts +++ b/src/main/codex/structured/background-work/codex-background-task-tracker.ts @@ -11,11 +11,15 @@ import { type CodexBackgroundTaskEvent } from './codex-background-task-frames' import { CodexSubagentExecutions } from './codex-subagent-executions' -import { CodexBackgroundCommandTracker } from './codex-background-command-tracker' +import { + CodexBackgroundCommandTracker, + type CodexBackgroundCommandChange +} from './codex-background-command-tracker' import { CodexChildWorkEvidence } from './codex-child-work-evidence' import type { CodexAbandonedCommand } from '../prompts/codex-prompt-registry' import type { CodexStructuredSessionAdapterDeps } from '../session-lifecycle/codex-structured-session-state' import { boundSubagentLabel } from '../../../native-chat/agent-session-journal/item-lifecycle/journal-subagent-item' +import { codexChildCommandDescription } from '../../../../shared/codex-child-command-description' export type CodexChildWorkSink = { deliver: (evidence: AgentChildWorkEvidence[]) => void @@ -40,6 +44,7 @@ export type CodexTerminalStopSupport = 'supported' | 'unsupported' | 'unknown' export class CodexBackgroundTaskTracker { private publishedFingerprint = '[]' private publishedState: AgentSessionBackgroundTaskState | null = null + private readonly projectedTasks = new Map() private readonly commands: CodexBackgroundCommandTracker private readonly childWork: CodexChildWorkEvidence private terminalStops: CodexTerminalStopSupport | 'probing' = 'unknown' @@ -91,11 +96,18 @@ export class CodexBackgroundTaskTracker { turns: { threadId: string; turnId: string }[] terminals: { threadId: string; processId: string }[] } { - const named = new Set(taskIds) - const lineage = this.executions - .workingChildren() - .filter((child) => named.has(child.agentThreadId)) - .flatMap((child) => this.executions.lineage(child.agentThreadId)) + const named = new Set( + taskIds.filter((id) => { + const child = this.executions.find(id) + return child?.registered && child.execution?.state === 'working' + }) + ) + const lineage = named.size + ? this.executions.lineage( + named, + this.commands.liveCommands().map((command) => command.threadId) + ) + : [] const threads = [...new Set(lineage.map((child) => child.agentThreadId))] return { turns: threads.flatMap((threadId) => { @@ -147,16 +159,16 @@ export class CodexBackgroundTaskTracker { ] observeCodexExecutionFrame(this.executions, frame, this.primaryThreadId) this.childWork.observe(event, frame, commands) - if (!frame) { - return itemEvent || commands.length > 0 ? this.refresh() : false - } - // Children can outlive the parent turn; republish without settling or sweeping them. - return this.refresh() + // The journal may have dirtied this shared registry before admitting the frame. + return this.updateProjection(this.executions.takeChangedThreads(), commands) + ? this.refresh() + : false } clear(processExit?: StructuredAgentSessionEndedEvent['processExit']): boolean { this.childWork.clear(this.commands.clear(), processExit) this.executions.clear() + this.projectedTasks.clear() return this.refresh() } @@ -188,6 +200,63 @@ export class CodexBackgroundTaskTracker { ] } + private updateProjection( + threads: readonly string[], + commands: readonly CodexBackgroundCommandChange[] + ): boolean { + let changed = false + for (const threadId of threads) { + const child = this.executions.find(threadId) + const task = + child?.registered && child.execution?.state === 'working' + ? { + id: `codex-agent:${threadId}`, + kind: 'agent' as const, + ...(child.label ? { description: boundSubagentLabel(child.label) } : {}) + } + : null + changed = this.projectTask(`codex-agent:${threadId}`, task) || changed + for (const command of this.commands.threadCommands(threadId)) { + changed = this.projectCommand(command) || changed + } + } + for (const command of commands) { + changed = this.projectCommand(command) || changed + } + return changed + } + + private projectCommand(command: CodexBackgroundCommandChange): boolean { + if (command.type === 'ended') { + return this.projectTask(command.taskId, null) + } + const child = this.executions.find(command.threadId) + if (!command.backgrounded || (child?.registered && child.execution?.state === 'working')) { + return this.projectTask(command.task.id, null) + } + const label = + command.threadId === this.primaryThreadId ? null : this.executions.label(command.threadId) + const task = label + ? { + ...command.task, + description: codexChildCommandDescription(label, command.task.description) + } + : command.task + return this.projectTask(task.id, task) + } + + private projectTask(id: string, task: AgentSessionBackgroundTask | null): boolean { + if (task === null) { + return this.projectedTasks.delete(id) + } + const previous = this.projectedTasks.get(id) + if (previous?.kind === task.kind && previous.description === task.description) { + return false + } + this.projectedTasks.set(id, task) + return true + } + private refresh(): boolean { const tasks = this.tasks() const fingerprint = JSON.stringify(tasks) diff --git a/src/main/codex/structured/background-work/codex-child-work-evidence.ts b/src/main/codex/structured/background-work/codex-child-work-evidence.ts index e53243989f8..4c7bba71fab 100644 --- a/src/main/codex/structured/background-work/codex-child-work-evidence.ts +++ b/src/main/codex/structured/background-work/codex-child-work-evidence.ts @@ -207,14 +207,21 @@ export class CodexChildWorkEvidence { const lastMessage = ofTurn(facts.lastMessage, turnId)?.text const { totalTokens } = facts const outcome = codexChildTurnOutcome(state) - this.publish(facts, JSON.stringify(['ended', turnId, state]), (observedAt) => ({ - type: 'ended', - observedAt, - handle: { idKind: 'thread_id', id: threadId, runId: turnId }, - outcome, - ...(lastMessage ? { lastMessage } : {}), - ...(totalTokens !== undefined ? { totalTokens } : {}) - })) + const published = this.publish( + facts, + JSON.stringify(['ended', turnId, state]), + (observedAt) => ({ + type: 'ended', + observedAt, + handle: { idKind: 'thread_id', id: threadId, runId: turnId }, + outcome, + ...(lastMessage ? { lastMessage } : {}), + ...(totalTokens !== undefined ? { totalTokens } : {}) + }) + ) + if (facts.lastMessage?.turnId === turnId && (published || state !== 'unverifiable')) { + facts.lastMessage = undefined + } return } for (const [itemId, call] of facts.openCalls) { @@ -267,19 +274,21 @@ export class CodexChildWorkEvidence { } } - private publish(facts: ChildFacts, fingerprint: string, edge: CodexPendingChildWork): void { + private publish(facts: ChildFacts, fingerprint: string, edge: CodexPendingChildWork): boolean { if (facts.published !== fingerprint) { facts.published = fingerprint this.pending.push(edge) + return true } + return false } // Reassert ownership for work admitted before its owner's record existed. private requeueOwnedBy(threadId: string): void { this.queueCommands(this.liveCommands(threadId)) - for (const spawned of this.executions.workingChildren()) { + for (const spawned of this.executions.workingSpawnedBy(threadId)) { const facts = this.facts.get(spawned.agentThreadId) - if (spawned.spawnerThreadId === threadId && facts?.published !== undefined) { + if (facts?.published !== undefined) { facts.published = undefined this.queueChild(spawned.agentThreadId) } diff --git a/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts b/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts index 49e7defffbd..3580b37a4de 100644 --- a/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts +++ b/src/main/codex/structured/background-work/codex-structured-child-work-producer.test.ts @@ -1,3 +1,4 @@ +import { CodexBackgroundTaskTracker } from './codex-background-task-tracker' import { acquireReadyCodexForTest, fakeCodex, @@ -193,6 +194,66 @@ const shellFrame = ( }) describe('Codex structured child-work producer', () => { + it('delivers pending previews once across late announcements and verdict refinements', () => { + const tracker = new CodexBackgroundTaskTracker(THREAD_ID) + const send = (frame: Frame) => { + tracker.observe({ ...frame, threadId: String(frame.params.threadId) }) + return tracker.drainChildWorkEvidence(100) + } + const message = (turnId: string, text: string) => + item('item/completed', REVIEWER, turnId, { + type: 'agentMessage', + id: `reply-${text}`, + text + }) + send(turn('turn/started', REVIEWER, 'r1')) + send(message('r1', 'before announcement')) + expect(send({ method: 'thread/closed', params: { threadId: REVIEWER } })).toEqual([]) + expect(send(spawned(REVIEWER, 'review', 'p1'))).toEqual([ + expect.objectContaining({ type: 'ended', lastMessage: 'before announcement' }) + ]) + expect(send(message('r1', 'refined reply'))).toEqual([]) + expect(send(turn('turn/completed', REVIEWER, 'r1'))).toEqual([ + expect.objectContaining({ type: 'ended', outcome: 'succeeded', lastMessage: 'refined reply' }) + ]) + send(message('r2', 'future reply')) + expect(send(turn('turn/started', REVIEWER, 'r2'))).toEqual([ + expect.objectContaining({ + type: 'live', + child: expect.objectContaining({ lastMessage: 'future reply' }) + }) + ]) + expect(send({ method: 'thread/closed', params: { threadId: REVIEWER } })).toEqual([ + expect.objectContaining({ type: 'ended', lastMessage: 'future reply' }) + ]) + expect(send(turn('turn/completed', REVIEWER, 'r2'))).toEqual([ + { + type: 'ended', + observedAt: 100, + handle: { idKind: 'thread_id', id: REVIEWER, runId: 'r2' }, + outcome: 'succeeded' + } + ]) + }) + + it('keeps the published task order when an earlier helper resumes', () => { + const tracker = new CodexBackgroundTaskTracker(THREAD_ID) + const send = (frame: Frame) => { + tracker.observe({ ...frame, threadId: String(frame.params.threadId) }) + tracker.publishChildWork() + } + for (const child of [REVIEWER, 'second-helper']) { + send(spawned(child, child, 'p1')) + send(turn('turn/started', child, 'r1')) + } + send(turn('turn/completed', REVIEWER, 'r1')) + send(turn('turn/started', REVIEWER, 'r2')) + expect(tracker.state?.tasks?.map((task) => task.id)).toEqual([ + 'codex-agent:thread-reviewer', + 'codex-agent:second-helper' + ]) + }) + it('delivers evidence only after the journal wrote and published the frame', async () => { const { send, records } = await producer() const deliveries = [ diff --git a/src/main/codex/structured/background-work/codex-subagent-executions.ts b/src/main/codex/structured/background-work/codex-subagent-executions.ts index 243455beb9e..ceb01772b8c 100644 --- a/src/main/codex/structured/background-work/codex-subagent-executions.ts +++ b/src/main/codex/structured/background-work/codex-subagent-executions.ts @@ -15,6 +15,7 @@ export type CodexChildExecution = { export type CodexExecutionChild = { agentThreadId: string + observationOrder: number registered: boolean label: string | null /** Spawn announcements arrive on the parent's thread. */ @@ -28,6 +29,10 @@ export type CodexExecutionChild = { export class CodexSubagentExecutions { private readonly children = new Map() private readonly settledTurns = new Map() + private readonly working = new Map() + private readonly workingOrder: CodexExecutionChild[] = [] + private readonly workingBySpawner = new Map>() + private readonly changed = new Set() register( agentThreadId: string, @@ -35,6 +40,7 @@ export class CodexSubagentExecutions { spawnerThreadId?: string ): CodexExecutionChild { const child = this.child(agentThreadId) + const previousLabel = child.label // Keep the original spawner across duplicate announcement frames. child.spawnerThreadId ??= spawnerThreadId ?? null child.registered = true @@ -44,6 +50,10 @@ export class CodexSubagentExecutions { ?.trim() .replace(/\s+/g, ' ') .slice(0, MAX_SUBAGENT_FIELD_CHARS + 1) || null + this.updateWorking(child) + if (previousLabel !== child.label) { + this.changed.add(agentThreadId) + } return child } @@ -83,6 +93,7 @@ export class CodexSubagentExecutions { } if (state === 'working' || !child.execution || child.execution.turnId === turnId) { child.execution = execution + this.updateWorking(child) } return { child, execution } } @@ -113,42 +124,76 @@ export class CodexSubagentExecutions { return this.children.get(agentThreadId) } - lineage(agentThreadId: string): CodexExecutionChild[] { - const spawnedByThread = new Map() - for (const child of this.children.values()) { - if (child.spawnerThreadId === null) { - continue + lineage(roots: ReadonlySet, commandThreads: Iterable): CodexExecutionChild[] { + const ancestors = new Map() + const spawnedBy = new Map() + const candidates = new Set([...this.working.keys(), ...commandThreads]) + for (const threadId of candidates) { + let id: string | null = threadId + while (id !== null && !ancestors.has(id)) { + const child = this.children.get(id) + ancestors.set(id, child) + if (!child) { + break + } + if (child.spawnerThreadId !== null) { + const siblings = spawnedBy.get(child.spawnerThreadId) ?? [] + siblings.push(child) + spawnedBy.set(child.spawnerThreadId, siblings) + } + id = child.spawnerThreadId } - const siblings = spawnedByThread.get(child.spawnerThreadId) ?? [] - siblings.push(child.agentThreadId) - spawnedByThread.set(child.spawnerThreadId, siblings) } const lineage: CodexExecutionChild[] = [] const seen = new Set() - const pending = [agentThreadId] - for (let id = pending.pop(); id !== undefined; id = pending.pop()) { - const child = this.children.get(id) - if (!child || seen.has(id)) { - continue - } - seen.add(id) - lineage.push(child) - for (const spawned of spawnedByThread.get(id) ?? []) { - pending.push(spawned) + const orderedRoots = [...roots] + .flatMap((root) => { + const child = ancestors.get(root) + return child ? [child] : [] + }) + .sort((a, b) => a.observationOrder - b.observationOrder) + for (const root of orderedRoots) { + const pending = [root.agentThreadId] + for (let id = pending.pop(); id !== undefined; id = pending.pop()) { + const child = ancestors.get(id) + if (!child || seen.has(id)) { + continue + } + seen.add(id) + lineage.push(child) + const spawned = spawnedBy.get(id) ?? [] + spawned.sort((a, b) => a.observationOrder - b.observationOrder) + for (const child of spawned) { + pending.push(child.agentThreadId) + } } } return lineage } workingChildren(): CodexExecutionChild[] { - return [...this.children.values()].filter( - (child) => child.registered && child.execution?.state === 'working' + return [...this.workingOrder] + } + + workingSpawnedBy(threadId: string): CodexExecutionChild[] { + return [...(this.workingBySpawner.get(threadId) ?? [])].sort( + (a, b) => a.observationOrder - b.observationOrder ) } + takeChangedThreads(): string[] { + const threads = [...this.changed] + this.changed.clear() + return threads + } + clear(): void { this.children.clear() this.settledTurns.clear() + this.working.clear() + this.workingOrder.length = 0 + this.workingBySpawner.clear() + this.changed.clear() } retentionSizes(): { children: number; settledTurns: number } { @@ -162,6 +207,7 @@ export class CodexSubagentExecutions { } const child: CodexExecutionChild = { agentThreadId, + observationOrder: this.children.size, registered: false, label: null, spawnerThreadId: null, @@ -173,6 +219,36 @@ export class CodexSubagentExecutions { return child } + private updateWorking(child: CodexExecutionChild): void { + const working = child.registered && child.execution?.state === 'working' + if (working !== this.working.has(child.agentThreadId)) { + this.changed.add(child.agentThreadId) + if (working) { + this.working.set(child.agentThreadId, child) + const next = this.workingOrder.findIndex( + (other) => other.observationOrder > child.observationOrder + ) + this.workingOrder.splice(next === -1 ? this.workingOrder.length : next, 0, child) + } else { + this.working.delete(child.agentThreadId) + this.workingOrder.splice(this.workingOrder.indexOf(child), 1) + } + } + const spawner = child.spawnerThreadId + if (spawner !== null) { + const children = this.workingBySpawner.get(spawner) ?? new Set() + if (working) { + children.add(child) + this.workingBySpawner.set(spawner, children) + } else { + children.delete(child) + if (children.size === 0) { + this.workingBySpawner.delete(spawner) + } + } + } + } + private numberTurn(child: CodexExecutionChild, turnId: string): void { if (child.turnOrdinals.has(turnId)) { return diff --git a/src/main/codex/structured/background-work/codex-subagent-interrupts.test.ts b/src/main/codex/structured/background-work/codex-subagent-interrupts.test.ts index a5e88e26ac0..c77e2ac248d 100644 --- a/src/main/codex/structured/background-work/codex-subagent-interrupts.test.ts +++ b/src/main/codex/structured/background-work/codex-subagent-interrupts.test.ts @@ -46,7 +46,24 @@ async function runningHelper(routes: Record) { .map((call) => call.params) const stop = (taskIds: string[], fence = 7) => adapter.stopBackgroundTasks({ sessionId: 'session-1', fence, taskIds }) - return { adapter, evidence, notify, interrupts, stop } + const spawn = (parent: string, child: string, turnId: string) => { + notify('item/started', { + threadId: parent, + turnId, + item: { + type: 'subAgentActivity', + id: `spawn-${child}`, + kind: 'started', + agentThreadId: child, + agentPath: `/root/${child}` + } + }) + notify('turn/started', { + threadId: child, + turn: { id: `${child}-turn`, status: 'inProgress' } + }) + } + return { adapter, evidence, notify, interrupts, stop, spawn } } describe('Codex sub-agent Stop', () => { @@ -74,6 +91,94 @@ describe('Codex sub-agent Stop', () => { expect(codex.interrupts()).toEqual([]) }) + it('stops a resumed parent before descendants across a settled helper and its surviving shell', async () => { + const timeout = new CodexAppServerTimeoutError('codex app-server turn/interrupt timed out') + let timeOut = true + let running = true + const terminated: unknown[] = [] + const codex = await runningHelper({ + 'turn/interrupt': (params) => { + if (timeOut && params?.threadId === 'grandchild') { + throw timeout + } + return {} + }, + 'thread/backgroundTerminals/list': (params) => ({ + data: running && params?.threadId === 'intermediary' ? [{ processId: '4343' }] : [], + nextCursor: null + }), + 'thread/backgroundTerminals/terminate': (params) => { + terminated.push(params) + running = false + return { terminated: true } + } + }) + codex.spawn(HELPER, 'intermediary', HELPER_TURN) + codex.spawn('intermediary', 'grandchild', 'intermediary-turn') + codex.notify('item/started', { + threadId: 'intermediary', + turnId: 'intermediary-turn', + item: { + type: 'commandExecution', + id: 'surviving-shell', + processId: '4343', + source: 'unifiedExecStartup', + command: 'sleep 90', + status: 'inProgress' + } + }) + for (const [threadId, id] of [ + ['intermediary', 'intermediary-turn'], + [HELPER, HELPER_TURN] + ]) { + codex.notify('turn/completed', { threadId, turn: { id, status: 'completed' } }) + } + codex.notify('turn/started', { + threadId: HELPER, + turn: { id: 'helper-turn-2', status: 'inProgress' } + }) + await new Promise((resolve) => setImmediate(resolve)) + await expect(codex.stop(['grandchild', HELPER])).rejects.toBe(timeout) + expect(codex.interrupts()).toEqual([ + { threadId: HELPER, turnId: 'helper-turn-2' }, + { threadId: 'grandchild', turnId: 'grandchild-turn' } + ]) + expect(terminated).toEqual([]) + timeOut = false + await expect(codex.stop([HELPER])).resolves.toEqual({ cancelled: true }) + expect(terminated).toEqual([{ threadId: 'intermediary', processId: '4343' }]) + }) + + it('interrupts an explicitly named descendant before a sibling timeout across a commandless settled helper', async () => { + const timeout = new CodexAppServerTimeoutError('codex app-server turn/interrupt timed out') + const codex = await runningHelper({ + 'turn/interrupt': (params) => { + if (params?.threadId === 'earlier-sibling') { + throw timeout + } + return {} + } + }) + codex.spawn(HELPER, 'earlier-sibling', HELPER_TURN) + codex.spawn(HELPER, 'intermediary', HELPER_TURN) + codex.spawn('intermediary', 'grandchild', 'intermediary-turn') + codex.notify('turn/completed', { + threadId: 'intermediary', + turn: { id: 'intermediary-turn', status: 'completed' } + }) + for (const taskIds of [ + [HELPER, 'grandchild'], + ['grandchild', HELPER] + ]) { + await expect(codex.stop(taskIds)).rejects.toBe(timeout) + expect(codex.interrupts().slice(-3)).toEqual([ + { threadId: HELPER, turnId: HELPER_TURN }, + { threadId: 'grandchild', turnId: 'grandchild-turn' }, + { threadId: 'earlier-sibling', turnId: 'earlier-sibling-turn' } + ]) + } + }) + async function helperAndDevServer(interrupt: Route) { const running = ['4242'] const terminated: unknown[] = [] diff --git a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts index 47779af453c..3fe0e337ea9 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { createCodexModelCatalogProbe } from './codex-model-catalog-probe' import { runCodexAppServerSession, @@ -14,6 +14,46 @@ const MODEL_ROW = { isDefault: true } +afterEach(() => vi.unstubAllGlobals()) + +it.each(['saved', 'recover'] as const)( + 'composes the Windows %s catalog environment before lookup and listing', + async (lookup) => { + vi.stubGlobal('process', { ...process, platform: 'win32' }) + const probe = createCodexModelCatalogProbe({ + resolveEnvironment: async () => ({ PATH: '/inherited/bin', TOKEN: 'inherited' }), + resolveSavedEnvironment: async () => ({ PATH: '/saved/bin', TOKEN: 'saved' }), + resolveEnv: () => ({ + path: '/configured/bin', + tOKEN: 'configured', + codex_home: '/configured/home' + }), + resolveCommand: (options) => { + expect(options?.pathEnv).toBe('/configured/bin') + return { command: '/configured/bin/codex.exe', prefixArgs: [] } + }, + runSession: async (invocation, body) => { + expect(invocation.env).toEqual({ + PATH: '/configured/bin', + TOKEN: 'configured', + CODEX_HOME: '/pinned' + }) + return body({ + request: async (method: string) => + method === 'config/read' ? { config: {} } : { data: [MODEL_ROW], nextCursor: null }, + notify: () => {} + }) + } + }) + const resolved = await probe.resolve?.( + { variable: 'CODEX_HOME', path: '/pinned' }, + '/probe', + lookup + ) + expect((await resolved?.run())?.models[0]?.id).toBe('gpt-live') + } +) + describe('codex model catalog probe', () => { it.each([[[]]])( "lists a command line with arguments %j from Orca's folder for every chat", diff --git a/src/main/codex/structured/catalog/codex-model-catalog-probe.ts b/src/main/codex/structured/catalog/codex-model-catalog-probe.ts index dc72b22ea32..fe4b82a24a2 100644 --- a/src/main/codex/structured/catalog/codex-model-catalog-probe.ts +++ b/src/main/codex/structured/catalog/codex-model-catalog-probe.ts @@ -3,6 +3,7 @@ import { type StructuredAgentResolutionOperation } from '../../../native-chat/structured-agent-command-resolution' import { codexStructuredLaunchArgs } from '../launch/codex-structured-launch-args' +import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' import { envWithPathRelativeTo } from '../../../../shared/node-cli-command-resolution' import type { AgentSessionAccountKind } from '../../../../shared/agent-session/agent-session-availability' import { AgentModelCatalogUnavailableError } from '../../../native-chat/agent-model-catalog/agent-model-catalog-unavailable' @@ -57,13 +58,14 @@ export function createCodexModelCatalogProbe( ) => { assertStructuredAgentResolutionCurrent(operation) const accountHomePath = requireLegacyAgentSessionAccountHome(accountHome).path - const overlay = { ...deps.resolveEnv?.() } + const overlay = overlayEnvironmentVariables({}, deps.resolveEnv?.(), process.platform) const readEnvironment = lookup === 'saved' ? deps.resolveSavedEnvironment : deps.resolveEnvironment const { command, prefixArgs, environment } = await resolveCodexStructuredInvocation({ ...deps, operation, - resolveEnvironment: async () => ({ ...(await readEnvironment?.()), ...overlay }), + resolveEnvironment: async () => + overlayEnvironmentVariables((await readEnvironment?.()) ?? {}, overlay, process.platform), ...(lookup === 'recover' ? {} : { refreshEnvironmentAfterMiss: undefined }), ...(launchDirectory ? { resolveWorkingDirectory: () => launchDirectory } : {}) }) diff --git a/src/main/codex/structured/catalog/codex-structured-model-catalog.ts b/src/main/codex/structured/catalog/codex-structured-model-catalog.ts index bdf90b22526..b15e3e58291 100644 --- a/src/main/codex/structured/catalog/codex-structured-model-catalog.ts +++ b/src/main/codex/structured/catalog/codex-structured-model-catalog.ts @@ -101,6 +101,57 @@ export type CodexModelCatalogListing = { listedServiceTiers?: readonly string[] } +export type CodexModelPages = { + models: AgentSessionModelOption[] + /** False when a page was malformed, a row unreadable, or the page cap cut the listing short. */ + complete: boolean +} + +/** Pages `model/list` (hidden rows excluded) through any transport's request. */ +export async function listCodexModelPages( + request: (params: Record) => Promise +): Promise { + const models: AgentSessionModelOption[] = [] + const seen = new Set() + let cursor: string | null = null + let complete = true + for (let page = 0; page < MAX_MODEL_PAGES; page += 1) { + const response = record( + await request({ + limit: MODEL_PAGE_LIMIT, + includeHidden: false, + ...(cursor ? { cursor } : {}) + }) + ) + if (!Array.isArray(response?.data)) { + complete = false + } + const rows = Array.isArray(response?.data) ? response.data : [] + for (const row of rows) { + const parsed = modelOption(row) + if (!parsed && record(row)?.hidden !== true) { + complete = false + } + if (parsed && !seen.has(parsed.id)) { + seen.add(parsed.id) + models.push(parsed) + } + } + if ( + response?.nextCursor !== null && + response?.nextCursor !== undefined && + !text(response.nextCursor) + ) { + complete = false + } + cursor = text(response?.nextCursor) + if (!cursor) { + break + } + } + return { models, complete: complete && cursor === null } +} + export async function fetchCodexModelCatalogListing(input: { connection: Pick timeoutMs?: number @@ -123,43 +174,14 @@ export async function fetchCodexModelCatalogListing(input: { } return Math.min(remaining, input.timeoutMs ?? remaining) } - const parsedModels: AgentSessionModelOption[] = [] - let cursor: string | null = null - let complete = true - for (let page = 0; page < MAX_MODEL_PAGES; page += 1) { - const response = record( - await input.connection.request( - 'model/list', - { limit: MODEL_PAGE_LIMIT, includeHidden: false, ...(cursor ? { cursor } : {}) }, - { timeoutMs: remainingTimeout() } - ) - ) - assertStructuredAgentResolutionCurrent(input.operation) - if (!Array.isArray(response?.data)) { - complete = false - } - const rows = Array.isArray(response?.data) ? response.data : [] - for (const row of rows) { - const parsed = modelOption(row) - if (!parsed && record(row)?.hidden !== true) { - complete = false - } - if (parsed && !parsedModels.some((model) => model.id === parsed.id)) { - parsedModels.push(parsed) - } - } - if ( - response?.nextCursor !== null && - response?.nextCursor !== undefined && - !text(response.nextCursor) - ) { - complete = false - } - cursor = text(response?.nextCursor) - if (!cursor) { - break - } - } + const { models: parsedModels, complete } = await listCodexModelPages((params) => + input.connection + .request('model/list', params, { timeoutMs: remainingTimeout() }) + .then((response) => { + assertStructuredAgentResolutionCurrent(input.operation) + return response + }) + ) const configured = await readCodexConfiguredLaunchDefaults( input.connection, remainingTimeout(), @@ -168,7 +190,7 @@ export async function fetchCodexModelCatalogListing(input: { assertStructuredAgentResolutionCurrent(input.operation) return { models: applyCodexConfiguredLaunchDefaults(parsedModels, configured), - complete: complete && cursor === null && configured !== null, + complete: complete && configured !== null, ...(configured ? { configured: { diff --git a/src/main/codex/structured/catalog/codex-usage-limits.ts b/src/main/codex/structured/catalog/codex-usage-limits.ts index 491657029dc..ca4bfd0c639 100644 --- a/src/main/codex/structured/catalog/codex-usage-limits.ts +++ b/src/main/codex/structured/catalog/codex-usage-limits.ts @@ -49,8 +49,12 @@ export class CodexUsageLimits { } failure(payload: unknown) { - const error = readCodexErrorInfo(payload)?.error - if (!error || !USAGE_LIMIT_ERRORS.includes(error)) { + const info = readCodexErrorInfo(payload) + if ( + !info || + (!USAGE_LIMIT_ERRORS.includes(info.error) && + !(info.error === 'responseTooManyFailedAttempts' && info.status === 429)) + ) { return null } const message = readCodexErrorMessage(payload) diff --git a/src/main/codex/structured/journal/codex-provider-retry-row.test.ts b/src/main/codex/structured/journal/codex-provider-retry-row.test.ts index d6d98dffaf3..22510166c37 100644 --- a/src/main/codex/structured/journal/codex-provider-retry-row.test.ts +++ b/src/main/codex/structured/journal/codex-provider-retry-row.test.ts @@ -166,14 +166,16 @@ describe('a Codex stream error it is about to retry', () => { 'stream disconnected before completion: error sending request for url (http://127.0.0.1:9/v1/responses)' const errorFrameRows = reduced(rows).flatMap((row) => row.body.kind === 'status' && row.body.providerFrame?.kind === 'notification:error' - ? [{ tone: row.body.tone, text: row.body.text }] + ? [row.body] : [] ) - expect(errorFrameRows).toEqual([ - { tone: 'warning', text: `Codex is retrying: Reconnecting... 1/2.\n${cause}` }, - { tone: 'warning', text: `Codex is retrying: Reconnecting... 2/2.\n${cause}` }, - { tone: 'error', text: cause } + expect(errorFrameRows).toMatchObject([ + { tone: 'warning', failure: { kind: 'providerRetrying' } }, + { tone: 'warning', failure: { kind: 'providerRetrying' } }, + { tone: 'error', failure: { kind: 'providerResponseFailed' } } ]) + expect(errorFrameRows[2]?.text).not.toContain(cause) + expect(errorFrameRows[2]?.providerFrame?.payload.head).toContain(cause) expect(reduced(rows).map((row) => row.body)).toContainEqual( expect.objectContaining({ kind: 'turn', state: 'completed', outcome: 'failure' }) ) diff --git a/src/main/codex/structured/journal/codex-structured-journal-generic-frames.ts b/src/main/codex/structured/journal/codex-structured-journal-generic-frames.ts index 4e4c73c68e6..55f95da2325 100644 --- a/src/main/codex/structured/journal/codex-structured-journal-generic-frames.ts +++ b/src/main/codex/structured/journal/codex-structured-journal-generic-frames.ts @@ -28,9 +28,7 @@ import { isWordlessProviderFrame } from '../../../../shared/native-chat/native-chat-provider-frame-summary' import type { CodexRowAttribution } from '../background-work/codex-subagent-linkage' -import { codexAuthenticationFailure } from '../session-lifecycle/codex-authentication-failure' -import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' -import { CodexUsageLimits } from '../catalog/codex-usage-limits' +import { CodexTurnFailures } from './codex-turn-failures' const OVERFLOW_BUCKET = '__codex-generic-overflow__' type TurnRows = { drawn: number; wordless: number } @@ -74,7 +72,7 @@ export class CodexJournalGenericFrames { private bookkeepingBytes = 0 private fallbackSequence = 0 private cancelSuppressionFlush: (() => void) | null = null - private readonly usageLimits = new CodexUsageLimits() + private readonly failures: CodexTurnFailures constructor( private readonly deps: Pick< @@ -85,6 +83,11 @@ export class CodexJournalGenericFrames { }, private readonly activeTurn: (threadId: string) => string | null ) { + this.failures = new CodexTurnFailures({ + account: deps.account, + activeTurn, + append: (threadId, payload, frame) => this.appendFrameRow(threadId, payload, frame) + }) this.schedule = deps.schedule ?? defaultSchedule this.suppressionCoalesceMs = deps.coalesceMs ?? 60 } @@ -94,31 +97,26 @@ export class CodexJournalGenericFrames { payload: unknown, threadId: string ): CodexJournalTranslationAdmission { - if (this.usageLimits.observe(kind, payload)) { + if (this.failures.observe(kind, payload)) { return CODEX_JOURNAL_ADMITTED } + if (kind === 'notification:error' && !readCodexErrorWillRetry(payload)) { + return this.failures.appendTerminal(kind, payload, payload, threadId) + } const translated = unhandledProviderFrameJournalItem('codex', kind, payload) - // Declined frames count as success; rejection would force-close the provider. - const ended = kind === 'notification:error' && !readCodexErrorWillRetry(payload) - const usageLimit = ended ? this.usageLimits.failure(payload) : null - const failure = - usageLimit ?? (ended ? codexAuthenticationFailure(payload, this.deps.account?.()) : null) - return translated - ? this.appendFrameRow(threadId, payload, { - ...translated, - body: failure - ? { - ...translated.body, - ...(usageLimit ? { tone: 'warning' } : {}), - ...agentSessionFailureWords(failure, { - provider: 'codex', - agentName: 'Codex', - surface: 'row' - }) - } - : translated.body - }) - : CODEX_JOURNAL_ADMITTED + return translated ? this.appendFrameRow(threadId, payload, translated) : CODEX_JOURNAL_ADMITTED + } + + appendCompletionFailure( + payload: unknown, + threadId: string, + onShown: (turnId: string) => void + ): CodexJournalTranslationAdmission { + return this.failures.appendCompletion(payload, threadId, onShown) + } + + forgetTurnFailure(threadId: string, turnId: string): void { + this.failures.forget(threadId, turnId) } appendFrameRow( @@ -159,7 +157,9 @@ export class CodexJournalGenericFrames { const identity = { provider: 'orca' as const, clientMessageId: - translated.body.failure?.kind === 'usageLimitReached' && frameTurnId + translated.body.failure && + translated.body.failure.kind !== 'providerRetrying' && + frameTurnId ? `terminal-failure:codex:${JSON.stringify([threadId, frameTurnId])}` : `provider-frame:codex:${this.deps.acquisitionId ?? 'acquisition'}:${this.fallbackSequence}` } @@ -181,7 +181,11 @@ export class CodexJournalGenericFrames { : { ...rows, drawn: rows.drawn + 1 } ) this.recordBucket(bucket) - return publish(this.deps.sink) + const publication = publish(this.deps.sink) + if (publication.accepted && translated.body.failure?.kind === 'providerRetrying') { + this.failures.observeRetry(payload, threadId) + } + return publication } suppress(threadId: string, turnId: string, count = 1): void { @@ -243,6 +247,7 @@ export class CodexJournalGenericFrames { dispose(): void { this.cancelSuppressionFlush?.() + this.failures.dispose() this.genericRowsByTurn.clear() this.suppressedRowsByTurn.clear() this.bucketOrder.clear() diff --git a/src/main/codex/structured/journal/codex-structured-journal-translation.ts b/src/main/codex/structured/journal/codex-structured-journal-translation.ts index 142a8a16d9a..a5cfa72d0bb 100644 --- a/src/main/codex/structured/journal/codex-structured-journal-translation.ts +++ b/src/main/codex/structured/journal/codex-structured-journal-translation.ts @@ -210,9 +210,21 @@ function createCodexTranslation( return CODEX_JOURNAL_ADMITTED } if (event.method === 'turn/started' || event.method === 'turn/completed') { - return event.method === 'turn/started' - ? turnBoundaries.start(event) - : turnBoundaries.complete(event) + if (event.method === 'turn/started') { + return turnBoundaries.start(event) + } + const turnId = readCodexTurnId(event.params) ?? activeTurns.current(event.threadId) + const failure = genericFrames.appendCompletionFailure(event.params, event.threadId, (id) => + commands.errorShown({ turnId: id }) + ) + if (!failure.accepted) { + return failure + } + const admission = turnBoundaries.complete(event) + if (admission.accepted && turnId) { + genericFrames.forgetTurnFailure(event.threadId, turnId) + } + return admission } const compaction = compactions.handle(event) if (compaction) { diff --git a/src/main/codex/structured/journal/codex-turn-failures.test.ts b/src/main/codex/structured/journal/codex-turn-failures.test.ts new file mode 100644 index 00000000000..9a89ea774a8 --- /dev/null +++ b/src/main/codex/structured/journal/codex-turn-failures.test.ts @@ -0,0 +1,216 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { describe, expect, it } from 'vitest' +import { createCodexJournalTranslator } from './codex-structured-journal-translation' +import { + LIFECYCLE_KEY, + THREAD_ID, + TURN_ID, + notification, + recorder, + reduced, + translatorFor +} from './codex-turn-lifecycle-contract-test-fixture' + +const DIAGNOSTIC = 'Provider diagnostic: internal request failure' + +function error(code: unknown, extra: Record = {}) { + return { + threadId: THREAD_ID, + turnId: TURN_ID, + willRetry: false, + error: { message: DIAGNOSTIC, codexErrorInfo: code }, + ...extra + } +} + +function statuses(tap: ReturnType) { + return reduced(tap.rows).flatMap((row) => + row.body.kind === 'status' && row.body.failure?.kind !== 'providerRetrying' ? [row.body] : [] + ) +} + +describe('Codex terminal failure categories', () => { + it.each([ + ['rateLimitExceeded', 'usageLimitReached'], + ['flexUnavailable', 'providerUnavailable'], + ['modelNotFound', 'modelUnavailable'], + ['policyCapacityUnavailable', 'providerUnavailable'], + ['misalignmentPolicyViolation', 'providerSafetyStopped'], + ['serverOverloaded', 'providerUnavailable'], + ['cyberPolicy', 'providerSafetyStopped'] + ])('categorizes %s without exposing its diagnostic', (code, kind) => { + for (const info of [code, { [code]: { httpStatusCode: 401 } }]) { + const tap = recorder() + const translator = translatorFor(tap) + translator.handle(notification('error', error(info))) + expect(statuses(tap)).toMatchObject([{ failure: { kind } }]) + expect(statuses(tap)[0]?.text).not.toContain(DIAGNOSTIC) + expect(statuses(tap)[0]?.providerFrame?.payload.head).toContain(DIAGNOSTIC) + translator.dispose() + } + }) + + it('uses the existing usage-limit category for HTTP 429 retry exhaustion', () => { + const tap = recorder() + const translator = translatorFor(tap) + translator.handle( + notification('error', error({ responseTooManyFailedAttempts: { httpStatusCode: 429 } })) + ) + expect(statuses(tap)).toMatchObject([ + { tone: 'warning', failure: { kind: 'usageLimitReached' } } + ]) + }) + + it('ends a recorded-shape failed completion carrying an unknown future code', () => { + const frames: { + case: string + method: string + params: { + threadId: string + turn?: { id: string; status: string; error?: Record } + } + }[] = readFileSync( + join(__dirname, '../../__fixtures__/codex-app-server-turn-endings.jsonl'), + 'utf8' + ) + .trim() + .split('\n') + .map((line) => JSON.parse(line)) + const captured = frames.find( + (frame) => frame.case === '0.141.0-conn-refused' && frame.method === 'turn/completed' + ) + if (!captured?.params.turn) { + throw new Error('Missing captured failed completion') + } + const tap = recorder() + const translator = createCodexJournalTranslator({ + sink: tap.sink, + sessionId: 'session-1', + primaryThreadId: () => captured.params.threadId + }) + const on = (method: string, params: unknown) => + translator.handle({ + type: 'notification', + sessionId: 'session-1', + threadId: captured.params.threadId, + method, + params + }) + on('turn/started', { turn: { id: captured.params.turn.id } }) + expect(reduced(tap.rows).map((row) => row.body)).toMatchObject([ + { kind: 'turn', state: 'running' } + ]) + expect( + on('turn/completed', { + ...captured.params, + turn: { + ...captured.params.turn, + error: { ...captured.params.turn.error, codexErrorInfo: 'futureFailureAfter0167' } + } + }) + ).toEqual({ accepted: true }) + expect(reduced(tap.rows).map((row) => row.body)).toMatchObject([ + { kind: 'turn', state: 'completed', outcome: 'failure' }, + { kind: 'status', failure: { kind: 'providerResponseFailed' } } + ]) + }) + + it('shows a completion-only safety stop while preserving an ordinary Stop', () => { + for (const error of [{ message: DIAGNOSTIC, codexErrorInfo: 'tooManyDenials' }, null]) { + const tap = recorder() + const translator = translatorFor(tap) + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + translator.handle( + notification('turn/completed', { turn: { id: TURN_ID, status: 'interrupted', error } }) + ) + expect(reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY)?.body).toMatchObject({ + kind: 'turn', + state: 'interrupted', + outcome: 'cancellation' + }) + expect(statuses(tap)).toMatchObject( + error ? [{ failure: { kind: 'providerSafetyStopped' } }] : [] + ) + } + }) + + it('keeps completion-only sign-in diagnostics behind Details', () => { + const tap = recorder() + const translator = translatorFor(tap) + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + translator.handle( + notification('turn/completed', { + turn: { + id: TURN_ID, + status: 'failed', + error: error({ responseStreamDisconnected: { httpStatusCode: 401 } }).error + } + }) + ) + expect(statuses(tap)).toMatchObject([{ failure: { kind: 'notSignedIn' } }]) + expect(statuses(tap)[0]?.text).not.toContain(DIAGNOSTIC) + expect(statuses(tap)[0]?.providerFrame?.payload.head).toContain(DIAGNOSTIC) + }) + + it('keeps recovered sign-in advice through completion backpressure without another failure row', () => { + const tap = recorder() + let rejectCompletion = true + tap.sink.tryAppendItem = (identity, body, options) => { + if (body.kind === 'turn' && body.state === 'completed' && rejectCompletion) { + rejectCompletion = false + return { accepted: false, reason: 'backpressure' } + } + tap.sink.appendItem(identity, body, options) + return { accepted: true } + } + const translator = translatorFor(tap) + translator.handle(notification('turn/started', { turn: { id: TURN_ID } })) + translator.handle( + notification('error', { + ...error({ responseStreamDisconnected: { httpStatusCode: 401 } }, { willRetry: true }), + error: { + message: 'Reconnecting... 1/2', + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 401 } }, + additionalDetails: DIAGNOSTIC + } + }) + ) + translator.handle(notification('error', error('other'))) + const completion = notification('turn/completed', { + turn: { id: TURN_ID, status: 'failed', error: error('other').error } + }) + expect(translator.handle(completion)).toEqual({ accepted: false, reason: 'backpressure' }) + expect(translator.handle(completion)).toEqual({ accepted: true }) + const terminal = tap.rows.filter( + (row) => row.body.kind === 'status' && row.body.failure?.kind !== 'providerRetrying' + ) + expect(terminal.map((row) => row.body)).toMatchObject([{ failure: { kind: 'notSignedIn' } }]) + expect(statuses(tap)[0]?.text).not.toContain(DIAGNOSTIC) + expect(statuses(tap)[0]?.providerFrame?.payload.head).toContain(DIAGNOSTIC) + expect(reduced(tap.rows).find((row) => row.key === LIFECYCLE_KEY)?.body).toMatchObject({ + state: 'completed', + outcome: 'failure' + }) + }) + + it('uses the last non-other retry only for matching text and scope, including empty details', () => { + const tap = recorder() + const translator = translatorFor(tap) + const retry = (code: unknown, details: string) => + notification('error', { + ...error(code, { willRetry: true }), + error: { message: DIAGNOSTIC, codexErrorInfo: code, additionalDetails: details } + }) + translator.handle(retry({ responseStreamDisconnected: { httpStatusCode: 401 } }, '')) + translator.handle(notification('error', error('other'))) + expect(statuses(tap).at(-1)?.failure?.kind).toBe('providerResponseFailed') + translator.handle(retry({ responseStreamDisconnected: { httpStatusCode: 401 } }, DIAGNOSTIC)) + translator.handle(retry('futureRetryCode', DIAGNOSTIC)) + translator.handle(notification('error', error('other'))) + expect(statuses(tap).at(-1)?.failure?.kind).toBe('providerResponseFailed') + translator.handle(retry({ responseStreamDisconnected: { httpStatusCode: 401 } }, DIAGNOSTIC)) + translator.handle(notification('error', error('other', { turnId: 'another-turn' }))) + expect(statuses(tap).at(-1)?.failure?.kind).toBe('providerResponseFailed') + }) +}) diff --git a/src/main/codex/structured/journal/codex-turn-failures.ts b/src/main/codex/structured/journal/codex-turn-failures.ts new file mode 100644 index 00000000000..48b30d08edf --- /dev/null +++ b/src/main/codex/structured/journal/codex-turn-failures.ts @@ -0,0 +1,240 @@ +import { createHash } from 'node:crypto' +import { agentSessionFailureFact } from '../../../../shared/agent-session/failures/agent-session-failure' +import type { AgentSessionAccountKind } from '../../../../shared/agent-session/agent-session-availability' +import { + readCodexErrorInfo, + readCodexTurnId, + readCodexTurnStatus +} from '../../app-server/codex-structured-thread-facts' +import { readRecord } from '../../app-server/codex-item-field-readers' +import { codexAuthenticationFailure } from '../session-lifecycle/codex-authentication-failure' +import { CodexUsageLimits } from '../catalog/codex-usage-limits' +import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' +import { + unhandledProviderFrameJournalItem, + type UnhandledProviderFrameJournalItem +} from '../../../native-chat/agent-session-wire/providers/unhandled-provider-frame' +import { + CODEX_JOURNAL_ADMITTED, + type CodexJournalTranslationAdmission +} from './codex-structured-journal-contracts' +import { MAX_CODEX_GENERIC_TURN_BUCKETS } from './codex-structured-journal-limits' +import type { AgentJournalStatusItem } from '../../../../shared/agent-session/journal/agent-session-journal-types' + +type ErrorInfo = { error: string; status?: number } +type TerminalSignature = { code?: string; message?: string; status?: number } +type FailureEvidence = + | { phase: 'retry'; info: ErrorInfo; text: string } + | { phase: 'terminal'; signature: TerminalSignature } + +function digest(value: string): string { + return createHash('sha256').update(value).digest('hex') +} + +function scopeKey(threadId: string, turnId: string | null): string | null { + return turnId === null ? null : digest(JSON.stringify([threadId, turnId])) +} + +function errorStatus(payload: unknown): number | undefined { + const status = readCodexErrorInfo(payload)?.status + return typeof status === 'number' && Number.isFinite(status) ? status : undefined +} + +function failureText(payload: unknown): string | undefined { + const error = readRecord(readRecord(payload).error) + return typeof error.additionalDetails === 'string' + ? error.additionalDetails + : typeof error.message === 'string' + ? error.message + : undefined +} + +function terminalSignature(payload: unknown): TerminalSignature { + const info = readCodexErrorInfo(payload) + const message = readRecord(readRecord(payload).error).message + const status = errorStatus(payload) + return { + ...(info ? { code: digest(info.error) } : {}), + ...(typeof message === 'string' ? { message: digest(message) } : {}), + ...(status !== undefined ? { status } : {}) + } +} + +export class CodexTurnFailures { + private readonly usageLimits = new CodexUsageLimits() + private readonly evidence = new Map() + + constructor( + private readonly deps: { + account?: () => AgentSessionAccountKind | undefined + activeTurn: (threadId: string) => string | null + append: ( + threadId: string, + payload: unknown, + frame: Omit & { body: AgentJournalStatusItem } + ) => CodexJournalTranslationAdmission + } + ) {} + + appendTerminal( + kind: string, + payload: unknown, + errorPayload: unknown, + threadId: string + ): CodexJournalTranslationAdmission { + const translated = unhandledProviderFrameJournalItem('codex', kind, payload, undefined, { + reportsFailure: true + }) + if (!translated) { + return CODEX_JOURNAL_ADMITTED + } + const failure = this.failure(errorPayload, threadId, this.deps.account?.()) + const admission = this.deps.append(threadId, payload, { + ...translated, + body: { + ...translated.body, + ...(failure.kind === 'usageLimitReached' ? { tone: 'warning' } : {}), + ...agentSessionFailureWords(failure, { + provider: 'codex', + agentName: 'Codex', + surface: 'row' + }) + } + }) + if (admission.accepted) { + this.admittedTerminal( + errorPayload, + threadId, + readCodexTurnId(payload) ?? this.deps.activeTurn(threadId) + ) + } + return admission + } + + appendCompletion( + payload: unknown, + threadId: string, + onShown: (turnId: string) => void + ): CodexJournalTranslationAdmission { + const turn = readRecord(readRecord(payload).turn) + const status = readCodexTurnStatus(payload) + const turnId = readCodexTurnId(payload) ?? this.deps.activeTurn(threadId) + if (!turnId || (status !== 'failed' && !(status === 'interrupted' && turn.error))) { + return CODEX_JOURNAL_ADMITTED + } + const errorPayload = { turnId, error: turn.error, willRetry: false } + const admission = this.repeatsTerminal(errorPayload, threadId, turnId) + ? CODEX_JOURNAL_ADMITTED + : this.appendTerminal('notification:turn/completed', payload, errorPayload, threadId) + if (admission.accepted) { + onShown(turnId) + } + return admission + } + + observe(kind: string, payload: unknown): boolean { + return this.usageLimits.observe(kind, payload) + } + + observeRetry(payload: unknown, threadId: string): void { + const info = readCodexErrorInfo(payload) + const text = failureText(payload) + const key = scopeKey(threadId, readCodexTurnId(payload)) + if (!key || !info || info.error === 'other' || text === undefined) { + return + } + this.remember(key, { + phase: 'retry', + info: { + error: info.error.length <= 128 ? info.error : 'other', + status: errorStatus(payload) + }, + text: digest(text) + }) + } + + private failure(payload: unknown, threadId: string, account?: AgentSessionAccountKind) { + let info = readCodexErrorInfo(payload) + const key = scopeKey(threadId, readCodexTurnId(payload)) + const previous = key ? this.evidence.get(key) : undefined + const text = failureText(payload) + if ( + readRecord(payload).willRetry === false && + info?.error === 'other' && + previous?.phase === 'retry' && + text !== undefined && + previous.text === digest(text) + ) { + info = previous.info + } + const effective = { + error: { + ...readRecord(readRecord(payload).error), + codexErrorInfo: info ? { [info.error]: { httpStatusCode: info.status } } : undefined + } + } + const existing = + this.usageLimits.failure(effective) ?? codexAuthenticationFailure(effective, account) + if (existing) { + // Sign-in advice must not quote provider text; the bounded frame retains diagnostics. + return existing.kind === 'notSignedIn' ? { ...existing, detail: undefined } : existing + } + switch (info?.error ?? 'other') { + case 'modelNotFound': + return agentSessionFailureFact('modelUnavailable') + case 'serverOverloaded': + case 'flexUnavailable': + case 'policyCapacityUnavailable': + return agentSessionFailureFact('providerUnavailable') + case 'cyberPolicy': + case 'misalignmentPolicyViolation': + case 'tooManyDenials': + return agentSessionFailureFact('providerSafetyStopped') + default: + return agentSessionFailureFact('providerResponseFailed') + } + } + + private repeatsTerminal(payload: unknown, threadId: string, turnId: string): boolean { + const key = scopeKey(threadId, turnId) + const previous = key ? this.evidence.get(key) : undefined + if (previous?.phase !== 'terminal') { + return false + } + const next = terminalSignature(payload) + return ( + (next.code === undefined || next.code === previous.signature.code) && + (next.message === undefined || next.message === previous.signature.message) && + (next.status === undefined || next.status === previous.signature.status) + ) + } + + private admittedTerminal(payload: unknown, threadId: string, turnId: string | null): void { + const key = scopeKey(threadId, turnId) + if (key) { + this.remember(key, { phase: 'terminal', signature: terminalSignature(payload) }) + } + } + + forget(threadId: string, turnId: string): void { + const key = scopeKey(threadId, turnId) + if (key) { + this.evidence.delete(key) + } + } + + dispose(): void { + this.evidence.clear() + } + + private remember(key: string, evidence: FailureEvidence): void { + this.evidence.delete(key) + this.evidence.set(key, evidence) + if (this.evidence.size > MAX_CODEX_GENERIC_TURN_BUCKETS) { + const oldest = this.evidence.keys().next().value + if (oldest !== undefined) { + this.evidence.delete(oldest) + } + } + } +} diff --git a/src/main/codex/structured/turns/codex-command-turn-claim.test.ts b/src/main/codex/structured/turns/codex-command-turn-claim.test.ts index 4a5a638401c..0895b51afb3 100644 --- a/src/main/codex/structured/turns/codex-command-turn-claim.test.ts +++ b/src/main/codex/structured/turns/codex-command-turn-claim.test.ts @@ -160,14 +160,20 @@ describe('a Codex turn a conversation command claims', () => { agentJournalItemKey(COMMAND.resultIdentity) ) expect(rows.map((write) => write.turnScope)).toEqual(rows.map(() => scope)) - expect( - rows.some( - (write) => - write.body.kind === 'status' && - write.body.tone === 'error' && - write.body.text.includes('Selected model is at capacity') - ) - ).toBe(true) + const failures = rows.filter( + (write) => write.body.kind === 'status' && write.body.tone === 'error' + ) + expect(failures.map((write) => write.body)).toMatchObject([ + { + kind: 'status', + failure: { kind: 'providerUnavailable' }, + providerFrame: { + payload: { + head: expect.stringContaining('Selected model is at capacity') + } + } + } + ]) }) it('leaves the next turn to write its own record after a failed compaction', () => { diff --git a/src/main/codex/trust/toml/config-toml-project-trust-spellings.test.ts b/src/main/codex/trust/toml/config-toml-project-trust-spellings.test.ts index 7f8eb5844cb..d90d03efd92 100644 --- a/src/main/codex/trust/toml/config-toml-project-trust-spellings.test.ts +++ b/src/main/codex/trust/toml/config-toml-project-trust-spellings.test.ts @@ -47,6 +47,42 @@ describe('project trust writes recognise every spelling of the project table', ( expect(updated).toBe([header, 'trust_level = "trusted"', ''].join('\n')) }) + + it.each([ + { + label: 'a literal string ending in four quotes', + argsLine: `args = ["-c", '''printf 'ok'''']` + }, + { + label: 'a basic string ending in four quotes', + argsLine: `args = ["-c", """printf "ok""""]` + } + ])('updates the project table after $label', ({ argsLine }) => { + const project = '/tmp/orca-toml-repro' + const original = [ + '[mcp_servers.repro]', + 'command = "sh"', + argsLine, + '', + `[projects."${project}"]`, + 'trust_level = "untrusted"', + '' + ].join('\n') + + const updated = upsertTrusted(original, project) + + expect(updated).toBe( + [ + '[mcp_servers.repro]', + 'command = "sh"', + argsLine, + '', + `[projects."${project}"]`, + 'trust_level = "trusted"', + '' + ].join('\n') + ) + }) }) describe('the config mirror treats every spelling as one project table', () => { diff --git a/src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts b/src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts index a6e056b27f6..117079bad27 100644 --- a/src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts +++ b/src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts @@ -118,6 +118,32 @@ describe('readTerminalCursorLineContext', () => { } }) + it.each([ + { typed: '', caret: 'T', dim: 'ry "how do I log an error?"', draft: null, typedText: '' }, + { typed: '', caret: 'f', dim: 'ix the login bug', draft: 'fix the login bug', typedText: '' }, + { typed: '', caret: 'a', dim: ' quick fix', draft: 'a quick fix', typedText: '' }, + { typed: '/mo', caret: 'd', dim: 'el', draft: '/model', typedText: '/mo' }, + { typed: '/commi', caret: 't', dim: ' [message]', draft: '/commit', typedText: '/commit' } + ])( + "reads Claude's caret glyph $caret after '$typed' before dim '$dim'", + ({ typed, caret, dim, draft, typedText }) => { + const cols = 80 + const terminal = new Terminal({ cols, rows: 8, allowProposedApi: true }) + try { + writeSync( + terminal, + `\x1b[?25l${'─'.repeat(cols)}\r\n❯ ${typed}\x1b7\x1b[7m${caret}\x1b[27m\x1b[2m${dim}\x1b[22m\r\n${'─'.repeat(cols)}\x1b8` + ) + const context = readTerminalCursorLineContext(terminal, terminal.rows) + expect(context).toMatchObject({ cursorHidden: true, cursorInverse: true }) + expect(detectTerminalComposerDraft(context)?.text ?? null).toBe(draft) + expect(readTerminalComposerTypedText(context)).toBe(typedText) + } finally { + terminal.dispose() + } + } + ) + it.each([ { cols: 19, cursorRowTail: 'proceed with the ', continuation: 'release' }, { cols: 18, cursorRowTail: 'proceed with the', continuation: ' release' } diff --git a/src/main/daemon/launch/daemon-exit-record.ts b/src/main/daemon/launch/daemon-exit-record.ts new file mode 100644 index 00000000000..ecd5af564f4 --- /dev/null +++ b/src/main/daemon/launch/daemon-exit-record.ts @@ -0,0 +1,59 @@ +export type DaemonExitRecord = { + pid: number + code: number | null + signal: NodeJS.Signals | null + atMs: number +} + +let lastDaemonExit: DaemonExitRecord | null = null +// An older exit (a planned restart, say) must not be blamed for a later, unrelated death. +const DAEMON_EXIT_RECORD_TTL_MS = 60_000 + +/** + * The daemon can vanish without writing its own log (for example a native abort when fork or thread + * creation fails at a process limit), so record how this process saw it end (#39166). + */ +type ExitEmitter = { + on(event: 'exit', listener: (code: number | null, signal: NodeJS.Signals | null) => void): unknown +} + +export function watchLaunchedDaemonExit(child: ExitEmitter, pid: number): void { + // A predecessor's exit (a planned restart, say) must not be blamed on this daemon's later death. + lastDaemonExit = null + let seen = false + try { + child.on('exit', (code: number | null, signal: NodeJS.Signals | null) => { + if (seen) { + return + } + seen = true + lastDaemonExit = { pid, code, signal, atMs: Date.now() } + console.warn(`[daemon] Daemon process ${pid} exited: ${describeDaemonExit(lastDaemonExit)}`) + }) + } catch { + // Diagnostics only: a launch must never fail because its exit could not be watched. + } +} + +/** Exit facts for the respawn log; null when this process did not launch the daemon that died. */ +export function takeLastDaemonExit(nowMs = Date.now()): DaemonExitRecord | null { + const exit = lastDaemonExit + lastDaemonExit = null + return exit && nowMs - exit.atMs <= DAEMON_EXIT_RECORD_TTL_MS ? exit : null +} + +export function describeDaemonExit(exit: Pick): string { + if (exit.signal) { + return `signal ${exit.signal}` + } + return exit.code === null ? 'unknown status' : `code ${exit.code}` +} + +/** Shared by every respawn path so the main log says why the old daemon ended, when it is known. */ +export function daemonDiedRespawnMessage(nowMs = Date.now()): string { + const exit = takeLastDaemonExit(nowMs) + // Unknown when another app session launched it, or when the socket closed before the exit event. + return exit + ? `[daemon] Daemon process died (pid ${exit.pid}, ${describeDaemonExit(exit)}) — respawning` + : '[daemon] Daemon process died (exit status not observed) — respawning' +} diff --git a/src/main/daemon/launch/daemon-launched-child.ts b/src/main/daemon/launch/daemon-launched-child.ts index c8a2fdd2211..f0e595b1990 100644 --- a/src/main/daemon/launch/daemon-launched-child.ts +++ b/src/main/daemon/launch/daemon-launched-child.ts @@ -10,6 +10,7 @@ import { import { parseDaemonReadyIdentity } from '../endpoint/identity/daemon-ready-identity' import { unlinkOwnedDaemonPidFile } from './daemon-spawner' import { childProcessHasExited } from '@orca/process-host/process-tree-termination' +import { watchLaunchedDaemonExit } from './daemon-exit-record' /** Default readiness IPC budget; callers may allow longer. */ export const DAEMON_CHILD_STARTUP_TIMEOUT_MS = 10_000 @@ -202,6 +203,7 @@ async function launchDaemonChildAttempt( releaseStderr() child.disconnect() child.unref() + watchLaunchedDaemonExit(child, readyIdentity.pid) resolve() } } diff --git a/src/main/daemon/launch/testing/daemon-exit-record.test.ts b/src/main/daemon/launch/testing/daemon-exit-record.test.ts new file mode 100644 index 00000000000..fe7b4f78b49 --- /dev/null +++ b/src/main/daemon/launch/testing/daemon-exit-record.test.ts @@ -0,0 +1,57 @@ +import { EventEmitter } from 'node:events' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + daemonDiedRespawnMessage, + takeLastDaemonExit, + watchLaunchedDaemonExit +} from '../daemon-exit-record' + +afterEach(() => { + takeLastDaemonExit() + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('daemon exit record (#39166)', () => { + it('logs the exit signal and names it in the next respawn line', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const child = new EventEmitter() + watchLaunchedDaemonExit(child, 4242) + + child.emit('exit', null, 'SIGABRT') + + expect(warn).toHaveBeenCalledWith('[daemon] Daemon process 4242 exited: signal SIGABRT') + expect(daemonDiedRespawnMessage()).toBe( + '[daemon] Daemon process died (pid 4242, signal SIGABRT) — respawning' + ) + // Consumed: a later death without an observed exit must not reuse it. + expect(daemonDiedRespawnMessage()).toBe( + '[daemon] Daemon process died (exit status not observed) — respawning' + ) + }) + + it('reports an exit code, and ignores an exit too old to explain this death', () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const child = new EventEmitter() + watchLaunchedDaemonExit(child, 7) + child.emit('exit', 134, null) + expect(daemonDiedRespawnMessage()).toContain('(pid 7, code 134)') + + vi.useFakeTimers({ now: 1_000_000 }) + const stale = new EventEmitter() + watchLaunchedDaemonExit(stale, 8) + stale.emit('exit', 0, null) + expect(daemonDiedRespawnMessage(1_000_000 + 120_000)).toContain('exit status not observed') + }) + + it('forgets a predecessor exit once a replacement daemon launches', () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}) + const restarted = new EventEmitter() + watchLaunchedDaemonExit(restarted, 11) + restarted.emit('exit', null, 'SIGTERM') + + watchLaunchedDaemonExit(new EventEmitter(), 12) + + expect(daemonDiedRespawnMessage()).toContain('exit status not observed') + }) +}) diff --git a/src/main/daemon/providers/lifecycle/daemon-provider-init.ts b/src/main/daemon/providers/lifecycle/daemon-provider-init.ts index 83be5d1ec40..3d5cf86fc34 100644 --- a/src/main/daemon/providers/lifecycle/daemon-provider-init.ts +++ b/src/main/daemon/providers/lifecycle/daemon-provider-init.ts @@ -1,3 +1,4 @@ +import { daemonDiedRespawnMessage } from '../../launch/daemon-exit-record' import { getLocalPtyProvider } from '../../../ipc/pty/provider/registry' import { rebindLocalProviderListeners } from '../../../ipc/pty/provider/listener-lifecycle' import { @@ -109,7 +110,7 @@ export async function initDaemonPtyProvider( respawn: async (reason: DaemonRespawnReason) => { // A wedged daemon can look dead here; launch reports the proven replacement cause after recovery. if (reason === 'daemon_died') { - console.warn('[daemon] Daemon process died — respawning') + console.warn(daemonDiedRespawnMessage()) // Synthetic exits during manual restart must not enter the crash bucket. if (!isDaemonRestartInFlight()) { trackDaemonRetired('died_respawn') diff --git a/src/main/daemon/providers/lifecycle/daemon-provider-restart.ts b/src/main/daemon/providers/lifecycle/daemon-provider-restart.ts index 71aca99d97b..a76aeb2cd36 100644 --- a/src/main/daemon/providers/lifecycle/daemon-provider-restart.ts +++ b/src/main/daemon/providers/lifecycle/daemon-provider-restart.ts @@ -1,3 +1,4 @@ +import { daemonDiedRespawnMessage } from '../../launch/daemon-exit-record' import { rebindLocalProviderListeners, unbindLocalProviderListeners @@ -135,7 +136,7 @@ async function runRestartDaemon( respawn: async (reason: DaemonRespawnReason) => { // A wedged daemon can look dead here; launch reports the proven replacement cause after recovery. if (reason === 'daemon_died') { - console.warn('[daemon] Daemon process died — respawning') + console.warn(daemonDiedRespawnMessage()) // Synthetic exits during manual restart must not enter the crash bucket. if (!isDaemonRestartInFlight()) { trackDaemonRetired('died_respawn') diff --git a/src/main/environment-providers/environment-provider-driver-contract.test-support.ts b/src/main/environment-providers/environment-provider-driver-contract.test-support.ts new file mode 100644 index 00000000000..0ca2c695584 --- /dev/null +++ b/src/main/environment-providers/environment-provider-driver-contract.test-support.ts @@ -0,0 +1,105 @@ +// Shared lifecycle contract every EnvironmentProviderDriver must pass; drivers call it from their test. +import { describe, expect, it } from 'vitest' +import { + getEphemeralVmRecipeResultConnection, + getEphemeralVmRecipeResultProjectRoot, + isAbsoluteRuntimePath +} from '../../shared/ephemeral-vm-recipes' +import { + ENVIRONMENT_PROVIDER_ERROR_CODES, + isEnvironmentProviderError, + type EnvironmentCreateSpec, + type EnvironmentProviderDriver, + type EnvironmentReady +} from './environment-provider-driver' + +export type EnvironmentProviderDriverContractHarness = { + driver: EnvironmentProviderDriver + /** Ids the backing provider still holds; destroy must leave none behind. */ + liveEnvironmentIds: () => Promise + /** A fresh driver over the same backing provider, as after an Orca restart. */ + reopenDriver: () => EnvironmentProviderDriver +} + +// Handles are persisted with the runtime record, so later calls only ever see the JSON form. +function reload(handle: T): T { + return JSON.parse(JSON.stringify(handle)) +} + +export function runEnvironmentProviderDriverContract( + name: string, + makeHarness: () => Promise, + spec: (workspaceId: string) => EnvironmentCreateSpec = (workspaceId) => ({ workspaceId }) +): void { + describe(`${name} satisfies the environment provider driver contract`, () => { + function expectReady(driver: EnvironmentProviderDriver, ready: EnvironmentReady): void { + expect(ready.handle.driverId).toBe(driver.id) + expect(ready.handle.environmentId).not.toBe('') + expect(['orca-server', 'ssh']).toContain( + getEphemeralVmRecipeResultConnection(ready.result).type + ) + expect(isAbsoluteRuntimePath(getEphemeralVmRecipeResultProjectRoot(ready.result))).toBe(true) + if (driver.capabilities.maxSessionMs !== null) { + expect(ready.session.deadlineAt).not.toBeNull() + expect(ready.session.deadlineAt! - ready.session.startedAt).toBeLessThanOrEqual( + driver.capabilities.maxSessionMs + ) + } + } + + it('creates, suspends, resumes and destroys one environment without leaking it', async () => { + const { driver, liveEnvironmentIds, reopenDriver } = await makeHarness() + const phases: string[] = [] + const created = await driver.create(spec('ws-contract-1'), { + onProgress: ({ phase }) => phases.push(phase) + }) + expectReady(driver, created) + expect(phases.length).toBeGreaterThan(0) + expect(await liveEnvironmentIds()).toContain(created.handle.environmentId) + expect((await driver.status(created.handle)).status).toBe('running') + + const suspended = await driver.suspend(created.handle) + expect(suspended.status).toBe('suspended') + expect((await driver.status(created.handle)).status).toBe('suspended') + + const resumed = await driver.resume(created.handle) + expectReady(driver, resumed) + expect(resumed.handle.environmentId).toBe(created.handle.environmentId) + expect((await driver.status(created.handle)).status).toBe('running') + + await driver.destroy(created.handle) + expect(await liveEnvironmentIds()).not.toContain(created.handle.environmentId) + // Idempotent: cleanup retries after a lost response or a restart must not fail. + await reopenDriver().destroy(reload(created.handle)) + }) + + it('refuses to bring back a destroyed environment, even after a restart', async () => { + const { driver, liveEnvironmentIds, reopenDriver } = await makeHarness() + const created = await driver.create(spec('ws-contract-2')) + await driver.destroy(created.handle) + const error = await reopenDriver() + .resume(reload(created.handle)) + .then( + () => null, + (caught: unknown) => caught + ) + expect(isEnvironmentProviderError(error)).toBe(true) + expect(await liveEnvironmentIds()).not.toContain(created.handle.environmentId) + }) + + it('rejects a cancelled create with a catalogued error and leaks nothing', async () => { + const { driver, liveEnvironmentIds } = await makeHarness() + const controller = new AbortController() + controller.abort() + const error = await driver.create(spec('ws-contract-3'), { signal: controller.signal }).then( + () => null, + (caught: unknown) => caught + ) + expect(isEnvironmentProviderError(error)).toBe(true) + expect(ENVIRONMENT_PROVIDER_ERROR_CODES).toContain( + isEnvironmentProviderError(error) ? error.code : null + ) + expect(await liveEnvironmentIds()).toEqual([]) + }) + }) +} diff --git a/src/main/environment-providers/environment-provider-driver.ts b/src/main/environment-providers/environment-provider-driver.ts new file mode 100644 index 00000000000..7edfb2d1310 --- /dev/null +++ b/src/main/environment-providers/environment-provider-driver.ts @@ -0,0 +1,125 @@ +// One lifecycle seam for VM-backed workspaces: every environment provider answers the same calls, +// and capability flags (not provider ids) decide what the UI offers. +import type { EphemeralVmRecipeResult, JsonValue } from '../../shared/ephemeral-vm-recipes' + +export type EnvironmentProviderCapabilities = Readonly<{ + /** Suspend keeps memory and processes; false means suspend/resume is a reboot from disk. */ + memoryPause: boolean + /** Hard per-session cap enforced by the provider; null when sessions are unbounded. */ + maxSessionMs: number | null + /** The filesystem (worktree, auth homes, orcad identity) survives suspend. */ + fsPersistOnStop: boolean + /** Orca-owned idle stop; null when the provider has none. */ + idleStopMs: number | null +}> + +export type EnvironmentProviderPhase = + | 'provisioning' + | 'booting' + | 'connecting' + | 'suspending' + | 'resuming' + | 'destroying' + +export type EnvironmentProviderCallContext = { + signal?: AbortSignal + onProgress?: (progress: { phase: EnvironmentProviderPhase; message?: string }) => void +} + +export type EnvironmentCreateSpec = { + /** Orca's workspace id; one environment per workspace. */ + workspaceId: string + workspaceName?: string + projectId?: string + machineSize?: string + region?: string + repo?: { url: string; ref?: string } +} + +/** Persisted with the runtime record; `driverState` is opaque to everything but the driver. */ +export type EnvironmentHandle = { + driverId: string + environmentId: string + driverState: Record +} + +export type EnvironmentSessionInfo = { + startedAt: number + /** When the provider will end this session regardless of activity. */ + deadlineAt: number | null +} + +export type EnvironmentStatus = + | 'provisioning' + | 'running' + | 'suspending' + | 'suspended' + | 'resuming' + | 'destroying' + | 'destroyed' + | 'failed' + +export type EnvironmentStatusSnapshot = { + status: EnvironmentStatus + session: EnvironmentSessionInfo | null +} + +export type EnvironmentReady = { + handle: EnvironmentHandle + /** Same document a shell recipe prints, so runtime records, pairing and resume keep one path. */ + result: EphemeralVmRecipeResult + session: EnvironmentSessionInfo +} + +export type EnvironmentProviderDriver = { + readonly id: string + readonly capabilities: EnvironmentProviderCapabilities + create( + spec: EnvironmentCreateSpec, + ctx?: EnvironmentProviderCallContext + ): Promise + resume(handle: EnvironmentHandle, ctx?: EnvironmentProviderCallContext): Promise + suspend( + handle: EnvironmentHandle, + ctx?: EnvironmentProviderCallContext + ): Promise + /** Idempotent: an environment that is already gone resolves. */ + destroy(handle: EnvironmentHandle, ctx?: EnvironmentProviderCallContext): Promise + status( + handle: EnvironmentHandle, + ctx?: EnvironmentProviderCallContext + ): Promise +} + +export const ENVIRONMENT_PROVIDER_ERROR_CODES = [ + 'unauthorized', + 'not_found', + 'conflict', + 'invalid_request', + 'unavailable', + 'timeout', + 'aborted', + 'invalid_response' +] as const + +export type EnvironmentProviderErrorCode = (typeof ENVIRONMENT_PROVIDER_ERROR_CODES)[number] + +export class EnvironmentProviderError extends Error { + readonly code: EnvironmentProviderErrorCode + /** Machine-readable provider detail, e.g. the Orca failure-copy code behind the message. */ + readonly reason: string | null + + constructor(code: EnvironmentProviderErrorCode, message: string, reason: string | null = null) { + super(message) + this.name = 'EnvironmentProviderError' + this.code = code + this.reason = reason + } +} + +export function isEnvironmentProviderError( + error: unknown, + code?: EnvironmentProviderErrorCode +): error is EnvironmentProviderError { + return error instanceof EnvironmentProviderError && (code === undefined || error.code === code) +} diff --git a/src/main/environment-providers/shell-recipe-driver.test.ts b/src/main/environment-providers/shell-recipe-driver.test.ts new file mode 100644 index 00000000000..d7cafb409b5 --- /dev/null +++ b/src/main/environment-providers/shell-recipe-driver.test.ts @@ -0,0 +1,68 @@ +import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach } from 'vitest' +import { encodePairingOffer } from '../../shared/remote-runtime/pairing/pairing' +import { PAIRING_OFFER_VERSION } from '../../shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import { runEnvironmentProviderDriverContract } from './environment-provider-driver-contract.test-support' +import { ShellRecipeDriver } from './shell-recipe-driver' + +const tmpRoots: string[] = [] + +afterEach(() => { + for (const root of tmpRoots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +// A recipe whose "VMs" are files in a state dir, so the contract can see what destroy left behind. +function makeFileBackedRecipe(): { repoPath: string; stateDir: string; recipe: OrcaVmRecipe } { + const repoPath = mkdtempSync(join(tmpdir(), 'orca-shell-recipe-driver-')) + tmpRoots.push(repoPath) + const stateDir = join(repoPath, 'vms') + mkdirSync(stateDir) + const pairingCode = encodePairingOffer({ + v: PAIRING_OFFER_VERSION, + endpoint: 'wss://vm.example.com', + deviceToken: 'token', + publicKeyB64: 'public-key' + }) + const vmFile = `require('node:path').join(${JSON.stringify(stateDir)}, process.env.ORCA_VM_INSTANCE_ID)` + const printResult = `console.log(JSON.stringify({ schemaVersion: 1, pairingCode: ${JSON.stringify(pairingCode)}, projectRoot: '/workspace/repo' }))` + const scripts = { + create: `require('node:fs').writeFileSync(${vmFile}, 'running'); ${printResult}`, + suspend: `require('node:fs').writeFileSync(${vmFile}, 'suspended')`, + // Like a real provider: a destroyed VM cannot be woken. + resume: `const fs = require('node:fs'); if (!fs.existsSync(${vmFile})) process.exit(1); fs.writeFileSync(${vmFile}, 'running'); ${printResult}`, + destroy: `require('node:fs').rmSync(${vmFile}, { force: true })` + } + const commands = Object.fromEntries( + Object.entries(scripts).map(([mode, source]) => { + const scriptPath = join(repoPath, `${mode}.js`) + writeFileSync(scriptPath, source) + return [mode, `"${process.execPath}" "${scriptPath}"`] + }) + ) + return { + repoPath, + stateDir, + recipe: { + id: 'file-backed', + name: 'File-backed VM', + create: commands.create, + suspend: commands.suspend, + resume: commands.resume, + destroy: commands.destroy + } + } +} + +runEnvironmentProviderDriverContract('ShellRecipeDriver', async () => { + const { repoPath, stateDir, recipe } = makeFileBackedRecipe() + return { + driver: new ShellRecipeDriver(recipe, repoPath), + liveEnvironmentIds: async () => readdirSync(stateDir), + reopenDriver: () => new ShellRecipeDriver(recipe, repoPath) + } +}) diff --git a/src/main/environment-providers/shell-recipe-driver.ts b/src/main/environment-providers/shell-recipe-driver.ts new file mode 100644 index 00000000000..4d962fbc744 --- /dev/null +++ b/src/main/environment-providers/shell-recipe-driver.ts @@ -0,0 +1,286 @@ +// orca.yaml environment recipes and plugin VM recipes as an environment provider: each lifecycle +// call runs the recipe's shell step, exactly as the runtime service did before the driver seam. +import { z } from 'zod' +import type { OrcaVmRecipe } from '../../shared/orca-yaml-hook-types' +import { + EphemeralVmRecipeResultSchema, + type EphemeralVmRecipeResult, + type JsonValue +} from '../../shared/ephemeral-vm-recipes' +import { + runEphemeralVmRecipeCleanup, + runEphemeralVmRecipeResume, + runEphemeralVmRecipeStart, + runEphemeralVmRecipeSuspend, + type EphemeralVmRecipeCleanupArgs, + type EphemeralVmRecipeContext, + type EphemeralVmRecipeLifecycleArgs, + type EphemeralVmRecipeStartArgs +} from '../../shared/ephemeral-vm-recipe-runner' +import { EPHEMERAL_VM_FAILURE_COPY } from '../../shared/ephemeral-vm-failure-copy' +import { getProvisionedRootResumeIntegrityError } from '../ephemeral-vm/resume-integrity' +import { + EnvironmentProviderError, + isEnvironmentProviderError, + type EnvironmentCreateSpec, + type EnvironmentHandle, + type EnvironmentProviderCallContext, + type EnvironmentProviderCapabilities, + type EnvironmentProviderDriver, + type EnvironmentReady, + type EnvironmentStatus, + type EnvironmentStatusSnapshot +} from './environment-provider-driver' + +export const SHELL_RECIPE_DRIVER_ID = 'shell-recipe' + +type RecipeStepArgs = Omit + +type RecipeStepFailure = { + error?: string + errorCode?: string + exitCode: number | null + aborted?: true + timedOut?: true +} + +const DriverStateSchema = z.object({ + recipeResult: EphemeralVmRecipeResultSchema, + projectId: z.string().optional(), + workspaceId: z.string().optional(), + workspaceName: z.string().optional() +}) + +export class ShellRecipeDriver implements EnvironmentProviderDriver { + readonly id = SHELL_RECIPE_DRIVER_ID + readonly capabilities: EnvironmentProviderCapabilities + // Recipes have no status step, so status only covers calls this instance ran; the runtime + // record stays the persisted source of truth. + private readonly statuses = new Map() + + constructor( + private readonly recipe: OrcaVmRecipe, + private readonly repoPath: string + ) { + this.capabilities = { + memoryPause: false, + maxSessionMs: null, + fsPersistOnStop: Boolean(recipe.suspend && recipe.resume), + idleStopMs: null + } + } + + // Recipe-shaped steps keep stdout/stderr and failure copy for runtime records and diagnostics. + runCreate(args: RecipeStepArgs) { + return runEphemeralVmRecipeStart({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + runSuspend(args: RecipeStepArgs) { + return runEphemeralVmRecipeSuspend({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + runResume(args: RecipeStepArgs) { + return runEphemeralVmRecipeResume({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + runDestroy(args: RecipeStepArgs) { + return runEphemeralVmRecipeCleanup({ ...args, recipe: this.recipe, repoPath: this.repoPath }) + } + + create(spec: EnvironmentCreateSpec, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.createOnce(spec, ctx)) + } + + suspend(handle: EnvironmentHandle, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.suspendOnce(handle, ctx)) + } + + resume(handle: EnvironmentHandle, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.resumeOnce(handle, ctx)) + } + + destroy(handle: EnvironmentHandle, ctx: EnvironmentProviderCallContext = {}) { + return catalogued(() => this.destroyOnce(handle, ctx)) + } + + private async createOnce( + spec: EnvironmentCreateSpec, + ctx: EnvironmentProviderCallContext + ): Promise { + ctx.onProgress?.({ phase: 'provisioning' }) + const start = await this.runCreate({ + context: { + projectId: spec.projectId, + workspaceId: spec.workspaceId, + workspaceName: spec.workspaceName, + repoUrl: spec.repo?.url, + ref: spec.repo?.ref + }, + signal: ctx.signal + }) + if (!start.ok) { + const error = toProviderError(start) + if (start.recipeResult) { + // The VM exists even though Orca rejected its result; release it rather than leak it. + const cleanup = await this.runDestroy({ + context: start.context, + recipeResult: start.recipeResult + }) + if (!cleanup.ok || cleanup.skipped) { + const detail = cleanup.error ?? EPHEMERAL_VM_FAILURE_COPY.destroyDisabled + throw new EnvironmentProviderError(error.code, `${error.message} ${detail}`, error.reason) + } + } + throw error + } + const handle = toHandle(start.context, start.result) + this.statuses.set(handle.environmentId, 'running') + return toReady(handle, start.result) + } + + private async suspendOnce( + handle: EnvironmentHandle, + ctx: EnvironmentProviderCallContext + ): Promise { + const { context, recipeResult } = this.readHandle(handle) + ctx.onProgress?.({ phase: 'suspending' }) + const suspend = await this.runSuspend({ context, recipeResult, signal: ctx.signal }) + if (!suspend.ok) { + throw toProviderError(suspend) + } + // No suspend step: the VM keeps running. + const status = suspend.skipped ? 'running' : 'suspended' + this.statuses.set(handle.environmentId, status) + return { status, session: null } + } + + private async resumeOnce( + handle: EnvironmentHandle, + ctx: EnvironmentProviderCallContext + ): Promise { + const { context, recipeResult } = this.readHandle(handle) + ctx.onProgress?.({ phase: 'resuming' }) + const resume = await this.runResume({ context, recipeResult, signal: ctx.signal }) + if (!resume.ok) { + throw toProviderError(resume) + } + const result = resume.skipped ? recipeResult : resume.result + const integrityError = getProvisionedRootResumeIntegrityError(recipeResult, result) + if (integrityError) { + throw new EnvironmentProviderError('conflict', integrityError) + } + this.statuses.set(handle.environmentId, 'running') + return toReady(toHandle(context, result), result) + } + + private async destroyOnce( + handle: EnvironmentHandle, + ctx: EnvironmentProviderCallContext + ): Promise { + if (this.statuses.get(handle.environmentId) === 'destroyed') { + return + } + const { context, recipeResult } = this.readHandle(handle) + ctx.onProgress?.({ phase: 'destroying' }) + const cleanup = await this.runDestroy({ context, recipeResult, signal: ctx.signal }) + if (!cleanup.ok) { + throw toProviderError(cleanup) + } + if (cleanup.skipped) { + throw new EnvironmentProviderError( + 'invalid_request', + EPHEMERAL_VM_FAILURE_COPY.destroyDisabled, + 'destroyDisabled' + ) + } + this.statuses.set(handle.environmentId, 'destroyed') + } + + async status(handle: EnvironmentHandle): Promise { + const status = this.statuses.get(handle.environmentId) + if (!status) { + throw new EnvironmentProviderError('not_found', 'This driver has not run that environment.') + } + return { status, session: null } + } + + private readHandle(handle: EnvironmentHandle): { + context: EphemeralVmRecipeContext + recipeResult: EphemeralVmRecipeResult + } { + if (handle.driverId !== this.id) { + throw new EnvironmentProviderError('invalid_request', 'Handle belongs to another driver.') + } + if (this.statuses.get(handle.environmentId) === 'destroyed') { + throw new EnvironmentProviderError('not_found', 'Environment was destroyed.') + } + const state = DriverStateSchema.safeParse(handle.driverState) + if (!state.success) { + throw new EnvironmentProviderError('invalid_request', 'Handle has no recipe result.') + } + const { recipeResult, ...fields } = state.data + return { + context: { + ...fields, + instanceId: handle.environmentId, + recipeId: this.recipe.id, + repoPath: this.repoPath + }, + recipeResult + } + } +} + +function toHandle( + context: EphemeralVmRecipeContext, + recipeResult: EphemeralVmRecipeResult +): EnvironmentHandle { + const { instanceId, projectId, workspaceId, workspaceName } = context + if (!instanceId) { + throw new EnvironmentProviderError('invalid_response', 'Recipe run has no instance id.') + } + // Round-trip through JSON so the persisted state is plain data (drops undefined fields). + const driverState: Record = JSON.parse( + JSON.stringify({ recipeResult, projectId, workspaceId, workspaceName }) + ) + return { + driverId: SHELL_RECIPE_DRIVER_ID, + environmentId: instanceId, + driverState + } +} + +function toReady(handle: EnvironmentHandle, result: EphemeralVmRecipeResult): EnvironmentReady { + return { handle, result, session: { startedAt: Date.now(), deadlineAt: null } } +} + +// Spawn errors and a missing repo dir surface as plain errors; the contract promises catalogued ones. +async function catalogued(run: () => Promise): Promise { + try { + return await run() + } catch (error) { + if (isEnvironmentProviderError(error)) { + throw error + } + throw new EnvironmentProviderError( + 'unavailable', + error instanceof Error ? error.message : String(error) + ) + } +} + +function toProviderError(failure: RecipeStepFailure): EnvironmentProviderError { + const code = failure.aborted + ? 'aborted' + : failure.timedOut + ? 'timeout' + : // The step exited cleanly but Orca rejected what it printed. + failure.exitCode === 0 + ? 'invalid_response' + : 'unavailable' + return new EnvironmentProviderError( + code, + failure.error ?? 'Recipe step failed.', + failure.errorCode ?? null + ) +} diff --git a/src/main/ephemeral-vm/failed-start-cleanup.ts b/src/main/ephemeral-vm/failed-start-cleanup.ts index 7a1eaf9921d..129c03caac3 100644 --- a/src/main/ephemeral-vm/failed-start-cleanup.ts +++ b/src/main/ephemeral-vm/failed-start-cleanup.ts @@ -16,10 +16,8 @@ import { type EphemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' import type { ProvisionEphemeralVmRuntimeArgs } from './runtime-service' -import { - runEphemeralVmRecipeCleanup, - type EphemeralVmRecipeContext -} from '../../shared/ephemeral-vm-recipe-runner' +import type { EphemeralVmRecipeContext } from '../../shared/ephemeral-vm-recipe-runner' +import { ShellRecipeDriver } from '../environment-providers/shell-recipe-driver' type FailedStart = { context: EphemeralVmRecipeContext @@ -74,9 +72,7 @@ async function getCleanupError( start: FailedStart ): Promise { try { - const cleanup = await runEphemeralVmRecipeCleanup({ - repoPath: args.repoPath, - recipe: args.recipe, + const cleanup = await new ShellRecipeDriver(args.recipe, args.repoPath).runDestroy({ context: start.context, recipeResult: start.recipeResult, signal: args.signal, diff --git a/src/main/ephemeral-vm/pending-vm-checkouts.test.ts b/src/main/ephemeral-vm/pending-vm-checkouts.test.ts new file mode 100644 index 00000000000..e89c84df283 --- /dev/null +++ b/src/main/ephemeral-vm/pending-vm-checkouts.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { + PendingVmCheckoutRegistry, + publishPendingVmCheckoutRepoChanges +} from './pending-vm-checkouts' + +describe('PendingVmCheckoutRegistry', () => { + it('tells phones to re-read each repo whose pending checkout appeared or went away', () => { + const registry = new PendingVmCheckoutRegistry() + registry.publish(1, [{ repoId: 'already', path: '/x' }]) + const notified: string[] = [] + const stop = publishPendingVmCheckoutRepoChanges(registry, (repoId) => notified.push(repoId)) + + registry.publish(2, [{ repoId: 'vm', path: '/srv/repo' }]) + expect(notified).toEqual(['vm']) + + // Another window's unrelated change does not re-announce this repo. + registry.publish(1, []) + expect(notified).toEqual(['vm', 'already']) + + registry.publish(2, []) + expect(notified).toEqual(['vm', 'already', 'vm']) + + stop() + registry.publish(2, [{ repoId: 'later', path: '/l' }]) + expect(notified).toEqual(['vm', 'already', 'vm']) + }) +}) diff --git a/src/main/ephemeral-vm/pending-vm-checkouts.ts b/src/main/ephemeral-vm/pending-vm-checkouts.ts new file mode 100644 index 00000000000..289ed7b3f9a --- /dev/null +++ b/src/main/ephemeral-vm/pending-vm-checkouts.ts @@ -0,0 +1,89 @@ +import { + indexPendingVmCheckouts, + EMPTY_PENDING_VM_CHECKOUT_INDEX, + type PendingVmCheckout, + type PendingVmCheckoutIndex +} from '../../shared/pending-vm-checkouts' + +/** + * VM checkouts whose creates are still in progress, per publishing window. Every window, the + * paired phone's host lists and the jump palette read the union, so none lists a checkout the + * create has not adopted yet. + */ +export class PendingVmCheckoutRegistry { + private readonly byOwner = new Map() + private index: PendingVmCheckoutIndex = EMPTY_PENDING_VM_CHECKOUT_INDEX + private readonly listeners = new Set<() => void>() + + /** Replaces one window's set; an empty list drops the window. An unchanged set is a no-op. */ + publish(ownerId: number, checkouts: PendingVmCheckout[]): void { + const before = this.byOwner.get(ownerId) ?? [] + if (sameCheckouts(before, checkouts)) { + return + } + if (checkouts.length === 0) { + this.byOwner.delete(ownerId) + } else { + this.byOwner.set(ownerId, checkouts) + } + this.index = indexPendingVmCheckouts([...this.byOwner.values()].flat()) + this.listeners.forEach((listener) => listener()) + } + + list(): PendingVmCheckout[] { + return [...this.byOwner.values()].flat() + } + + /** What one window needs from the others; it already holds its own. */ + listExcept(ownerId: number): PendingVmCheckout[] { + return [...this.byOwner].flatMap(([owner, checkouts]) => (owner === ownerId ? [] : checkouts)) + } + + current(): PendingVmCheckoutIndex { + return this.index + } + + onChanged(listener: () => void): () => void { + this.listeners.add(listener) + return () => this.listeners.delete(listener) + } +} + +/** + * Calls `notify` with each repo whose pending checkouts changed, so paired phones re-read their + * host workspace lists instead of keeping rows from a fetch made before the change reached main. + */ +export function publishPendingVmCheckoutRepoChanges( + registry: PendingVmCheckoutRegistry, + notify: (repoId: string) => void +): () => void { + const keyOf = (checkout: PendingVmCheckout): string => `${checkout.repoId}\0${checkout.path}` + let before = new Map(registry.list().map((checkout) => [keyOf(checkout), checkout.repoId])) + return registry.onChanged(() => { + const after = new Map(registry.list().map((checkout) => [keyOf(checkout), checkout.repoId])) + const changed = new Set() + for (const [key, repoId] of before) { + if (!after.has(key)) { + changed.add(repoId) + } + } + for (const [key, repoId] of after) { + if (!before.has(key)) { + changed.add(repoId) + } + } + before = after + changed.forEach(notify) + }) +} + +function sameCheckouts(left: PendingVmCheckout[], right: PendingVmCheckout[]): boolean { + return ( + left.length === right.length && + left.every( + (checkout, i) => checkout.repoId === right[i].repoId && checkout.path === right[i].path + ) + ) +} + +export const pendingVmCheckouts = new PendingVmCheckoutRegistry() diff --git a/src/main/ephemeral-vm/runtime-service.ts b/src/main/ephemeral-vm/runtime-service.ts index 4eba637eea1..cb87758dd92 100644 --- a/src/main/ephemeral-vm/runtime-service.ts +++ b/src/main/ephemeral-vm/runtime-service.ts @@ -4,15 +4,12 @@ import { updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' -import { - runEphemeralVmRecipeCleanup, - runEphemeralVmRecipeResume, - runEphemeralVmRecipeSuspend, - runEphemeralVmRecipeStart, - type EphemeralVmRecipeContext, - type EphemeralVmRecipeStartFailure, - type EphemeralVmRecipeStartSuccess +import type { + EphemeralVmRecipeContext, + EphemeralVmRecipeStartFailure, + EphemeralVmRecipeStartSuccess } from '../../shared/ephemeral-vm-recipe-runner' +import { ShellRecipeDriver } from '../environment-providers/shell-recipe-driver' import { beginEphemeralVmProvisioning, endEphemeralVmProvisioning, @@ -24,7 +21,8 @@ import { getProvisionedRootResumeIntegrityError } from './resume-integrity' import { runControlledEphemeralVmRuntimeCleanup } from './runtime-cleanup-control' import { ephemeralVmFailure, - pickEphemeralVmFailureCode + pickEphemeralVmFailureCode, + type EphemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' export type ProvisionEphemeralVmRuntimeArgs = { @@ -86,32 +84,20 @@ export type SuspendEphemeralVmRuntimeResult = runtime: EphemeralVmRuntimeRecord skipped: boolean } - | { + | ({ ok: false runtime: EphemeralVmRuntimeRecord - error: string - } + } & EphemeralVmFailure) -export type ResumeEphemeralVmRuntimeResult = - | { - ok: true - runtime: EphemeralVmRuntimeRecord - skipped: boolean - } - | { - ok: false - runtime: EphemeralVmRuntimeRecord - error: string - } +/** Same shape as suspend: success may be a skipped no-op; failure carries the coded reason. */ +export type ResumeEphemeralVmRuntimeResult = SuspendEphemeralVmRuntimeResult export async function provisionEphemeralVmRuntime( args: ProvisionEphemeralVmRuntimeArgs ): Promise { const writeAhead = beginEphemeralVmProvisioning(args) try { - const start = await runEphemeralVmRecipeStart({ - repoPath: args.repoPath, - recipe: args.recipe, + const start = await new ShellRecipeDriver(args.recipe, args.repoPath).runCreate({ context: { projectId: args.projectId, workspaceId: args.workspaceId, @@ -183,9 +169,7 @@ async function cleanupEphemeralVmRuntimeOnce( cleanupLastError: null, updatedAt: now }) - const cleanup = await runEphemeralVmRecipeCleanup({ - repoPath: args.repoPath, - recipe: args.recipe, + const cleanup = await new ShellRecipeDriver(args.recipe, args.repoPath).runDestroy({ context: contextFromRuntime(args.repoPath, running), recipeResult: running.recipeResult, signal: args.signal, @@ -227,9 +211,7 @@ export async function suspendEphemeralVmRuntime( if (!existing.recipeResult) { throw new Error(`Ephemeral VM runtime never finished provisioning: ${args.runtimeId}`) } - const suspend = await runEphemeralVmRecipeSuspend({ - repoPath: args.repoPath, - recipe: args.recipe, + const suspend = await new ShellRecipeDriver(args.recipe, args.repoPath).runSuspend({ context: contextFromRuntime(args.repoPath, existing), recipeResult: existing.recipeResult, signal: args.signal, @@ -238,15 +220,16 @@ export async function suspendEphemeralVmRuntime( }) if (!suspend.ok) { - const failed = updateEphemeralVmRuntimeStatus(args.userDataPath, existing.id, { - status: 'suspend_failed', - updatedAt: Date.now() - }) - return { ok: false, runtime: failed, error: suspend.error ?? 'Suspend failed.' } + const failure = { + error: suspend.error ?? 'Suspend failed.', + ...pickEphemeralVmFailureCode(suspend) + } + return recordLifecycleFailure(args.userDataPath, existing.id, 'suspend_failed', failure) } const suspended = updateEphemeralVmRuntimeStatus(args.userDataPath, existing.id, { status: suspend.skipped ? existing.status : 'suspended', + ...(suspend.skipped ? {} : { lifecycleLastError: null }), updatedAt: Date.now() }) return { ok: true, runtime: suspended, skipped: suspend.skipped } @@ -264,9 +247,7 @@ export async function resumeEphemeralVmRuntime( if (!existing.recipeResult) { throw new Error(`Ephemeral VM runtime never finished provisioning: ${args.runtimeId}`) } - const resume = await runEphemeralVmRecipeResume({ - repoPath: args.repoPath, - recipe: args.recipe, + const resume = await new ShellRecipeDriver(args.recipe, args.repoPath).runResume({ context: contextFromRuntime(args.repoPath, existing), recipeResult: existing.recipeResult, signal: args.signal, @@ -275,32 +256,43 @@ export async function resumeEphemeralVmRuntime( }) if (!resume.ok) { - const failed = updateEphemeralVmRuntimeStatus(args.userDataPath, existing.id, { - status: 'resume_failed', - updatedAt: Date.now() - }) - return { ok: false, runtime: failed, error: resume.error } + const failure = { error: resume.error, ...pickEphemeralVmFailureCode(resume) } + return recordLifecycleFailure(args.userDataPath, existing.id, 'resume_failed', failure) } const resumeIntegrityError = resume.skipped ? null : getProvisionedRootResumeIntegrityError(existing.recipeResult, resume.result) if (resumeIntegrityError) { - const failed = updateEphemeralVmRuntimeStatus(args.userDataPath, existing.id, { - status: 'resume_failed', - updatedAt: Date.now() + return recordLifecycleFailure(args.userDataPath, existing.id, 'resume_failed', { + error: resumeIntegrityError }) - return { ok: false, runtime: failed, error: resumeIntegrityError } } const runtime = updateEphemeralVmRuntimeStatus(args.userDataPath, existing.id, { status: 'running', + lifecycleLastError: null, ...(!resume.skipped ? { recipeResult: resume.result } : {}), updatedAt: Date.now() }) return { ok: true, runtime, skipped: resume.skipped } } +/** Persist the failed status with its reason so the sidebar can explain it after a restart. */ +function recordLifecycleFailure( + userDataPath: string, + runtimeId: string, + status: 'suspend_failed' | 'resume_failed', + failure: EphemeralVmFailure +): { ok: false; runtime: EphemeralVmRuntimeRecord } & EphemeralVmFailure { + const runtime = updateEphemeralVmRuntimeStatus(userDataPath, runtimeId, { + status, + lifecycleLastError: failure, + updatedAt: Date.now() + }) + return { ok: false, runtime, ...failure } +} + function contextFromRuntime( repoPath: string, runtime: EphemeralVmRuntimeRecord diff --git a/src/main/ephemeral-vm/workspace-lifecycle-result.ts b/src/main/ephemeral-vm/workspace-lifecycle-result.ts new file mode 100644 index 00000000000..9697758071a --- /dev/null +++ b/src/main/ephemeral-vm/workspace-lifecycle-result.ts @@ -0,0 +1,16 @@ +import type { + EphemeralVmRuntimeRecord, + EphemeralVmWorkspaceLifecycleResult +} from '../../shared/ephemeral-vm-runtimes' +import { ephemeralVmFailureFromError } from '../../shared/ephemeral-vm-failure-copy' + +/** Thrown IPC errors keep only the message; a value keeps the code for the renderer catalog. */ +export async function toWorkspaceLifecycleResult( + run: () => Promise +): Promise { + try { + return { ok: true, runtime: await run() } + } catch (error) { + return { ok: false, ...ephemeralVmFailureFromError(error) } + } +} diff --git a/src/main/ephemeral-vm/workspace-resume.ts b/src/main/ephemeral-vm/workspace-resume.ts index 4572fe00cf5..10d07137160 100644 --- a/src/main/ephemeral-vm/workspace-resume.ts +++ b/src/main/ephemeral-vm/workspace-resume.ts @@ -8,6 +8,11 @@ import { getEphemeralVmRecipeResultPairingCode } from '../../shared/ephemeral-vm-recipes' import { resolveEnvironment } from '../../shared/remote-runtime/host-store/runtime-environment-store' +import { + EphemeralVmFailureError, + ephemeralVmFailureFromError, + pickEphemeralVmFailureCode +} from '../../shared/ephemeral-vm-failure-copy' import { resumeEphemeralVmRuntime } from './runtime-service' import { connectRuntimeOwnedSshTarget, refreshRuntimeOwnedSshTarget } from './runtime-ssh' import { noteRecipeVmWakePairing } from './recipe-vm-wake-pairings' @@ -58,9 +63,22 @@ export async function resumeEphemeralVmWorkspace( } const restoreAfterFailedRecovery = (): void => { if (lostContact) { + // The record stays as it was; a lifecycle error only shows on a resume_failed VM. updateEphemeralVmRuntimeStatus(userDataPath, runtime.id, { status: runtime.status }) } } + // After the recipe marked the VM running, an SSH host Orca cannot reach again is still a failed + // resume, saved with its reason so the row can explain it after a restart. + const failAfterResume = (error: unknown): void => { + if (lostContact) { + restoreAfterFailedRecovery() + return + } + updateEphemeralVmRuntimeStatus(userDataPath, runtime.id, { + status: 'resume_failed', + lifecycleLastError: ephemeralVmFailureFromError(error) + }) + } const recipeContext = getRuntimeRecipeContext(store, userDataPath, runtime.id) if (lostContact && runtime.connectionMode === 'orca-server' && !recipeContext.recipe.resume) { // Nothing can restart this VM, and only the user can tell whether it is gone. Retry the @@ -78,7 +96,10 @@ export async function resumeEphemeralVmWorkspace( }) if (!result.ok) { restoreAfterFailedRecovery() - throw new Error(result.error) + throw new EphemeralVmFailureError({ + error: result.error, + ...pickEphemeralVmFailureCode(result) + }) } if (lostContact && runtime.runtimeEnvironmentId) { // The resume restarted the VM; its server's old failures say nothing about the new boot. @@ -90,6 +111,7 @@ export async function resumeEphemeralVmWorkspace( const connection = getEphemeralVmRecipeResultConnection(result.runtime.recipeResult) // SSH servers use their target and have no pairing to refresh. if (!result.skipped && connection.type !== 'ssh' && runtime.runtimeEnvironmentId) { + // A pairing failure leaves the VM running: retrying the recipe's resume on it would fail. const pairingCode = getEphemeralVmRecipeResultPairingCode(result.runtime.recipeResult) if (!pairingCode) { throw new Error('Resume result did not include an Orca Server pairing code.') @@ -139,13 +161,7 @@ export async function resumeEphemeralVmWorkspace( reestablishWokenServer(userDataPath, ssh.environmentId) return woken } catch (error) { - if (lostContact) { - restoreAfterFailedRecovery() - } else { - updateEphemeralVmRuntimeStatus(userDataPath, result.runtime.id, { - status: 'resume_failed' - }) - } + failAfterResume(error) throw error } } diff --git a/src/main/ephemeral-vm/workspace-suspend.ts b/src/main/ephemeral-vm/workspace-suspend.ts index 7b79aa813f5..844a804d5ea 100644 --- a/src/main/ephemeral-vm/workspace-suspend.ts +++ b/src/main/ephemeral-vm/workspace-suspend.ts @@ -4,6 +4,10 @@ import { findWorkspaceEphemeralVmRuntime } from '../../shared/ephemeral-vm-works import { suspendEphemeralVmRuntime } from './runtime-service' import { disconnectRuntimeOwnedSshTarget } from './runtime-ssh' import { getRuntimeRecipeContext } from '../ipc/ephemeral-vm-recipe-context' +import { + EphemeralVmFailureError, + pickEphemeralVmFailureCode +} from '../../shared/ephemeral-vm-failure-copy' export async function suspendEphemeralVmWorkspace( store: Store, @@ -22,7 +26,10 @@ export async function suspendEphemeralVmWorkspace( runtimeId: runtime.id }) if (!result.ok) { - throw new Error(result.error) + throw new EphemeralVmFailureError({ + error: result.error, + ...pickEphemeralVmFailureCode(result) + }) } // A skipped suspend leaves the VM running, so its SSH connection must remain live. if (runtime.connectionMode === 'ssh' && !result.skipped) { diff --git a/src/main/github/client/lookup/pr-for-branch-outcome.ts b/src/main/github/client/lookup/pr-for-branch-outcome.ts index 77da7abdf59..34bf63bc8ef 100644 --- a/src/main/github/client/lookup/pr-for-branch-outcome.ts +++ b/src/main/github/client/lookup/pr-for-branch-outcome.ts @@ -12,8 +12,73 @@ import { hostedReviewLocalGitOptionArgs, githubPRStackExecutionScope } from './. import type { GitHubPRBranchLookupOptions } from './pull-request-lookup-data' import { prRefreshUpstreamError } from './../gh-error-predicates' import { resolvePRForBranchOutcome } from './branch-lookup-resolution' +import { readRecentOpenPROutcome, recordPRLastOutcome, startPRLookup } from './pr-last-outcome' const reads: CoalescedProbes = new Map() +function prLookupScope( + repoPath: string, + connectionId: string | null | undefined, + options: GitHubPRBranchLookupOptions +) { + const localGitOptions = hostedReviewLocalGitOptionArgs(options)[0] ?? {} + const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)) + return { + localGitOptions, + ghOptions, + executionScope: githubPRStackExecutionScope(connectionId, localGitOptions), + generation: scopeGeneration( + hostedReviewRepoScope(repoPath, getRepoExecutionHostId({ connectionId })) + ), + readScope: githubReadExecutionScope(ghOptions) + } +} + +function lastOutcomeKey( + repoPath: string, + branchName: string, + scope: ReturnType +): string { + return JSON.stringify([ + scope.executionScope, + repoPath, + scope.generation, + branchName, + scope.readScope + ]) +} + +/** A phone read may take the last lookup's open PR; it was already observed when it was looked up. */ +export async function readRecentPhonePROutcome( + repoPath: string, + branch: string, + linkedPRNumber: number | null, + connectionId: string | null, + fallbackPRNumber: number | null, + options: GitHubPRBranchLookupOptions +): Promise { + if (options.userRefresh === true) { + return null + } + return withGitHubRepoExecution( + repoPath, + connectionId, + hostedReviewLocalGitOptionArgs(options)[0] ?? {}, + async () => + readRecentOpenPROutcome( + lastOutcomeKey( + repoPath, + branch.replace(/^refs\/heads\//, ''), + prLookupScope(repoPath, connectionId, options) + ), + { + linkedPRNumber, + fallbackPRNumber: linkedPRNumber === null ? fallbackPRNumber : null, + currentHeadOid: options.currentHeadOid ?? null + } + ) + ) +} + export async function getPRForBranchOutcome( repoPath: string, branch: string, @@ -36,16 +101,12 @@ export async function getPRForBranchOutcome( ) { return { kind: 'no-pr', fetchedAt: Date.now() } } - const localGitArgs = hostedReviewLocalGitOptionArgs(options) - const localGitOptions = localGitArgs[0] ?? {} - const context = githubRepoContext(repoPath, connectionId, localGitOptions) - const ghOptions = ghRepoExecOptions(context) - const executionScope = githubPRStackExecutionScope(connectionId, localGitOptions) - + const scope = prLookupScope(repoPath, connectionId, options) + const { localGitOptions, ghOptions, executionScope } = scope const key = JSON.stringify([ executionScope, repoPath, - scopeGeneration(hostedReviewRepoScope(repoPath, getRepoExecutionHostId({ connectionId }))), + scope.generation, branchName, linkedPRNumber ?? null, fallbackPRNumber ?? null, @@ -53,15 +114,17 @@ export async function getPRForBranchOutcome( options.currentHeadOid ?? null, options.checkPageLimit ?? null, options.exactRepository ?? null, - githubReadExecutionScope(ghOptions) + scope.readScope ]) return runCoalescedProbe( reads, key, async () => { await acquire() + const start = startPRLookup() + let outcome: PRRefreshOutcome try { - return await resolvePRForBranchOutcome({ + outcome = await resolvePRForBranchOutcome({ repoPath, branchName, linkedPRNumber, @@ -73,10 +136,18 @@ export async function getPRForBranchOutcome( executionScope }) } catch (err) { - return prRefreshUpstreamError(err) + outcome = prRefreshUpstreamError(err) } finally { release() } + const narrowed = options.checkPageLimit !== undefined || options.exactRepository + recordPRLastOutcome(lastOutcomeKey(repoPath, branchName, scope), { + start, + linkedPRNumber: linkedPRNumber ?? null, + fallbackPRNumber: fallbackPRNumber ?? null, + outcome: narrowed ? null : outcome + }) + return outcome }, 2 * 60_000, options diff --git a/src/main/github/client/lookup/pr-last-outcome.ts b/src/main/github/client/lookup/pr-last-outcome.ts new file mode 100644 index 00000000000..f5c7cb383be --- /dev/null +++ b/src/main/github/client/lookup/pr-last-outcome.ts @@ -0,0 +1,70 @@ +import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' + +// A phone's re-read right after the desktop's own lookup reuses it instead of asking GitHub again. +const PHONE_REUSE_MAX_AGE_MS = 30_000 +const MAX_ENTRIES = 256 + +type PRLookupStart = { startedAt: number; sequence: number } + +type PRLastOutcome = { + start: PRLookupStart + linkedPRNumber: number | null + fallbackPRNumber: number | null + // null: the last lookup was narrowed (CI-line watch), so nothing is reusable until a full one. + outcome: PRRefreshOutcome | null +} + +const lastOutcomes = new Map() +let lookupSequence = 0 + +// Two lookups can start in the same millisecond; the sequence still orders them. +export function startPRLookup(): PRLookupStart { + lookupSequence += 1 + return { startedAt: Date.now(), sequence: lookupSequence } +} + +export function recordPRLastOutcome(key: string, entry: PRLastOutcome): void { + const existing = lastOutcomes.get(key) + // A lookup that started earlier but settled later must not replace a newer answer. + if (existing && existing.start.sequence > entry.start.sequence) { + return + } + lastOutcomes.delete(key) + lastOutcomes.set(key, entry) + const now = Date.now() + for (const [oldestKey, oldest] of lastOutcomes) { + if (lastOutcomes.size <= MAX_ENTRIES && now - oldest.start.startedAt < PHONE_REUSE_MAX_AGE_MS) { + break + } + lastOutcomes.delete(oldestKey) + } +} + +/** Only an open PR whose own head is the request's head: a push can't have moved it, and merged or + * fallback rules still get a real lookup. */ +export function readRecentOpenPROutcome( + key: string, + request: { + linkedPRNumber: number | null + fallbackPRNumber: number | null + currentHeadOid: string | null + } +): PRRefreshOutcome | null { + const entry = lastOutcomes.get(key) + const outcome = entry?.outcome + if ( + !entry || + outcome?.kind !== 'found' || + Date.now() - entry.start.startedAt >= PHONE_REUSE_MAX_AGE_MS || + (outcome.pr.state !== 'open' && outcome.pr.state !== 'draft') || + entry.linkedPRNumber !== request.linkedPRNumber || + // The stored fallback number may be how it was found; another fallback could find another PR. + (outcome.pr.number === entry.fallbackPRNumber && + entry.fallbackPRNumber !== request.fallbackPRNumber) || + !request.currentHeadOid || + outcome.pr.headSha !== request.currentHeadOid + ) { + return null + } + return outcome +} diff --git a/src/main/github/pr-refresh-candidate-policy.ts b/src/main/github/pr-refresh-candidate-policy.ts index 963c74e8d3e..cb82cfe9e36 100644 --- a/src/main/github/pr-refresh-candidate-policy.ts +++ b/src/main/github/pr-refresh-candidate-policy.ts @@ -1,3 +1,4 @@ +import { shouldAcceptMergedFallbackPR } from '../../shared/github/pr-branch-fallback-rule' import { reviewRefreshIntervalMs } from '../../shared/review-refresh-policy' import type { GitHubPRRefreshAlias, @@ -18,14 +19,6 @@ type PRBranchLookupCandidate = Pick< 'localGitOptions' | 'linkedPRNumber' | 'fallbackPRNumber' | 'fallbackPRSource' | 'currentHeadOid' > -function shouldAcceptMergedFallbackPR(candidate: PRBranchLookupCandidate): boolean { - return ( - candidate.linkedPRNumber == null && - candidate.fallbackPRNumber != null && - candidate.fallbackPRSource != null - ) -} - export function hostedReviewOptionArgs( candidate: PRBranchLookupCandidate, reason: GitHubPRRefreshReason = 'visible', diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index 4c013a2ae5f..2fbb0d816ef 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -268,7 +268,7 @@ export async function refreshPRNow( plannedRetryAt = retry.nextVisibleErrorRetryAt(key, visibility.candidate(key, candidate)) broadcastOutcome = retry.withErrorSchedule(outcome, plannedRetryAt) } - events.observe(candidate, outcome) + events.observe(candidate, outcome, aliases) retry.noteManualGate(key, broadcastOutcome) events.broadcast( { aliases, reason, outcome: broadcastOutcome, requestStartedAt }, diff --git a/src/main/github/pr-refresh-event-publisher.ts b/src/main/github/pr-refresh-event-publisher.ts index 6af7047cb5e..50d21b652ef 100644 --- a/src/main/github/pr-refresh-event-publisher.ts +++ b/src/main/github/pr-refresh-event-publisher.ts @@ -1,4 +1,5 @@ import type { + GitHubPRRefreshAlias, GitHubPRRefreshCandidate, GitHubPRRefreshEvent, GitHubPRRefreshReason, @@ -8,9 +9,11 @@ import type { import { recordCoalescedCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' import { prRefreshRenderers } from './pr-refresh-renderer-port' +// `aliases`: every checkout the read stood for (one read can serve several linked to the same PR). export type PRRefreshOutcomeObserver = ( candidate: GitHubPRRefreshCandidate, - outcome: PRRefreshOutcome + outcome: PRRefreshOutcome, + aliases: readonly GitHubPRRefreshAlias[] ) => void const DIAGNOSTIC_BREADCRUMB_MIN_INTERVAL_MS = 30_000 @@ -27,10 +30,14 @@ export class PRRefreshEventPublisher { } /** Every read of a PR reaches every observer once, whatever surface caused it. */ - observe(candidate: GitHubPRRefreshCandidate, outcome: PRRefreshOutcome): void { + observe( + candidate: GitHubPRRefreshCandidate, + outcome: PRRefreshOutcome, + aliases: readonly GitHubPRRefreshAlias[] = [] + ): void { for (const observer of this.observers) { try { - observer(candidate, outcome) + observer(candidate, outcome, aliases) } catch (error) { // One observer's failure must not hide the read from the others or fail the refresh. console.warn('[pr-refresh] outcome observer failed', error) diff --git a/src/main/github/pr-refresh-queue-drainer.ts b/src/main/github/pr-refresh-queue-drainer.ts index 05670a82697..9f77729381f 100644 --- a/src/main/github/pr-refresh-queue-drainer.ts +++ b/src/main/github/pr-refresh-queue-drainer.ts @@ -269,7 +269,7 @@ export class PRRefreshQueueDrainer { ) broadcastOutcome = this.retry.withErrorSchedule(outcome, plannedRetryAt) } - this.events.observe(next.candidate, outcome) + this.events.observe(next.candidate, outcome, aliases) this.retry.noteManualGate(next.key, broadcastOutcome) this.events.broadcast( { aliases, reason: next.reason, outcome: broadcastOutcome, requestStartedAt }, diff --git a/src/main/github/pull-request-changed-events.test.ts b/src/main/github/pull-request-changed-events.test.ts new file mode 100644 index 00000000000..2f846d7612a --- /dev/null +++ b/src/main/github/pull-request-changed-events.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import type { GitHubPRRefreshCandidate } from '../../shared/github/pull-request-refresh-types' +import type { PRInfo } from '../../shared/github/pull-request-types' +import { pullRequestChangeObserver, type PullRequestChange } from './pull-request-changed-events' + +const candidate: GitHubPRRefreshCandidate = { + cacheKey: '/repo::feature', + repoKind: 'git', + repoId: 'repo-1', + repoPath: '/repo', + branch: 'feature', + worktreeId: 'repo-1::/repo' +} + +const pr: PRInfo = { + number: 42, + title: 'Add feature', + state: 'open', + url: 'https://github.com/acme/app/pull/42', + checksStatus: 'pending', + checksSummary: { state: 'pending', total: 1, passed: 0, failed: 0, pending: 1, neutral: 0 }, + updatedAt: '2026-11-09T10:00:00Z', + mergeable: 'MERGEABLE', + headSha: 'abc123' +} + +describe('pullRequestChangeObserver', () => { + it('publishes a found PR only when it differs from the last one published', () => { + const published: PullRequestChange[] = [] + const observe = pullRequestChangeObserver((change) => published.push(change)) + + observe(candidate, { kind: 'found', pr, fetchedAt: 1 }, []) + // Same PR read again, with a field outside the change set moved. + observe(candidate, { kind: 'found', pr: { ...pr, title: 'Renamed' }, fetchedAt: 2 }, []) + observe( + candidate, + { + kind: 'upstream-error', + errorType: 'network', + message: 'offline', + fetchedAt: 3 + }, + [] + ) + // A read that couldn't load the checks reports neutral with no summary. + const { checksSummary: _unloaded, ...withoutChecks } = pr + observe( + candidate, + { kind: 'found', pr: { ...withoutChecks, checksStatus: 'neutral' }, fetchedAt: 4 }, + [] + ) + observe( + candidate, + { + kind: 'found', + pr: { + ...pr, + checksStatus: 'success', + checksSummary: { + state: 'success', + total: 1, + passed: 1, + failed: 0, + pending: 0, + neutral: 0 + } + }, + fetchedAt: 5 + }, + [] + ) + + expect(published).toEqual([ + { worktreeId: 'repo-1::/repo', repoId: 'repo-1', branch: 'feature' }, + { worktreeId: 'repo-1::/repo', repoId: 'repo-1', branch: 'feature' } + ]) + }) + + // Checkouts linked to the same PR share one coordinator read. + it('publishes for every checkout one read stood for', () => { + const published: PullRequestChange[] = [] + const observe = pullRequestChangeObserver((change) => published.push(change)) + const sibling = { + cacheKey: '/repo-b::other', + repoPath: '/repo-b', + branch: 'other', + worktreeId: 'repo-1::/repo-b' + } + + observe(candidate, { kind: 'found', pr, fetchedAt: 1 }, [candidate, sibling]) + + expect(published).toEqual([ + { worktreeId: 'repo-1::/repo', repoId: 'repo-1', branch: 'feature' }, + { worktreeId: 'repo-1::/repo-b', repoId: 'repo-1', branch: 'other' } + ]) + }) +}) diff --git a/src/main/github/pull-request-changed-events.ts b/src/main/github/pull-request-changed-events.ts new file mode 100644 index 00000000000..a7171c3a76d --- /dev/null +++ b/src/main/github/pull-request-changed-events.ts @@ -0,0 +1,64 @@ +import type { PRRefreshOutcome } from '../../shared/github/pull-request-refresh-types' +import type { CheckStatus } from '../../shared/github/pull-request-types' +import type { RuntimeClientEvent } from '../../shared/runtime-client-events' +import type { PRRefreshOutcomeObserver } from './pr-refresh-event-publisher' + +export type PullRequestChange = Omit< + Extract, + 'type' +> + +type PublishedPR = { summary: string; checks: CheckStatus | null } + +// An evicted checkout costs one repeat event, so the bound only caps memory. +const MAX_TRACKED_CHECKOUTS = 256 + +// Errors say nothing about the PR, so they never publish. +function observedPR(outcome: PRRefreshOutcome, last: PublishedPR | undefined): PublishedPR | null { + if (outcome.kind === 'no-pr') { + return { summary: 'no-pr', checks: null } + } + if (outcome.kind !== 'found') { + return null + } + const { number, state, headSha, updatedAt, checksStatus, checksSummary } = outcome.pr + return { + summary: JSON.stringify([number, state, headSha ?? null, updatedAt ?? null]), + // A read that couldn't load the checks (an error, or a watch read's page cap) reports 'neutral' without a summary. + checks: checksSummary ? checksStatus : (last?.checks ?? null) + } +} + +/** + * Reports a checkout's PR only when a read finds it different from what was last reported: the + * coordinator observes every refresh, including unchanged follow-ups, and each event costs a phone read. + */ +export function pullRequestChangeObserver( + publish: (change: PullRequestChange) => void +): PRRefreshOutcomeObserver { + const published = new Map() + const publishIfChanged = (change: PullRequestChange, outcome: PRRefreshOutcome): void => { + const key = `${change.worktreeId}\0${change.branch}` + const last = published.get(key) + const next = observedPR(outcome, last) + if (!next || (next.summary === last?.summary && next.checks === last.checks)) { + return + } + published.delete(key) + published.set(key, next) + const oldest = published.keys().next().value + if (published.size > MAX_TRACKED_CHECKOUTS && oldest !== undefined) { + published.delete(oldest) + } + publish(change) + } + return (candidate, outcome, aliases) => { + // One read can stand for several checkouts linked to the same PR. A client's own read names + // no checkout, and that client already holds the answer. + for (const { worktreeId, repoId, branch } of [candidate, ...aliases]) { + if (worktreeId) { + publishIfChanged({ worktreeId, repoId: repoId ?? candidate.repoId, branch }, outcome) + } + } + } +} diff --git a/src/main/gitlab/branch-review-discovery.test.ts b/src/main/gitlab/branch-review-discovery.test.ts index cb406957f60..e2b918de272 100644 --- a/src/main/gitlab/branch-review-discovery.test.ts +++ b/src/main/gitlab/branch-review-discovery.test.ts @@ -92,7 +92,7 @@ it('fails a legacy traversal rather than selecting from an incomplete foreign pr await expect(createGitLabBranchDiscovery(args)('feature')).rejects.toThrow('incomplete') }) -it.each([100, 1000])( +it.each([1000])( 'walks %s raw legacy rows once before choosing an eligible source', async (count) => { read.mockResolvedValue({ stdout: JSON.stringify([row(1, 'opened', 8)]) }) diff --git a/src/main/gitlab/branch-review-source.test.ts b/src/main/gitlab/branch-review-source.test.ts index 5fcbd9a3ae2..ce8bd23a5a5 100644 --- a/src/main/gitlab/branch-review-source.test.ts +++ b/src/main/gitlab/branch-review-source.test.ts @@ -8,7 +8,7 @@ const resolve = (urls: string[]) => beforeEach(() => { identity.mockReset().mockResolvedValue({ id: 1, path: 'team/app' }) }) -it.each([10, 100])( +it.each([10])( 'ignores %s valid hosted mirrors in either URL order without probing them', async (count) => { const mirrors = Array.from({ length: count }, (_, i) => `git@mirror${i}.example:team/app.git`) diff --git a/src/main/gitlab/merged-mr-commit-membership.test.ts b/src/main/gitlab/merged-mr-commit-membership.test.ts index f078334387e..46a95f8a5a2 100644 --- a/src/main/gitlab/merged-mr-commit-membership.test.ts +++ b/src/main/gitlab/merged-mr-commit-membership.test.ts @@ -26,7 +26,7 @@ beforeEach(() => { pages.mockReset() viewer.mockReset().mockResolvedValue({ id: 1 }) }) -it.each([10, 100])( +it.each([10])( 'reuses a complete 500-commit result across %s admitted refreshes and coalesces a cold walk', async (count) => { pages.mockImplementation(async ([endpoint]: string[]) => { diff --git a/src/main/gitlab/mr-discussion-notes.test.ts b/src/main/gitlab/mr-discussion-notes.test.ts index 845fbaf581e..07d9ec0c878 100644 --- a/src/main/gitlab/mr-discussion-notes.test.ts +++ b/src/main/gitlab/mr-discussion-notes.test.ts @@ -68,53 +68,3 @@ it('never presents a successful prefix after a later discussion page fails', asy fetchDiscussionComments('/repo', { host: 'gitlab.com', path: 'g/p' }, 'mr', 7) ).rejects.toThrow('incomplete') }) - -it.each([100, 1000])('measures complete realistic discussions at %s rows', async (count) => { - const body = `## Review\n\nPlease preserve the existing owner across reconnects.\n\n\`\`\`typescript\nconst state = await readOwner()\nreturn state.current\n\`\`\`\n\n${'The next request should retain the confirmed state and report incomplete reads. '.repeat( - 20 - )}` - let rawBytes = 0 - pages.mockImplementation(async ([endpoint]: string[]) => { - const page = Number(new URL(endpoint, 'https://gitlab.com').searchParams.get('page')) - const rows = Array.from({ length: Math.min(100, count - (page - 1) * 100) }, (_, i) => ({ - id: `discussion-${page}-${i}`, - notes: [ - { - id: (page - 1) * 100 + i, - body, - created_at: '2026-11-08T00:00:00Z', - author: { username: 'me', avatar_url: 'https://gitlab.com/avatar.png' }, - resolvable: true, - resolved: false, - position: { new_path: 'src/file.ts', new_line: 17 } - } - ] - })) - const serialized = JSON.stringify(rows) - rawBytes += Buffer.byteLength(serialized) - return { - body: serialized, - headers: { 'x-next-page': page * 100 < count ? String(page + 1) : '' } - } - }) - const before = process.memoryUsage().heapUsed - const start = performance.now() - const result = await fetchDiscussionComments( - '/repo', - { host: 'gitlab.com', path: 'g/p' }, - 'mr', - 7 - ) - const normalized = performance.now() - const wireBytes = Buffer.byteLength(JSON.stringify(result)) - console.info('gitlab-review-parity-discussions', { - count, - rawBytes, - wireBytes, - readParseSortMs: normalized - start, - serializeMs: performance.now() - normalized, - heapDeltaBytes: process.memoryUsage().heapUsed - before - }) - expect(result).toHaveLength(count) - expect(pages).toHaveBeenCalledTimes(count / 100) -}) diff --git a/src/main/host/electron-speech-services.ts b/src/main/host/electron-speech-services.ts index 42985f217ac..ad43bc912e0 100644 --- a/src/main/host/electron-speech-services.ts +++ b/src/main/host/electron-speech-services.ts @@ -1,6 +1,8 @@ import { net } from 'electron' import { ModelManager } from '../speech/model-manager' import { SttService } from '../speech/stt-service' +import { createSttGpuPolicy } from '../speech/stt-gpu-failure-marker' +import { spawnSttWorkerWithCpuFallback } from '../speech/stt-worker-cpu-fallback' import { spawnSttUtilityProcess } from '../speech/stt-worker-utility-process' import type { SpeechServiceFactories } from '../speech/speech-runtime-service' import type { @@ -41,5 +43,8 @@ export const openElectronSpeechDownloadRequest: OpenSpeechDownloadRequest = (url export const electronSpeechServiceFactories: SpeechServiceFactories = { createModelManager: (customModelsDir) => new ModelManager(customModelsDir, openElectronSpeechDownloadRequest), - createSttService: (models) => new SttService(models, spawnSttUtilityProcess) + createSttService: (models, gpuEnabled) => { + const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled) + return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttUtilityProcess, gpu)) + } } diff --git a/src/main/ipc/ephemeral-vm-provision-cancel.test.ts b/src/main/ipc/ephemeral-vm-provision-cancel.test.ts index 0243488d077..5ffa3e55049 100644 --- a/src/main/ipc/ephemeral-vm-provision-cancel.test.ts +++ b/src/main/ipc/ephemeral-vm-provision-cancel.test.ts @@ -11,6 +11,7 @@ const { getPathMock, handleMock, resolveProvisionedRootSourceMock } = vi.hoisted })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, removeHandler: vi.fn() } })) diff --git a/src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts b/src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts index fcfc5dd9e11..190c3268bc4 100644 --- a/src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts +++ b/src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts @@ -15,6 +15,7 @@ const { connectRuntimeOwnedSshTargetMock, getPathMock, handleMock, removeHandler ) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, removeHandler: removeHandlerMock } })) diff --git a/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts b/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts index 37645f8f1d0..96a52a900b4 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts @@ -16,6 +16,7 @@ const { getPathMock, handleMock, removeRuntimeOwnedSshTargetMock, removeHandlerM ) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, ipcMain: { handle: handleMock, removeHandler: removeHandlerMock } })) diff --git a/src/main/ipc/ephemeral-vm-runtime-handlers.ts b/src/main/ipc/ephemeral-vm-runtime-handlers.ts index af566602f62..8a721827c74 100644 --- a/src/main/ipc/ephemeral-vm-runtime-handlers.ts +++ b/src/main/ipc/ephemeral-vm-runtime-handlers.ts @@ -1,9 +1,13 @@ -import { app, ipcMain } from 'electron' +import { app, BrowserWindow, ipcMain } from 'electron' import type { Store } from '../persistence/loading-store/store' import { listEphemeralVmRuntimes, updateEphemeralVmRuntimeStatus } from '../../shared/ephemeral-vm-runtime-store' +import { + EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, + onEphemeralVmRuntimesChanged +} from '../../shared/ephemeral-vm-runtime-store-events' import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes' import { cleanupOwnedEphemeralVmRuntime } from '../ephemeral-vm/owned-runtime-cleanup' import { stopEphemeralVmRuntimeCleanup } from '../ephemeral-vm/runtime-cleanup-control' @@ -15,6 +19,35 @@ import { getRuntimeRecipeContext } from './ephemeral-vm-recipe-context' import { ephemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' import { attachEphemeralVmRuntimeToWorkspace } from '../ephemeral-vm/runtime-attachment' import { forgetInterruptedEphemeralVmProvision } from '../ephemeral-vm/runtime-provisioning-persistence' +import { pendingVmCheckouts } from '../ephemeral-vm/pending-vm-checkouts' +import { + parsePendingVmCheckouts, + PENDING_VM_CHECKOUTS_CHANGED_CHANNEL +} from '../../shared/pending-vm-checkouts' + +let stopRuntimesChangedBroadcast: (() => void) | null = null +let runtimesChangedBroadcastQueued = false + +/** One coalesced signal per tick: a lifecycle op writes the store several times. */ +function broadcastEphemeralVmRuntimesChanged(): void { + if (runtimesChangedBroadcastQueued) { + return + } + runtimesChangedBroadcastQueued = true + setImmediate(() => { + runtimesChangedBroadcastQueued = false + for (const window of BrowserWindow.getAllWindows()) { + if (window.isDestroyed()) { + continue + } + try { + window.webContents.send(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL) + } catch { + // A renderer can disappear between isDestroyed() and send(). + } + } + }) +} export type EphemeralVmCleanupCommandResult = { runtimeId: string @@ -24,13 +57,63 @@ export type EphemeralVmCleanupCommandResult = { message?: string } +let detachPendingCheckoutBroadcast: (() => void) | null = null +const pendingCheckoutOwners = new Set() + +function broadcastPendingVmCheckouts(): void { + for (const window of BrowserWindow.getAllWindows()) { + if (window.isDestroyed()) { + continue + } + try { + window.webContents.send( + PENDING_VM_CHECKOUTS_CHANGED_CHANNEL, + pendingVmCheckouts.listExcept(window.webContents.id) + ) + } catch { + // A renderer can disappear between isDestroyed() and send(). + } + } +} + +/** Windows publish the VM checkouts their creates have not adopted yet; every window reads the union. */ +function registerPendingVmCheckoutHandlers(): void { + ipcMain.removeHandler('ephemeralVm:publishPendingCheckouts') + ipcMain.removeHandler('ephemeralVm:listPendingCheckouts') + detachPendingCheckoutBroadcast?.() + detachPendingCheckoutBroadcast = pendingVmCheckouts.onChanged(broadcastPendingVmCheckouts) + ipcMain.handle('ephemeralVm:publishPendingCheckouts', (event, value: unknown): void => { + const sender = event.sender + const ownerId = sender.id + if (!pendingCheckoutOwners.has(ownerId)) { + pendingCheckoutOwners.add(ownerId) + // A closed or crashed window's creates cannot finish; its hides go with it. A reloaded + // window publishes its empty set when it starts. + const drop = (): void => { + pendingCheckoutOwners.delete(ownerId) + sender.removeListener('render-process-gone', drop) + pendingVmCheckouts.publish(ownerId, []) + } + sender.once('destroyed', drop) + sender.once('render-process-gone', drop) + } + pendingVmCheckouts.publish(ownerId, parsePendingVmCheckouts(value)) + }) + ipcMain.handle('ephemeralVm:listPendingCheckouts', (event) => + pendingVmCheckouts.listExcept(event.sender.id) + ) +} + export function registerEphemeralVmRuntimeHandlers(store: Store): void { + registerPendingVmCheckoutHandlers() ipcMain.removeHandler('ephemeralVm:attachWorkspace') ipcMain.removeHandler('ephemeralVm:listRuntimes') ipcMain.removeHandler('ephemeralVm:cleanup') ipcMain.removeHandler('ephemeralVm:stopCleanup') ipcMain.removeHandler('ephemeralVm:forgetRuntime') ipcMain.removeHandler('ephemeralVm:getCleanupCommand') + stopRuntimesChangedBroadcast?.() + stopRuntimesChangedBroadcast = onEphemeralVmRuntimesChanged(broadcastEphemeralVmRuntimesChanged) ipcMain.handle('ephemeralVm:listRuntimes', (): EphemeralVmRuntimeRecord[] => { return listEphemeralVmRuntimes(app.getPath('userData')) diff --git a/src/main/ipc/ephemeral-vm.test.ts b/src/main/ipc/ephemeral-vm.test.ts index 1847714de86..6dd61f6f944 100644 --- a/src/main/ipc/ephemeral-vm.test.ts +++ b/src/main/ipc/ephemeral-vm.test.ts @@ -30,6 +30,7 @@ const { })) vi.mock('electron', () => ({ + BrowserWindow: { getAllWindows: () => [] }, app: { getPath: getPathMock }, @@ -52,6 +53,7 @@ vi.mock('./runtime-environments/runtime-environments', () => ({ import { registerEphemeralVmHandlers } from './ephemeral-vm' import { suspendEphemeralVmWorkspace } from '../ephemeral-vm/workspace-suspend' import { resumeEphemeralVmWorkspace } from '../ephemeral-vm/workspace-resume' +import { toWorkspaceLifecycleResult } from '../ephemeral-vm/workspace-lifecycle-result' const tempDirs: string[] = [] @@ -405,6 +407,95 @@ describe('registerEphemeralVmHandlers', () => { ) }) + it('returns coded suspend and resume failures and keeps them on the record', async () => { + const userDataPath = makeDir('orca-ephemeral-vm-ipc-user-data-') + const repoPath = makeDir('orca-ephemeral-vm-ipc-repo-') + getPathMock.mockReturnValue(userDataPath) + mkdirSync(join(repoPath, 'scripts'), { recursive: true }) + const startPath = join(repoPath, 'scripts', 'start.js') + const suspendPath = join(repoPath, 'scripts', 'suspend.js') + const resumePath = join(repoPath, 'scripts', 'resume.js') + writeFileSync( + startPath, + [ + 'console.log(JSON.stringify({', + ' schemaVersion: 1,', + ` pairingCode: ${JSON.stringify(makePairingCode())},`, + " projectRoot: '/workspace/repo'", + '}))' + ].join('\n') + ) + writeFileSync(suspendPath, "if (require('fs').existsSync('fail-suspend.txt')) process.exit(4)") + writeFileSync(resumePath, 'process.exit(3)') + writeFileSync( + join(repoPath, 'orca.yaml'), + [ + 'environmentRecipes:', + ' - id: cloud-sandbox', + ' name: Cloud Sandbox', + ` create: ${JSON.stringify(nodeCommand(startPath))}`, + ` suspend: ${JSON.stringify(nodeCommand(suspendPath))}`, + ` resume: ${JSON.stringify(nodeCommand(resumePath))}`, + ' destroy: none' + ].join('\n') + ) + const store = makeStore(repoPath) + registerEphemeralVmHandlers(store as never) + const provisioned = (await handlers.get('ephemeralVm:provision')?.(null, { + repoId: 'repo-1', + recipeId: 'cloud-sandbox' + } as never)) as { ok: true; runtime: { id: string } } + await handlers.get('ephemeralVm:attachWorkspace')?.(null, { + runtimeId: provisioned.runtime.id, + workspaceId: 'workspace-1' + } as never) + const suspend = () => + toWorkspaceLifecycleResult(async () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the suspend reads only getRepo and getRepos, which makeStore provides. + await suspendEphemeralVmWorkspace(store as never, 'workspace-1') + return null + }) + + writeFileSync(join(repoPath, 'fail-suspend.txt'), '') + expect(await suspend()).toEqual({ + ok: false, + error: 'Suspend exited with code 4.', + errorCode: 'suspendExited', + errorParams: { exitCode: 4 } + }) + expect(listEphemeralVmRuntimes(userDataPath)[0]).toMatchObject({ + status: 'suspend_failed', + lifecycleLastErrorCode: 'suspendExited' + }) + + rmSync(join(repoPath, 'fail-suspend.txt')) + expect(await suspend()).toEqual({ ok: true, runtime: null }) + // A successful suspend clears the earlier suspend failure from the record. + expect(listEphemeralVmRuntimes(userDataPath)[0]?.lifecycleLastErrorCode).toBeUndefined() + + const resumeFailed = await toWorkspaceLifecycleResult(() => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the resume reads only getRepo and getRepos, which makeStore provides. + resumeEphemeralVmWorkspace(store as never, 'workspace-1', { + sshHeld: false, + sshUserDisconnects: 0 + }) + ) + expect(resumeFailed).toEqual({ + ok: false, + error: 'Resume exited with code 3.', + errorCode: 'resumeExited', + errorParams: { exitCode: 3 } + }) + expect(listEphemeralVmRuntimes(userDataPath)).toEqual([ + expect.objectContaining({ + status: 'resume_failed', + lifecycleLastError: 'Resume exited with code 3.', + lifecycleLastErrorCode: 'resumeExited', + lifecycleLastErrorParams: { exitCode: 3 } + }) + ]) + }) + it('redacts recipe stdout when provisioning fails', async () => { const userDataPath = makeDir('orca-ephemeral-vm-ipc-user-data-') const repoPath = makeDir('orca-ephemeral-vm-ipc-repo-') diff --git a/src/main/ipc/pty-claude-agent-view-readiness.test.ts b/src/main/ipc/pty-claude-agent-view-readiness.test.ts index 98f2bf3f711..5d446710807 100644 --- a/src/main/ipc/pty-claude-agent-view-readiness.test.ts +++ b/src/main/ipc/pty-claude-agent-view-readiness.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { describe, expect, it, onTestFinished, vi } from 'vitest' import { join } from 'node:path' import { tmpdir } from 'node:os' import * as agentView from '../claude/agent-view/agent-view-service' @@ -57,46 +57,37 @@ describe.each(['local', 'daemon'] as const)('%s PTY navigation readiness', (prov const { daemonSpawnAndGetEnv } = createDaemonActiveProviderFixtures({ handlers, mainWindow }) it('spawns a plain shell while reconciliation is pending', async () => { - let release = () => {} - const gate = new Promise((resolve) => { - release = resolve - }) + const gate = Promise.withResolvers() + const reconcileStarted = Promise.withResolvers() const config = join(tmpdir(), 'orca-spawn-pending-agent-view-config') vi.stubEnv('CLAUDE_CONFIG_DIR', config) - const reconcileConfig = vi.fn(() => gate) const service = new agentView.ClaudeAgentViewService( join(tmpdir(), 'orca-spawn-pending-agent-view'), { - reconcileConfig, + reconcileConfig: () => { + reconcileStarted.resolve() + return gate.promise + }, ensurePlugin: async () => join(tmpdir(), 'orca-spawn-agent-view-plugin'), loginEnv: async () => ({ CLAUDE_CONFIG_DIR: config }), listProfiles: async () => [] } ) - const settings = createGlobalSettingsFixture({ claudeSubagentNavigationEnabled: true }) - let reconciled = false - const reconcile = service.reconcile(settings).then(() => { - reconciled = true - }) - await vi.waitFor(() => expect(reconcileConfig).toHaveBeenCalledOnce()) const serviceSpy = vi.spyOn(agentView, 'getClaudeAgentViewService').mockReturnValue(service) - let env: Record | undefined - const spawn = ( - provider === 'daemon' - ? daemonSpawnAndGetEnv({}, undefined, () => settings) - : spawnAndGetEnv({}, undefined, undefined, () => settings) - ).then((result) => { - env = result - }) - try { - await vi.waitFor(() => expect(env).toBeDefined()) - expect(reconciled).toBe(false) - expect(env).not.toHaveProperty('ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR') - } finally { - release() - await Promise.all([reconcile, spawn]) + // Runs on timeout too, when a regressed spawn never settles. + onTestFinished(() => { + gate.resolve() serviceSpy.mockRestore() vi.unstubAllEnvs() - } + }) + const settings = createGlobalSettingsFixture({ claudeSubagentNavigationEnabled: true }) + const reconcile = service.reconcile(settings) + await reconcileStarted.promise + const env = await (provider === 'daemon' + ? daemonSpawnAndGetEnv({}, undefined, () => settings) + : spawnAndGetEnv({}, undefined, undefined, () => settings)) + expect(env).not.toHaveProperty('ORCA_CLAUDE_AGENT_VIEW_PLUGIN_DIR') + gate.resolve() + await reconcile }) }) diff --git a/src/main/ipc/register-core-handlers/register-core-handlers.ts b/src/main/ipc/register-core-handlers/register-core-handlers.ts index 846a93300a6..e7d56746c88 100644 --- a/src/main/ipc/register-core-handlers/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers/register-core-handlers.ts @@ -199,7 +199,7 @@ export function registerCoreHandlers( registerGrokAccountHandlers() registerCursorAccountHandlers() registerRateLimitHandlers(rateLimits, codexAccounts) - registerGitHubHandlers(store, stats) + registerGitHubHandlers(store, stats, runtime) registerGitLabHandlers(store) registerHostedReviewHandlers(store, stats) registerLinearHandlers() diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index af8b9c5fe8f..68ae1b3aed9 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -38,6 +38,7 @@ export function registerRepoHandlers( ipcMain.removeHandler('projectGroups:list') ipcMain.removeHandler('projectGroups:create') ipcMain.removeHandler('projectGroups:update') + ipcMain.removeHandler('projectGroups:updateMany') ipcMain.removeHandler('projectGroups:delete') ipcMain.removeHandler('projectGroups:moveProject') ipcMain.removeHandler('projectGroups:scanNested') diff --git a/src/main/ipc/repos/project-group-handlers.ts b/src/main/ipc/repos/project-group-handlers.ts index 1dd1ccfe7e4..bb9462b3349 100644 --- a/src/main/ipc/repos/project-group-handlers.ts +++ b/src/main/ipc/repos/project-group-handlers.ts @@ -12,6 +12,7 @@ import { ProjectGroupScanNestedArgs, ProjectGroupSelectorArgs, ProjectGroupUpdateArgs, + ProjectGroupUpdateManyArgs, parseProjectGroupIpcArgs } from './repo-ipc-arg-schemas' import { @@ -54,6 +55,19 @@ export function registerProjectGroupHandlers(mainWindow: BrowserWindow, store: S return updated }) + ipcMain.handle('projectGroups:updateMany', (_event, rawArgs: unknown): ProjectGroup[] | null => { + const args = parseProjectGroupIpcArgs( + ProjectGroupUpdateManyArgs, + rawArgs, + 'invalid_project_group_update_many_args' + ) + const updated = store.updateProjectGroups(args.mutations) + if (updated?.length) { + notifyReposChanged(mainWindow) + } + return updated + }) + ipcMain.handle('projectGroups:delete', (_event, rawArgs: unknown): boolean => { const args = parseProjectGroupIpcArgs( ProjectGroupSelectorArgs, diff --git a/src/main/ipc/repos/repo-ipc-arg-schemas.ts b/src/main/ipc/repos/repo-ipc-arg-schemas.ts index 32e99ac2f1a..8e3d46c8b44 100644 --- a/src/main/ipc/repos/repo-ipc-arg-schemas.ts +++ b/src/main/ipc/repos/repo-ipc-arg-schemas.ts @@ -30,6 +30,10 @@ export const ProjectGroupSelectorArgs = z.object({ groupId: z.string().min(1) }) +export const ProjectGroupUpdateManyArgs = z.object({ + mutations: z.array(ProjectGroupUpdateArgs) +}) + export const ProjectHostSetupExistingFolderIpcArgs = z.object({ projectId: z.string().min(1), projectProviderIdentity: z diff --git a/src/main/ipc/repos/repo-update-handler.ts b/src/main/ipc/repos/repo-update-handler.ts index 205243cc719..d4fea3f3571 100644 --- a/src/main/ipc/repos/repo-update-handler.ts +++ b/src/main/ipc/repos/repo-update-handler.ts @@ -17,6 +17,7 @@ import { } from '../../../shared/worktree/visibility-sources' import { prepareLocalWorktreeRootForRepo } from '../../workspaces/creation/worktree-root-preparation' import { commitProvenRepoKindChange } from '../../workspaces/catalog/folder-repo-git-conversion' +import { normalizeDictationTerms } from '../../../shared/dictation-dictionary' import { invalidateAuthorizedRootsCache } from '../worktrees/removal/registered-worktree-roots-cache' import { notifyReposChanged } from './repos-changed-notification' import { @@ -45,6 +46,7 @@ export function registerRepoUpdateHandler(mainWindow: BrowserWindow, store: Stor | 'worktreeBasePath' | 'kind' | 'symlinkPaths' + | 'dictationTerms' | 'issueSourcePreference' | 'forkSyncMode' | 'agentWorkspaceTrust' @@ -110,6 +112,14 @@ export function registerRepoUpdateHandler(mainWindow: BrowserWindow, store: Stor delete updates.symlinkPaths } } + if ('dictationTerms' in updates) { + const terms = normalizeDictationTerms(updates.dictationTerms) + if (terms) { + updates.dictationTerms = terms + } else { + delete updates.dictationTerms + } + } if ('worktreeBasePath' in updates && updates.worktreeBasePath !== undefined) { const v = updates.worktreeBasePath as unknown if (typeof v !== 'string') { diff --git a/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts b/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts index 6cf56a3929e..f2203bafd2b 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-mobile-relay-hosts.ts @@ -23,7 +23,10 @@ import { } from './runtime-environment-managed-tunnel' import { wslHostsGateOpen } from '../../wsl/host-lifecycle/wsl-host-gate' import type { WslHostPhoneReach } from '../../wsl/host-lifecycle/wsl-host-phone-reach' -import { getWslHostPhoneGate } from '../../wsl/host-lifecycle/wsl-host-service-instance' +import { + getWslHostPhoneGate, + onWslHostStatusesChanged +} from '../../wsl/host-lifecycle/wsl-host-service-instance' import type { SshConnectionState } from '../../../shared/ssh-types' import { getRegisteredSshState, @@ -41,6 +44,7 @@ import { runtimeEnvironmentManualDisconnectCount } from './runtime-environment-manual-disconnect' import { onRuntimeEnvironmentStatusPublished } from './runtime-environment-status-owner' +import { watchRuntimeEnvironmentRegistry } from './runtime-environment-preference' import { getRuntimeEnvironmentTransportGeneration } from './runtime-environment-transport-generation' import { getRuntimeEnvironmentRegistryRoot } from './runtime-environment-registry-root' import { recipeVmServerState } from './runtime-environment-recipe-vm-wake' @@ -195,7 +199,18 @@ export function createRuntimeEnvironmentMobileRelayHosts(): MobileDesktopRelayHo retirementListeners.add(listener) return () => retirementListeners.delete(listener) }, - onStatusChanged: onRuntimeEnvironmentStatusPublished, + // A WSL host's reach (hidden, stopped, ready) is part of its listing too. + onStatusChanged: (listener) => { + const stopStatus = onRuntimeEnvironmentStatusPublished(listener) + const stopWsl = onWslHostStatusesChanged(listener) + return () => { + stopStatus() + stopWsl() + } + }, + // Its own watch: serve has no window, so the renderer catalog broadcast never runs there. + onCatalogChanged: (listener) => + watchRuntimeEnvironmentRegistry(userDataPath, listener, 'Phone server list'), watchChanges: (host, expected, callbacks) => watchRuntimeEnvironmentChanges(userDataPath, host.environmentId, expected, callbacks) } diff --git a/src/main/ipc/runtime-environments/runtime-environment-preference.ts b/src/main/ipc/runtime-environments/runtime-environment-preference.ts index 2bcac60766b..df39b8a9402 100644 --- a/src/main/ipc/runtime-environments/runtime-environment-preference.ts +++ b/src/main/ipc/runtime-environments/runtime-environment-preference.ts @@ -55,19 +55,35 @@ export function watchRuntimeEnvironmentPreference( } // Reconcile changes made while the native watch was being installed. const initialCheck = setImmediate(repairPreference) - // Watch the file: macOS directory watches recursively stream Orca's own userData writes. - const registryWatch = watchFileAcrossReplacement( - getEnvironmentStorePath(userDataPath), + const stopRegistryWatch = watchRuntimeEnvironmentRegistry( + userDataPath, () => { repairPreference() onRegistryChanged() }, - (error) => console.warn('[runtime-environments] Active Server preference watch failed:', error) + 'Active Server preference' + ) + return () => { + clearImmediate(initialCheck) + stopRegistryWatch() + } +} + +/** Calls `onChanged` after any write to the saved-server registry, in-app or by the CLI. */ +export function watchRuntimeEnvironmentRegistry( + userDataPath: string, + onChanged: () => void, + owner: string +): () => void { + // Watch the file: macOS directory watches recursively stream Orca's own userData writes. + const registryWatch = watchFileAcrossReplacement( + getEnvironmentStorePath(userDataPath), + onChanged, + (error) => console.warn(`[runtime-environments] ${owner} watch failed:`, error) ) const sweep = setInterval(() => void registryWatch.refresh(), REGISTRY_REBIND_SWEEP_MS) sweep.unref?.() return () => { - clearImmediate(initialCheck) clearInterval(sweep) void registryWatch.close() } diff --git a/src/main/ipc/runtime.test.ts b/src/main/ipc/runtime.test.ts index 9c8b0cebdf1..426ee56ba12 100644 --- a/src/main/ipc/runtime.test.ts +++ b/src/main/ipc/runtime.test.ts @@ -21,6 +21,7 @@ vi.mock('electron', () => ({ } })) import { registerRuntimeHandlers } from './runtime' +import { EphemeralVmFailureError } from '../../shared/ephemeral-vm-failure-copy' describe('registerRuntimeHandlers', () => { beforeEach(() => { @@ -41,10 +42,36 @@ describe('registerRuntimeHandlers', () => { const registration = handleMock.mock.calls.find( ([channel]) => channel === 'ephemeralVm:resumeWorkspace' ) - await expect(registration![1]({}, { workspaceId: 'repo::/vm' })).resolves.toBe(record) + await expect(registration![1]({}, { workspaceId: 'repo::/vm' })).resolves.toEqual({ + ok: true, + runtime: record + }) expect(runtime.wakeWorkspaceVm).toHaveBeenCalledWith('repo::/vm') }) + it('returns coded VM wake and suspend failures as values so the code reaches the window', async () => { + const failure = { + error: 'Resume exited with code 3.', + errorCode: 'resumeExited', + errorParams: { exitCode: 3 } + } + const runtime = { + wakeWorkspaceVm: vi.fn().mockRejectedValue(new EphemeralVmFailureError(failure)), + suspendWorkspaceVm: vi.fn().mockRejectedValue(new Error('Suspend failed.')) + } + registerRuntimeHandlers(runtime as never) + const handler = (channel: string) => + handleMock.mock.calls.find(([registered]) => registered === channel)![1] + + await expect( + handler('ephemeralVm:resumeWorkspace')({}, { workspaceId: 'repo::/vm' }) + ).resolves.toEqual({ ok: false, ...failure }) + await expect( + handler('ephemeralVm:suspendWorkspace')({}, { workspaceId: 'repo::/vm' }) + ).resolves.toEqual({ ok: false, error: 'Suspend failed.' }) + expect(runtime.suspendWorkspaceVm).toHaveBeenCalledWith('repo::/vm') + }) + // #37067: a phone's re-read on the add's reposChanged came before this publish. it('rejects a graph publication queued by a superseded main frame', () => { diff --git a/src/main/ipc/runtime.ts b/src/main/ipc/runtime.ts index 52565e74f8e..7dadefd1eee 100644 --- a/src/main/ipc/runtime.ts +++ b/src/main/ipc/runtime.ts @@ -14,6 +14,7 @@ import { RpcDispatcher } from '../runtime/rpc/dispatcher' import { DESKTOP_RPC_CALLER } from '../runtime/rpc/rpc-caller-identity' import { ALL_RPC_METHODS } from '../runtime/rpc/methods/rpc-method-registry' import { DesktopRuntimeSenderLifecycle } from './desktop-runtime-sender-lifecycle' +import { toWorkspaceLifecycleResult } from '../ephemeral-vm/workspace-lifecycle-result' import { publishMobileProjectSections } from '../runtime/sidebar-inputs/mobile-project-sections-snapshot' function boundTerminalFitRestore(pending: Promise): Promise { @@ -34,10 +35,18 @@ export function registerRuntimeHandlers(runtime: OrcaRuntimeService): void { ipcMain.removeHandler('runtime:subscribe') ipcMain.removeAllListeners('runtime:unsubscribe') ipcMain.removeHandler('ephemeralVm:resumeWorkspace') + ipcMain.removeHandler('ephemeralVm:suspendWorkspace') // The window's wake shares the runtime's single VM wake path with its sleep's suspend. ipcMain.handle('ephemeralVm:resumeWorkspace', (_event, args: { workspaceId: string }) => - runtime.wakeWorkspaceVm(args.workspaceId) + toWorkspaceLifecycleResult(() => runtime.wakeWorkspaceVm(args.workspaceId)) + ) + // Suspend VM with nothing open; a workspace with open panels sleeps, which suspends it after. + ipcMain.handle('ephemeralVm:suspendWorkspace', (_event, args: { workspaceId: string }) => + toWorkspaceLifecycleResult(async () => { + await runtime.suspendWorkspaceVm(args.workspaceId) + return null + }) ) ipcMain.handle( diff --git a/src/main/ipc/source-control/github-pr-refresh-handlers.ts b/src/main/ipc/source-control/github-pr-refresh-handlers.ts index cc5c4d9c03f..7ddae33d2f8 100644 --- a/src/main/ipc/source-control/github-pr-refresh-handlers.ts +++ b/src/main/ipc/source-control/github-pr-refresh-handlers.ts @@ -7,6 +7,7 @@ import type { PRRefreshOutcome } from '../../../shared/github/pull-request-refresh-types' import type { Repo } from '../../../shared/repo-types' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { getPRForBranch } from '../../github/client/lookup/get-pr-for-branch' import type { GitHubPRBranchLookupOptions } from '../../github/client/lookup/pull-request-lookup-data' import { @@ -18,6 +19,7 @@ import { setPRRefreshRegistrationCheck } from '../../github/pr-refresh-coordinator' import { setPRRefreshRendererPort } from '../../github/pr-refresh-renderer-port' +import { pullRequestChangeObserver } from '../../github/pull-request-changed-events' import { electronPRRefreshRenderer } from '../../host/electron-pr-refresh-renderer' import type { Store } from '../../persistence/loading-store/store' import type { StatsCollector } from '../../stats/collector' @@ -35,7 +37,11 @@ import { abortWhenRendererGone } from '../renderer-lifetime-abort' const visibilityCleanupRegistered = new Set() -export function registerGitHubPRRefreshHandlers(store: Store, stats: StatsCollector): void { +export function registerGitHubPRRefreshHandlers( + store: Store, + stats: StatsCollector, + runtime: Pick +): void { // The windows these handlers serve are the renderers the coordinator reports to. setPRRefreshRendererPort(electronPRRefreshRenderer) function recordPRIfNeeded(repo: Repo, outcome: PRRefreshOutcome): void { @@ -57,6 +63,10 @@ export function registerGitHubPRRefreshHandlers(store: Store, stats: StatsCollec recordPRIfNeeded(repo, outcome) } }) + // Only the desktop drives the coordinator; serve and orcad have no publisher, so phones keep polling there. + addPRRefreshOutcomeObserver( + pullRequestChangeObserver((change) => runtime.notifyPullRequestChangedForRemoteClients(change)) + ) setPRRefreshRegistrationCheck((candidate) => isPRRefreshCandidateRegistered(candidate, store.getRepos()) ) diff --git a/src/main/ipc/source-control/github-repo-access-guards.test.ts b/src/main/ipc/source-control/github-repo-access-guards.test.ts index c2bf906593a..36550af5e22 100644 --- a/src/main/ipc/source-control/github-repo-access-guards.test.ts +++ b/src/main/ipc/source-control/github-repo-access-guards.test.ts @@ -179,11 +179,12 @@ const { getIssue: getIssueMock, listWorkItems: listWorkItemsMock } = mocks.clien describe('registerGitHubHandlers', () => { const harness = createGitHubIpcHarness(mocks) const { handlers, store, stats } = harness + const runtime = { notifyPullRequestChangedForRemoteClients: () => {} } beforeEach(harness.reset) it('rejects unknown repository paths', async () => { - registerGitHubHandlers(store as never, stats as never) + registerGitHubHandlers(store as never, stats as never, runtime) // Background issue reads are async (they check the repo's WSL distro first), so access errors reject. await expect(async () => @@ -197,7 +198,7 @@ describe('registerGitHubHandlers', () => { }) it('rejects GitHub source context from a different host', async () => { - registerGitHubHandlers(store as never, stats as never) + registerGitHubHandlers(store as never, stats as never, runtime) await expect(async () => handlers['gh:listWorkItems'](null, { diff --git a/src/main/ipc/source-control/github.ts b/src/main/ipc/source-control/github.ts index 0958deea226..af4186e3829 100644 --- a/src/main/ipc/source-control/github.ts +++ b/src/main/ipc/source-control/github.ts @@ -1,4 +1,5 @@ import type { Store } from '../../persistence/loading-store/store' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import type { StatsCollector } from '../../stats/collector' import { registerGitHubAccountHandlers } from './github-account-handlers' import { registerGitHubIssueMutationHandlers } from './github-issue-mutation-handlers' @@ -9,8 +10,12 @@ import { registerGitHubPRReviewHandlers } from './github-pr-review-handlers' import { registerGitHubProjectViewHandlers } from './github-project-view-handlers' import { registerGitHubWorkItemHandlers } from './github-work-item-handlers' -export function registerGitHubHandlers(store: Store, stats: StatsCollector): void { - registerGitHubPRRefreshHandlers(store, stats) +export function registerGitHubHandlers( + store: Store, + stats: StatsCollector, + runtime: Pick +): void { + registerGitHubPRRefreshHandlers(store, stats, runtime) registerGitHubWorkItemHandlers(store) registerGitHubPRReadHandlers(store) registerGitHubPRReviewHandlers(store) diff --git a/src/main/ipc/speech.ts b/src/main/ipc/speech.ts index 42f92f7445e..98f7f52f9b0 100644 --- a/src/main/ipc/speech.ts +++ b/src/main/ipc/speech.ts @@ -6,9 +6,7 @@ import { type MessagePortMain } from 'electron' import { abortWhenRendererGone } from './renderer-lifetime-abort' -import { join } from 'node:path' -import { writeFile, unlink } from 'node:fs/promises' -import { createHash } from 'node:crypto' +import { dictationTermsFor } from '../../shared/dictation-dictionary' import { SPEECH_MODEL_CATALOG } from '../speech/model-catalog' import { deleteLocalSpeechModel } from '../speech/speech-model-deletion' import { getSpeechModelManager, getSpeechSttService } from '../speech/speech-runtime-service' @@ -17,7 +15,15 @@ import { getOpenAiSpeechApiKeyProtection, hasOpenAiSpeechApiKey } from '../speech/openai-api-key-store' -import { saveVerifiedOpenAiSpeechApiKey } from '../speech/openai-api-key-verification' +import { + saveVerifiedOpenAiCompatibleSpeechProvider, + saveVerifiedOpenAiSpeechApiKey +} from '../speech/openai-api-key-verification' +import { + clearOpenAiCompatibleSpeechProvider, + summarizeOpenAiCompatibleSpeechProvider +} from '../speech/openai-compatible-speech-provider-store' +import type { DictationContext, OpenAiCompatibleSpeechProvider } from '../../shared/speech-types' import type { Store } from '../persistence/loading-store/store' export function registerSpeechHandlers(store: Store): void { @@ -43,6 +49,25 @@ export function registerSpeechHandlers(store: Store): void { return { configured: false, protection: null } }) + ipcMain.handle('speech:getOpenAiCompatibleProvider', () => { + try { + return summarizeOpenAiCompatibleSpeechProvider() + } catch { + return null + } + }) + + ipcMain.handle( + 'speech:saveOpenAiCompatibleProvider', + async (_event, input: OpenAiCompatibleSpeechProvider) => { + await saveVerifiedOpenAiCompatibleSpeechProvider(input) + } + ) + + ipcMain.handle('speech:clearOpenAiCompatibleProvider', () => { + clearOpenAiCompatibleSpeechProvider() + }) + ipcMain.handle('speech:downloadModel', async (event, modelId: string) => { const manager = getSpeechModelManager(store) const window = BrowserWindow.fromWebContents(event.sender) @@ -85,29 +110,6 @@ export function registerSpeechHandlers(store: Store): void { }) }) - const getHotwordsFilePath = (content: string): string => { - const digest = createHash('sha256').update(content).digest('hex').slice(0, 12) - // sherpa-onnx cannot read non-ASCII Windows paths; use the ASCII-safe model cache for hotwords. - return join(getSpeechModelManager(store).getModelsDir(), `speech-hotwords-${digest}.txt`) - } - - const hotwordFileUsers = new Map() - const retainHotwordsFile = (path: string): ((written: boolean) => void) => { - const entry = hotwordFileUsers.get(path) ?? { users: 0, written: false } - entry.users += 1 - hotwordFileUsers.set(path, entry) - return (written) => { - entry.written ||= written - entry.users -= 1 - if (entry.users === 0) { - hotwordFileUsers.delete(path) - if (entry.written) { - unlink(path).catch(() => {}) - } - } - } - } - // Renderer run ids restart per document; a retired document's owner must not be reused by its successor. const retiredDocumentCounts = new Map() const getDesktopOwner = (senderId: number, sessionId: string): string => @@ -126,7 +128,7 @@ export function registerSpeechHandlers(store: Store): void { ipcMain.handle( 'speech:startDictation', - async (event, modelId: string, hotwords?: string[], sessionId = 'desktop') => { + async (event, modelId: string, context?: DictationContext, sessionId = 'desktop') => { const senderId = event.sender.id const owner = getDesktopOwner(senderId, sessionId) const audioPort = pendingAudioPorts.get(owner) @@ -137,8 +139,6 @@ export function registerSpeechHandlers(store: Store): void { audioPort?.close() return { directAudio } } - let resolvedHotwordsPath: string | undefined - let releaseHotwords: ((written: boolean) => void) | undefined let rendererRetired = false const rendererLifetime = abortWhenRendererGone(event.sender) let sessionListenerRemoved = false @@ -180,14 +180,6 @@ export function registerSpeechHandlers(store: Store): void { } } - if (hotwords && hotwords.length > 0) { - const content = `${hotwords.map((w) => `${w} :2.0`).join('\n')}\n` - const hotwordsFilePath = getHotwordsFilePath(content) - releaseHotwords = retainHotwordsFile(hotwordsFilePath) - await writeFile(hotwordsFilePath, content, 'utf-8') - resolvedHotwordsPath = hotwordsFilePath - } - if (rendererRetired || window.isDestroyed()) { cleanupSessionListener() return { directAudio } @@ -212,6 +204,9 @@ export function registerSpeechHandlers(store: Store): void { case 'final': window.webContents.send('speech:final', { text: msg.text ?? '', sessionId }) break + case 'speech-pending': + window.webContents.send('speech:pending', { pending: msg.pending, sessionId }) + break case 'stopped': cleanupSessionListener() window.webContents.send('speech:stopped', { sessionId }) @@ -225,7 +220,10 @@ export function registerSpeechHandlers(store: Store): void { break } }, - resolvedHotwordsPath, + dictationTermsFor(store.getSettings().voice, { + dictationTerms: context?.repoTerms, + displayName: context?.repoName + }), owner, store.getSettings().voice ) @@ -245,7 +243,6 @@ export function registerSpeechHandlers(store: Store): void { cleanupSessionListener() throw err } finally { - releaseHotwords?.(resolvedHotwordsPath !== undefined) if (!directAudio) { audioPort?.close() } diff --git a/src/main/linear/linear-issue-detail.ts b/src/main/linear/linear-issue-detail.ts index 8b5137754a7..9bcd6d107c6 100644 --- a/src/main/linear/linear-issue-detail.ts +++ b/src/main/linear/linear-issue-detail.ts @@ -7,7 +7,6 @@ import { mapRawIssueForWorkspace } from './linear-issue-query-support' import { loadLinearSdk } from './linear-sdk' type LinearIssueDetailNode = LinearIssueNode & { - project?: { id: string; name: string; url?: string | null; color?: string | null } | null children?: { nodes?: NonNullable } | null } type LinearIssueDetailResponse = { issue?: LinearIssueDetailNode | null } @@ -66,14 +65,6 @@ export async function readLinearIssueDetail( return { ...mapRawIssueForWorkspace(entry, issue), updatedAt: new Date(issue.updatedAt).toISOString(), - project: issue.project - ? { - id: issue.project.id, - name: issue.project.name, - url: issue.project.url ?? undefined, - color: issue.project.color ?? undefined - } - : undefined, subIssues: issue.children?.nodes } } diff --git a/src/main/linear/linear-issue-query-documents.ts b/src/main/linear/linear-issue-query-documents.ts index 11f4d410d74..54eacb6ac2a 100644 --- a/src/main/linear/linear-issue-query-documents.ts +++ b/src/main/linear/linear-issue-query-documents.ts @@ -28,6 +28,12 @@ export type LinearIssueNode = { name?: string | null key?: string | null } | null + project?: { + id: string + name: string + url?: string | null + color?: string | null + } | null assignee?: { id: string displayName: string @@ -85,6 +91,12 @@ export const LINEAR_ISSUE_NODE_FIELDS = ` name key } + project { + id + name + url + color + } assignee { id displayName diff --git a/src/main/linear/linear-issue-query-support.ts b/src/main/linear/linear-issue-query-support.ts index 2c4b3a4479d..b2daf98f271 100644 --- a/src/main/linear/linear-issue-query-support.ts +++ b/src/main/linear/linear-issue-query-support.ts @@ -67,6 +67,14 @@ export function mapRawIssueForWorkspace( name: issue.team?.name ?? '', key: issue.team?.key ?? '' }, + project: issue.project + ? { + id: issue.project.id, + name: issue.project.name, + url: issue.project.url ?? undefined, + color: issue.project.color ?? undefined + } + : undefined, labels: labelNodes.map((label) => label.name), // Full-replace writes need all label IDs, even when display nodes are paginated. labelIds: issue.labelIds ?? labelNodes.map((label) => label.id), diff --git a/src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts b/src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts index 9ef3706d191..f936524ddd1 100644 --- a/src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts +++ b/src/main/managed-server/migration/linking/orcad-migration-repository-link.test.ts @@ -472,20 +472,6 @@ describe('moving the host again after its server was stopped', () => { expect(groupName(server, parent.id)).toBe('Parent renamed on the server') }) - // Hiding server-owned groups must preserve inherited host ownership for later folders. - it('still moves a later folder workspace that takes its host from the server’s group', async () => { - const groupId = groupDesktopRepo() - await convert() - stopServer() - await convert() - const folder = store.createFolderWorkspace({ - projectGroupId: groupId, - folderPath: '/root/notes' - }) - await expect(runDelta()).resolves.toMatchObject({ outcome: 'moved' }) - expect(server.getFolderWorkspace(folder.id)?.projectGroupId).toBe(groupId) - }) - // Groups absent from the server still move, even when only a linked project used them. it('moves a linked project’s group the server does not hold, so later rows can use it', async () => { otherDesktopAddsSameCheckout() diff --git a/src/main/native-chat/agent-conversation-copy-error.ts b/src/main/native-chat/agent-conversation-copy-error.ts index 8924223a2a2..64fb08a76f8 100644 --- a/src/main/native-chat/agent-conversation-copy-error.ts +++ b/src/main/native-chat/agent-conversation-copy-error.ts @@ -8,6 +8,8 @@ import type { AgentSessionRefusalDetailsByCode } from '../../shared/agent-sessio /** Only copy errors authored here may pass through the host's generic provider failure. */ export class AgentConversationCopyError extends Error {} +export class AgentConversationCopyStartError extends AgentConversationCopyError {} + export function agentConversationCopyRefusal( code: C, details: NoInfer, diff --git a/src/main/native-chat/agent-session-journal/item-lifecycle/journal-prompt-body-bounds.ts b/src/main/native-chat/agent-session-journal/item-lifecycle/journal-prompt-body-bounds.ts index 34945214586..d8114bb097d 100644 --- a/src/main/native-chat/agent-session-journal/item-lifecycle/journal-prompt-body-bounds.ts +++ b/src/main/native-chat/agent-session-journal/item-lifecycle/journal-prompt-body-bounds.ts @@ -13,6 +13,7 @@ export const MAX_JOURNAL_PROMPT_OPTIONS = 64 export const MAX_JOURNAL_GROUPED_PROMPT_QUESTIONS = 4 const JOURNAL_PROMPT_OPTION_LIMITS = { inlineHeadBytes: 1024 } +const JOURNAL_PROMPT_OPTION_PREVIEW_LIMITS = { inlineHeadBytes: 8 * 1024 } // Agent prompt content permits larger bounds than client replies but must still fit settlement batches. const JOURNAL_PROMPT_TEXT_LIMITS = { inlineHeadBytes: 128 * 1024 } const JOURNAL_PROMPT_ID_MAX_BYTES = 1024 @@ -133,7 +134,10 @@ function boundPromptOptions( label: boundInlineText(option.label, JOURNAL_PROMPT_OPTION_LIMITS).text, ...(option.description === undefined ? {} - : { description: boundInlineText(option.description, JOURNAL_PROMPT_OPTION_LIMITS).text }) + : { description: boundInlineText(option.description, JOURNAL_PROMPT_OPTION_LIMITS).text }), + ...(option.preview === undefined + ? {} + : { preview: boundInlineText(option.preview, JOURNAL_PROMPT_OPTION_PREVIEW_LIMITS).text }) })) } diff --git a/src/main/native-chat/agent-session-journal/item-lifecycle/journal-prompt-preview-persistence.test.ts b/src/main/native-chat/agent-session-journal/item-lifecycle/journal-prompt-preview-persistence.test.ts new file mode 100644 index 00000000000..e4f2a12f4f8 --- /dev/null +++ b/src/main/native-chat/agent-session-journal/item-lifecycle/journal-prompt-preview-persistence.test.ts @@ -0,0 +1,96 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { + AGENT_JOURNAL_THREAD_SCOPE, + type AgentJournalQuestionItem +} from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' +import { openAgentSessionJournal } from '../journal-store-factory' +import { + closeTestJournalHostDatabases, + openTestJournalHostDatabase +} from '../store-lifecycle/journal-host-database-test-support' +import { boundJournalPromptBody, cancelledJournalPromptBody } from './journal-prompt-body-bounds' + +let root: string | undefined + +afterEach(async () => { + await closeTestJournalHostDatabases() + if (root) { + await rm(root, { recursive: true, force: true }) + } +}) + +// Control characters escape to six bytes each, so this question only fits a journal row on its own. +const CONTROL = '\u0001' +// Each preview fits the 8 KiB bound, so it must come back exactly as written. +const PREVIEWS = [1, 2, 3, 4].map((q) => + [1, 2, 3, 4].map((o) => `layout ${q}.${o}${CONTROL.repeat(8_192 - 12)}`) +) + +function largestQuestion(): AgentJournalQuestionItem { + const questions = [1, 2, 3, 4].map((q) => ({ + id: `q${q}`, + question: `Question ${q}${CONTROL.repeat(30_000)}`, + multiSelect: false, + options: [1, 2, 3, 4].map((o) => ({ + id: `q${q}:choice-${o}`, + label: `Layout ${o}`, + preview: PREVIEWS[q - 1]![o - 1]! + })) + })) + return boundJournalPromptBody({ + kind: 'question', + question: '4 grouped questions from Claude', + options: [], + questions, + resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } + }) +} + +it('saves, cancels and reopens a question whose previews make it larger than one batch', async () => { + root = await mkdtemp(join(tmpdir(), 'orca-prompt-previews-')) + const open = () => + openAgentSessionJournal({ + identity: { + sessionId: 'session-previews', + workspaceId: 'workspace-1', + hostId: 'local', + agent: 'codex', + providerHandle: codexProviderHandle('thread-1') + }, + database: openTestJournalHostDatabase(root!), + now: () => 1_000 + }) + const identity = { provider: 'orca' as const, clientMessageId: 'claude-prompt:session:req-1' } + const body = largestQuestion() + const journal = await open() + await journal.appendItem(identity, body, { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE }) + await journal.appendLifecycleBatch({ + settlementId: 'cancel-prompt', + fence: 1, + mutations: [ + { + kind: 'item', + identity, + body: cancelledJournalPromptBody(body)!, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + } + ] + }) + await journal.close() + + const reopened = await open() + const saved = reopened + .snapshot() + .items.map((item) => item.body) + .find((item): item is AgentJournalQuestionItem => item.kind === 'question') + await reopened.close() + expect(saved).toMatchObject({ kind: 'question', resolution: { state: 'cancelled' } }) + const previews = saved!.questions!.flatMap((question) => + question.options.map((option) => option.preview) + ) + expect(previews).toEqual(PREVIEWS.flat()) +}) diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts index 5c60bb1c6bc..dba1bd926a7 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork-source.ts @@ -9,7 +9,10 @@ import { type AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' -import { isAgentSessionRefusalError } from '../../../../shared/agent-session/failures/agent-session-wire-refusals' +import { + isAgentSessionRefusalError, + type AgentSessionRefusalError +} from '../../../../shared/agent-session/failures/agent-session-wire-refusals' import { isAgentSessionForkSourceAdmissionRefusal } from '../../../../shared/agent-session/failures/agent-session-definitive-refusal' import { AGENT_SESSION_FAILURE_COPY, @@ -17,6 +20,7 @@ import { } from '../../../../shared/agent-session/failures/agent-session-failure-copy' import { AgentConversationCopyError, + AgentConversationCopyStartError, agentConversationCopyRefusal } from '../../agent-conversation-copy-error' import { acpAgentName } from '../../../acp/session/acp-structured-agent-definitions' @@ -70,7 +74,7 @@ async function resolveForkSource(input: StructuredAgentSessionForkInput) { const capability = host.deps.agents.capabilities(input.agent)?.fork const { head, pendingClear } = activeProviderContext(record) const fail = ( - message: string, + message: string | AgentSessionRefusalError, reason: | 'conversationCleared' | 'rewindUnconfirmed' @@ -79,16 +83,16 @@ async function resolveForkSource(input: StructuredAgentSessionForkInput) { | 'providerRejected' | 'launchFolderMissing' = 'savedConversationMissing' ): never => { - const refusal = agentConversationCopyRefusal( - 'agent_session_operation_invalid', - { reason }, - message - ) - if (original) { + const refusal = + typeof message === 'string' + ? agentConversationCopyRefusal('agent_session_operation_invalid', { reason }, message) + : message + const failureReason = refusal.refusal.details?.reason + if (original && !(refusal.cause instanceof AgentConversationCopyStartError)) { const piece = - reason === 'savedConversationMissing' + failureReason === 'savedConversationMissing' ? 'forkOriginalMissing' - : reason === 'turnActive' + : failureReason === 'turnActive' ? 'forkOriginalLatestOnly' : 'forkOriginalUnavailable' const title = record.conversationName?.trim() diff --git a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts index ae112b21465..184a31f819a 100644 --- a/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts +++ b/src/main/native-chat/agent-session-wire/acquisition/structured-agent-session-fork.ts @@ -51,7 +51,7 @@ export async function prepareStructuredAgentSessionFork( accountHome: record.accountHome }).catch((error: unknown) => { if (isAgentSessionRefusalError(error)) { - throw error + return fail(error) } host.deps.logger.warn('native conversation copy failed', { scope: 'chat-fork', diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop-deps.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop-deps.ts index b8502b87fe4..040de3949c9 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop-deps.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop-deps.ts @@ -1,4 +1,5 @@ import type { AgentJournalSubmission } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionJournal } from '../../agent-session-journal/journal-store' import type { UnsentSendHold } from '../../agent-session-journal/queued-messages/journal-unsent-send-hold' import type { AgentChatPermissionChoice } from '../../../../shared/agent-launch/permissions/agent-chat-permission-mode' import type { StructuredAgentSessionStartFlights } from '../startup/structured-agent-session-start-flight' @@ -20,6 +21,10 @@ import type { } from '../host/structured-agent-session-host-types' export type StructuredAgentSessionDeliveryLoopDeps = { + captureTitleSourceUnavailable?: ( + sessionId: string, + journal: AgentSessionJournal + ) => (() => void) | undefined startFlights?: Pick deliveryOrder: StructuredAgentSessionDeliveryOrder sessions: ReadonlyMap diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop.ts index 392fab76744..584b12e8095 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-delivery-loop.ts @@ -299,6 +299,10 @@ export class StructuredAgentSessionDeliveryLoop { /** Clear under serialization so the next accept can wake a new loop. */ private stop(sessionId: string): 'stop' { + const journal = this.deps.sessions.get(sessionId)?.journal + if (journal && this.running.has(sessionId)) { + this.deps.captureTitleSourceUnavailable?.(sessionId, journal)?.() + } this.running.delete(sessionId) this.deps.deliveryOrder.parkSends(sessionId) return 'stop' diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-host-delivery.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-host-delivery.ts index 4d22aeb5e8a..7537b242ae6 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-host-delivery.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-host-delivery.ts @@ -87,6 +87,8 @@ export function createStructuredAgentSessionConversationDelivery(input: { > }): StructuredAgentSessionConversationDelivery { const { deps, sessions } = input + const captureTitleSourceUnavailable = (sessionId: string, journal: AgentSessionJournal) => + deps.conversationNaming?.captureTitleSourceUnavailable?.(sessionId, journal) const retainedWork = (sessionId: string, continuingId?: string) => ({ currentWork: () => hostStructuredAgentSessionCurrentWork({ store: deps.store, sessions }, sessionId), @@ -101,6 +103,7 @@ export function createStructuredAgentSessionConversationDelivery(input: { [...(sessions.get(sessionId)?.child?.heldSends?.() ?? [])].some((id) => id !== continuingId) }) const loop = new StructuredAgentSessionDeliveryLoop({ + captureTitleSourceUnavailable, sessions, adapter: deps.adapter, agents: deps.agents, @@ -239,13 +242,19 @@ export function createStructuredAgentSessionConversationDelivery(input: { const wakesQueued = new Set() const afterCommit = (sessionId: string, journal: AgentSessionJournal): void => { input.deliveryOrder.reconcile(sessionId, journal) + if (wakesQueued.has(sessionId)) { + return + } + const sourceUnavailable = captureTitleSourceUnavailable(sessionId, journal) const work = hostStructuredAgentSessionCurrentWork({ store: deps.store, sessions }, sessionId) if ( - wakesQueued.has(sessionId) || !work || structuredAgentSessionCommandRunning(work) || !selectableStructuredSubmission(journal, work) ) { + if (!loop.isRunning(sessionId)) { + sourceUnavailable?.() + } return } wakesQueued.add(sessionId) @@ -256,6 +265,7 @@ export function createStructuredAgentSessionConversationDelivery(input: { }) .catch((error: unknown) => { wakesQueued.delete(sessionId) + sourceUnavailable?.() deps.logger.warn('waking the delivery loop after a commit failed', { scope: 'delivery-wake', sessionId, diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversations.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversations.ts index dba13c59687..69faf212bc2 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversations.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-conversations.ts @@ -138,7 +138,10 @@ export class StructuredAgentSessionConversations extends Map< return adopted } - observeConversationPublications(sessionId: string, observer: PublicationObserver): () => void { + observeConversationPublications = ( + sessionId: string, + observer: PublicationObserver + ): (() => void) => { if (this.ended) { this.deliverHint(observer, { kind: 'end', source: null, journal: null }, () => {}) return () => {} diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts index 47a2ed7ede4..9673d8f4f10 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts @@ -245,6 +245,10 @@ export type SetUserConversationName = StructuredAgentSessionConversationNaming[' export type StructuredChatNamingFailure = AgentSessionNamingError & { forName: string } export type StructuredAgentSessionConversationNaming = { + captureTitleSourceUnavailable?: ( + sessionId: string, + journal: AgentSessionJournal + ) => (() => void) | undefined publishName: (workspaceId: string, sessionId: string) => void activeSessionIds: () => string[] failure: (sessionId: string) => StructuredChatNamingFailure | undefined diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts index 2413f4f7a98..1d4ed8ab39b 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host.ts @@ -304,9 +304,9 @@ export class StructuredAgentSessionHost { readonly continuationContext: ReturnType - observeConversationPublications: typeof this.sessions.observeConversationPublications = ( - ...args - ) => this.sessions.observeConversationPublications(...args) + observeConversationPublications = this.sessions.observeConversationPublications + beginConversationTitleWait = (sessionId: string) => + this.runtimeState.acquireAborts.begin(sessionId) journalSnapshot = (sessionId: string) => this.backgroundTasks.journalSnapshot(sessionId) journalCurrentRead = this.reads.journalCurrentRead queuedSendAnswer = this.reads.queuedSendAnswer diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture.ts index 49d54ab848a..8bd8ec50fd5 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig-provider.test-fixture.ts @@ -1,5 +1,5 @@ import type { AgentMessageSource } from '../../../../../shared/agent-session/agent-session-message-source' -import { vi, type Mock } from 'vitest' +import { expect, vi, type Mock } from 'vitest' import { parseAgentJournalItemKey } from '../../../../../shared/agent-session/journal/agent-session-journal-item-key' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../../shared/agent-session/journal/agent-session-journal-types' import { activeProviderContext } from '../../../../../shared/agent-session/agent-session-provider-context' @@ -35,6 +35,18 @@ export type QueuedRigProviderOptions = { /** How long a winding-down child is given after the interrupt before the Stop ends it. */ export const QUEUED_RIG_STOP_GRACE_MS = 2_000 +export async function proveQueuedRigStart( + host: StructuredAgentSessionHost, + sessionId: string, + proveOpen: () => void +): Promise { + await eventually(() => + expect(host.collaboratorsForTests().sessions.get(sessionId)?.child?.phase).toBe('starting') + ) + proveOpen() + await Promise.resolve() +} + export function createQueuedRigProvider( store: Pick, options: QueuedRigProviderOptions, diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture.ts index d5bc36ec59d..7325f03f268 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture.ts @@ -32,11 +32,13 @@ import { seedQueuedRigLegacyJournal } from './structured-agent-session-queued-le import { createStructuredAgentSessionLogger } from '../structured-agent-session-logger' import { createQueuedRigProvider, + proveQueuedRigStart, eventually, type RigSendOptions, type QueuedRigProviderOptions } from './structured-agent-session-queued-message-rig-provider.test-fixture' import { claudeAndCodexDeclared } from '../../providers/testing/structured-agent-session-adapter-router-test-support' +import { createTestParams } from './structured-agent-session-create-test-fixture' export const QUEUED_RIG_CALLER = { callerKey: 'client-1' } export type QueuedMessageTestRig = Awaited> @@ -44,6 +46,7 @@ export type QueuedMessageTestRig = Awaited number @@ -97,7 +100,11 @@ export async function createQueuedMessageTestRig( : {}) }) const pinLegacy = options.legacyInputs && seedQueuedRigLegacyJournal(root, SESSION, options.agent) - expect(await host.attach(QUEUED_RIG_CALLER, firstAttach)).toMatchObject({ ok: true }) + expect( + options.atRest + ? await host.create(QUEUED_RIG_CALLER, createTestParams(undefined, firstAttach)) + : await host.attach(QUEUED_RIG_CALLER, firstAttach) + ).toMatchObject({ ok: true }) if (pinLegacy) { pinLegacy(host) } @@ -274,14 +281,6 @@ export async function createQueuedMessageTestRig( }) } - async function proveStart(): Promise { - await eventually(() => - expect(host.collaboratorsForTests().sessions.get(SESSION)?.child?.phase).toBe('starting') - ) - provider.proveOpen() - await Promise.resolve() - } - async function dispose(): Promise { await host.flushAllStreamedEvents() await closeTestJournalHostDatabase(root) @@ -325,7 +324,7 @@ export async function createQueuedMessageTestRig( queuePause, restartOffers, resume, - proveStart, + proveStart: () => proveQueuedRigStart(host, SESSION, provider.proveOpen), dispose } } diff --git a/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-queue.ts b/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-queue.ts index 40c82e530c5..777553f8c7f 100644 --- a/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-queue.ts +++ b/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-queue.ts @@ -49,6 +49,7 @@ export class StructuredAgentSessionSinkQueue { private readonly buffered: Admitted[] = [] private readonly waitingPublications = new Map() private readonly waiters: StructuredAgentSessionDrainWaiter[] = [] + private readonly boundListeners = new Set<() => void>() constructor( private readonly deps: { @@ -76,6 +77,16 @@ export class StructuredAgentSessionSinkQueue { journalLinkage = (): StructuredAgentSessionLinkageJournal | null => this.target?.journal ?? null + onJournalBound = (listener: () => void): (() => void) => { + if (!this.closed) { + this.boundListeners.add(listener) + if (this.target) { + listener() + } + } + return () => this.boundListeners.delete(listener) + } + journalHistory = (): StructuredAgentSessionHistoryJournal | null => this.target?.journal ?? null journalItems = (): StructuredAgentSessionTransitionJournal | null => this.target?.journal ?? null @@ -104,6 +115,13 @@ export class StructuredAgentSessionSinkQueue { for (const operation of this.buffered.splice(0)) { this.handOver(operation, target) } + for (const listener of this.boundListeners) { + try { + listener() + } catch (error) { + this.fail(error) + } + } } unbind(): void { @@ -112,6 +130,7 @@ export class StructuredAgentSessionSinkQueue { close(): void { this.closed = true + this.boundListeners.clear() this.dropBuffered() this.updateBackpressure() } diff --git a/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink.ts b/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink.ts index 1f3fec98a57..31a4e93c384 100644 --- a/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink.ts +++ b/src/main/native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink.ts @@ -125,6 +125,8 @@ export type StructuredAgentSessionEventSink = StructuredAgentSessionTransitionSi ): StructuredAgentSessionSinkAdmission journalEpoch?(): string | null journalLinkage?(): StructuredAgentSessionLinkageJournal | null + /** Deferred sinks notify after binding; an already-bound listener runs immediately. */ + onJournalBound?(listener: () => void): () => void journalHistory?(): StructuredAgentSessionHistoryJournal | null /** Apply the journal’s personal-Stop cancellation rule; false until bound. */ journalStopDecidesTurn?(turnId: string, endedAt: number): boolean @@ -268,6 +270,7 @@ export function createDeferredStructuredAgentSessionEventSink(deps: { ...createStructuredAgentSessionTransitionMembers(queue), journalEpoch: queue.journalEpoch, journalLinkage: queue.journalLinkage, + onJournalBound: queue.onJournalBound, journalHistory: queue.journalHistory, journalStopDecidesTurn: queue.journalStopDecidesTurn, appendLifecycleBatch: (settlementId, mutations) => { diff --git a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-usage-limit-chain.test.ts b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-usage-limit-chain.test.ts index f7bb5197d1b..69919de597b 100644 --- a/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-usage-limit-chain.test.ts +++ b/src/main/native-chat/agent-session-wire/observations/structured-agent-session-status-usage-limit-chain.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' import { agentSessionFailureFact } from '../../../../shared/agent-session/failures/agent-session-failure' import { agentSessionFailureWords } from '../../../../shared/agent-session/failures/agent-session-failure-words' @@ -8,44 +8,13 @@ import { agentJournalItemKey, agentJournalSubmissionKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key' -import type * as UsageLimitChain from '../recovery/structured-agent-session-usage-limit-chain' import { - hostUsageLimitCut, usageLimitContinueMessageId, usageLimitContinueTag } from '../recovery/structured-agent-session-usage-limit-chain' -import { - chainReads, - countedItems, - countedSubmissions -} from '../recovery/structured-agent-session-usage-limit-chain-reads-test-support' import { StructuredAgentSessionJournalProjections } from './structured-agent-session-status-journal-projection' -let reads = chainReads() -vi.mock('../recovery/structured-agent-session-usage-limit-chain', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - hostUsageLimitCut: vi.fn((...[snapshot, cut]: Parameters) => - actual.hostUsageLimitCut( - { - items: countedItems(snapshot.items, reads), - submissions: countedSubmissions(snapshot.submissions, reads) - }, - cut - ) - ) - } -}) - const fixture = createFixture() -let measured = 0 -const derivations = () => - vi.mocked(hostUsageLimitCut).mock.calls.filter(([, cut]) => cut !== null).length -beforeEach(() => { - vi.mocked(hostUsageLimitCut).mockClear() - reads = chainReads() -}) async function limitedTurn( journal: AgentSessionJournal, @@ -115,58 +84,9 @@ async function hostContinue( return clientMessageId } -async function personTurn(journal: AgentSessionJournal, name: string) { - const clientMessageId = `person-${name}` - await journal.appendSubmission({ - clientMessageId, - payloadFingerprint: clientMessageId, - body: { kind: 'message', role: 'user', blocks: [] }, - origin: 'client', - fence: 1 - }) - await journal.resolveDispatch({ - clientMessageId, - state: 'accepted', - providerIdentity: null, - fence: 1 - }) - await journal.appendItem( - { provider: 'orca', clientMessageId: `turn-${name}` }, - { - kind: 'turn', - turnId: name, - state: 'completed', - outcome: 'success', - completedAt: 1, - userItemId: agentJournalSubmissionKey(clientMessageId) - }, - { fence: 1, turnScope: AGENT_JOURNAL_THREAD_SCOPE } - ) -} - -/** A person's limited turn of `rows` rows and one automatic continue that hit the limit again after `rows` more. - * `olderRows` puts a long earlier turn first, and the person's turn is then opened by the agent's echo. */ -async function chainOfOne(journal: AgentSessionJournal, rows: number, olderRows?: number) { - let opened: { userItemId?: string } = {} - if (olderRows !== undefined) { - await limitedTurn(journal, 'older', olderRows) - const echo = { provider: 'orca' as const, clientMessageId: 'provider-echo-root' } - await journal.appendSubmission({ - clientMessageId: 'person-root', - payloadFingerprint: 'person-root', - body: { kind: 'message', role: 'user', blocks: [] }, - origin: 'client', - fence: 1 - }) - await journal.resolveDispatch({ - clientMessageId: 'person-root', - state: 'accepted', - providerIdentity: echo, - fence: 1 - }) - opened = { userItemId: agentJournalItemKey(echo) } - } - const first = await limitedTurn(journal, 'first', rows, opened) +/** A limited turn and one automatic continue that hits the limit again. */ +async function chainOfOne(journal: AgentSessionJournal, rows: number) { + const first = await limitedTurn(journal, 'first', rows) const sent = await hostContinue( journal, { turnItemId: first.turnScope.turnItemId, resetsAt: 60_000 }, @@ -184,76 +104,6 @@ async function chainOfOne(journal: AgentSessionJournal, rows: number, olderRows? }) } -it('derives the chain only when the status projection rebuilds', async () => { - const journal = await fixture.open() - const projections = new StructuredAgentSessionJournalProjections() - const cut = await chainOfOne(journal, 0) - expect(projections.read(journal, null).usageLimitCut?.chain).toBe(1) - projections.read(journal, null) - expect(derivations()).toBe(1) - await journal.appendItem( - { provider: 'orca', clientMessageId: 'late' }, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'late' }] }, - cut - ) - expect(projections.read(journal, null).usageLimitCut?.chain).toBe(1) - expect(derivations()).toBe(2) -}) - -// Bounds come from what the walk must read: the chain's own turns once each way, never the history before it. -it('reads the chain tail linearly, whatever history precedes it', async () => { - const measure = async (history: number, rows: number, olderRows?: number) => { - const journal = await fixture.open({ - identity: { ...fixture.IDENTITY, sessionId: `measure-${(measured += 1)}` } - }) - for (let index = 0; index < history; index += 1) { - await personTurn(journal, `old-${index}`) - } - await chainOfOne(journal, rows, olderRows) - reads = chainReads() - const chain = new StructuredAgentSessionJournalProjections().read(journal, null).usageLimitCut - ?.chain - return { chain, total: reads.total } - } - const short = await measure(50, 0) - const long = await measure(500, 0) - expect([short.chain, long.chain]).toEqual([1, 1]) - expect(long.total).toBe(short.total) - // An echo-opened root names a key no row carries; its opener is still found without reading the turn before. - const echoed = await measure(0, 0, 50) - const echoedLong = await measure(0, 0, 500) - expect([echoed.chain, echoedLong.chain]).toEqual([1, 1]) - expect(echoedLong.total).toBe(echoed.total) - const rows = await measure(0, 200) - const tenfold = await measure(0, 2_000) - expect([rows.chain, tenfold.chain]).toEqual([1, 1]) - // Each of the two turns' rows is read a few fields at a time on one pass back and one pass forward. - expect(tenfold.total).toBeLessThanOrEqual(10 * 2 * 2_000 + short.total) - expect(tenfold.total - short.total).toBeLessThanOrEqual(10 * (rows.total - short.total) + 50) -}) - -it('scans the sends once when the turn opener matches none of them', async () => { - const measure = async (sends: number) => { - const journal = await fixture.open({ - identity: { ...fixture.IDENTITY, sessionId: `measure-${(measured += 1)}` } - }) - for (let index = 0; index < sends; index += 1) { - await personTurn(journal, `old-${index}`) - } - await limitedTurn(journal, 'unmatched', 0, { userItemId: 'provider-echo-never-attributed' }) - reads = chainReads() - const chain = new StructuredAgentSessionJournalProjections().read(journal, null).usageLimitCut - ?.chain - return { chain, total: reads.total } - } - const few = await measure(50) - const many = await measure(500) - expect([few.chain, many.chain]).toEqual([0, 0]) - // Two fields of each send are compared to the opener, newest first, and nothing is read twice. - expect(many.total).toBeLessThanOrEqual(2 * 500 + 20) - expect(many.total - few.total).toBeLessThanOrEqual(2 * 450) -}) - it('stops counting a link when its earlier usage limit is revised to another reset', async () => { const journal = await fixture.open() const projections = new StructuredAgentSessionJournalProjections() diff --git a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts index 3427d6bf0c6..492ff9bc30c 100644 --- a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts +++ b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter-router.ts @@ -96,6 +96,9 @@ export class StructuredAgentSessionAdapterRouter implements Adapter { } } + captureConversationTitleOwner: NonNullable = (record) => + this.liveOwnerOrNull(record.sessionId)?.captureConversationTitleOwner?.(record) ?? null + renameProviderSession: NonNullable = (input) => this.capabilityOwner( input.record.sessionId, diff --git a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts index d327cb5c9d3..31a3adcbf6b 100644 --- a/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts +++ b/src/main/native-chat/agent-session-wire/providers/structured-agent-session-adapter.ts @@ -347,6 +347,10 @@ export type StructuredAgentSessionAdapter = StructuredAgentSessionAdapterStop & inheritance?: boolean }): Promise | undefined stopProviderNaming?(): void + captureConversationTitleOwner?(record: AgentSessionRecord): { + isCurrent: (record: AgentSessionRecord) => boolean + generate: (firstPrompt: string, shouldExecute: () => boolean) => Promise + } | null /** True proves child exit; root/processless verdicts throw only after finalization (stopAgentSessionProviderRoot). */ closeSession?( sessionId: string, diff --git a/src/main/native-chat/agent-session-wire/publication/history/agent-session-history-subagent-roster.test.ts b/src/main/native-chat/agent-session-wire/publication/history/agent-session-history-subagent-roster.test.ts new file mode 100644 index 00000000000..57c49408903 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/publication/history/agent-session-history-subagent-roster.test.ts @@ -0,0 +1,43 @@ +import { expect, it } from 'vitest' +import type { AgentJournalRenderItem } from '../../../../../shared/agent-session/journal/agent-session-journal-types' +import { offPageSubagentRoster } from './agent-session-history-subagent-roster' + +it('supplies the off-page owner name for a page containing only its shell task', () => { + const entry = { id: 'owner', label: 'Audit', state: 'stopped' as const } + const owner: AgentJournalRenderItem = { + itemId: 'owner-row', + sequence: 1, + revision: 1, + observedAt: 1, + turnScope: { kind: 'thread' }, + body: { + kind: 'message', + role: 'assistant', + blocks: [{ ...entry, type: 'subagent', groupId: 'turn' }] + } + } + const shell: AgentJournalRenderItem = { + itemId: 'shell-row', + sequence: 2, + revision: 1, + observedAt: 2, + turnScope: { kind: 'thread' }, + agentId: 'shell', + parentAgentId: 'owner', + producerKind: 'background', + body: { + kind: 'message', + role: 'assistant', + blocks: [ + { + type: 'background-task', + taskId: 'shell', + kind: 'command', + label: 'sleep', + state: 'working' + } + ] + } + } + expect(offPageSubagentRoster([owner, shell], [shell])).toMatchObject([{ entry }]) +}) diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain-reads-test-support.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain-reads-test-support.ts deleted file mode 100644 index c98141d2f98..00000000000 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain-reads-test-support.ts +++ /dev/null @@ -1,71 +0,0 @@ -import type { - AgentJournalRenderItem, - AgentJournalSubmission -} from '../../../../shared/agent-session/journal/agent-session-journal-types' - -type ChainSubmission = Pick - -/** What a chain derivation looked at: distinct rows and submissions, and every field read in total. */ -export type ChainReads = { visited: Set; total: number } - -export const chainReads = (): ChainReads => ({ visited: new Set(), total: 0 }) - -/** Rows the derivation looks at: each read of a row's fields counts, and marks that row visited. */ -export function countedItems( - items: readonly AgentJournalRenderItem[], - reads: ChainReads -): AgentJournalRenderItem[] { - return items.map((item, index) => { - const mark = () => { - reads.visited.add(`item-${index}`) - reads.total += 1 - } - return { - revision: item.revision, - sequence: item.sequence, - observedAt: item.observedAt, - get itemId() { - mark() - return item.itemId - }, - get body() { - mark() - return item.body - }, - get turnScope() { - mark() - return item.turnScope - }, - get agentId() { - mark() - return item.agentId - } - } - }) -} - -export function countedSubmissions( - submissions: readonly ChainSubmission[], - reads: ChainReads -): ChainSubmission[] { - return submissions.map((submission, index) => { - const mark = () => { - reads.visited.add(`submission-${index}`) - reads.total += 1 - } - return { - get clientMessageId() { - mark() - return submission.clientMessageId - }, - get providerItemId() { - mark() - return submission.providerItemId - }, - get origin() { - mark() - return submission.origin - } - } - }) -} diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.test.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.test.ts index 2cd900f2e50..a7acfc1f53f 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.test.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-chain.test.ts @@ -11,11 +11,6 @@ import { usageLimitContinueMessageId, usageLimitContinueTag } from './structured-agent-session-usage-limit-chain' -import { - chainReads, - countedItems, - countedSubmissions -} from './structured-agent-session-usage-limit-chain-reads-test-support' type Submission = Pick @@ -69,26 +64,6 @@ function conversation(history: number, links: number) { return { items, submissions, cut } } -it('reads only the chain, never the older conversation, at N and 10N rows of history', () => { - const measure = (history: number) => { - const { items, submissions, cut } = conversation(history, 3) - const reads = chainReads() - const chain = usageLimitContinueChain( - countedItems(items, reads), - countedSubmissions(submissions, reads), - cut - ) - return { chain, reads: reads.visited.size } - } - const small = measure(1_000) - const large = measure(10_000) - expect(small.chain).toBe(3) - expect(large.chain).toBe(3) - // Three links of a send row, a turn and its limit row, plus the person's limited turn before them. - expect(large.reads).toBe(small.reads) - expect(small.reads).toBeLessThanOrEqual(40) -}) - it('counts a continue across a slash-command turn run after the cut it answers', () => { const { items, submissions, cut } = conversation(2, 1) // A /compact between the person's limited turn and the automatic continue, as the latest-turn read skips it. diff --git a/src/main/native-chat/structured-chat-name-publication.ts b/src/main/native-chat/structured-chat-name-publication.ts new file mode 100644 index 00000000000..f344d0fc605 --- /dev/null +++ b/src/main/native-chat/structured-chat-name-publication.ts @@ -0,0 +1,50 @@ +import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { StructuredChatNamingDeps } from './structured-chat-naming' + +export async function runStructuredChatNameGeneration(input: { + automaticTitle?: Parameters[3] + getRecord: () => AgentSessionRecord | null | undefined + applicable: (current?: AgentSessionRecord) => boolean + generate: ( + stillCurrent: () => boolean, + automaticTitle?: Parameters[3] + ) => Promise<{ name: string; shouldApply?: (record?: AgentSessionRecord) => boolean } | null> + setName: ( + name: string, + applicable: (record: AgentSessionRecord) => boolean + ) => Promise +}): Promise { + let owner: ((record: AgentSessionRecord) => boolean) | undefined + const stillCurrent = (latest?: AgentSessionRecord) => { + const record = latest ?? input.getRecord() + return !!record && input.applicable(record) && (owner?.(record) ?? true) + } + if (!stillCurrent()) { + return + } + const name = await input.generate( + stillCurrent, + input.automaticTitle + ? { + ...input.automaticTitle, + retainOwnership: (check) => { + owner = check + } + } + : undefined + ) + if (!name || !stillCurrent()) { + return + } + const named = await input.setName( + name.name, + (current) => stillCurrent(current) && (name.shouldApply?.(current) ?? true) + ) + // Independent fallback retains the canonical name/context owner; only timeout retains live ownership. + if (!named && name.shouldApply && stillCurrent()) { + const fallback = await input.generate(stillCurrent) + if (fallback && stillCurrent()) { + await input.setName(fallback.name, stillCurrent) + } + } +} diff --git a/src/main/native-chat/structured-chat-naming-title.test.ts b/src/main/native-chat/structured-chat-naming-title.test.ts new file mode 100644 index 00000000000..c83dbaab30a --- /dev/null +++ b/src/main/native-chat/structured-chat-naming-title.test.ts @@ -0,0 +1,134 @@ +import { expect, it, vi } from 'vitest' +import { + createStructuredChatNamingHandler, + type StructuredChatNamingDeps +} from './structured-chat-naming' +import { agentSessionRecordFixture } from './agent-session-record-test-fixture' +import { + compareAndSetAgentSessionRecordName, + setAgentSessionRecordUserName +} from '../runtime/agent-session/records/agent-session-record-conversation-name' + +function rig( + generate: StructuredChatNamingDeps['generate'], + captureAutomaticTitle: StructuredChatNamingDeps['captureAutomaticTitle'] = () => ({ owner: null }) +) { + let record = agentSessionRecordFixture({ sessionId: 'chat-1' }) + let beforeWrite: (() => Promise) | undefined + const handler = createStructuredChatNamingHandler({ + getStore: () => ({ + getRecord: () => record, + compareAndSetConversationName: async (_id, name, expected, context, applicable) => + compareAndSetAgentSessionRecordName( + async (apply) => { + if (expected !== null) { + await beforeWrite?.() + } + record = apply(record) + return record + }, + name, + expected, + context, + applicable + ), + setUserConversationName: async (_id, name, write) => { + const result = setAgentSessionRecordUserName(record, name, write, 1) + record = result.record + return result + } + }), + getSettings: () => ({ nativeChatAutoName: true }), + readFirstPrompt: async () => 'Repair login', + readJournalFirstPrompt: async () => 'Repair login', + workerTaskTitle: () => null, + generate, + captureAutomaticTitle, + wait: async () => {}, + onNamed: () => {}, + logger: { warn: vi.fn(), error: vi.fn() } + }) + return { + handler, + record: () => record, + beforeWrite: (run: () => Promise) => { + beforeWrite = run + }, + start: () => + handler( + { + sessionId: 'chat-1', + workspaceId: 'workspace-1', + agent: 'claude', + status: 'working', + latestPrompt: 'Repair login', + updatedAt: 1 + }, + { replay: false, firstInputSubmissionKey: 'input-1' } + ), + done: () => vi.waitFor(() => expect(handler.activeSessionIds()).toEqual([])) + } +} + +it('tries CLI reuse once while independent generation retries, and skips it on manual regeneration', async () => { + const reuse = vi.fn() + const generate = vi.fn( + async (_record, _prompt, _current, automatic) => { + if (automatic) { + reuse() + } + return generate.mock.calls.length === 1 + ? { error: 'Retry independent generation' } + : { name: 'Login repair' } + } + ) + const state = rig(generate) + state.start() + await state.done() + expect(state.record().conversationName).toBe('Login repair') + expect(reuse).toHaveBeenCalledOnce() + state.handler.regenerate('chat-1') + await state.done() + expect(reuse).toHaveBeenCalledOnce() +}) + +it.each(['owner', 'same-text rename'] as const)( + 'rejects a queued title write after %s changes', + async (change) => { + let owned = true + const state = rig( + async (_record, _prompt, _current, automatic) => + automatic ? { name: 'CLI title', shouldApply: () => owned } : { name: 'Independent title' }, + () => ({ + owner: { isCurrent: () => owned, generate: async () => null } + }) + ) + state.beforeWrite(async () => { + if (change === 'owner') { + owned = false + } else { + await state.handler.setUserName('chat-1', 'Repair login', 'rename') + } + }) + state.start() + await state.done() + expect(state.record().conversationName).toBe( + change === 'owner' ? 'Independent title' : 'Repair login' + ) + } +) + +it('uses current naming settings if they change while the title write is queued', async () => { + let eligible = true + const generate = vi.fn( + async (_record, _prompt, _current, automatic) => + automatic ? { name: 'CLI title', shouldApply: () => eligible } : { name: 'Configured title' } + ) + const state = rig(generate) + state.beforeWrite(async () => { + eligible = false + }) + state.start() + await state.done() + expect(state.record().conversationName).toBe('Configured title') +}) diff --git a/src/main/native-chat/structured-chat-naming-types.ts b/src/main/native-chat/structured-chat-naming-types.ts new file mode 100644 index 00000000000..9f8b4c8fb34 --- /dev/null +++ b/src/main/native-chat/structured-chat-naming-types.ts @@ -0,0 +1,52 @@ +import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { GlobalSettings } from '../../shared/global-settings-types' +import type { AgentSessionRecordStore } from '../runtime/agent-session/records/agent-session-record-store' +import type { AgentGenerationFailureOutput } from '../text-generation/agent-failure-output' +import type { StructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' +import type { StructuredAgentSessionAdapter } from './agent-session-wire/providers/structured-agent-session-adapter' +import type { AgentSessionJournal } from './agent-session-journal/journal-store' + +export type AutomaticChatTitle = { + owner: ReturnType> + pending?: { + ready: Promise + ended: () => boolean + recheck: () => void + unavailable: (journal: AgentSessionJournal) => void + dispose: () => void + } + retainOwnership?: (isCurrent: (record: AgentSessionRecord) => boolean) => void +} + +/** null means unavailable/canceled: no failure to display or retry. */ +export type StructuredChatNameGeneration = + | { name: string; shouldApply?: (record?: AgentSessionRecord) => boolean } + | { error: string; errorCode?: string; failureOutput?: AgentGenerationFailureOutput } + | null + +export type StructuredChatNamingDeps = { + getStore: () => Pick< + AgentSessionRecordStore, + 'getRecord' | 'compareAndSetConversationName' | 'setUserConversationName' + > | null + getSettings: () => Pick + readFirstPrompt: (sessionId: string, hostStartedAt: number) => Promise + /** The current context's first prompt, for a name the user asked for again. */ + readJournalFirstPrompt: (sessionId: string) => Promise + now?: () => number + workerTaskTitle: (record: AgentSessionRecord) => { title: string } | null + captureAutomaticTitle?: ( + record: AgentSessionRecord, + firstInputSubmissionKey?: string, + applicable?: () => boolean + ) => AutomaticChatTitle | undefined + generate: ( + record: AgentSessionRecord, + firstPrompt: string, + shouldExecute?: () => boolean, + automaticTitle?: AutomaticChatTitle + ) => Promise + onNamed: (workspaceId: string, sessionId: string) => void + logger: StructuredAgentSessionLogger + wait?: (ms: number) => Promise +} diff --git a/src/main/native-chat/structured-chat-naming-work.ts b/src/main/native-chat/structured-chat-naming-work.ts index 0772d0f3446..c3a9ab0f345 100644 --- a/src/main/native-chat/structured-chat-naming-work.ts +++ b/src/main/native-chat/structured-chat-naming-work.ts @@ -1,8 +1,45 @@ import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import type { AutomaticChatTitle, StructuredChatNamingDeps } from './structured-chat-naming-types' +import type { AgentSessionJournal } from './agent-session-journal/journal-store' -export type NamingRequest = { record: AgentSessionRecord; automatic: boolean; firstPrompt?: string } +export type NamingRequest = { + record: AgentSessionRecord + automatic: boolean + firstPrompt?: string + automaticTitle?: AutomaticChatTitle + seedingName?: string | null +} type NamingJob = { desired?: NamingRequest; executing?: NamingRequest; preparing: boolean } +export function namingRequestOwnsRecord(request: NamingRequest, current: AgentSessionRecord) { + return ( + !request.automaticTitle?.pending?.ended() && + current.conversationNameSource !== 'user' && + (current.conversationName === request.record.conversationName || + (request.seedingName !== undefined && current.conversationName === request.seedingName)) && + (current.providerContextBoundary?.operationId ?? null) === + (request.record.providerContextBoundary?.operationId ?? null) + ) +} + +export function automaticChatNamingRequest( + deps: StructuredChatNamingDeps, + record: AgentSessionRecord, + firstInputSubmissionKey: string | undefined, + applicable: (request: NamingRequest) => boolean +): NamingRequest { + const request: NamingRequest = { record, automatic: true } + if ( + record.conversationName === undefined && + !(!record.providerContextBoundary && deps.workerTaskTitle(record)) + ) { + request.automaticTitle = deps.captureAutomaticTitle?.(record, firstInputSubmissionKey, () => + applicable(request) + ) + } + return request +} + export function createStructuredChatNamingWork(deps: { applicable: (request: NamingRequest) => boolean prepare: (request: NamingRequest) => Promise @@ -21,6 +58,7 @@ export function createStructuredChatNamingWork(deps: { .execute(request, firstPrompt) .catch((error: unknown) => deps.warn(sessionId, error)) .finally(() => { + request.automaticTitle?.pending?.dispose() job.executing = undefined drain(sessionId, job) deps.changed(request.record) @@ -31,7 +69,8 @@ export function createStructuredChatNamingWork(deps: { } } return { - run(record: AgentSessionRecord, automatic: boolean) { + run(request: NamingRequest) { + const { record, automatic } = request const { sessionId } = record const job: NamingJob = jobs.get(sessionId) ?? { preparing: false } const pending = job.desired ?? job.executing @@ -42,9 +81,12 @@ export function createStructuredChatNamingWork(deps: { record.providerContextBoundary?.operationId && !(automatic && !pending.automatic && pending.firstPrompt === undefined) ) { + request.automaticTitle?.pending?.dispose() return } - job.desired = { record, automatic } + job.desired?.automaticTitle?.pending?.dispose() + job.executing?.automaticTitle?.pending?.dispose() + job.desired = request jobs.set(sessionId, job) if (!job.preparing) { job.preparing = true @@ -53,10 +95,14 @@ export function createStructuredChatNamingWork(deps: { const request = job.desired try { const prepared = await deps.prepare(request) + if (!prepared) { + request.automaticTitle?.pending?.dispose() + } if (job.desired === request) { job.desired = prepared ?? undefined } } catch (error) { + request.automaticTitle?.pending?.dispose() if (job.desired === request) { job.desired = undefined } @@ -73,6 +119,23 @@ export function createStructuredChatNamingWork(deps: { } deps.changed(record) }, + recheck(sessionId: string) { + const job = jobs.get(sessionId) + job?.desired?.automaticTitle?.pending?.recheck() + job?.executing?.automaticTitle?.pending?.recheck() + }, + captureSourceUnavailable(sessionId: string, journal: AgentSessionJournal) { + const job = jobs.get(sessionId) + const desired = job?.desired?.automaticTitle?.pending + const executing = job?.executing?.automaticTitle?.pending + if (!desired && !executing) { + return undefined + } + return () => { + desired?.unavailable(journal) + executing?.unavailable(journal) + } + }, activeSessionIds: () => [...jobs] .filter( diff --git a/src/main/native-chat/structured-chat-naming.ts b/src/main/native-chat/structured-chat-naming.ts index 98604d411f9..ec4e230b256 100644 --- a/src/main/native-chat/structured-chat-naming.ts +++ b/src/main/native-chat/structured-chat-naming.ts @@ -1,5 +1,19 @@ +import type { + StructuredChatNameGeneration, + StructuredChatNamingDeps +} from './structured-chat-naming-types' +export type { + StructuredChatNameGeneration, + StructuredChatNamingDeps +} from './structured-chat-naming-types' +import { runStructuredChatNameGeneration } from './structured-chat-name-publication' import { chatNamingFailure } from '../../shared/chat-naming-failure-copy' -import { createStructuredChatNamingWork, type NamingRequest } from './structured-chat-naming-work' +import { + automaticChatNamingRequest, + createStructuredChatNamingWork, + namingRequestOwnsRecord, + type NamingRequest +} from './structured-chat-naming-work' import type { StructuredAgentSessionStatusObserverOptions } from './agent-session-wire/observations/structured-agent-session-status-observation' import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' @@ -9,8 +23,6 @@ import { } from '../../shared/source-control/ai/generation/conversation-name-generation' import { hasStructuredChatPromptText } from '../../shared/agent-session/requests/structured-agent-session-first-prompt' import { sliceAtCodeUnitLimit } from '../../shared/surrogate-safe-text-slice' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { AgentSessionRecordStore } from '../runtime/agent-session/records/agent-session-record-store' import { formatAgentGenerationFailureOutputForDisplay, type AgentGenerationFailureOutput @@ -19,37 +31,7 @@ import type { StructuredAgentSessionConversationNaming, StructuredChatNamingFailure } from './agent-session-wire/host/structured-agent-session-host-types' -import { - neverThrowingStructuredAgentSessionLogger, - type StructuredAgentSessionLogger -} from './agent-session-wire/host/structured-agent-session-logger' - -/** null means unavailable/canceled: no failure to display or retry. */ -export type StructuredChatNameGeneration = - | { name: string } - | { error: string; errorCode?: string; failureOutput?: AgentGenerationFailureOutput } - | null - -export type StructuredChatNamingDeps = { - getStore: () => Pick< - AgentSessionRecordStore, - 'getRecord' | 'compareAndSetConversationName' | 'setUserConversationName' - > | null - getSettings: () => Pick - readFirstPrompt: (sessionId: string, hostStartedAt: number) => Promise - /** The current context's first prompt, for a name the user asked for again. */ - readJournalFirstPrompt: (sessionId: string) => Promise - now?: () => number - workerTaskTitle: (record: AgentSessionRecord) => { title: string } | null - generate: ( - record: AgentSessionRecord, - firstPrompt: string, - shouldExecute?: () => boolean - ) => Promise - onNamed: (workspaceId: string, sessionId: string) => void - logger: StructuredAgentSessionLogger - wait?: (ms: number) => Promise -} +import { neverThrowingStructuredAgentSessionLogger } from './agent-session-wire/host/structured-agent-session-logger' const GENERATION_RETRY_DELAYS_MS = [2000, 4000] const NAMING_ERROR_LIMIT = 1024 @@ -79,6 +61,7 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps error }) const refresh = (workspaceId: string, sessionId: string) => { + work.recheck(sessionId) try { deps.onNamed(workspaceId, sessionId) } catch (error) { @@ -89,33 +72,36 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps const record = deps.getStore()?.getRecord(sessionId) return !!record && contextId(record) === context } - const applicable = (request: NamingRequest) => { - const store = deps.getStore() + const applicable = (request: NamingRequest, latest?: AgentSessionRecord) => { + const current = latest ?? deps.getStore()?.getRecord(request.record.sessionId) return ( - !!store && - generationStillCurrent(store, request.record) && + !!current && + namingRequestOwnsRecord(request, current) && (!request.automatic || deps.getSettings().nativeChatAutoName !== false) ) } const work = createStructuredChatNamingWork({ applicable, prepare, - execute: async (request, firstPrompt) => { - if (!applicable(request)) { - return - } - const name = await generateName( - request.record, - firstPrompt, - request.record.conversationName ?? '', - request.automatic ? GENERATION_RETRY_DELAYS_MS : [], - () => applicable(request) - ) - const store = deps.getStore() - if (name && store && applicable(request)) { - await setName(store, request.record, name) - } - }, + execute: (request, firstPrompt) => + runStructuredChatNameGeneration({ + automaticTitle: request.automaticTitle, + getRecord: () => deps.getStore()?.getRecord(request.record.sessionId), + applicable: (current) => applicable(request, current), + generate: (stillCurrent, automaticTitle) => + generateName( + request.record, + firstPrompt, + request.record.conversationName ?? '', + request.automatic ? GENERATION_RETRY_DELAYS_MS : [], + stillCurrent, + automaticTitle + ), + setName: async (name, applicable) => { + const store = deps.getStore() + return store ? setName(store, request.record, name, applicable) : null + } + }), changed: (record) => refresh(record.location.workspaceId, record.sessionId), warn }) @@ -153,18 +139,24 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps firstPrompt: string, forName: string, retryDelays: readonly number[], - stillCurrent: () => boolean - ): Promise { + stillCurrent: () => boolean, + automaticTitle?: Parameters[3] + ): Promise<{ name: string; shouldApply?: (record?: AgentSessionRecord) => boolean } | null> { attempted.set(record.sessionId, contextId(record)) for (let attempt = 0; stillCurrent(); attempt += 1) { let failure: NamingRunFailure try { - const result = await deps.generate(record, firstPrompt, stillCurrent) + const result = await deps.generate( + record, + firstPrompt, + stillCurrent, + attempt === 0 ? automaticTitle : undefined + ) if (!result) { return null } if ('name' in result && result.name) { - return result.name + return result } failure = 'error' in result ? result : chatNamingFailure('noName') } catch (error) { @@ -189,27 +181,24 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps return null } - async function setName(store: NamingStore, record: AgentSessionRecord, name: string) { + async function setName( + store: NamingStore, + record: AgentSessionRecord, + name: string, + applicable?: (record: AgentSessionRecord) => boolean + ) { const named = await store.compareAndSetConversationName( record.sessionId, name, record.conversationName ?? null, - contextId(record) + contextId(record), + applicable ) if (named) { forget(record.sessionId) refresh(named.location.workspaceId, named.sessionId) } - } - - const generationStillCurrent = (store: NamingStore, record: AgentSessionRecord) => { - const current = store.getRecord(record.sessionId) - return ( - current !== null && - current.conversationNameSource !== 'user' && - current.conversationName === record.conversationName && - contextId(current) === contextId(record) - ) + return named } async function prepare(request: NamingRequest): Promise { @@ -241,9 +230,10 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps return { ...request, firstPrompt } } // Seeding is independent of the expensive execution owner. + request.seedingName = conversationNameSeed(firstPrompt) const seeded = await store.compareAndSetConversationName( record.sessionId, - conversationNameSeed(firstPrompt), + request.seedingName, null, contextId(record) ) @@ -251,6 +241,7 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps return null } request.record = seeded + delete request.seedingName request.firstPrompt = firstPrompt refresh(seeded.location.workspaceId, seeded.sessionId) return request @@ -274,7 +265,9 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps return } attempted.set(summary.sessionId, contextId(record)) - work.run(record, true) + work.run( + automaticChatNamingRequest(deps, record, options.firstInputSubmissionKey, applicable) + ) } catch (error) { warn(summary.sessionId, error) } @@ -282,6 +275,7 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps const naming: StructuredAgentSessionConversationNaming = { publishName: refresh, + captureTitleSourceUnavailable: work.captureSourceUnavailable, activeSessionIds: work.activeSessionIds, failure, failureOutput: (sessionId) => { @@ -294,7 +288,7 @@ export function createStructuredChatNamingHandler(deps: StructuredChatNamingDeps if (!store || !record) { return false } - work.run(record, false) + work.run({ record, automatic: false }) return true }, // Not a job: a pending generation must not swallow the user's rename. The record's 'user' diff --git a/src/main/native-chat/structured-chat-title-handover.ts b/src/main/native-chat/structured-chat-title-handover.ts new file mode 100644 index 00000000000..ecd72d6daad --- /dev/null +++ b/src/main/native-chat/structured-chat-title-handover.ts @@ -0,0 +1,183 @@ +import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/agent-session-record' +import { sessionCrewChanges } from '../runtime/orchestration/crew/crew-changes' +import type { StructuredAgentSessionHost } from './agent-session-wire/host/structured-agent-session-host' +import type { JournalPublication } from './agent-session-wire/host/structured-agent-session-conversations' +import type { AutomaticChatTitle } from './structured-chat-naming-types' + +export function deferredStructuredChatTitle(input: { + record: AgentSessionRecord + firstInputSubmissionKey: string + host: StructuredAgentSessionHost + currentHost: () => StructuredAgentSessionHost | null + applicable: () => boolean + eligible: () => boolean + subscribeSettings: (changed: () => void) => () => void +}): NonNullable { + const { sessionId } = input.record + const ready = Promise.withResolvers() + const releases: (() => void)[] = [] + let settled = false + let ended = false + let publication: JournalPublication | undefined + const release = (dispose: () => void) => (settled ? dispose() : releases.push(dispose)) + const settle = (owner: AutomaticChatTitle['owner'] = null) => { + if (settled) { + return + } + settled = true + for (const dispose of releases.splice(0)) { + dispose() + } + ready.resolve(owner) + } + const dispose = () => { + ended = true + settle() + } + const store = input.host.deps.store + const recheck = () => { + if (settled) { + return + } + try { + if ( + input.currentHost() !== input.host || + input.host.deps.store !== store || + !input.applicable() + ) { + dispose() + } else if (!input.eligible()) { + settle() + } + } catch { + settle() + } + } + const pending: NonNullable = { + ready: ready.promise, + ended: () => ended, + recheck, + unavailable: (journal) => { + if (publication?.journal === journal) { + settle() + } + }, + dispose + } + let key: unknown + try { + key = JSON.parse(input.firstInputSubmissionKey) + } catch { + settle() + } + if ( + !Array.isArray(key) || + key.length !== 2 || + typeof key[0] !== 'string' || + !key[0] || + typeof key[1] !== 'string' || + !key[1] + ) { + settle() + return pending + } + const [epoch, clientMessageId] = key + const abort = input.host.beginConversationTitleWait(sessionId) + release(abort.end) + const aborted = () => settle() + abort.signal.addEventListener('abort', aborted, { once: true }) + release(() => abort.signal.removeEventListener('abort', aborted)) + if (abort.signal.aborted) { + settle() + } + if (settled) { + return pending + } + try { + release(input.subscribeSettings(recheck)) + release( + sessionCrewChanges.subscribe((facets) => { + if (facets.has('topology') || facets.has('records')) { + recheck() + } + }) + ) + release( + input.host.observeConversationPublications(sessionId, { + next: (hint) => { + if (settled) { + return + } + if (hint.kind === 'end') { + dispose() + return + } + recheck() + if (settled) { + return + } + if ( + hint.kind === 'detach' || + !hint.source || + !hint.journal || + hint.cursor?.epoch !== epoch + ) { + settle() + return + } + if (publication && (publication.source !== hint.source || hint.kind === 'reset')) { + settle() + return + } + const submission = hint.journal.submission(clientMessageId) + const card = submission?.queuedMessageId + ? hint.journal.queuedMessages.get(submission.queuedMessageId) + : undefined + if ( + !submission || + submission.dispatchState !== 'pending' || + card?.holdReason || + card?.state === 'withdrawn' || + card?.state === 'returned' + ) { + settle() + return + } + if (!publication) { + publication = hint + // A reset cannot prove which child first received an already handed-over input. + if ( + hint.kind !== 'reset' || + submission.handedOverAt !== undefined || + !submission.handoverRecorded + ) { + settle() + } + return + } + for (const row of hint.rows ?? []) { + if ( + row.kind !== 'dispatch' || + row.state !== 'pending' || + row.epoch !== hint.journal.physicalCursor().epoch || + row.clientMessageId !== clientMessageId + ) { + continue + } + const record = store.getRecord(sessionId) + const owner = + record && record.lease.runtimeFence === row.fence + ? input.host.deps.adapter.captureConversationTitleOwner?.(record) + : null + settle(owner && record && owner.isCurrent(record) ? owner : null) + return + } + }, + error: () => settle() + }) + ) + } catch { + settle() + } + return pending +} diff --git a/src/main/orcad/orcad-plaintext-credential-migration.ts b/src/main/orcad/orcad-plaintext-credential-migration.ts index f93b8cc0441..f2bc98d95d7 100644 --- a/src/main/orcad/orcad-plaintext-credential-migration.ts +++ b/src/main/orcad/orcad-plaintext-credential-migration.ts @@ -18,6 +18,7 @@ import { API_KEY_ENVELOPE_PREFIX, getZcodePlanApiKeyPath } from '../zcode/zcode- import { COOKIE_ENVELOPE_PREFIX, getMiniMaxCookiePath } from '../minimax/minimax-cookie-store' import { miniMaxApiKeyEnvelopeFile } from '../minimax/minimax-api-key-store' import { openCodeGoApiKeyEnvelopeFile } from '../opencode/opencode-go-api-key-store' +import { openAiCompatibleSpeechProviderEnvelopeFile } from '../speech/openai-compatible-speech-provider-store' type PlaintextCredentialTarget = { path: string @@ -53,7 +54,8 @@ function listPlaintextCredentialTargets(): PlaintextCredentialTarget[] { { path: getMiniMaxCookiePath(), envelopePrefix: COOKIE_ENVELOPE_PREFIX, raw: true }, { path: getZcodePlanApiKeyPath(), envelopePrefix: API_KEY_ENVELOPE_PREFIX }, miniMaxApiKeyEnvelopeFile(), - openCodeGoApiKeyEnvelopeFile() + openCodeGoApiKeyEnvelopeFile(), + openAiCompatibleSpeechProviderEnvelopeFile() ] } diff --git a/src/main/orcad/orcad-speech-services.ts b/src/main/orcad/orcad-speech-services.ts index 9188661c106..d9c0c661c90 100644 --- a/src/main/orcad/orcad-speech-services.ts +++ b/src/main/orcad/orcad-speech-services.ts @@ -1,14 +1,19 @@ import { ModelManager } from '../speech/model-manager' import { openNodeSpeechDownloadRequest } from '../speech/node-speech-download-request' -import { canReadOpenAiSpeechApiKey } from '../speech/openai-api-key-store' +import { canReadCloudSpeechCredentials } from '../speech/cloud-transcription-target' import type { SpeechServiceFactories } from '../speech/speech-runtime-service' import { SttService } from '../speech/stt-service' +import { createSttGpuPolicy } from '../speech/stt-gpu-failure-marker' +import { spawnSttWorkerWithCpuFallback } from '../speech/stt-worker-cpu-fallback' import { spawnSttForkedProcess } from '../speech/stt-worker-forked-process' // Local speech needs the installed app recognizer supplied by orca serve. export const orcadSpeechServiceFactories: SpeechServiceFactories = { createModelManager: (customModelsDir) => // Headless key reads cannot open keychain prompts, so readiness may verify decryption. - new ModelManager(customModelsDir, openNodeSpeechDownloadRequest, canReadOpenAiSpeechApiKey), - createSttService: (models) => new SttService(models, spawnSttForkedProcess) + new ModelManager(customModelsDir, openNodeSpeechDownloadRequest, canReadCloudSpeechCredentials), + createSttService: (models, gpuEnabled) => { + const gpu = createSttGpuPolicy(models.getModelsDir(), gpuEnabled) + return new SttService(models, () => spawnSttWorkerWithCpuFallback(spawnSttForkedProcess, gpu)) + } } diff --git a/src/main/persistence/applying-settings/persistence-settings-update.test.ts b/src/main/persistence/applying-settings/persistence-settings-update.test.ts index 0f35da8f31b..3117cabecaa 100644 --- a/src/main/persistence/applying-settings/persistence-settings-update.test.ts +++ b/src/main/persistence/applying-settings/persistence-settings-update.test.ts @@ -82,6 +82,30 @@ describe('Store', () => { expect(isLocalWorktreeScanGenerationCurrent('r1', generation)).toBe(false) }) + it('saves a pasted workspace directory with leading spaces as the absolute path it names', async () => { + const store = await createStore() + store.updateSettings({ workspaceDir: '/Users/me/dev' }) + const historyBefore = store.getSettings().workspaceDirHistory + + // Padding before an absolute path would otherwise resolve inside every repo. + expect(store.updateSettings({ workspaceDir: ' /Users/me/dev' }).workspaceDir).toBe( + '/Users/me/dev' + ) + expect(store.getSettings().workspaceDirHistory).toEqual(historyBefore) + // Trailing characters and relative paths can be real folder names. + expect(store.updateSettings({ workspaceDir: '/tmp/workspaces ' }).workspaceDir).toBe( + '/tmp/workspaces ' + ) + expect(store.updateSettings({ workspaceDir: ' ~notes' }).workspaceDir).toBe(' ~notes') + if (process.platform === 'win32') { + expect(store.updateSettings({ workspaceDir: ' C:\\work' }).workspaceDir).toBe('C:\\work') + } else { + // ~\ and a leading \ are relative off Windows, so the value stays exact. + expect(store.updateSettings({ workspaceDir: ' ~\\work' }).workspaceDir).toBe(' ~\\work') + expect(store.updateSettings({ workspaceDir: ' \\work' }).workspaceDir).toBe(' \\work') + } + }) + it('updateSettings deep-merges and clamps notification custom sound volume', async () => { const store = await createStore() store.updateSettings({ diff --git a/src/main/persistence/applying-settings/settings-update.ts b/src/main/persistence/applying-settings/settings-update.ts index 6a3f0e2997f..32220723e6a 100644 --- a/src/main/persistence/applying-settings/settings-update.ts +++ b/src/main/persistence/applying-settings/settings-update.ts @@ -42,7 +42,7 @@ import { normalizeNotificationSettings } from './onboarding-normalization' import { retireLegacyInstructionsForClearedTextActionRecipes } from './source-control-settings' import { buildWorkspaceDirHistoryForUpdate, - expandWorkspaceDirHome, + normalizeWorkspaceDirSetting, stripRetiredGlobalSettings } from './terminal-settings-migrations' @@ -59,7 +59,7 @@ export function updateSettings( updates: Partial, options: { notifyListeners?: boolean; originWebContentsId?: number } = {} ): GlobalSettings { - const sanitizedUpdates = expandWorkspaceDirHome(stripRetiredGlobalSettings(updates)) + const sanitizedUpdates = normalizeWorkspaceDirSetting(stripRetiredGlobalSettings(updates)) const linkBehavior = updates.terminalLinkClickBehavior if (linkBehavior === 'actions' || linkBehavior === 'open' || linkBehavior === 'none') { // Loaded defaults are ambiguous; synchronize the legacy switch only on an explicit write. diff --git a/src/main/persistence/applying-settings/terminal-settings-migrations.ts b/src/main/persistence/applying-settings/terminal-settings-migrations.ts index 8aa8b021824..ae54a94349e 100644 --- a/src/main/persistence/applying-settings/terminal-settings-migrations.ts +++ b/src/main/persistence/applying-settings/terminal-settings-migrations.ts @@ -12,14 +12,39 @@ import { normalizeTuiAgentEnvRecord } from '../../../shared/agent-launch/choices/tui-agent-launch-defaults' import { expandLeadingHomePath } from '../../filesystem/home-path-expansion' +import { normalizeWorkspaceDirInput } from '../../../shared/worktree/workspace-dir-input' -/** Unexpanded, a leading ~ resolves inside each repo and worktrees land in /~ (#34944). */ -export function expandWorkspaceDirHome(settings: Partial): Partial { +/** A raw ~ or padded absolute path resolves inside each repo (#34944, STA-14308); normalize at the store boundary. */ +export function normalizeWorkspaceDirSetting( + settings: Partial +): Partial { return typeof settings.workspaceDir === 'string' - ? { ...settings, workspaceDir: expandLeadingHomePath(settings.workspaceDir, homedir()) } + ? { + ...settings, + workspaceDir: expandLeadingHomePath( + normalizeWorkspaceDirInput(settings.workspaceDir, process.platform === 'win32'), + homedir() + ) + } : settings } +/** Keep a repaired saved spelling in history so checkouts under its old root keep their visibility. */ +export function normalizeLoadedWorkspaceDirSetting( + settings: Partial, + defaults: GlobalSettings +): Partial { + const normalized = normalizeWorkspaceDirSetting(settings) + if (normalized.workspaceDir === settings.workspaceDir) { + return normalized + } + const history = buildWorkspaceDirHistoryForUpdate( + { ...defaults, ...settings }, + { workspaceDir: normalized.workspaceDir } + ) + return history ? { ...normalized, workspaceDirHistory: history } : normalized +} + export function buildWorkspaceDirHistoryForUpdate( current: GlobalSettings, updates: Partial diff --git a/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts b/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts index 1b6fa84cecf..ce56101aebd 100644 --- a/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts +++ b/src/main/persistence/loading-store/normalize-loaded-global-settings.test.ts @@ -3,6 +3,7 @@ import { expect, it } from 'vitest' import { resolveAntigravityChatAuthConfig } from '../../../shared/antigravity-chat-auth-config' import { getDefaultPersistedState, getDefaultVoiceSettings } from '../../../shared/constants' import type { PersistedState } from '../../../shared/persisted-state-types' +import { buildKnownOrcaWorkspaceLayouts } from '../../../shared/worktree/ownership' import { normalizeLoadedGlobalSettings } from './normalize-loaded-global-settings' import { prepareLoadedTerminalSettings } from './prepare-loaded-terminal-settings' import { prepareLoadedProfileSettings } from './prepare-loaded-profile-settings' @@ -57,3 +58,19 @@ it('stores Auto as Toggle plus hold-to-record so older builds keep a working sho false ]) }) + +it('loads a padded workspace directory as the absolute path while keeping its old root known', () => { + const settings = normalizeLegacyProfile({ + workspaceDir: ' /Users/me/dev', + nestWorkspaces: false, + workspaceDirHistory: [] + }) + + expect(settings.workspaceDir).toBe('/Users/me/dev') + // Checkouts an older build placed under / /Users/me/dev keep their known layout. + expect( + buildKnownOrcaWorkspaceLayouts(settings, { path: '/repo', worktreeBasePath: undefined }).map( + (layout) => layout.path + ) + ).toContain('/repo/ /Users/me/dev') +}) diff --git a/src/main/persistence/loading-store/normalize-loaded-global-settings.ts b/src/main/persistence/loading-store/normalize-loaded-global-settings.ts index 34e15219fa8..c75ab18a38c 100644 --- a/src/main/persistence/loading-store/normalize-loaded-global-settings.ts +++ b/src/main/persistence/loading-store/normalize-loaded-global-settings.ts @@ -17,7 +17,7 @@ import { projectSourceControlAiToLegacyCommitMessageAi } from '../../../shared/s import { normalizeNativeChatShellEnvironmentVariables } from '../../../shared/native-chat/native-chat-shell-environment' import { publishedLegacyChatPermissionMode } from '../../../shared/agent-launch/permissions/agent-chat-permission-mode' import { - expandWorkspaceDirHome, + normalizeLoadedWorkspaceDirSetting, stripRetiredGlobalSettings } from '../applying-settings/terminal-settings-migrations' import { readLegacySidekickFlag } from '../applying-settings/onboarding-normalization' @@ -88,7 +88,10 @@ export function normalizeLoadedGlobalSettings( return { ...defaults.settings, // Legacy stored booleans cannot distinguish opt-in from the old default; retain explicit true. - ...expandWorkspaceDirHome(stripRetiredGlobalSettings(parsed.settings)), + ...normalizeLoadedWorkspaceDirSetting( + stripRetiredGlobalSettings(parsed.settings), + defaults.settings + ), agentDefaultSurface: normalizeAgentDefaultSurface(parsed.settings?.agentDefaultSurface), nativeChatAppearance: normalizeNativeChatAppearanceSettings( parsed.settings?.nativeChatAppearance diff --git a/src/main/persistence/loading-store/project-collection-operations.ts b/src/main/persistence/loading-store/project-collection-operations.ts index e6d90ede3b8..2e67007eefc 100644 --- a/src/main/persistence/loading-store/project-collection-operations.ts +++ b/src/main/persistence/loading-store/project-collection-operations.ts @@ -138,6 +138,12 @@ export class ProjectCollectionOperations { return getProjectGroupOperations(this).deleteProjectGroup(groupId) } + updateProjectGroups( + mutations: Parameters[0] + ): ProjectGroup[] | null { + return getProjectGroupOperations(this).updateProjectGroups(mutations) + } + getFolderWorkspaces(): FolderWorkspace[] { return getFolderWorkspaceOperations(this).getFolderWorkspaces() } diff --git a/src/main/persistence/loading-store/repo-lifecycle-operations.ts b/src/main/persistence/loading-store/repo-lifecycle-operations.ts index 1b1748da2e4..ea15fa64885 100644 --- a/src/main/persistence/loading-store/repo-lifecycle-operations.ts +++ b/src/main/persistence/loading-store/repo-lifecycle-operations.ts @@ -187,6 +187,7 @@ export class RepoLifecycleOperations { | 'folderUpgradeGitRootPath' | 'executionHostId' | 'symlinkPaths' + | 'dictationTerms' | 'issueSourcePreference' | 'forkSyncMode' | 'agentWorkspaceTrust' diff --git a/src/main/persistence/tracking-repos/project-group-batch-update.test.ts b/src/main/persistence/tracking-repos/project-group-batch-update.test.ts new file mode 100644 index 00000000000..a5867523bba --- /dev/null +++ b/src/main/persistence/tracking-repos/project-group-batch-update.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { getDefaultPersistedState } from '../../../shared/constants' +import { createProjectGroup } from '../../../shared/project-groups' +import { ProjectGroupPersistenceOperations } from './project-group-operations' + +function fixture() { + const state = getDefaultPersistedState('/workspace') + state.projectGroups = ['a', 'b', 'other'].map((id, tabOrder) => ({ + ...createProjectGroup({ name: id, createdFrom: 'manual', tabOrder }), + id + })) + const operations = new ProjectGroupPersistenceOperations({ + state, + scheduleSave: () => {}, + removeWorkspaceLineageForRemovedFolder: () => {}, + pruneMobileClientTabSelections: () => {} + }) + return { state, operations } +} + +describe('batch project group updates', () => { + it('updates and clears ranks for selected groups without changing unrelated groups', () => { + const { state, operations } = fixture() + const other = { ...state.projectGroups![2] } + + expect( + operations.updateProjectGroups([ + { groupId: 'b', updates: { rootProjectOrder: 2000, tabOrder: 4 } }, + { groupId: 'a', updates: { rootProjectOrder: 1000, isCollapsed: true } } + ]) + ).toMatchObject([ + { id: 'b', rootProjectOrder: 2000, tabOrder: 4 }, + { id: 'a', rootProjectOrder: 1000, isCollapsed: true } + ]) + operations.updateProjectGroups([ + { groupId: 'a', updates: { rootProjectOrder: null } }, + { groupId: 'b', updates: { rootProjectOrder: 3000 } } + ]) + + expect(state.projectGroups).toMatchObject([ + { id: 'a', tabOrder: 0, isCollapsed: true }, + { id: 'b', rootProjectOrder: 3000, tabOrder: 4 }, + other + ]) + expect(state.projectGroups![0].rootProjectOrder).toBeUndefined() + expect(state.projectGroups![2]).toEqual(other) + }) + + it('rejects the entire batch when a group has disappeared', () => { + const { state, operations } = fixture() + const before = structuredClone(state.projectGroups) + + expect( + operations.updateProjectGroups([ + { groupId: 'a', updates: { rootProjectOrder: 1000 } }, + { groupId: 'missing', updates: { rootProjectOrder: 2000 } } + ]) + ).toBeNull() + expect(state.projectGroups).toEqual(before) + }) +}) diff --git a/src/main/persistence/tracking-repos/project-group-operations.ts b/src/main/persistence/tracking-repos/project-group-operations.ts index e0ff47e67fd..cd7d55bf99c 100644 --- a/src/main/persistence/tracking-repos/project-group-operations.ts +++ b/src/main/persistence/tracking-repos/project-group-operations.ts @@ -1,5 +1,9 @@ import type { PersistedState } from '../../../shared/persisted-state-types' -import type { ProjectGroup, ProjectGroupUpdate } from '../../../shared/project-group-types' +import type { + ProjectGroup, + ProjectGroupMutation, + ProjectGroupUpdate +} from '../../../shared/project-group-types' import { createProjectGroup, getProjectGroupSubtreeIds, @@ -73,6 +77,28 @@ export class ProjectGroupPersistenceOperations { if (!group) { return null } + this.applyGroupUpdate(group, updates) + this.scheduleSave() + return group + } + + updateProjectGroups(mutations: readonly ProjectGroupMutation[]): ProjectGroup[] | null { + const byId = new Map((this.state.projectGroups ?? []).map((group) => [group.id, group])) + if (mutations.some(({ groupId }) => !byId.has(groupId))) { + return null + } + const updated = mutations.map(({ groupId, updates }) => { + const group = byId.get(groupId)! + this.applyGroupUpdate(group, updates) + return group + }) + if (updated.length > 0) { + this.scheduleSave() + } + return updated + } + + private applyGroupUpdate(group: ProjectGroup, updates: ProjectGroupUpdate): void { if (updates.name !== undefined) { group.name = normalizeProjectGroupName(updates.name, group.name) } @@ -94,8 +120,6 @@ export class ProjectGroupPersistenceOperations { group.color = typeof updates.color === 'string' ? updates.color : null } group.updatedAt = Date.now() - this.scheduleSave() - return group } deleteProjectGroup(groupId: string): boolean { diff --git a/src/main/persistence/tracking-repos/repo-update-operations.ts b/src/main/persistence/tracking-repos/repo-update-operations.ts index 8841638c145..ee07378f475 100644 --- a/src/main/persistence/tracking-repos/repo-update-operations.ts +++ b/src/main/persistence/tracking-repos/repo-update-operations.ts @@ -101,6 +101,7 @@ export class RepoUpdatePersistenceOperations { | 'folderUpgradeGitRootPath' | 'executionHostId' | 'symlinkPaths' + | 'dictationTerms' | 'issueSourcePreference' | 'defaultJiraProject' | 'forkSyncMode' diff --git a/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.test.ts b/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.test.ts index 826f1844ebe..25238ec9690 100644 --- a/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.test.ts +++ b/src/main/rate-limits/providers/codex/codex-rate-limit-window-classification.test.ts @@ -17,11 +17,6 @@ function usedPercentByWindow(result: CodexRateLimitWindowsSnapshot | null): { describe('classifyCodexRateLimitWindows', () => { it.each([ - { - name: 'null windows', - result: null, - expected: { session: null, weekly: null } - }, { name: 'reordered known windows', result: { @@ -30,22 +25,6 @@ describe('classifyCodexRateLimitWindows', () => { }, expected: { session: 21, weekly: 81 } }, - { - name: 'weekly-only primary window', - result: { - primary: { usedPercent: 22, windowDurationMins: 10080 }, - secondary: null - }, - expected: { session: null, weekly: 22 } - }, - { - name: 'session-only secondary window', - result: { - primary: null, - secondary: { usedPercent: 31, windowDurationMins: 300 } - }, - expected: { session: 31, weekly: null } - }, { name: 'duplicate session windows', result: { @@ -70,14 +49,6 @@ describe('classifyCodexRateLimitWindows', () => { }, expected: { session: null, weekly: 61 } }, - { - name: 'malformed duration with positional fallback', - result: { - primary: { usedPercent: 71, windowDurationMins: '300' }, - secondary: null - }, - expected: { session: 71, weekly: null } - }, { name: 'reordered near-canonical windows', result: { @@ -94,22 +65,6 @@ describe('classifyCodexRateLimitWindows', () => { }, expected: { session: 84, weekly: 83 } }, - { - name: 'outside-tolerance unknown windows', - result: { - primary: { usedPercent: 91, windowDurationMins: 302 }, - secondary: { usedPercent: 92, windowDurationMins: 10082 } - }, - expected: { session: 91, weekly: 92 } - }, - { - name: 'unknown windows without durations', - result: { - primary: { usedPercent: 101 }, - secondary: { usedPercent: 102 } - }, - expected: { session: 101, weekly: 102 } - }, { name: 'known session wins over unknown primary fallback', result: { diff --git a/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts b/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts index e4dbe1245d0..c4667e40ead 100644 --- a/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts +++ b/src/main/rate-limits/providers/codex/codex-rate-limit-wsl-home-gate.test.ts @@ -81,22 +81,6 @@ describe('Codex quota poll home for a WSL account (E9)', () => { expect(resolution).toEqual({ kind: 'skip' }) }) - it('prepares the home when the targeted distro runs, and leaves host targets alone', async () => { - const h = harness(['orca-w'], () => homeIn('orca-w')) - - await expect( - resolveCodexRateLimitHomeUnlessStopped( - h.source, - { runtime: 'wsl', wslDistro: 'orca-w' }, - h.deps - ) - ).resolves.toEqual({ kind: 'ready', codexHomePath: homeIn('orca-w') }) - await resolveCodexRateLimitHomeUnlessStopped(h.source, { runtime: 'host' }, h.deps) - - expect(h.prepareForRateLimitFetch).toHaveBeenLastCalledWith({ runtime: 'host' }) - expect(h.deps.isRunning).toHaveBeenCalledOnce() - }) - it('skips when no distro can be named', async () => { const h = harness([], () => null) h.deps.defaultDistro.mockResolvedValue(null) diff --git a/src/main/rate-limits/providers/grok/grok-auth.test.ts b/src/main/rate-limits/providers/grok/grok-auth.test.ts index ccff545612a..646519c9f54 100644 --- a/src/main/rate-limits/providers/grok/grok-auth.test.ts +++ b/src/main/rate-limits/providers/grok/grok-auth.test.ts @@ -76,35 +76,6 @@ describe('readGrokAuthSession', () => { } ) - it('falls back to the first tokenized entry when no auth.x.ai key exists', async () => { - vi.doMock('node:fs', () => ({ - existsSync: vi.fn(() => true), - readFileSync: vi.fn(() => - JSON.stringify({ - 'https://alternate.example.com::client': { - key: 'alt-token', - user_id: 'alt-user', - email: 'alt@example.com', - expires_at: '2099-01-01T00:00:00.000Z' - } - }) - ) - })) - const { readGrokAuthSession } = await import('./grok-auth') - - expect(readGrokAuthSession()).toEqual({ - status: 'ok', - session: { - accessToken: 'alt-token', - userId: 'alt-user', - email: 'alt@example.com', - teamId: null, - expiresAtMs: Date.parse('2099-01-01T00:00:00.000Z'), - oidcClientId: null - } - }) - }) - it('skips an expired auth.x.ai client entry when a fresh one follows it', async () => { vi.doMock('node:fs', () => ({ existsSync: vi.fn(() => true), diff --git a/src/main/runtime/agent-session/environment/structured-agent-environment-overrides.test.ts b/src/main/runtime/agent-session/environment/structured-agent-environment-overrides.test.ts new file mode 100644 index 00000000000..1a31295d11e --- /dev/null +++ b/src/main/runtime/agent-session/environment/structured-agent-environment-overrides.test.ts @@ -0,0 +1,26 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { createStructuredAgentEnvironmentResolvers } from './structured-agent-shell-environment' + +afterEach(() => vi.unstubAllGlobals()) + +it.each([ + ['win32', { TOKEN: 'configured', PATH: '/configured/bin', KEEP: 'keep' }], + [ + 'linux', + { + TOKEN: 'inherited', + PATH: '/inherited/bin', + tOKEN: 'configured', + path: '/configured/bin', + KEEP: 'keep' + } + ] +] as const)('composes the effective agent environment on %s', async (platform, expected) => { + vi.stubGlobal('process', { ...process, platform }) + const environment = createStructuredAgentEnvironmentResolvers({ + resolveEnvironment: async () => ({ TOKEN: 'inherited', PATH: '/inherited/bin', KEEP: 'keep' }), + resolveAgentLaunchEnv: () => ({ tOKEN: 'configured', path: '/configured/bin' }) + }) + expect(await environment.resolveAgentEnvironment('claude')).toEqual(expected) + expect(await environment.resolveAgentEnvironment('codex')).toEqual(expected) +}) diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts index 1c0a13e22b6..87bd9cad5e9 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment-catalog.test.ts @@ -40,13 +40,14 @@ const cleanups: (() => void)[] = [] afterEach(() => { cleanups.splice(0).forEach((stop) => stop()) vi.restoreAllMocks() + vi.unstubAllGlobals() shell.current = { PATH: '/a', IGNORED: 'a' } shell.next = { ...shell.current } shell.saved = [] shell.nextSaved = [] }) -function rig() { +function rig(overlay?: Record) { const record = { ...agentSessionRecordFixture(), provider: 'grok', @@ -67,7 +68,8 @@ function rig() { workspaceMayOverrideDefaultModel: defaults }) const environment = createStructuredAgentEnvironmentResolvers({ - resolveShellEnvironmentPolicy: () => ({ inheritAll: false, names: [] }) + resolveShellEnvironmentPolicy: () => ({ inheritAll: false, names: [] }), + resolveAgentLaunchEnv: () => overlay ?? {} }) cleanups.push(service.stop, environment.bindCatalogSources(['grok'])) const listing = (id: string) => ({ @@ -84,6 +86,22 @@ function rig() { } } +it('keeps a Windows catalog source while only a shadowed inherited path changes', async () => { + vi.stubGlobal('process', { ...process, platform: 'win32' }) + const overlay = { path: '/configured/bin' } + const h = rig(overlay) + const source = h.service.captureSource(h.record) + cleanups.push(() => source.release?.()) + await captureHostShellEnvironment(async () => { + shell.next = { PATH: '/changed', IGNORED: 'a' } + }) + expect(source()).toBe(true) + await captureHostShellEnvironment(async () => { + overlay.path = '/new-configured/bin' + }) + expect(source()).toBe(false) +}) + it('retires a producer on effective Refresh before new publication and fences late defaults and new old reports', async () => { const h = rig() await agentModelCatalogStore.attachPersistence({ diff --git a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts index b4996cff6ff..e050391680d 100644 --- a/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts +++ b/src/main/runtime/agent-session/environment/structured-agent-shell-environment.ts @@ -11,6 +11,7 @@ import { resolvePathEnvKey } from '../../../pty/environment/windows-path-segment-merge' import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' import { nativeChatShellEnvironmentPolicy, type NativeChatShellEnvironmentPolicy @@ -29,24 +30,6 @@ function definedEnv(env: NodeJS.ProcessEnv): Record { return defined } -/** Overlays shell variables on Orca's env; win32 names are case-insensitive, so drop the base spelling. */ -function overlayShellVariables( - base: Record, - shellVariables: Record, - platform: NodeJS.Platform -): Record { - const merged = { ...base } - if (platform === 'win32') { - const overlaid = new Set(Object.keys(shellVariables).map((key) => key.toUpperCase())) - for (const key of Object.keys(merged)) { - if (overlaid.has(key.toUpperCase())) { - delete merged[key] - } - } - } - return { ...merged, ...shellVariables } -} - function pickShellVariables( shellEnv: NodeJS.ProcessEnv, names: readonly string[], @@ -78,7 +61,7 @@ export function structuredAgentBaseEnvironment(input: { return definedEnv(input.shellEnv) } const platform = input.platform ?? process.platform - return overlayShellVariables( + return overlayEnvironmentVariables( definedEnv(input.processEnv ?? process.env), pickShellVariables(input.shellEnv, input.policy.names, platform), platform @@ -246,7 +229,11 @@ export function createStructuredAgentEnvironmentResolvers( const base = structuredAgentBaseEnvironment({ shellEnv, policy, processEnv }) return new Map( agents.map((agent) => { - const effective = { ...base, ...overlays.get(agent) } + const effective = overlayEnvironmentVariables( + base, + overlays.get(agent), + process.platform + ) return [agent, structuredAgentEnvironmentIdentity(effective)] }) ) @@ -258,10 +245,12 @@ export function createStructuredAgentEnvironmentResolvers( } }, resolveBaseEnvironment: resolveBase, - resolveAgentEnvironment: async (agent) => ({ - ...(await resolveBase()), - ...sources.resolveAgentLaunchEnv?.(agent) - }) + resolveAgentEnvironment: async (agent) => + overlayEnvironmentVariables( + await resolveBase(), + sources.resolveAgentLaunchEnv?.(agent), + process.platform + ) } } diff --git a/src/main/runtime/agent-session/installation/runtime-structured-agent-host-env.test.ts b/src/main/runtime/agent-session/installation/runtime-structured-agent-host-env.test.ts new file mode 100644 index 00000000000..744e51d8736 --- /dev/null +++ b/src/main/runtime/agent-session/installation/runtime-structured-agent-host-env.test.ts @@ -0,0 +1,34 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { RuntimeStructuredAgentHost } from './runtime-structured-agent-host' +import { resolveStructuredClaudeAccountHomePath } from '../environment/structured-agent-account-home' + +vi.mock('../../terminal/wait/terminal-wait-visible-probe', () => ({ + OrcaRuntimeWithStartTuiIdleVisibleReadProbe: class {} +})) +afterEach(() => vi.unstubAllGlobals()) + +abstract class LaunchRuntime extends RuntimeStructuredAgentHost { + configuredEnvironment() { + return this.structuredAgentLaunchEnv('claude', { + agentDefaultEnv: { claude: { claude_config_dir: '/configured/home' } } + }) + } +} + +it('uses the same configured Windows home for account identity, then honors the host account', async () => { + vi.stubGlobal('process', { ...process, platform: 'win32' }) + let host: Record = {} + const runtime: LaunchRuntime = Object.assign(Object.create(LaunchRuntime.prototype), { + accounts: { hostLaunchEnvFor: () => host } + }) + const accountHome = () => + resolveStructuredClaudeAccountHomePath({ + launchEnv: runtime.configuredEnvironment(), + wslDistro: null, + getClaudeConfigDirectory: () => '/fallback/home' + }) + expect(await accountHome()).toBe('/configured/home') + host = { CLAUDE_CONFIG_DIR: '/host/home' } + expect(runtime.configuredEnvironment()).toEqual({ CLAUDE_CONFIG_DIR: '/host/home' }) + expect(await accountHome()).toBe('/host/home') +}) diff --git a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts index faea7c1089d..4bc70ab1968 100644 --- a/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts +++ b/src/main/runtime/agent-session/installation/runtime-structured-agent-host.ts @@ -8,6 +8,7 @@ import { structuredAgentConfiguredArgs } from '../../../native-chat/structured-a import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' import { resolveTuiAgentLaunchEnv } from '../../../../shared/agent-launch/choices/tui-agent-launch-defaults' +import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' import type { GlobalSettings } from '../../../../shared/global-settings-types' import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' import type { RuntimeWorkspaceCatalog } from '../../workspaces/catalog/workspace-catalog' @@ -25,10 +26,11 @@ export abstract class RuntimeStructuredAgentHost extends OrcaRuntimeWithStartTui agent: StructuredAgentId, settings: Pick ) { - return { - ...resolveTuiAgentLaunchEnv(agent, settings), - ...this.accounts.hostLaunchEnvFor(agent) - } + return overlayEnvironmentVariables( + overlayEnvironmentVariables({}, resolveTuiAgentLaunchEnv(agent, settings), process.platform), + this.accounts.hostLaunchEnvFor(agent), + process.platform + ) } protected structuredAgentCatalogDependencies(): StructuredAgentModelCatalogDeps { diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-env-preflight.test.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-env-preflight.test.ts new file mode 100644 index 00000000000..41906268caa --- /dev/null +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-env-preflight.test.ts @@ -0,0 +1,21 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { resolveHostStructuredAgentLaunchEnvironment } from './structured-agent-launch-support' +import type * as Environment from '../environment/structured-agent-shell-environment' + +vi.mock('../environment/structured-agent-shell-environment', async (importOriginal) => ({ + ...(await importOriginal()), + resolveHostAgentBaseEnvironment: async () => ({ + TOKEN: 'inherited', + PATH: '/inherited/bin', + KEEP: 'keep' + }) +})) +afterEach(() => vi.unstubAllGlobals()) + +it('uses the configured Windows environment for launch preflight', async () => { + vi.stubGlobal('process', { ...process, platform: 'win32' }) + const env = await resolveHostStructuredAgentLaunchEnvironment('claude', { + agentDefaultEnv: { claude: { tOKEN: 'configured', path: '/configured/bin' } } + }) + expect(env).toEqual({ TOKEN: 'configured', PATH: '/configured/bin', KEEP: 'keep' }) +}) diff --git a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts index 16e51d3da17..d6c402cb949 100644 --- a/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts +++ b/src/main/runtime/agent-session/launch/structured-agent-launch-support.ts @@ -1,6 +1,7 @@ import type { AgentSessionExecutionLocation } from '../../../../shared/agent-session/lifecycle/agent-session-record' import type { StructuredAgentId } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle' import type { GlobalSettings } from '../../../../shared/global-settings-types' +import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' import { resolveTuiAgentLaunchEnv, @@ -101,10 +102,11 @@ export async function resolveHostStructuredAgentLaunchEnvironment( agent: string, settings: LaunchEnvironmentSettings ): Promise> { - return { - ...(await resolveHostAgentBaseEnvironment(settings)), - ...(isTuiAgent(agent) ? resolveTuiAgentLaunchEnv(agent, settings) : {}) - } + return overlayEnvironmentVariables( + await resolveHostAgentBaseEnvironment(settings), + isTuiAgent(agent) ? resolveTuiAgentLaunchEnv(agent, settings) : undefined, + process.platform + ) } /** What a chat start of `agent` on this host launches from, for a child that serves no chat. */ diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.test.ts new file mode 100644 index 00000000000..4592b0590c1 --- /dev/null +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.test.ts @@ -0,0 +1,27 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { agentSessionRecordFixture } from '../../../../shared/agent-session/lifecycle/agent-session-record.test-fixture' +import { chatNamingAgentTarget } from './structured-chat-naming-agent-launch' + +afterEach(() => vi.unstubAllGlobals()) + +it('reapplies configured Windows naming variables and keeps the recorded account pin', async () => { + vi.stubGlobal('process', { ...process, platform: 'win32' }) + const target = await chatNamingAgentTarget( + agentSessionRecordFixture(), + '/workspace', + async () => ({ + TOKEN: 'inherited', + PATH: '/inherited/bin', + CLAUDE_CONFIG_DIR: '/ambient/home' + }), + { agentDefaultEnv: { claude: { tOKEN: 'configured', path: '/configured/bin' } } } + ) + if (target.kind !== 'local') { + throw new Error('Naming did not resolve a local launch') + } + expect(target.env).toEqual({ + TOKEN: 'configured', + PATH: '/configured/bin', + CLAUDE_CONFIG_DIR: '/home/user/.claude' + }) +}) diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts index 56c13c34fd8..24f0049e695 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-agent-launch.ts @@ -1,6 +1,7 @@ import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' import { requireLegacyAgentSessionAccountHome } from '../../../../shared/agent-session/lifecycle/agent-session-account-home' import { resolveTuiAgentLaunchEnv } from '../../../../shared/agent-launch/choices/tui-agent-launch-defaults' +import { overlayEnvironmentVariables } from '../../../../shared/environment-overlay' import { acpLaunchSpecFor } from '../../../acp/launch/acp-launch-registry' import { getClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' import { @@ -30,10 +31,11 @@ export async function chatNamingAgentTarget( } const home = requireLegacyAgentSessionAccountHome(record.accountHome) if (record.provider === 'claude') { - env = { - ...withoutInheritedClaudeConfigDir(env), - ...resolveTuiAgentLaunchEnv('claude', settings) - } + env = overlayEnvironmentVariables( + withoutInheritedClaudeConfigDir(env), + resolveTuiAgentLaunchEnv('claude', settings), + process.platform + ) const path = await resolveClaudeStructuredLaunchHome(getClaudeProfileRouter(), env, home.path) const patch = claudeConfigDirEnvPatch(path, { env }) return { kind: 'local', cwd, env: { CLAUDE_CONFIG_DIR: undefined, ...env, ...patch } } diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts index f4082664bd6..b2bad3c6433 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts @@ -1,3 +1,19 @@ +import { ClaudeProfileRouter } from '../../../claude-accounts/claude-profile-router' +import { + acquired, + fakeClaude, + identityFor, + recordingJournalSink, + PROVIDER_SESSION_ID +} from '../../../claude/structured/claude-structured-session-test-support' +import type { AgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-record' +import type { Query } from '@anthropic-ai/claude-agent-sdk' +import { createClaudeControlSurface } from '../../../claude/claude-agent-sdk-control-requests' +import { + createStructuredChatNamingHandler, + type StructuredChatNamingDeps +} from '../../../native-chat/structured-chat-naming' +import { compareAndSetAgentSessionRecordName } from '../records/agent-session-record-conversation-name' import { rm } from 'node:fs/promises' import { installClaudeProfileRouter } from '../../../claude-accounts/claude-profile-installed-router' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -7,6 +23,20 @@ import { normalizeSourceControlAiSettings } from '../../../../shared/source-cont import { structuredChatNamingDeps } from './structured-chat-naming-runtime' import type { AgentJournalSnapshot } from '../../../../shared/agent-session/journal/agent-session-journal-types' import type * as TextGeneration from '../../../text-generation/commit-message-text-generation' +import type { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' +import { + createQueuedMessageTestRig, + QUEUED_RIG_CALLER +} from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-queued-message-rig.test-fixture' +import { holdDelivery } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-delivery-hold.test-fixture' +import { holdUnsentSends } from '../../../native-chat/agent-session-journal/queued-messages/journal-unsent-send-hold' +import { AgentSessionAcquisitionRootExitObservedError } from '../../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors' +import { AgentSessionStartFailure } from '../../../native-chat/agent-session-wire/startup/structured-agent-session-start-failure' +import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../../shared/agent-session/journal/agent-session-journal-types' +import { + HOST_TEST_SESSION, + hostTestOperationId +} from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' const mocks = vi.hoisted(() => ({ account: vi.fn((_provider: string, id: string) => ({ @@ -14,7 +44,13 @@ const mocks = vi.hoisted(() => ({ XDG_STATE_HOME: `/profiles/${id}/state` })), native: vi.fn(async () => 'Native title'), - generate: vi.fn(async () => ({ success: true as const, name: 'Login repair' })), + titleOwner: vi.fn(), + host: vi.fn<() => StructuredAgentSessionHost | undefined>(), + record: vi.fn(), + generate: vi.fn(async () => ({ + success: true as const, + name: 'Login repair' + })), target: vi.fn(async (cwd: string) => ({ kind: 'local' as const, cwd })), publishConversationName: vi.fn<(sessionId: string) => void>(), journalCurrentRead: vi.fn<(sessionId: string) => Promise>() @@ -28,11 +64,15 @@ vi.mock('../../../agent-hooks/first-work/first-work-generation-target', () => ({ resolveGenerationTarget: mocks.target })) vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ - getStructuredAgentSessionHost: () => ({ - deps: { adapter: { generateText: mocks.native } }, - publishConversationName: mocks.publishConversationName, - journalCurrentRead: mocks.journalCurrentRead - }) + getStructuredAgentSessionHost: () => + mocks.host() ?? { + deps: { + store: { getRecord: mocks.record }, + adapter: { generateText: mocks.native, captureConversationTitleOwner: mocks.titleOwner } + }, + publishConversationName: mocks.publishConversationName, + journalCurrentRead: mocks.journalCurrentRead + } })) vi.mock('../../../managed-data-accounts/service', () => ({ @@ -43,13 +83,20 @@ vi.mock('../../../managed-data-accounts/service', () => ({ })) const roots: string[] = [] afterEach(async () => { + vi.useRealTimers() installClaudeProfileRouter(undefined) await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) }) -beforeEach(() => vi.clearAllMocks()) +beforeEach(() => { + vi.clearAllMocks() + mocks.titleOwner.mockReset() + mocks.host.mockReset() + mocks.record.mockReset() +}) function rig() { const settings = getDefaultSettings('/isolated') + const settingsListeners = new Set<() => void>() settings.defaultTuiAgent = 'codex' settings.sourceControlAi = normalizeSourceControlAiSettings(settings.sourceControlAi) const runtime = { @@ -67,13 +114,99 @@ function rig() { const logger = { warn: vi.fn(), error: vi.fn() } return { settings, + settingsChanged: () => settingsListeners.forEach((changed) => changed()), runtime, logger, - deps: structuredChatNamingDeps(() => ({ getSettings: () => settings }), runtime, logger) + deps: structuredChatNamingDeps( + () => ({ + getSettings: () => settings, + onSettingsChanged: (changed) => { + settingsListeners.add(changed) + return () => { + settingsListeners.delete(changed) + } + } + }), + runtime, + logger + ) } } describe('structured chat naming runtime', () => { + it('uses the CLI title only for automatic default naming and honors changed settings', async () => { + const state = rig() + const record = agentSessionRecordFixture() + const pending = Promise.withResolvers() + const generate = vi.fn(() => pending.promise) + mocks.titleOwner.mockReturnValue({ isCurrent: () => true, generate }) + const result = state.deps.generate( + record, + 'Repair login', + () => true, + state.deps.captureAutomaticTitle!(record) + ) + await vi.waitFor(() => expect(generate).toHaveBeenCalled()) + pending.resolve('Broken chat title') + expect(await result).toMatchObject({ name: 'Broken chat title' }) + expect(mocks.generate).not.toHaveBeenCalled() + await state.deps.generate(record, 'Repair login') + expect(mocks.generate).toHaveBeenCalledOnce() + + generate.mockImplementationOnce(async () => { + state.settings.sourceControlAi!.actions!.conversationName = { + commandInputTemplate: 'Custom {basePrompt}' + } + return 'Wrong settings title' + }) + expect( + await state.deps.generate( + record, + 'Repair login', + () => true, + state.deps.captureAutomaticTitle!(record) + ) + ).toEqual({ name: 'Login repair' }) + }) + + it.each(['action', 'shared', 'legacy', 'seeded-default', 'effort', 'template'] as const)( + 'preserves authored %s naming choices without consulting the CLI', + async (choice) => { + const state = rig() + const source = state.settings.sourceControlAi! + if (choice === 'action') { + source.modelOverridesByOperation = { + conversationName: { selectedModelByAgent: { claude: 'opus' } } + } + } + if (choice === 'shared') { + source.selectedModelByAgent = { claude: 'opus' } + } + if (choice === 'legacy') { + state.settings.commitMessageAi!.selectedModelByAgent = { claude: 'opus' } + } + if (choice === 'seeded-default') { + state.settings.commitMessageAi!.selectedModelByAgent = { claude: 'sonnet' } + state.settings.commitMessageAi!.selectedThinkingByModel = { sonnet: 'high' } + } + if (choice === 'effort') { + source.selectedThinkingByModel = { sonnet: 'high' } + } + if (choice === 'template') { + source.actions!.conversationName = { commandInputTemplate: 'Custom {basePrompt}' } + } + const record = agentSessionRecordFixture() + expect( + await state.deps.generate( + record, + 'Repair login', + () => true, + state.deps.captureAutomaticTitle!(record) + ) + ).toEqual({ name: 'Login repair' }) + expect(mocks.titleOwner).not.toHaveBeenCalled() + } + ) it.each(['grok', 'antigravity'] as const)( 'codes %s native naming failures without exposing provider text', async (provider) => { @@ -94,3 +227,497 @@ describe('structured chat naming runtime', () => { } ) }) + +function automaticNaming(state: ReturnType, before?: 'prompt' | 'seed') { + let record = agentSessionRecordFixture() + record.sessionId = 'session-1' + record.lease.sessionId = 'session-1' + record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID + const blocked = Promise.withResolvers() + const entered = Promise.withResolvers() + const awaitPreparationRelease = async (stage: 'prompt' | 'seed') => { + if (before === stage) { + entered.resolve() + await blocked.promise + } + } + const store = { + getRecord: () => record, + compareAndSetConversationName: async (_id, name, expected, context, applicable) => + compareAndSetAgentSessionRecordName( + async (apply) => { + if (expected === null) { + await awaitPreparationRelease('seed') + } + record = apply(record) + return record + }, + name, + expected, + context, + applicable + ), + setUserConversationName: vi.fn() + } satisfies NonNullable> + mocks.record.mockImplementation(() => record) + const handler = createStructuredChatNamingHandler({ + ...state.deps, + getStore: () => store, + readFirstPrompt: async () => { + await awaitPreparationRelease('prompt') + return 'Repair login' + }, + wait: async () => {} + }) + return { + handler, + entered: entered.promise, + release: () => blocked.resolve(), + record: () => record, + replace: () => { + record = { ...record, lease: { ...record.lease, runtimeFence: 8 } } + }, + start: () => + handler( + { + sessionId: record.sessionId, + workspaceId: 'workspace-1', + agent: 'claude', + status: 'working', + latestPrompt: 'Repair login', + updatedAt: 1 + }, + { replay: false, firstInputSubmissionKey: 'input-1' } + ) + } +} + +it.each(['prompt', 'seed', 'workspace', 'support'] as const)( + 'retains the accepted input owner while %s preparation is pending', + async (stage) => { + const state = rig() + const blocked = Promise.withResolvers() + const entered = Promise.withResolvers() + if (stage === 'workspace') { + state.runtime.resolveWorkspace.mockImplementationOnce(async () => { + entered.resolve() + await blocked.promise + return { path: '/workspace/folder', executionHostId: 'local' } + }) + } + const naming = automaticNaming( + state, + stage === 'prompt' || stage === 'seed' ? stage : undefined + ) + const control = vi.fn(async () => 'Successor title') + mocks.titleOwner.mockImplementation(() => { + const fence = naming.record().lease.runtimeFence + return { + isCurrent: (current: AgentSessionRecord) => current.lease.runtimeFence === fence, + generate: async (_prompt: string, shouldExecute: () => boolean) => { + if (stage === 'support') { + entered.resolve() + await blocked.promise + } + return shouldExecute() ? control() : null + } + } + }) + naming.start() + await (stage === 'workspace' || stage === 'support' ? entered.promise : naming.entered) + naming.replace() + naming.release() + blocked.resolve() + await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) + expect(control).not.toHaveBeenCalled() + expect(mocks.generate).toHaveBeenCalledOnce() + expect(naming.record().conversationName).toBe('Login repair') + } +) + +it.each([false, true])( + 'bounds timeout fallback to its owner (retired=%s), retries independently, and ignores late CLI results', + async (retired) => { + const state = rig() + const pending = Promise.withResolvers() + const generateSessionTitle = vi.fn(() => pending.promise) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this flow calls only the feature-detected title method. + const controls = createClaudeControlSurface({ generateSessionTitle } as unknown as Query) + let owned = true + mocks.titleOwner.mockReturnValue({ + isCurrent: () => owned, + generate: controls.generateSessionTitle + }) + mocks.generate + .mockResolvedValueOnce({ success: false, error: 'Retry naming' }) + .mockImplementationOnce(async () => { + if (retired) { + owned = false + } + return { success: true, name: 'Recovered name' } + }) + const naming = automaticNaming(state) + vi.useFakeTimers() + naming.start() + await vi.advanceTimersByTimeAsync(30_000) + expect(naming.record().conversationName).toBe(retired ? 'Repair login' : 'Recovered name') + pending.resolve('Late CLI name') + await vi.advanceTimersByTimeAsync(0) + expect(naming.record().conversationName).toBe(retired ? 'Repair login' : 'Recovered name') + expect(generateSessionTitle).toHaveBeenCalledOnce() + expect(mocks.generate).toHaveBeenCalledTimes(2) + expect(naming.handler.activeSessionIds()).toEqual([]) + } +) + +it.each([ + { support: 'unsupported' as const, transition: 'close', response: 'unused' }, + { support: 'unknown' as const, transition: 'replacement', response: 'unused' }, + { support: 'supported' as const, transition: 'replacement', response: 'error' }, + { support: 'supported' as const, transition: 'close', response: 'null' } +])( + 'finishes independent naming after $transition with support=$support and response=$response', + async ({ support, transition, response }) => { + const cli = fakeClaude() + const adapter = await acquired(cli, { cliFlag: async () => support }) + const state = rig() + const naming = automaticNaming(state) + const entered = Promise.withResolvers() + const independent = + Promise.withResolvers< + Awaited> + >() + const control = vi.fn(async () => { + if (response === 'error') { + throw new Error('Optional control rejected') + } + return response === 'null' ? null : 'Wrong live title' + }) + cli.connections[0]!.generateSessionTitle = control + mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record)) + mocks.generate.mockImplementationOnce(async () => { + entered.resolve() + return independent.promise + }) + try { + naming.start() + await entered.promise + await adapter.closeSession('session-1') + if (transition === 'replacement') { + naming.replace() + await adapter.acquire({ + identity: identityFor(), + fence: 8, + spawnToken: 'replacement', + events: recordingJournalSink() + }) + cli.connections[1]!.generateSessionTitle = control + } + independent.resolve({ success: true, name: 'Independent completion' }) + await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) + expect(naming.record().conversationName).toBe('Independent completion') + expect(control).toHaveBeenCalledTimes(response === 'unused' ? 0 : 1) + } finally { + await adapter.closeAll() + cli.dispose() + } + } +) + +it('discards a retired CLI result and publishes only independent fallback text', async () => { + const cli = fakeClaude() + const adapter = await acquired(cli) + const state = rig() + const naming = automaticNaming(state) + const pending = Promise.withResolvers() + const started = Promise.withResolvers() + cli.connections[0]!.generateSessionTitle = async () => { + started.resolve() + return pending.promise + } + mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record)) + try { + naming.start() + await started.promise + await adapter.closeSession('session-1') + pending.resolve('Stale CLI title') + await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) + expect(naming.record().conversationName).toBe('Login repair') + } finally { + await adapter.closeAll() + cli.dispose() + } +}) + +it.each(['capture', 'pending result'] as const)( + 'keeps the seed and existing naming failure when account lookup fails at %s', + async (stage) => { + const cli = fakeClaude() + const adapter = await acquired(cli) + const state = rig() + const naming = automaticNaming(state) + const router = new ClaudeProfileRouter({ + getSettings: () => ({ + claudeManagedAccounts: [], + activeClaudeManagedAccountId: null, + agentStatusHooksEnabled: false, + disabledTuiAgents: [] + }), + dataRoot: '/isolated', + userHome: '/users/test', + env: {} + }) + const preparation = vi.spyOn(router, 'preparation') + installClaudeProfileRouter(router) + const unavailable = () => { + throw new Error('Selected account folder missing') + } + const pending = Promise.withResolvers() + const started = Promise.withResolvers() + cli.connections[0]!.generateSessionTitle = async () => { + started.resolve() + return pending.promise + } + mocks.titleOwner.mockImplementation((record) => adapter.captureConversationTitleOwner(record)) + state.runtime.resolveNamingEnvironment.mockImplementation(async () => unavailable()) + try { + if (stage === 'capture') { + preparation.mockImplementation(unavailable) + } + naming.start() + if (stage === 'pending result') { + await started.promise + preparation.mockImplementation(unavailable) + pending.resolve('Unusable account title') + } + await vi.waitFor(() => expect(naming.handler.activeSessionIds()).toEqual([])) + expect(naming.record().conversationName).toBe('Repair login') + expect(naming.handler.failure('session-1')?.messageCode).toBe('agentNotRun') + } finally { + await adapter.closeAll() + cli.dispose() + } + } +) + +async function atRestNaming() { + const state = rig() + const chat = await createQueuedMessageTestRig({ + agent: 'claude', + atRest: true, + starting: true, + restartable: true + }) + await vi.waitFor(() => + expect( + chat.host.collaboratorsForTests().conversationDelivery.loop.isRunning(HOST_TEST_SESSION) + ).toBe(false) + ) + mocks.host.mockReturnValue(chat.host) + const title = vi.fn(async () => 'CLI first handover title') + chat.host.deps.adapter.captureConversationTitleOwner = (_record) => { + const child = chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)?.child + if (!child || child.phase !== 'ready') { + return null + } + const isCurrent = (current: AgentSessionRecord) => + current.lease.runtimeFence === child.fence && + chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)?.child === child + return { isCurrent, generate: title } + } + const handler = createStructuredChatNamingHandler({ ...state.deps, now: () => 0 }) + chat.host.deps.onSessionStatusChanged = handler + chat.host.deps.conversationNaming = handler + const done = () => vi.waitFor(() => expect(handler.activeSessionIds()).toEqual([])) + const seeded = () => + vi.waitFor(() => + expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Repair login') + ) + return { state, chat, title, handler, done, seeded } +} + +it.each(['fresh', 'startup retry', 'projected context'] as const)( + 'names an at-rest chat from its first ready handover (%s)', + async (scenario) => { + const { chat, title, done, seeded } = await atRestNaming() + try { + expect(chat.starts).not.toHaveBeenCalled() + const journal = chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal + if (scenario === 'projected context') { + await journal.replaceEpochItems('handle_forked', 1, []) + expect(journal.cursor().epoch).not.toBe(journal.physicalCursor().epoch) + } + if (scenario === 'startup retry') { + chat.failNextStart( + new AgentSessionAcquisitionRootExitObservedError( + new AgentSessionStartFailure(new Error('Temporary start failure'), 'safe') + ) + ) + } + const sent = chat.send('Repair login') + expect(await sent.result).toMatchObject({ ok: true }) + await seeded() + expect(title).not.toHaveBeenCalled() + expect(mocks.generate).not.toHaveBeenCalled() + await journal.resolveDispatch({ + clientMessageId: 'different-input', + state: 'pending', + fence: chat.store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence, + turnScope: AGENT_JOURNAL_THREAD_SCOPE + }) + expect(title).not.toHaveBeenCalled() + await chat.proveStart() + await done() + expect(chat.dispatch).toHaveBeenCalled() + expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe( + 'CLI first handover title' + ) + expect(title).toHaveBeenCalledOnce() + expect(chat.starts).toHaveBeenCalledTimes(scenario === 'startup retry' ? 2 : 1) + expect(mocks.generate).not.toHaveBeenCalled() + } finally { + await chat.dispose() + } + } +) + +it.each(['same-text rename', 'settings', 'auto-off', 'shutdown', 'Stop', 'close', 'held'] as const)( + 'releases a pending first-input title on %s without adopting a future child', + async (exit) => { + const { chat, state, title, handler, done, seeded } = await atRestNaming() + const preclaim = exit === 'Stop' || exit === 'close' || exit === 'held' ? holdDelivery() : null + let stopping: Promise | undefined + try { + expect(await chat.send('Repair login').result).toMatchObject({ ok: true }) + await seeded() + if (exit === 'same-text rename') { + await handler.setUserName(HOST_TEST_SESSION, 'Repair login', 'rename') + } + if (exit === 'settings') { + state.settings.sourceControlAi!.actions!.conversationName = { + commandInputTemplate: 'Custom {basePrompt}' + } + state.settingsChanged() + } + if (exit === 'auto-off') { + state.settings.nativeChatAutoName = false + state.settingsChanged() + } + if (exit === 'shutdown') { + chat.host.stopDelivery() + } + if (preclaim) { + await preclaim.held + expect(chat.starts).not.toHaveBeenCalled() + if (exit === 'Stop') { + stopping = chat.stop() + } + if (exit === 'close') { + stopping = chat.host.close(HOST_TEST_SESSION, 'user-close') + } + if (exit === 'held') { + await holdUnsentSends( + chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal, + { + fence: chat.store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence, + hold: { cause: 'chatClosed' } + } + ) + } + } + await done() + const independent = + exit === 'settings' || exit === 'Stop' || exit === 'close' || exit === 'held' + expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe( + independent ? 'Login repair' : 'Repair login' + ) + expect(mocks.generate).toHaveBeenCalledTimes(independent ? 1 : 0) + expect(title).not.toHaveBeenCalled() + preclaim?.release() + await stopping + if (exit !== 'shutdown' && !preclaim) { + await chat.proveStart() + } + expect(title).not.toHaveBeenCalled() + } finally { + preclaim?.release() + await stopping + await chat.dispose() + } + } +) + +it('retires the selected first-handover source without adopting a replacement child', async () => { + const { chat, title, done } = await atRestNaming() + const entered = Promise.withResolvers() + const result = Promise.withResolvers() + title.mockImplementation(async () => { + entered.resolve() + return result.promise + }) + try { + expect(await chat.send('Repair login').result).toMatchObject({ ok: true }) + await chat.proveStart() + await entered.promise + await chat.host.close(HOST_TEST_SESSION, 'user-close') + const successor = chat.send('A follow-up') + expect(await successor.result).toMatchObject({ ok: true }) + await chat.proveStart() + result.resolve('Stale first CLI title') + await done() + expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Login repair') + expect(title).toHaveBeenCalledOnce() + } finally { + result.resolve('Late') + await chat.dispose() + } +}) + +it('finishes Send now naming during delivery even if recording its failure cannot commit', async () => { + const { chat, title, done, seeded } = await atRestNaming() + const release = chat.holdNextStart() + let releaseSecond: (() => void) | undefined + chat.failNextStart(new AgentSessionStartFailure(new Error('Startup refused'), 'never')) + const fields = { command: 'compact' as const } + const command = chat.host.conversationCommand(QUEUED_RIG_CALLER, { + ...fields, + envelope: chat.envelope(fields, 'agentSession.conversationCommand', hostTestOperationId()) + }) + try { + await vi.waitFor(() => expect(chat.starts).toHaveBeenCalledOnce()) + const sent = chat.send('Repair login') + const queued = await sent.result + if (!queued.ok || !('queued' in queued.value)) { + throw new Error('expected a queued receipt') + } + const messageId = queued.value.queued.messageId + expect(await chat.submission(sent.id)).toBeUndefined() + expect(await chat.sendNow(messageId)).toMatchObject({ ok: true }) + expect(await chat.handoff(messageId)).toMatchObject({ + queuedMessageId: messageId, + dispatchState: 'pending' + }) + await seeded() + const journal = chat.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal + const failure = vi + .spyOn(journal, 'appendLifecycleBatch') + .mockRejectedValue(new Error('Journal write unavailable')) + releaseSecond = chat.holdNextStart() + release() + await vi.waitFor(() => expect(chat.starts).toHaveBeenCalledTimes(2)) + chat.failNextStart(new AgentSessionStartFailure(new Error('Startup refused'), 'never')) + releaseSecond() + await done() + expect(chat.store.getRecord(HOST_TEST_SESSION)?.conversationName).toBe('Login repair') + expect((await chat.handoff(messageId))?.dispatchState).toBe('pending') + expect(title).not.toHaveBeenCalled() + failure.mockRestore() + } finally { + release() + releaseSecond?.() + vi.restoreAllMocks() + await chat.stop() + await command + await chat.dispose() + } +}) diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts index 8a1e7918a54..10a29046d2f 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts @@ -1,5 +1,10 @@ +import { ClaudeControlRequestTimeoutError } from '../../../claude/claude-agent-sdk-control-requests' import { normalizeSourceControlAiSettings } from '../../../../shared/source-control/ai/settings/source-control-ai-settings' -import { resolveSourceControlActionRecipe } from '../../../../shared/source-control/ai/source-control-ai-operation-policy' +import { + resolveSourceControlActionRecipe, + resolveInstructionsFromNormalized +} from '../../../../shared/source-control/ai/source-control-ai-operation-policy' +import { readSourceControlAiModelChoiceForHost } from '../../../../shared/source-control/ai/settings/source-control-ai-model-selection' import { normalizeSourceControlActionRecipe } from '../../../../shared/source-control/ai/recipes/source-control-ai-actions' import { renderConversationNamePrompt, @@ -22,6 +27,7 @@ import { resolveTextGenerationParams } from '../../../text-generation/commit-message-text-generation' import { resolveGenerationTarget } from '../../../agent-hooks/first-work/first-work-generation-target' +import { deferredStructuredChatTitle } from '../../../native-chat/structured-chat-title-handover' type StructuredChatNamingRuntime = { resolveWorkspace: ( @@ -33,11 +39,68 @@ type StructuredChatNamingRuntime = { retitleOpenTab: StructuredChatNamingDeps['onNamed'] } +function canReuseClaudeTitle( + current: Parameters[0], + model: string +): boolean { + const source = normalizeSourceControlAiSettings(current.sourceControlAi, current.commitMessageAi) + const recipe = resolveSourceControlActionRecipe({ + settings: current, + actionId: 'conversationName' + }) + const override = source.modelOverridesByOperation?.conversationName + const choices = [override, source, current.commitMessageAi] + return ( + !recipe.agentId && + !recipe.agentArgs?.trim() && + recipe.commandInputTemplate === '{basePrompt}' && + !resolveInstructionsFromNormalized(source, null, 'conversationName', undefined) && + !choices.some( + (choice) => + readSourceControlAiModelChoiceForHost(choice, LOCAL_COMMIT_MESSAGE_HOST_KEY, 'claude') !== + undefined + ) && + (override?.selectedThinkingByModel?.[model] ?? + source.selectedThinkingByModel[model] ?? + current.commitMessageAi?.selectedThinkingByModel?.[model]) === undefined + ) +} + +function resolveChatNamingParams( + current: Parameters[0], + provider: Parameters[0]['provider'], + recipe = resolveSourceControlActionRecipe({ settings: current, actionId: 'conversationName' }) +) { + const source = normalizeSourceControlAiSettings(current.sourceControlAi, current.commitMessageAi) + const useChatAgent = !recipe.agentId && !recipe.agentArgs?.trim() + return resolveTextGenerationParams( + useChatAgent + ? { + ...current, + sourceControlAi: { + ...source, + actions: { + ...source.actions, + conversationName: normalizeSourceControlActionRecipe({ + ...recipe, + agentId: provider + }) + } + } + } + : current, + LOCAL_COMMIT_MESSAGE_HOST_KEY, + 'conversationName', + null + ) +} + export function structuredChatNamingDeps( getStore: () => { getSettings: () => Parameters[0] & AgentLaunchProfileSettings & ReturnType + onSettingsChanged?: (changed: () => void) => () => void }, runtime: StructuredChatNamingRuntime, logger: StructuredAgentSessionLogger @@ -60,7 +123,49 @@ export function structuredChatNamingDeps( : '' }, workerTaskTitle: runtime.workerTaskTitle, - generate: async (record, firstPrompt, shouldExecute) => { + captureAutomaticTitle: (record, firstInputSubmissionKey, applicable) => { + const current = getStore().getSettings() + if ( + record.provider !== 'claude' || + record.location.wslDistro !== null || + current.nativeChatAutoName === false + ) { + return undefined + } + const settings = resolveChatNamingParams(current, record.provider) + if (!settings.ok || !canReuseClaudeTitle(current, settings.params.model)) { + return undefined + } + const host = getStructuredAgentSessionHost() + const owner = host?.deps.adapter.captureConversationTitleOwner?.(record) ?? null + return { + owner, + pending: + !owner && host && firstInputSubmissionKey && applicable + ? deferredStructuredChatTitle({ + record, + firstInputSubmissionKey, + host, + currentHost: getStructuredAgentSessionHost, + applicable, + eligible: () => { + const current = getStore().getSettings() + const resolved = resolveChatNamingParams(current, record.provider) + return resolved.ok && canReuseClaudeTitle(current, resolved.params.model) + }, + subscribeSettings: (changed) => + getStore().onSettingsChanged?.(changed) ?? (() => {}) + }) + : undefined + } + }, + generate: async function generate(record, firstPrompt, shouldExecute, automaticTitle) { + const titleOwner = automaticTitle?.pending + ? await automaticTitle.pending.ready + : automaticTitle?.owner + if (shouldExecute?.() === false || automaticTitle?.pending?.ended()) { + return null + } // Unsupported execution contexts keep the seed regardless of native naming settings. if (record.location.wslDistro !== null) { return null @@ -70,10 +175,6 @@ export function structuredChatNamingDeps( return null } const current = getStore().getSettings() - const source = normalizeSourceControlAiSettings( - current.sourceControlAi, - current.commitMessageAi - ) const recipe = resolveSourceControlActionRecipe({ settings: current, actionId: 'conversationName' @@ -108,30 +209,47 @@ export function structuredChatNamingDeps( return chatNamingFailure(record.provider === 'grok' ? 'grokFailed' : 'antigravityFailed') } } - const settings = resolveTextGenerationParams( - useChatAgent - ? { - ...current, - sourceControlAi: { - ...source, - actions: { - ...source.actions, - conversationName: normalizeSourceControlActionRecipe({ - ...recipe, - agentId: record.provider - }) - } - } - } - : current, - LOCAL_COMMIT_MESSAGE_HOST_KEY, - 'conversationName', - null - ) + const settings = resolveChatNamingParams(current, record.provider, recipe) if (!settings.ok) { logger.warn(settings.error, log) return { error: settings.error } } + if ( + automaticTitle && + record.provider === 'claude' && + current.nativeChatAutoName !== false && + canReuseClaudeTitle(current, settings.params.model) + ) { + const owner = titleOwner + if (owner) { + const isCurrent = ( + current = getStructuredAgentSessionHost()?.deps.store?.getRecord(record.sessionId) ?? + record + ) => (shouldExecute?.() ?? true) && owner.isCurrent(current) + const eligible = () => + getStore().getSettings().nativeChatAutoName !== false && + canReuseClaudeTitle(getStore().getSettings(), settings.params.model) + let output: unknown + try { + if (isCurrent()) { + output = await owner.generate(firstPrompt, () => isCurrent() && eligible()) + } + } catch (error) { + if (error instanceof ClaudeControlRequestTimeoutError) { + // A timed-out control is still in flight; its fallback keeps the original live owner. + automaticTitle.retainOwnership?.(owner.isCurrent) + if (!isCurrent()) { + return null + } + } + } + const name = typeof output === 'string' ? sanitizeGeneratedConversationName(output) : '' + if (name && isCurrent() && eligible()) { + return { name, shouldApply: (current) => isCurrent(current) && eligible() } + } + return generate(record, firstPrompt, shouldExecute, undefined) + } + } const target = useChatAgent ? await chatNamingAgentTarget( record, diff --git a/src/main/runtime/agent-session/records/agent-session-record-conversation-name.ts b/src/main/runtime/agent-session/records/agent-session-record-conversation-name.ts index 3b9df841fbe..96c62725300 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-conversation-name.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-conversation-name.ts @@ -77,11 +77,13 @@ export async function compareAndSetAgentSessionRecordName( ) => Promise, name: string | null, expected: string | null, - contextId: string | null = null + contextId: string | null = null, + applicable?: (record: AgentSessionRecord) => boolean ): Promise { let matched = false const record = await mutate((current) => { matched = + (applicable?.(current) ?? true) && current.conversationNameSource !== 'user' && (current.conversationName ?? null) === expected && (current.providerContextBoundary?.operationId ?? null) === contextId @@ -94,5 +96,6 @@ export type CompareAndSetConversationName = ( sessionId: string, name: string | null, expected: string | null, - contextId?: string | null + contextId?: string | null, + applicable?: (record: AgentSessionRecord) => boolean ) => Promise diff --git a/src/main/runtime/agent-session/records/agent-session-record-store.ts b/src/main/runtime/agent-session/records/agent-session-record-store.ts index 9462f27c275..5dc57674663 100644 --- a/src/main/runtime/agent-session/records/agent-session-record-store.ts +++ b/src/main/runtime/agent-session/records/agent-session-record-store.ts @@ -175,8 +175,20 @@ export class AgentSessionRecordStore extends AgentSessionRecordTabs { setUserConversationName = (sessionId: string, name: string, write: AgentSessionUserNameWrite) => setAgentSessionRecordUserNameThrough((apply) => this.mutate(sessionId, apply), name, write) - compareAndSetConversationName: CompareAndSetConversationName = (id, name, expected, context) => - compareAndSetAgentSessionRecordName((apply) => this.mutate(id, apply), name, expected, context) + compareAndSetConversationName: CompareAndSetConversationName = ( + id, + name, + expected, + context, + applicable + ) => + compareAndSetAgentSessionRecordName( + (apply) => this.mutate(id, apply), + name, + expected, + context, + applicable + ) /** Launch history is metadata and does not contend with the writer lease. */ pinLaunchDirectory = (sessionId: string, launchDirectory: string): Promise => diff --git a/src/main/runtime/construction/runtime-store-contract.ts b/src/main/runtime/construction/runtime-store-contract.ts index 429ecba0b77..e65b65778b7 100644 --- a/src/main/runtime/construction/runtime-store-contract.ts +++ b/src/main/runtime/construction/runtime-store-contract.ts @@ -21,6 +21,7 @@ export type RuntimeStore = { getProjectGroups?: Store['getProjectGroups'] createProjectGroup?: Store['createProjectGroup'] updateProjectGroup?: Store['updateProjectGroup'] + updateProjectGroups?: Store['updateProjectGroups'] deleteProjectGroup?: Store['deleteProjectGroup'] moveProjectToGroup?: Store['moveProjectToGroup'] getFolderWorkspace?: Store['getFolderWorkspace'] diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts index 6ad22696265..47bfa21315c 100644 --- a/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts +++ b/src/main/runtime/integrations/reviews/runtime-hosted-review-commands.ts @@ -13,7 +13,11 @@ import type { PRRefreshOutcome } from '../../../../shared/github/pull-request-refresh-types' import type { Repo } from '../../../../shared/repo-types' -import { getPRForBranchOutcome } from '../../../github/client/lookup/pr-for-branch-outcome' +import type { DeviceScope } from '../../../../shared/runtime-session-contracts' +import { + getPRForBranchOutcome, + readRecentPhonePROutcome +} from '../../../github/client/lookup/pr-for-branch-outcome' import { getRepoSlug, getRepoUpstream } from '../../../github/client/fetch/repo-slug-upstream' import type { GitHubPRBranchLookupOptions } from '../../../github/client/lookup/pull-request-lookup-data' import { admissionTierForRefreshReason } from '../../../github/pr-refresh-candidate-policy' @@ -72,7 +76,8 @@ export class RuntimeHostedReviewCommands { acceptMergedFallbackPR?: boolean, currentHeadOid?: string | null, reason?: GitHubPRRefreshReason, - userRefresh?: boolean + userRefresh?: boolean, + clientKind?: DeviceScope ): Promise { const repo = await this.deps.resolveRepo(repoSelector) const lookupOptions: GitHubPRBranchLookupOptions = { @@ -93,6 +98,20 @@ export class RuntimeHostedReviewCommands { const lookupOptionArgs: [] | [GitHubPRBranchLookupOptions] = Object.keys(lookupOptions).length > 0 ? [lookupOptions] : [] const connectionId = hostedReviewSshConnectionId(getStoredRepoExecutionHostId(repo)) + // Desktop callers and reason-carrying refreshes keep their own GitHub read. + if (clientKind === 'mobile' && reason === undefined) { + const recent = await readRecentPhonePROutcome( + repo.path, + branch, + linkedPRNumber ?? null, + connectionId, + fallbackPRNumber ?? null, + lookupOptions + ) + if (recent) { + return recent + } + } // Through the coordinator, so a client's read also serves this server's CI-line watches. return runHostedPRRead( { diff --git a/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts b/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts new file mode 100644 index 00000000000..00ec6e32707 --- /dev/null +++ b/src/main/runtime/integrations/reviews/runtime-hosted-review-pr-reuse.test.ts @@ -0,0 +1,153 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { + GitHubPRRefreshReason, + PRRefreshOutcome +} from '../../../../shared/github/pull-request-refresh-types' +import type { + GitHubRepoContext, + LocalGitExecOptions +} from '../../../github/github-repository-identity' +import type { Repo } from '../../../../shared/repo-types' +import type { DeviceScope } from '../../../../shared/runtime-session-contracts' +import { makePR } from '../../../github/pr-refresh-coordinator-test-harness' + +const mocks = vi.hoisted(() => ({ resolve: vi.fn() })) +vi.mock('../../../github/gh-utils', () => ({ + acquire: vi.fn(async () => {}), + release: vi.fn(), + githubRepoContext: ( + repoPath: string, + connectionId: string | null, + options: LocalGitExecOptions + ) => ({ repoPath, connectionId, ...options }), + ghRepoExecOptions: (context: GitHubRepoContext) => context +})) +vi.mock('../../../github/client/lookup/branch-lookup-resolution', () => ({ + resolvePRForBranchOutcome: mocks.resolve +})) +vi.mock('../../../github/pr-refresh-coordinator', () => ({ + runHostedPRRead: (_candidate: unknown, read: () => Promise) => read() +})) +import { RuntimeHostedReviewCommands } from './runtime-hosted-review-commands' + +const repo: Repo = { + id: 'repo-1', + path: '/repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0, + kind: 'git' +} +const commands = new RuntimeHostedReviewCommands({ + resolveRepo: async () => repo, + resolveTarget: async () => ({ repo, repoPath: repo.path }), + getExecutionOptions: () => undefined, + recordCreated: () => {} +}) +const desktopLookup: PRRefreshOutcome = { + kind: 'found', + pr: makePR({ number: 7, title: 'from desktop lookup', headSha: 'head-a' }), + fetchedAt: 1 +} +const freshLookup: PRRefreshOutcome = { + kind: 'found', + pr: makePR({ number: 7, title: 'from fresh lookup', headSha: 'head-a' }), + fetchedAt: 2 +} + +beforeEach(() => { + mocks.resolve.mockReset() + mocks.resolve.mockResolvedValueOnce(desktopLookup).mockResolvedValue(freshLookup) +}) + +describe('phone PR lookups reuse the desktop’s last result', () => { + it.each<{ + label: string + branch: string + headOid: string + clientKind?: DeviceScope + reason?: GitHubPRRefreshReason + userRefresh?: boolean + seedFallback?: number + fallback?: number + expected: string + }>([ + { + label: 'serves a phone read whose head is the PR head', + branch: 'served', + headOid: 'head-a', + clientKind: 'mobile', + expected: 'from desktop lookup' + }, + { + label: 'serves a phone read with the fallback number the PR was found by', + branch: 'same-fallback', + headOid: 'head-a', + clientKind: 'mobile', + seedFallback: 7, + fallback: 7, + expected: 'from desktop lookup' + }, + { + label: 'looks up again when the PR may have come from another fallback number', + branch: 'other-fallback', + headOid: 'head-a', + clientKind: 'mobile', + seedFallback: 7, + expected: 'from fresh lookup' + }, + { + label: 'looks up again when the PR head differs', + branch: 'moved', + headOid: 'head-b', + clientKind: 'mobile', + expected: 'from fresh lookup' + }, + { + label: 'looks up again for a phone read with a reason', + branch: 'reason', + headOid: 'head-a', + clientKind: 'mobile', + reason: 'visible', + expected: 'from fresh lookup' + }, + { + label: 'looks up again for a phone Refresh', + branch: 'refresh', + headOid: 'head-a', + clientKind: 'mobile', + userRefresh: true, + expected: 'from fresh lookup' + }, + { + label: 'looks up again for a desktop caller', + branch: 'desktop', + headOid: 'head-a', + clientKind: 'runtime', + expected: 'from fresh lookup' + } + ])('$label', async (testCase) => { + const { branch, headOid, clientKind, reason, userRefresh, expected } = testCase + await commands.getRepoPRForBranch( + repo.id, + branch, + null, + testCase.seedFallback ?? null, + false, + 'head-a', + 'visible' + ) + const outcome = await commands.getRepoPRForBranch( + repo.id, + branch, + null, + testCase.fallback ?? null, + false, + headOid, + reason, + userRefresh, + clientKind + ) + expect(outcome.kind === 'found' ? outcome.pr.title : null).toBe(expected) + }) +}) diff --git a/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay-hosts.ts b/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay-hosts.ts index 62d90ce20f9..8025a73be22 100644 --- a/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay-hosts.ts +++ b/src/main/runtime/mobile-desktop-relay/mobile-desktop-relay-hosts.ts @@ -77,6 +77,8 @@ export type MobileDesktopRelayHosts = { ) => Promise onEnvironmentRetired: (listener: (environmentId: string) => void) => () => void onStatusChanged: (listener: () => void) => () => void + /** The saved server list was edited (added, renamed, removed), here or by the CLI. */ + onCatalogChanged?: (listener: () => void) => () => void /** Windowless server events: onChange fires on ready, catalog changes and reconnect replay. * catalog is false only for worktreesChanged; repo/project-group writes never emit that event alone. */ watchChanges: ( diff --git a/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts index ab8229178c6..0c0a0ebeee0 100644 --- a/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts +++ b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.test.ts @@ -8,8 +8,6 @@ import { import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope' import type { RuntimeStatus } from '../../../shared/runtime-session-contracts' import type { SshConnectionState } from '../../../shared/ssh-types' -import { getDefaultWorkspaceSession } from '../../../shared/constants' -import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { MobileDesktopRelayHosts } from './mobile-desktop-relay-hosts' import { MobileRelayHostCatalog } from './mobile-relay-host-catalog' @@ -69,6 +67,7 @@ function fakeHosts( environments, pairingRevision: 1, retire: (_environmentId: string) => {}, + statusChanged: () => {}, sshTargetLabels: new Map(), sshConnectionStates: new Map() } @@ -119,22 +118,16 @@ function fakeHosts( state.retire = listener return () => {} }, - onStatusChanged: () => () => {}, + onStatusChanged: (listener) => { + state.statusChanged = listener + return () => {} + }, watchChanges: () => ({ close: () => {}, current: () => true }) } return { hosts, call, state } } -function catalog( - hosts: MobileDesktopRelayHosts, - labels = new Map(), - desktop: { - sessions?: Record> - recipeEnvironmentsFor?: ( - hostId: string - ) => ReadonlyMap - } = {} -) { +function catalog(hosts: MobileDesktopRelayHosts) { const serverRows = new PairedServerRowsProducer({ hasDemand: () => false, hostLabelOverrides: () => new Map() @@ -144,69 +137,13 @@ function catalog( catalog: new MobileRelayHostCatalog({ hosts, serverRows, - hostLabelOverrides: () => labels, - getWorkspaceSession: (hostId) => { - const session = desktop.sessions?.[hostId] - return session ? { ...getDefaultWorkspaceSession(), ...session } : null - }, - ...(desktop.recipeEnvironmentsFor - ? { recipeEnvironmentsFor: desktop.recipeEnvironmentsFor } - : {}) + hostLabelOverrides: () => new Map(), + getWorkspaceSession: () => null }) } } describe('mobile relay host catalog', () => { - it('names the recipe environment on rows whose VM this desktop created, and only those', async () => { - const { hosts, call } = fakeHosts([ - { id: 'env', name: 'Box', snapshot: snapshot('env', 'live') } - ]) - call.mockResolvedValueOnce( - psReply([ - { worktreeId: 'recipe-row', hostId: 'local' }, - { worktreeId: 'plain-row', hostId: 'local' } - ]) - ) - const lookups: string[] = [] - const { catalog: hostCatalog } = catalog(hosts, new Map(), { - recipeEnvironmentsFor: (hostId) => { - lookups.push(hostId) - return new Map([['recipe-row', { name: 'task', destroys: true }]]) - } - }) - await expect(hostCatalog.worktrees('runtime:env')).resolves.toEqual({ - worktrees: [ - { - worktreeId: 'recipe-row', - hostId: 'runtime:env', - recipeEnvironment: { name: 'task', destroys: true } - }, - { worktreeId: 'plain-row', hostId: 'runtime:env' } - ] - }) - // One store read per poll, not one per row. - expect(lookups).toEqual(['runtime:env']) - }) - - it("drops a server's own recipe-environment claim and survives an unreadable VM store", async () => { - const { hosts, call } = fakeHosts([ - { id: 'env', name: 'Box', snapshot: snapshot('env', 'live') } - ]) - call.mockResolvedValue( - psReply([ - { worktreeId: 'claimed', hostId: 'local', recipeEnvironment: { name: 'x', destroys: true } } - ]) - ) - const { catalog: hostCatalog } = catalog(hosts, new Map(), { - recipeEnvironmentsFor: () => { - throw new Error('store unreadable') - } - }) - await expect(hostCatalog.worktrees('runtime:env')).resolves.toEqual({ - worktrees: [{ worktreeId: 'claimed', hostId: 'runtime:env' }] - }) - }) - it('never serves rows from before a re-pair mid-fetch, and the next poll fetches the new server afresh', async () => { const { hosts, call, state } = fakeHosts([ { id: 'env', name: 'Box', snapshot: snapshot('env', 'live') } diff --git a/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.ts b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.ts index 491adb8f51f..f313e1e2c62 100644 --- a/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.ts +++ b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-catalog.ts @@ -20,6 +20,14 @@ import { SERVER_FETCH_TIMEOUT_MS } from './server-worktree-fetch' import { normalizePairedServerRow } from '../../../shared/sidebar-list/paired-server-rows' import type { MobileDesktopRelayHosts } from './mobile-desktop-relay-hosts' import { describeRelayHosts, relayHostFence } from './mobile-relay-host-descriptions' +import { + RelayHostListAnnouncer, + type RelayHostListAnnouncerSources +} from './mobile-relay-host-list-announcer' +import { + isPendingVmCheckout, + type PendingVmCheckoutIndex +} from '../../../shared/pending-vm-checkouts' export type MobileRelayRecipeEnvironmentLookup = ( hostId: string @@ -56,6 +64,8 @@ export class MobileRelayHostCatalog { hostLabelOverrides: () => ReadonlyMap getWorkspaceSession: (hostId: ExecutionHostId) => WorkspaceSessionState | null recipeEnvironmentsFor?: MobileRelayRecipeEnvironmentLookup + /** VM checkouts a desktop create has not adopted yet; the phone must not list them. */ + pendingVmCheckouts?: () => PendingVmCheckoutIndex now?: () => number } ) {} @@ -124,8 +134,9 @@ export class MobileRelayHostCatalog { return undefined } const key = worktreeIdentityKey(worktreeId) + const pending = this.options.pendingVmCheckouts?.() for (const raw of rows) { - if (raw.removing === true) { + if (raw.removing === true || (pending && isPendingVmCheckout(pending, raw))) { continue } const row = normalizePairedServerRow(hostId, raw) @@ -142,7 +153,27 @@ export class MobileRelayHostCatalog { return null } + private announcer: RelayHostListAnnouncer | null = null + list(): MobileRelayHostsListResult { + const result = this.describe() + this.announcer?.listed(result) + return result + } + + /** Calls `changed` whenever list() would answer differently, so phones need not poll it. */ + publishListChanges(sources: RelayHostListAnnouncerSources): () => void { + const announcer = new RelayHostListAnnouncer(this.options.hosts, () => this.describe(), sources) + this.announcer = announcer + return () => { + announcer.dispose() + if (this.announcer === announcer) { + this.announcer = null + } + } + } + + private describe(): MobileRelayHostsListResult { return { hosts: describeRelayHosts(this.options.hosts, this.options.hostLabelOverrides()).map( ({ @@ -211,10 +242,11 @@ export class MobileRelayHostCatalog { // The tag only decorates rows; an unreadable VM store must not blank the phone's list. recipeEnvironments = undefined } + const pending = this.options.pendingVmCheckouts?.() // Only desktop reads request background-removal support. return { worktrees: rows - .filter((row) => row.removing !== true) + .filter((row) => row.removing !== true && !(pending && isPendingVmCheckout(pending, row))) .map((row) => stampRecipeEnvironment( stampDesktopSidebarView(row, host.environmentId, desktopDeviceIds, sessionActivity), diff --git a/src/main/runtime/mobile-desktop-relay/mobile-relay-host-list-announcer.ts b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-list-announcer.ts new file mode 100644 index 00000000000..c5df332e736 --- /dev/null +++ b/src/main/runtime/mobile-desktop-relay/mobile-relay-host-list-announcer.ts @@ -0,0 +1,117 @@ +import type { RuntimeClientEvent } from '../../../shared/runtime-client-events' +import type { MobileRelayHostsListResult } from '../../../shared/remote-runtime/relay/mobile-relay-hosts-contract' +import type { MobileDesktopRelayHosts } from './mobile-desktop-relay-hosts' + +// A phone holding the list reads it at least every 60 s (its backstop); three missed reads means none is left. +export const PHONE_LIST_IDLE_MS = 3 * 60_000 + +export type RelayHostListAnnouncerSources = { + onClientEvent: (listener: (event: RuntimeClientEvent) => void) => () => void + changed: () => void +} + +type Watching = { announced: string; stop: () => void; idle: ReturnType } + +/** + * Calls `changed` whenever the host list would answer differently from what phones last saw. + * It watches only while phones read the list: a desktop no phone asks pays no watch or timer. + */ +export class RelayHostListAnnouncer { + private watching: Watching | null = null + private disposed = false + + constructor( + private readonly hosts: MobileDesktopRelayHosts, + private readonly describe: () => MobileRelayHostsListResult, + private readonly sources: RelayHostListAnnouncerSources + ) {} + + /** A phone just read `result`. */ + listed(result: MobileRelayHostsListResult): void { + if (this.disposed) { + return + } + if (this.watching) { + clearTimeout(this.watching.idle) + this.watching.idle = this.idleTimer() + return + } + // Later reads don't move the baseline: a read racing a change would hide it from other phones. + this.watching = { + announced: JSON.stringify(result), + stop: this.watch(), + idle: this.idleTimer() + } + } + + dispose(): void { + this.disposed = true + this.stopWatching() + } + + private idleTimer(): ReturnType { + const timer = setTimeout(() => this.stopWatching(), PHONE_LIST_IDLE_MS) + timer.unref?.() + return timer + } + + private stopWatching(): void { + const watching = this.watching + this.watching = null + if (watching) { + clearTimeout(watching.idle) + watching.stop() + } + } + + private watch(): () => void { + let queued = false + const check = (): void => { + if (queued) { + return + } + queued = true + // One change can reach several sources, e.g. a retirement and its new status owner. + queueMicrotask(() => { + queued = false + const watching = this.watching + if (!watching) { + return + } + const next = this.describeForAnnouncement() + if (next !== watching.announced) { + watching.announced = next + this.sources.changed() + } + }) + } + const stops = [ + this.hosts.onStatusChanged(check), + this.hosts.onEnvironmentRetired(check), + this.hosts.onCatalogChanged?.(check), + this.sources.onClientEvent((event) => { + // SSH targets carry managed servers' labels and health; host label overrides live in settings. + if ( + event.type === 'sshStateChanged' || + (event.type === 'settingsChanged' && event.keys.includes('hostSettingOverrides')) + ) { + check() + } + }) + ] + return () => { + for (const stop of stops) { + stop?.() + } + } + } + + // A store that can't be read must not throw here, outside any request; phones re-read and get the error. + private describeForAnnouncement(): string { + try { + return JSON.stringify(this.describe()) + } catch { + return 'unreadable' + } + } +} diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 8c28e659ffb..aeebd8bad02 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -61,6 +61,7 @@ import { HEADLESS_RUNTIME_WINDOW_ID } from '../../shared/runtime-session-contrac import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' import type { OrchestrationDb } from './orchestration/db/orchestration-db' import { continueRestoredWorkerMailSoon } from './rpc/methods/orchestration/messaging/settled-worker-follow-through' +import { PeerMailRelay } from './orchestration/federation/peer-mail/peer-mail-relay' const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDEBAR_INPUTS_IS_MAIN ? OrcaRuntimeWithSidebarTemporal @@ -68,6 +69,20 @@ const OrcaRuntimeSidebarBase: typeof OrcaRuntimeWithAgentTransitions = ORCA_SIDE // oxlint-disable-next-line typescript/no-unsafe-declaration-merging -- SAFETY: The existing Linear installer supplies the canonical prototype surface. class OrcaRuntimeService extends OrcaRuntimeSidebarBase { + // Lazy: the database can open, and arm relays, while the runtime is still constructing. + declare private peerMailRelay: PeerMailRelay | undefined + + override ensureOrchestrationFederationRelay(runId?: string): void { + super.ensureOrchestrationFederationRelay(runId) + this.peerMailRelay ??= new PeerMailRelay(this, () => this.orchestrationEnvironmentTransport) + this.peerMailRelay.ensure() + } + + override stopOrchestrationFederationRelay(): void { + super.stopOrchestrationFederationRelay() + this.peerMailRelay?.stop() + } + /** Sidebar facts are absent unless ORCA_SIDEBAR_INPUTS=main. */ get sidebarFacts() { return sidebarFactsRuntime(this) @@ -179,6 +194,11 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { publishSettingsChanges(this.store, (event) => this.emitClientEvent(event)) } + /** What mobileRelay.hosts.list answers changed. */ + notifyRelayHostsChanged(): void { + this.emitClientEvent({ type: 'relayHostsChanged' }) + } + private structuredAgentAvailability?: ReturnType /** Subscribe from first use; returns the release function. */ diff --git a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts index f15cb9c577a..a8d353e63a1 100644 --- a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts @@ -18,6 +18,7 @@ import { attachRemoteDispatchAttachmentCreate } from './federation/remote-dispat import { attachRemoteDispatchAttachmentRelease } from './federation/remote-dispatch-attachment-release' import { attachRemoteDispatchAttachmentStop } from './federation/remote-dispatch-attachment-stop' import { attachRemoteQuestionStore } from './federation/remote-question-store' +import { attachPeerMailStore } from './federation/peer-mail-store' import { attachLegacyAskOperation } from './legacy/legacy-ask-operation' import { attachLegacyCompatibilityCandidates } from './legacy/legacy-compatibility-candidates' import { attachLegacyCompatibilityPrincipals } from './legacy/legacy-compatibility-principals' @@ -122,6 +123,7 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void attachFederationRelayAck(ctor) attachFederationRelayImport(ctor) attachRemoteQuestionStore(ctor) + attachPeerMailStore(ctor) attachFederationRelayItem(ctor) attachWorkerTerminalResourceStore(ctor) attachWorkerTerminalTransfer(ctor) diff --git a/src/main/runtime/orchestration/db/federation/peer-mail-store.ts b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts new file mode 100644 index 00000000000..da829b40e5e --- /dev/null +++ b/src/main/runtime/orchestration/db/federation/peer-mail-store.ts @@ -0,0 +1,182 @@ +import type { MessageRow } from '../orchestration-records' +import type { MessageInsert } from '../messages/message-insert' +import { OrchestrationError } from '../../orchestration-error' +import { generateId } from '../generated-id' +import type { OrchestrationDb } from '../orchestration-db' + +export type PeerMailConversationRow = { + conversation_id: string + role: 'home' | 'peer' + environment_id: string | null + peer_fingerprint: string + local_party: string | null + local_pane_key: string | null + created_at: string +} + +export type PeerMailMessageRow = { + message_id: string + conversation_id: string + sender_label: string + remote_party: string | null +} + +/** The conversation this Orca opened for one local agent with one paired server's current pairing; reused for every send. */ +export function openHomePeerMailConversation( + this: OrchestrationDb, + params: { + environmentId: string + peerFingerprint: string + localParty: string + localPaneKey: string | null + } +): PeerMailConversationRow { + this.db + .prepare( + `INSERT INTO peer_mail_conversations ( + conversation_id, role, environment_id, peer_fingerprint, local_party, local_pane_key + ) VALUES (?, 'home', ?, ?, ?, ?) + ON CONFLICT(environment_id, local_party, peer_fingerprint) WHERE role = 'home' + DO UPDATE SET local_pane_key = COALESCE(excluded.local_pane_key, local_pane_key)` + ) + .run( + generateId('peerconv'), + params.environmentId, + params.peerFingerprint, + params.localParty, + params.localPaneKey + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly its row shape. + return this.db + .prepare( + `SELECT * FROM peer_mail_conversations + WHERE role = 'home' AND environment_id = ? AND local_party = ? AND peer_fingerprint = ?` + ) + .get(params.environmentId, params.localParty, params.peerFingerprint) as PeerMailConversationRow +} + +export function getPeerMailConversation( + this: OrchestrationDb, + conversationId: string +): PeerMailConversationRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly its row shape. + return this.db + .prepare('SELECT * FROM peer_mail_conversations WHERE conversation_id = ?') + .get(conversationId) as PeerMailConversationRow | undefined +} + +export function listHomePeerMailEnvironments(this: OrchestrationDb): string[] { + const statement = this.db.prepare( + `SELECT DISTINCT environment_id FROM peer_mail_conversations + WHERE role = 'home' AND environment_id IS NOT NULL` + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns. + const rows = statement.all() as { environment_id: string }[] + return rows.map((row) => row.environment_id) +} + +export function listPeerConversationIds(this: OrchestrationDb, peerFingerprint: string): string[] { + const statement = this.db.prepare( + `SELECT conversation_id FROM peer_mail_conversations + WHERE role = 'peer' AND peer_fingerprint = ?` + ) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly these columns. + const rows = statement.all(peerFingerprint) as { conversation_id: string }[] + return rows.map((row) => row.conversation_id) +} + +export function getPeerMailMessage( + this: OrchestrationDb, + messageId: string +): PeerMailMessageRow | undefined { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SELECT over this table returns exactly its row shape. + return this.db.prepare('SELECT * FROM peer_mail_messages WHERE message_id = ?').get(messageId) as + | PeerMailMessageRow + | undefined +} + +export function isPeerMailSenderLabel(this: OrchestrationDb, label: string): boolean { + return ( + this.db + .prepare('SELECT 1 FROM peer_mail_messages WHERE sender_label = ? LIMIT 1') + .get(label) !== undefined + ) +} + +/** Stores mail that crossed from a paired Orca once; a replayed id is a duplicate, even after a reset removed its row. */ +export function insertPeerMailMessage( + this: OrchestrationDb, + params: { + conversationId: string + /** Only a 'peer' conversation is created here, by the paired Orca that opened it. */ + peerFingerprint?: string + remoteParty: string | null + message: MessageInsert & { id: string; from: string } + } +): + | { message: MessageRow; duplicate: false } + | { message: MessageRow | undefined; duplicate: true } { + this.db.exec('SAVEPOINT peer_mail_insert') + try { + if (params.peerFingerprint !== undefined) { + const conversation = this.getPeerMailConversation(params.conversationId) + if ( + conversation && + (conversation.role !== 'peer' || conversation.peer_fingerprint !== params.peerFingerprint) + ) { + throw new OrchestrationError( + 'request_mismatch', + `Conversation ${params.conversationId} belongs to another server. Nothing was delivered.`, + { effectsApplied: false } + ) + } + if (!conversation) { + this.db + .prepare( + `INSERT INTO peer_mail_conversations (conversation_id, role, peer_fingerprint) + VALUES (?, 'peer', ?)` + ) + .run(params.conversationId, params.peerFingerprint) + } + } + if (this.getPeerMailMessage(params.message.id)) { + this.db.exec('RELEASE peer_mail_insert') + return { message: this.getMessageById(params.message.id), duplicate: true } + } + const message = this.insertMessage(params.message) + this.db + .prepare( + `INSERT INTO peer_mail_messages (message_id, conversation_id, sender_label, remote_party) + VALUES (?, ?, ?, ?)` + ) + .run(message.id, params.conversationId, params.message.from, params.remoteParty) + this.db.exec('RELEASE peer_mail_insert') + return { message, duplicate: false } + } catch (error) { + this.db.exec('ROLLBACK TO peer_mail_insert') + this.db.exec('RELEASE peer_mail_insert') + throw error + } +} + +export type PeerMailStoreMethods = { + openHomePeerMailConversation: typeof openHomePeerMailConversation + getPeerMailConversation: typeof getPeerMailConversation + listHomePeerMailEnvironments: typeof listHomePeerMailEnvironments + listPeerConversationIds: typeof listPeerConversationIds + getPeerMailMessage: typeof getPeerMailMessage + isPeerMailSenderLabel: typeof isPeerMailSenderLabel + insertPeerMailMessage: typeof insertPeerMailMessage +} + +export function attachPeerMailStore(ctor: { prototype: object }): void { + Object.assign(ctor.prototype, { + openHomePeerMailConversation, + getPeerMailConversation, + listHomePeerMailEnvironments, + listPeerConversationIds, + getPeerMailMessage, + isPeerMailSenderLabel, + insertPeerMailMessage + }) +} diff --git a/src/main/runtime/orchestration/db/orchestration-db-methods.ts b/src/main/runtime/orchestration/db/orchestration-db-methods.ts index 1de24dd9a41..824b031a2ee 100644 --- a/src/main/runtime/orchestration/db/orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/orchestration-db-methods.ts @@ -17,6 +17,7 @@ import type { RemoteDispatchAttachmentCreateMethods } from './federation/remote- import type { RemoteDispatchAttachmentReleaseMethods } from './federation/remote-dispatch-attachment-release' import type { RemoteDispatchAttachmentStopMethods } from './federation/remote-dispatch-attachment-stop' import type { RemoteQuestionStoreMethods } from './federation/remote-question-store' +import type { PeerMailStoreMethods } from './federation/peer-mail-store' import type { LegacyAskOperationMethods } from './legacy/legacy-ask-operation' import type { LegacyCompatibilityCandidatesMethods } from './legacy/legacy-compatibility-candidates' import type { LegacyCompatibilityPrincipalsMethods } from './legacy/legacy-compatibility-principals' @@ -119,6 +120,7 @@ export type OrchestrationDbMethods = AttemptObservationStoreMethods & FederationRelayAckMethods & FederationRelayImportMethods & RemoteQuestionStoreMethods & + PeerMailStoreMethods & FederationRelayItemMethods & StructuredMailSendStoreMethods & WorkerTerminalResourceStoreMethods & diff --git a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts index cd13b00ff8b..ac68ba65767 100644 --- a/src/main/runtime/orchestration/db/reset/orchestration-reset.ts +++ b/src/main/runtime/orchestration/db/reset/orchestration-reset.ts @@ -58,7 +58,7 @@ export function resetAll(this: OrchestrationDb): void { } export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined { - // Messages survive; close threads so orphaned questions cannot masquerade as generic replies. + // Messages survive, and so do replies waiting for a paired Orca to pull them; close threads so orphaned questions cannot masquerade as generic replies. const watermark = this.runResetTransaction(` DELETE FROM coordinator_runs; DELETE FROM decision_gates; @@ -70,7 +70,7 @@ export function resetTasks(this: OrchestrationDb): ResetRemovedWork | undefined DELETE FROM legacy_operation_receipts; DELETE FROM legacy_compatibility_principals; DELETE FROM legacy_adoptions; - DELETE FROM federation_relay_items; + DELETE FROM federation_relay_items WHERE kind <> 'peer_mail'; DELETE FROM remote_dispatch_attachments; DELETE FROM federated_dispatches; DELETE FROM worker_terminal_archives; diff --git a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts index 9d0faa09527..4eb92b8eef8 100644 --- a/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts +++ b/src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts @@ -115,6 +115,34 @@ CREATE TABLE IF NOT EXISTS remote_questions ( CREATE INDEX IF NOT EXISTS idx_remote_questions_dispatch_status ON remote_questions(dispatch_id, status); +-- Agent mail between paired Orcas. 'home': this Orca opened it for local_party and pulls replies +-- from environment_id over the pairing credential peer_fingerprint, so a re-pair opens a new one. 'peer': the paired Orca peer_fingerprint opened it here; its replies wait in +-- federation_relay_items under dispatch_id = conversation_id until that Orca pulls them. +CREATE TABLE IF NOT EXISTS peer_mail_conversations ( + conversation_id TEXT PRIMARY KEY, + role TEXT NOT NULL CHECK(role IN ('home', 'peer')), + environment_id TEXT, + peer_fingerprint TEXT NOT NULL, + local_party TEXT, + local_pane_key TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_peer_mail_home_pairing + ON peer_mail_conversations(environment_id, local_party, peer_fingerprint) WHERE role = 'home'; +CREATE INDEX IF NOT EXISTS idx_peer_mail_peer_fingerprint + ON peer_mail_conversations(peer_fingerprint, role); + +-- A message that crossed between paired Orcas: its reply goes back over its conversation, to remote_party. +CREATE TABLE IF NOT EXISTS peer_mail_messages ( + message_id TEXT PRIMARY KEY, + conversation_id TEXT NOT NULL, + sender_label TEXT NOT NULL, + remote_party TEXT +); + +CREATE INDEX IF NOT EXISTS idx_peer_mail_messages_sender ON peer_mail_messages(sender_label); + -- Deletes from tasks, dispatch_contexts and worker tables are recorded in removed_orchestration_work -- (removed-orchestration-work-store.ts). CREATE TABLE IF NOT EXISTS tasks ( diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-delivery.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-delivery.ts new file mode 100644 index 00000000000..80cd096e51f --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-delivery.ts @@ -0,0 +1,122 @@ +import { createHash } from 'node:crypto' +import { ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities' +import { z } from 'zod' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import type { PeerMailConversationRow } from '../../db/federation/peer-mail-store' +import { generateId } from '../../db/generated-id' +import { OrchestrationError } from '../../orchestration-error' +import type { OrchestrationWorkerServer } from '../environment-transport' + +export type PeerMailRuntime = Pick< + OrcaRuntimeService, + | 'getOrchestrationDb' + | 'resolveOrchestrationWorkerServer' + | 'callOrchestrationWorkerServer' + | 'notifyMessageArrived' + | 'readMachineName' + | 'getTerminalHandleForPaneKey' +> + +const NOTHING_SENT = { effectsApplied: false } as const +const RuntimeStatusCapabilities = z.object({ capabilities: z.array(z.string()).optional() }) +const DELIVER_TIMEOUT_MS = 15_000 + +/** "term_9f3c on Jinwoo's Mac": who sent it, and the Orca server it came from. */ +export function peerMailSenderLabel(runtime: PeerMailRuntime, sender: string): string { + return `${sender} on ${runtime.readMachineName()}` +} + +/** A retried mutation reuses its message id, so the server stores the mail once. */ +export function peerMailMessageId( + mutation: { callerFingerprint: string; requestId: string } | undefined +): string { + if (!mutation) { + return generateId('msg') + } + const digest = createHash('sha256') + .update(`${mutation.callerFingerprint}\0${mutation.requestId}`) + .digest('hex') + return `msg_${digest.slice(0, 12)}` +} + +/** Refuses before any effect when the server's Orca cannot receive mail or queue its replies. */ +export async function requirePeerMailServer( + runtime: PeerMailRuntime, + selector: string +): Promise { + const server = runtime.resolveOrchestrationWorkerServer(selector) + const status = RuntimeStatusCapabilities.safeParse( + await runtime.callOrchestrationWorkerServer( + server.environmentId, + 'status.get', + undefined, + DELIVER_TIMEOUT_MS, + undefined, + { expectedEnvironmentPairingRevision: server.pairingRevision } + ) + ) + if ( + !status.success || + !status.data.capabilities?.includes(ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY) + ) { + throw new OrchestrationError( + 'server_mail_unsupported', + `Server ${server.name} runs an older Orca that cannot receive agent mail from another server. Update Orca on ${server.name}, then send again. Nothing was sent.`, + { ...NOTHING_SENT, server: server.name } + ) + } + return server +} + +/** The pairing credential the server knows this Orca by; a re-pair starts new conversations under it. */ +export function peerMailPairing(server: OrchestrationWorkerServer): string { + return server.homePeerFingerprint ?? server.peerFingerprint +} + +/** Hands one message to the paired server; it stores it once and delivers it with its own mail code. */ +export async function deliverPeerMail( + runtime: PeerMailRuntime, + server: OrchestrationWorkerServer, + conversation: PeerMailConversationRow, + message: { + id: string + to: string + senderLabel: string + subject: string + body?: string + type?: 'status' | 'handoff' + priority?: 'normal' | 'high' | 'urgent' + threadId?: string + } +): Promise { + await runtime.callOrchestrationWorkerServer( + server.environmentId, + 'orchestration.peerMailDeliver', + { + conversationId: conversation.conversation_id, + messageId: message.id, + to: message.to, + senderLabel: message.senderLabel, + subject: message.subject, + ...(message.body !== undefined ? { body: message.body } : {}), + ...(message.type ? { type: message.type } : {}), + ...(message.priority ? { priority: message.priority } : {}), + ...(message.threadId ? { threadId: message.threadId } : {}) + }, + DELIVER_TIMEOUT_MS, + undefined, + { expectedEnvironmentPairingRevision: server.pairingRevision } + ) +} + +/** Where a pulled reply lands: the opener's current mailbox, following a terminal's remint by pane. */ +export function peerMailLocalRecipient( + runtime: PeerMailRuntime, + conversation: PeerMailConversationRow +): string { + const party = conversation.local_party ?? '' + const reminted = conversation.local_pane_key + ? runtime.getTerminalHandleForPaneKey(conversation.local_pane_key) + : null + return reminted ?? party +} diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts new file mode 100644 index 00000000000..e2ac481adc8 --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-relay.ts @@ -0,0 +1,183 @@ +import { z } from 'zod' +import type { OrcaRuntimeService } from '../../../orca-runtime' +import { PeerMailRelayPayload } from '../../../../../shared/rpc-contract/orchestration-peer-mail-params' +import { resolveBareOrchestrationRecipient } from '../../../rpc/methods/orchestration/messaging/recipient-routing' +import type { OrchestrationDb } from '../../db/orchestration-db' +import type { MessageRow } from '../../db/orchestration-records' +import { federationRelayRetryDelayMs } from '../relay/federation-relay-scheduler' +import type { OrchestrationEnvironmentTransport } from '../environment-transport' +import { peerMailLocalRecipient } from './peer-mail-delivery' + +// Under the relay edge's idle cutoff, so an idle pull ends by itself instead of being dropped. +const PULL_WAIT_MS = 20_000 +const PULL_TIMEOUT_MS = PULL_WAIT_MS + 15_000 + +const PulledPeerMail = z.object({ + items: z.array( + z.object({ + conversationId: z.string(), + sequence: z.number().int().positive(), + messageId: z.string(), + payload: z.string() + }) + ) +}) + +type Loop = { db: OrchestrationDb; stopped: boolean } + +/** One pull loop per paired server this Orca opened conversations with. The server never dials + * back: each pull waits there for a reply, stores it as local mail, then acknowledges it. */ +export class PeerMailRelay { + private readonly loops = new Map() + + constructor( + private readonly runtime: OrcaRuntimeService, + private readonly transport: () => OrchestrationEnvironmentTransport | null + ) {} + + ensure(): void { + if (!this.transport()) { + return + } + const db = this.runtime.getOrchestrationDb() + for (const environmentId of db.listHomePeerMailEnvironments()) { + const current = this.loops.get(environmentId) + if (current && !current.stopped && current.db === db) { + continue + } + const loop: Loop = { db, stopped: false } + this.loops.set(environmentId, loop) + void this.run(environmentId, loop) + } + } + + stop(): void { + for (const loop of this.loops.values()) { + loop.stopped = true + } + this.loops.clear() + } + + private isCurrent(environmentId: string, loop: Loop): boolean { + return ( + !loop.stopped && + this.loops.get(environmentId) === loop && + this.runtime.getOrchestrationDb() === loop.db + ) + } + + private async run(environmentId: string, loop: Loop): Promise { + let failures = 0 + while (this.isCurrent(environmentId, loop)) { + try { + await this.pullOnce(environmentId, loop) + failures = 0 + } catch { + if (this.isEnvironmentRemoved(environmentId)) { + // A removed server cannot answer; the next ensure re-arms it if it is added back. + break + } + failures += 1 + await new Promise((resolve) => { + setTimeout(resolve, federationRelayRetryDelayMs(failures)).unref?.() + }) + } + } + if (this.loops.get(environmentId) === loop) { + this.loops.delete(environmentId) + } + } + + /** A store read error keeps the loop retrying rather than ending it. */ + private isEnvironmentRemoved(environmentId: string): boolean { + try { + return this.transport()?.hasEnvironment?.(environmentId) === false + } catch { + return false + } + } + + private async pullOnce(environmentId: string, loop: Loop): Promise { + const response = await this.runtime.callOrchestrationWorkerServer( + environmentId, + 'orchestration.peerMailPull', + { waitMs: PULL_WAIT_MS }, + PULL_TIMEOUT_MS + ) + if (!this.isCurrent(environmentId, loop)) { + return + } + const { items } = PulledPeerMail.parse(response) + if (items.length === 0) { + return + } + const through = new Map() + for (const item of items) { + const stored = this.importReply(loop.db, environmentId, item) + // Wake before the ack: a replay after a failed ack finds the row stored and stays quiet. + if (stored) { + this.runtime.notifyMessageArrived(stored.to_handle, stored.type) + } + through.set( + item.conversationId, + Math.max(through.get(item.conversationId) ?? 0, item.sequence) + ) + } + await this.runtime.callOrchestrationWorkerServer( + environmentId, + 'orchestration.peerMailAck', + { + acknowledgments: [...through].map(([conversationId, throughSequence]) => ({ + conversationId, + throughSequence + })) + }, + 15_000 + ) + } + + /** Stores a pulled reply once; a replay after a crash before the ack finds the stored row. */ + private importReply( + db: OrchestrationDb, + environmentId: string, + item: z.infer['items'][number] + ): MessageRow | undefined { + const conversation = db.getPeerMailConversation(item.conversationId) + const payload = PeerMailRelayPayload.safeParse(safeJson(item.payload)) + if ( + conversation?.role !== 'home' || + conversation.environment_id !== environmentId || + !payload.success + ) { + // Nothing here can read it; acknowledging keeps the server's queue moving. + console.warn( + `[orchestration] Dropped unreadable reply ${item.messageId} from ${environmentId}` + ) + return undefined + } + const handle = peerMailLocalRecipient(this.runtime, conversation) + const recipient = resolveBareOrchestrationRecipient({ runtime: this.runtime, db, handle }) + const stored = db.insertPeerMailMessage({ + conversationId: conversation.conversation_id, + remoteParty: payload.data.fromAddress, + message: { + id: item.messageId, + from: payload.data.senderLabel, + to: recipient.ok ? recipient.to : handle, + subject: payload.data.subject, + body: payload.data.body, + threadId: payload.data.threadId ?? undefined, + runId: recipient.ok ? recipient.runId : undefined + } + }) + return stored.duplicate ? undefined : stored.message + } +} + +function safeJson(value: string): unknown { + try { + return JSON.parse(value) + } catch { + return null + } +} diff --git a/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts new file mode 100644 index 00000000000..0e2b13c329d --- /dev/null +++ b/src/main/runtime/orchestration/federation/peer-mail/peer-mail-waiters.ts @@ -0,0 +1,32 @@ +import type { OrchestrationDb } from '../../db/orchestration-db' + +const waiters = new WeakMap void>>() + +/** Wakes every pull waiting on this store; each re-reads its own conversations. */ +export function notifyPeerMailQueued(db: OrchestrationDb): void { + for (const wake of waiters.get(db) ?? []) { + wake() + } +} + +/** Resolves when a reply is queued, the wait ends, or the caller goes away. */ +export function waitForPeerMail( + db: OrchestrationDb, + timeoutMs: number, + signal?: AbortSignal +): Promise { + return new Promise((resolve) => { + const set = waiters.get(db) ?? new Set<() => void>() + waiters.set(db, set) + const done = (): void => { + clearTimeout(timer) + set.delete(done) + signal?.removeEventListener('abort', done) + resolve() + } + const timer = setTimeout(done, timeoutMs) + timer.unref?.() + set.add(done) + signal?.addEventListener('abort', done, { once: true }) + }) +} diff --git a/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts b/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts index 119c42b73cf..117f61bab8a 100644 --- a/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts +++ b/src/main/runtime/orchestration/mailbox/senders/agent-message-sender.ts @@ -43,9 +43,11 @@ export function agentMessageSender( ): AgentMessageSender { const party = senderParty(address, db) const snapshot = snapshotSender(senderSnapshot, party, reportedDispatchId) + // Mail from another server is named by its label: "term_9f3c on Jinwoo's Mac". + const peerLabel = !snapshot.name && db?.isPeerMailSenderLabel(address) ? address : null return { party, - name: agentMessageSenderName(snapshot.name), + name: agentMessageSenderName(snapshot.name ?? peerLabel), ...(snapshot.agent ? { agent: snapshot.agent } : {}) } } diff --git a/src/main/runtime/repositories/runtime-project-group-controller.ts b/src/main/runtime/repositories/runtime-project-group-controller.ts index a2552da93d5..175110e036b 100644 --- a/src/main/runtime/repositories/runtime-project-group-controller.ts +++ b/src/main/runtime/repositories/runtime-project-group-controller.ts @@ -1,7 +1,11 @@ import type { WorkspaceAttachmentMutation } from '../../../shared/workspace-attachments/workspace-attachment-mutation' import { refuseWslHostWindowsDrivePath } from '../terminal/launch/wsl-host-windows-drive-guard' import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup, ProjectGroupUpdate } from '../../../shared/project-group-types' +import type { + ProjectGroup, + ProjectGroupMutation, + ProjectGroupUpdate +} from '../../../shared/project-group-types' import type { Repo } from '../../../shared/repo-types' import type { FolderWorkspacePathStatus, @@ -137,6 +141,18 @@ export class RuntimeProjectGroupController { return { deleted } } + async updateGroups(mutations: readonly ProjectGroupMutation[]): Promise { + const store = this.deps.getStore() + if (!store?.updateProjectGroups) { + throw new Error('runtime_unavailable') + } + const updated = store.updateProjectGroups(mutations) + if (updated?.length) { + this.deps.notifyReposChanged() + } + return updated + } + async moveProject( repoSelector: string, groupId: string | null, diff --git a/src/main/runtime/repositories/runtime-repository-command-surface.ts b/src/main/runtime/repositories/runtime-repository-command-surface.ts index 928c9142fc4..8cc6306f3fb 100644 --- a/src/main/runtime/repositories/runtime-repository-command-surface.ts +++ b/src/main/runtime/repositories/runtime-repository-command-surface.ts @@ -49,6 +49,7 @@ export type RuntimeRepositoryCommandSurface = { listVisibleFolderWorkspaces: RuntimeProjectGroupController['listVisibleFolderWorkspaces'] createProjectGroup: RuntimeProjectGroupController['createGroup'] updateProjectGroup: RuntimeProjectGroupController['updateGroup'] + updateProjectGroups: RuntimeProjectGroupController['updateGroups'] deleteProjectGroup: RuntimeProjectGroupController['deleteGroup'] moveProjectToGroup: RuntimeProjectGroupController['moveProject'] createFolderWorkspace: RuntimeProjectGroupController['createFolderWorkspace'] @@ -128,6 +129,7 @@ export function installRuntimeRepositoryCommandSurface( listVisibleFolderWorkspaces: groups.listVisibleFolderWorkspaces.bind(groups), createProjectGroup: groups.createGroup.bind(groups), updateProjectGroup: groups.updateGroup.bind(groups), + updateProjectGroups: groups.updateGroups.bind(groups), deleteProjectGroup: groups.deleteGroup.bind(groups), moveProjectToGroup: groups.moveProject.bind(groups), createFolderWorkspace: groups.createFolderWorkspace.bind(groups), diff --git a/src/main/runtime/repositories/runtime-repository-settings-controller.ts b/src/main/runtime/repositories/runtime-repository-settings-controller.ts index ff8af0588e4..e9829d7f8f5 100644 --- a/src/main/runtime/repositories/runtime-repository-settings-controller.ts +++ b/src/main/runtime/repositories/runtime-repository-settings-controller.ts @@ -41,6 +41,7 @@ type RepositoryUpdates = Partial< | 'worktreeBasePath' | 'kind' | 'symlinkPaths' + | 'dictationTerms' | 'issueSourcePreference' | 'defaultJiraProject' | 'externalWorktreeVisibility' diff --git a/src/main/runtime/rpc/errors.ts b/src/main/runtime/rpc/errors.ts index 9331daefc63..ec158eadf27 100644 --- a/src/main/runtime/rpc/errors.ts +++ b/src/main/runtime/rpc/errors.ts @@ -15,6 +15,7 @@ import { import type { RpcEnvelopeMeta, RpcFailure, RpcSuccess } from './core' import { CONNECTOR_REPLY_ERROR_CODES } from '../../../shared/rpc-contract/connector-params' import { ORCHESTRATION_SESSION_CALLER_ERROR_CODES } from '../../../shared/orchestration/orchestration-session-caller-codes' +import { ORCHESTRATION_FEDERATION_ERROR_CODES } from '../../../shared/orchestration/orchestration-federation-error-codes' import { computerUseErrorRecoveryData } from '../../../shared/computer-use-error-recovery' import { COMPUTER_ERROR_CODES } from '../../../shared/computer-use-runtime-types' import { TerminalSplitOutcomeError } from '../../../shared/workspace-layout/terminal-split-outcome' @@ -144,15 +145,7 @@ const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet = new Set([ 'cursor_dispatch_mismatch', 'source_changed', 'transcript_required', - 'server_required', - 'worktree_not_found_on_server', - 'resource_server_mismatch', - 'peer_changed', - 'remote_runtime_unavailable', - 'runtime_timeout', - 'invalid_runtime_response', - 'capability_unsupported', - 'relay_quota_exceeded', + ...ORCHESTRATION_FEDERATION_ERROR_CODES, 'dispatch_capability_invalid', 'agent_unconfigured', 'worker_prompt_too_large', diff --git a/src/main/runtime/rpc/methods/orchestration/caller-show.ts b/src/main/runtime/rpc/methods/orchestration/caller-show.ts index 0d5f0856807..1b34a65bf3c 100644 --- a/src/main/runtime/rpc/methods/orchestration/caller-show.ts +++ b/src/main/runtime/rpc/methods/orchestration/caller-show.ts @@ -69,10 +69,19 @@ export const ORCHESTRATION_CALLER_METHODS = [ permission: 'workspace', params: null, // Dispatch already admitted the environment's session; do not resolve another caller from params. - handler: (_params, { orchestrationCaller }): OrchestrationCallerShowResult => ({ + handler: ( + _params, + { orchestrationCaller, orchestrationCompatibilityEvidence, runtime } + ): OrchestrationCallerShowResult => ({ caller: orchestrationCaller ? { orcaSessionId: formatOrcaSessionAddress(orchestrationCaller.orcaSessionId), live: true } - : null + : null, + // An Orca-launched agent's own pane and launch secret prove it is one; no hook needs to have fired. + terminal: + !orchestrationCaller && + runtime.verifyOrchestrationCompatibilityCaller(orchestrationCompatibilityEvidence, { + currentRuntimeLaunchSufficient: true + }) !== null }) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts index 589b69f3934..39c02e08332 100644 --- a/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/federation/federation-methods.ts @@ -1,9 +1,11 @@ import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from './federation-control' import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from './federation-relay' import { ORCHESTRATION_FEDERATION_ATTACH_METHODS } from './federation' +import { ORCHESTRATION_PEER_MAIL_METHODS } from './peer-mail-methods' export const ORCHESTRATION_FEDERATION_METHODS = [ ...ORCHESTRATION_FEDERATION_ATTACH_METHODS, ...ORCHESTRATION_FEDERATION_RELAY_METHODS, - ...ORCHESTRATION_FEDERATION_CONTROL_METHODS + ...ORCHESTRATION_FEDERATION_CONTROL_METHODS, + ...ORCHESTRATION_PEER_MAIL_METHODS ] diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts new file mode 100644 index 00000000000..da5ac7c2209 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail-methods.ts @@ -0,0 +1,181 @@ +import { defineMethod, type RpcContext } from '../../../core' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { isGeneratedId } from '../../../../orchestration/db/generated-id' +import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { FederationRelayItemRow } from '../../../../orchestration/db/orchestration-records' +import { resolveBareOrchestrationRecipient } from '../messaging/recipient-routing' +import { mayNameSession } from '../messaging/session-recipient' +import { waitForPeerMail } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters' +import { + PeerMailAckParams, + PeerMailDeliverParams, + PeerMailPullParams +} from '../../../../../../shared/rpc-contract/orchestration-peer-mail-params' + +const NOTHING_DELIVERED = { effectsApplied: false } as const +const MAX_PULL_WAIT_MS = 25_000 +const PULL_PAGE_SIZE = 50 + +/** Mail between servers comes only from a paired computer's Orca, never a phone or this Orca's own clients. */ +function requireRuntimePairing( + ctx: Pick +): string { + if ( + ctx.clientKind !== 'runtime' || + ctx.pairedDeviceId === undefined || + !ctx.authenticatedCallerFingerprint + ) { + throw new OrchestrationError( + 'mail_requires_server_pairing', + 'Agent mail between Orca servers comes only from a paired computer. Nothing was delivered.', + NOTHING_DELIVERED + ) + } + return ctx.authenticatedCallerFingerprint +} + +function pendingReplies(db: OrchestrationDb, peerFingerprint: string): FederationRelayItemRow[] { + const items: FederationRelayItemRow[] = [] + for (const conversationId of db.listPeerConversationIds(peerFingerprint)) { + if (items.length >= PULL_PAGE_SIZE) { + break + } + items.push( + ...db.listPendingFederationRelay(conversationId, 'to_home', PULL_PAGE_SIZE - items.length) + ) + } + return items +} + +export const ORCHESTRATION_PEER_MAIL_METHODS = [ + defineMethod({ + name: 'orchestration.peerMailDeliver', + permission: 'workspace', + params: PeerMailDeliverParams, + handler: async (params, ctx) => { + const peerFingerprint = requireRuntimePairing(ctx) + const { runtime } = ctx + const db = runtime.getOrchestrationDb() + if (!isGeneratedId(params.messageId, 'msg')) { + throw new OrchestrationError('invalid_argument', 'Mail between servers needs a message ID.') + } + // Replies wait in the relay keyed by conversation; any other id could name another Orca's dispatch there. + if (!isGeneratedId(params.conversationId, 'peerconv')) { + throw new OrchestrationError( + 'invalid_argument', + 'Mail between servers needs a conversation ID.', + NOTHING_DELIVERED + ) + } + const to = params.to + if (/^(run|dispatch|task):/.test(to) || to.startsWith('@')) { + throw new OrchestrationError( + 'invalid_argument', + `--on sends to one terminal or chat agent on this server; ${to} is a mailbox. Nothing was delivered.`, + NOTHING_DELIVERED + ) + } + // A retry after a lost answer is acknowledged even if the recipient has since gone. + const delivered = db.getPeerMailMessage(params.messageId) + if (delivered) { + const conversation = db.getPeerMailConversation(delivered.conversation_id) + if ( + delivered.conversation_id !== params.conversationId || + conversation?.peer_fingerprint !== peerFingerprint + ) { + throw new OrchestrationError( + 'request_mismatch', + `Message ${params.messageId} already belongs to another conversation. Nothing was delivered.`, + NOTHING_DELIVERED + ) + } + return { message: { id: params.messageId, to } } + } + if (mayNameSession(to)) { + // Recipient routing reads the session record store, which the host opens lazily. + await runtime.ensureStructuredAgentSessionHost().catch(() => undefined) + } + const recipient = resolveBareOrchestrationRecipient({ runtime, db, handle: to }) + if (!recipient.ok) { + throw new OrchestrationError( + recipient.code, + `${recipient.message} Nothing was delivered.`, + NOTHING_DELIVERED + ) + } + const paneKey = runtime.getLiveTerminalPaneKey(recipient.to) + if (paneKey && db.findActiveRemoteAttachmentForPane(paneKey)) { + // Its mailbox is its Dispatch, which only its Run home writes to. + throw new OrchestrationError( + 'invalid_argument', + `${to} is a worker for another Orca's Run; message it through that Run's coordinator. Nothing was delivered.`, + NOTHING_DELIVERED + ) + } + const stored = db.insertPeerMailMessage({ + conversationId: params.conversationId, + peerFingerprint, + remoteParty: null, + message: { + id: params.messageId, + from: params.senderLabel, + to: recipient.to, + subject: params.subject, + body: params.body, + type: params.type, + priority: params.priority, + threadId: params.threadId, + runId: recipient.runId + } + }) + if (!stored.duplicate) { + runtime.notifyMessageArrived(stored.message.to_handle, stored.message.type) + } + return { message: { id: params.messageId, to } } + } + }), + defineMethod({ + name: 'orchestration.peerMailPull', + permission: 'workspace', + params: PeerMailPullParams, + handler: async (params, ctx) => { + const peerFingerprint = requireRuntimePairing(ctx) + const db = ctx.runtime.getOrchestrationDb() + let items = pendingReplies(db, peerFingerprint) + const waitMs = Math.min(Math.max(params.waitMs ?? 0, 0), MAX_PULL_WAIT_MS) + if (items.length === 0 && waitMs > 0) { + await waitForPeerMail(db, waitMs, ctx.signal) + items = pendingReplies(ctx.runtime.getOrchestrationDb(), peerFingerprint) + } + return { + items: items.map((item) => ({ + conversationId: item.dispatch_id, + sequence: item.sequence, + messageId: item.message_id, + payload: item.payload + })) + } + } + }), + defineMethod({ + name: 'orchestration.peerMailAck', + permission: 'workspace', + params: PeerMailAckParams, + handler: (params, ctx) => { + const peerFingerprint = requireRuntimePairing(ctx) + const db = ctx.runtime.getOrchestrationDb() + for (const ack of params.acknowledgments) { + const conversation = db.getPeerMailConversation(ack.conversationId) + if (conversation?.role !== 'peer' || conversation.peer_fingerprint !== peerFingerprint) { + continue + } + db.acknowledgeFederationRelay({ + dispatchId: ack.conversationId, + direction: 'to_home', + throughSequence: ack.throughSequence + }) + } + return { acknowledged: params.acknowledgments.length } + } + }) +] diff --git a/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts new file mode 100644 index 00000000000..c624b2989fa --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/federation/peer-mail.test.ts @@ -0,0 +1,439 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + ORCHESTRATION_CONTRACT_VERSION, + ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY +} from '../../../../../../shared/orchestration/orchestration-runtime-capabilities' +import type { RuntimeRpcResponse } from '../../../../../../shared/runtime-rpc-envelope' +import { OrcaRuntimeService } from '../../../../orca-runtime' +import { OrchestrationDb } from '../../../../orchestration/db/orchestration-db' +import type { OrchestrationEnvironmentTransport } from '../../../../orchestration/federation/environment-transport' +import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import { RpcDispatcher } from '../../../dispatcher' +import type { RpcContext } from '../../../core' +import { ORCHESTRATION_METHODS } from '../orchestration' +import { ORCHESTRATION_REPLY_METHOD } from '../messaging/reply-method' +import { notifyPeerMailQueued } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters' + +// Retries run at once so a recovering pull loop is observable without waiting out its backoff. +vi.mock( + '../../../../orchestration/federation/relay/federation-relay-scheduler', + async (original) => ({ + ...(await original()), + federationRelayRetryDelayMs: () => 0 + }) +) + +const A_PANE = 'tab_a:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' +const B_PANE = 'tab_b:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +const CHAT_ON_A = 'orca_session_id:11111111-1111-4111-8111-111111111111' +const CHAT_ON_B = 'orca_session_id:22222222-2222-4222-8222-222222222222' + +type Side = { db: OrchestrationDb; runtime: OrcaRuntimeService; dispatcher: RpcDispatcher } + +describe('agent mail between paired Orca servers', () => { + let dir: string + let a: Side + let b: Side + let bCapabilities: (capabilities: string[]) => string[] + let bClientKind: 'runtime' | 'mobile' + let aCredential: string + let hasEnvironment: () => boolean + + function openSide(name: string, machine: string, transport?: OrchestrationEnvironmentTransport) { + const db = new OrchestrationDb(join(dir, `${name}.db`)) + const runtime = new OrcaRuntimeService(null, undefined, { + orchestrationEnvironmentTransport: transport + }) + vi.spyOn(runtime, 'readMachineName').mockReturnValue(machine) + vi.spyOn(runtime, 'getTerminalHandleForPaneKey').mockReturnValue(null) + const panes: Record = { term_a: A_PANE, term_b: B_PANE } + vi.spyOn(runtime, 'getLiveTerminalPaneKey').mockImplementation( + (handle) => panes[handle] ?? null + ) + vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) => panes[handle] ?? null) + runtime.setOrchestrationDb(db) + return { + db, + runtime, + dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }) + } + } + + const transport: OrchestrationEnvironmentTransport = { + resolve: () => ({ + environmentId: 'env_b', + name: 'devB', + peerFingerprint: 'fingerprint_b', + homePeerFingerprint: aCredential + }), + hasEnvironment: () => hasEnvironment(), + call: async (_selector, method, params) => { + if (method === 'status.get') { + const status = b.runtime.getStatus() + return { + id: 'status', + ok: true, + result: { ...status, capabilities: bCapabilities(status.capabilities ?? []) }, + _meta: { runtimeId: b.runtime.getRuntimeId() } + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads. + return (await b.dispatcher.dispatch( + { + id: `from_a_${method}`, + authToken: 'a-device-token', + method, + params, + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION + }, + { + authenticatedCallerFingerprint: aCredential, + pairedDeviceId: 'device_a', + clientKind: bClientKind + } + )) as RuntimeRpcResponse + } + } + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'orca-peer-mail-')) + bCapabilities = (capabilities) => capabilities + bClientKind = 'runtime' + aCredential = 'fingerprint_a' + hasEnvironment = () => true + b = openSide('b', 'Build Box') + a = openSide('a', "Jinwoo's Mac", transport) + }) + + afterEach(() => { + a.runtime.stopOrchestrationFederationRelay() + b.runtime.stopOrchestrationFederationRelay() + a.db.close() + b.db.close() + rmSync(dir, { recursive: true, force: true }) + }) + + let requestCount = 0 + function mutation(side: Side, method: string, params: Record) { + requestCount += 1 + return side.dispatcher.dispatch({ + id: `${method}_${requestCount}`, + authToken: 'local', + orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION, + orchestrationRequestId: `request_${requestCount}`, + method, + params + }) + } + + function chatReply(side: Side, caller: string, params: { id: string; body: string }) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads. + const orchestrationCaller = { + address: caller, + terminalHandle: null, + orcaSessionId: caller.slice('orca_session_id:'.length), + paneKey: null + } as unknown as OrchestrationSessionCaller + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads. + return ORCHESTRATION_REPLY_METHOD.handler(params, { + runtime: side.runtime, + orchestrationCaller + } as RpcContext) + } + + function mailFor(side: Side, handle: string) { + return side.db.getUnreadMessages(handle) + } + + it('carries a terminal agent mail to the paired server and its flagless reply back', async () => { + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Check the build', + body: 'Is main green?' + }) + expect(sent).toMatchObject({ ok: true, result: { server: 'devB', message: { to: 'term_b' } } }) + + const [onB] = mailFor(b, 'term_b') + expect(onB).toMatchObject({ from_handle: "term_a on Jinwoo's Mac", subject: 'Check the build' }) + + const replied = await mutation(b, 'orchestration.reply', { + id: onB!.id, + body: 'Green.', + from: 'term_b' + }) + expect(replied).toMatchObject({ + ok: true, + result: { message: { subject: 'Re: Check the build' } } + }) + + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1)) + const [back] = mailFor(a, 'term_a') + expect(back).toMatchObject({ + from_handle: 'term_b on Build Box', + subject: 'Re: Check the build', + body: 'Green.', + thread_id: onB!.id + }) + + await expect( + mutation(a, 'orchestration.reply', { id: back!.id, body: 'x', from: 'term_a', on: 'devB' }) + ).resolves.toMatchObject({ ok: false, error: { code: 'request_mismatch' } }) + + // The opener can keep answering, and the reply reaches the same agent again. + await expect( + mutation(a, 'orchestration.reply', { id: back!.id, body: 'Thanks.', from: 'term_a' }) + ).resolves.toMatchObject({ ok: true }) + expect(mailFor(b, 'term_b').map((message) => message.body)).toEqual(['Thanks.']) + }) + + it('returns a chat agent reply to the chat on the opening server', async () => { + const send = ORCHESTRATION_METHODS.find((method) => method.name === 'orchestration.send')! + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads. + await send.handler({ from: CHAT_ON_A, on: 'devB', to: 'term_b', subject: 'Plan?' }, { + runtime: a.runtime, + orchestrationCaller: { + address: CHAT_ON_A, + terminalHandle: null, + orcaSessionId: CHAT_ON_A.slice(16), + paneKey: null + } + } as unknown as RpcContext) + const [onB] = mailFor(b, 'term_b') + expect(onB!.from_handle).toBe(`${CHAT_ON_A} on Jinwoo's Mac`) + + await chatReply(b, CHAT_ON_B, { id: onB!.id, body: 'Plan attached.' }) + + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, CHAT_ON_A)).toHaveLength(1)) + expect(mailFor(a, CHAT_ON_A)[0]).toMatchObject({ + from_handle: `${CHAT_ON_B} on Build Box`, + body: 'Plan attached.' + }) + expect(a.db.getPeerMailMessage(mailFor(a, CHAT_ON_A)[0]!.id)?.remote_party).toBe(CHAT_ON_B) + }) + + it('delivers a reply queued before both servers restart exactly once', async () => { + await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Long job' + }) + const [onB] = mailFor(b, 'term_b') + await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Done.', from: 'term_b' }) + + a.runtime.stopOrchestrationFederationRelay() + a.db.close() + b.db.close() + b = openSide('b', 'Build Box') + a = openSide('a', "Jinwoo's Mac", transport) + + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1)) + const [conversationId] = b.db.listPeerConversationIds('fingerprint_a') + expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([]) + }) + + it('refuses an older server before sending anything', async () => { + bCapabilities = (capabilities) => + capabilities.filter((capability) => capability !== ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY) + + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Hello' + }) + + expect(sent).toMatchObject({ + ok: false, + error: { code: 'server_mail_unsupported', data: { effectsApplied: false } } + }) + expect(b.db.getInbox(10)).toEqual([]) + }) + + it('takes mail between servers only from a paired computer, not a phone', async () => { + bClientKind = 'mobile' + + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Hello' + }) + + expect(sent).toMatchObject({ + ok: false, + error: { code: 'mail_requires_server_pairing' } + }) + expect(b.db.getInbox(10)).toEqual([]) + }) + + it('acknowledges a retried delivery after its recipient is gone, storing it once', async () => { + const deliver = { + conversationId: 'peerconv_aaaaaaaaaaaa', + messageId: 'msg_aaaaaaaaaaaa', + to: 'term_b', + senderLabel: "term_a on Jinwoo's Mac", + subject: 'Once' + } + const first = await transport.call('devB', 'orchestration.peerMailDeliver', deliver) + vi.mocked(b.runtime.getLiveTerminalPaneKey).mockReturnValue(null) + + const retried = await transport.call('devB', 'orchestration.peerMailDeliver', deliver) + + expect(first).toMatchObject({ ok: true }) + expect(retried).toMatchObject({ ok: true, result: { message: { id: 'msg_aaaaaaaaaaaa' } } }) + expect(b.db.getInbox(10).filter((message) => message.subject === 'Once')).toHaveLength(1) + }) + + it('refuses payload fields before sending anything', async () => { + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Report', + payload: '{"taskId":"task_1"}' + }) + + expect(sent).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(b.db.getInbox(10)).toEqual([]) + }) + + it('refuses mail to a worker another Orca coordinates', async () => { + vi.spyOn(b.db, 'findActiveRemoteAttachmentForPane').mockImplementation((paneKey) => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test double carrying only the fields the code under test reads. + paneKey === B_PANE ? ({ dispatch_id: 'ctx_remote' } as never) : undefined + ) + + const sent = await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Side mail' + }) + + expect(sent).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(b.db.getInbox(10)).toEqual([]) + }) + + it('refuses a conversation ID that is not a peer conversation', async () => { + const delivered = await transport.call('devB', 'orchestration.peerMailDeliver', { + conversationId: 'ctx_aaaaaaaaaaaa', + messageId: 'msg_aaaaaaaaaaaa', + to: 'term_b', + senderLabel: "term_a on Jinwoo's Mac", + subject: 'Into a dispatch' + }) + + expect(delivered).toMatchObject({ ok: false, error: { code: 'invalid_argument' } }) + expect(b.db.getInbox(10)).toEqual([]) + }) + + it('keeps conversing with a server after it is re-paired', async () => { + await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'First' + }) + const [first] = mailFor(b, 'term_b') + await mutation(b, 'orchestration.reply', { id: first!.id, body: 'One.', from: 'term_b' }) + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1)) + const [answer] = mailFor(a, 'term_a') + b.db.markAsRead([first!.id]) + + aCredential = 'fingerprint_a_repaired' + await expect( + mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Second' + }) + ).resolves.toMatchObject({ ok: true }) + await expect( + mutation(a, 'orchestration.reply', { id: answer!.id, body: 'Thanks.', from: 'term_a' }) + ).resolves.toMatchObject({ ok: true }) + + expect(mailFor(b, 'term_b').map((message) => message.subject)).toEqual(['Second', 'Re: First']) + }) + + it('acknowledges a reply replayed after this Orca reset its mail', async () => { + await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Ask' + }) + const [onB] = mailFor(b, 'term_b') + await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Answer.', from: 'term_b' }) + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => expect(mailFor(a, 'term_a')).toHaveLength(1)) + const [conversationId] = b.db.listPeerConversationIds('fingerprint_a') + await vi.waitFor(() => + expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([]) + ) + + a.db.resetMessages() + // The ack was lost: the server serves the stored reply again. + b.db['db'].prepare('UPDATE federation_relay_items SET acked_at = NULL').run() + notifyPeerMailQueued(b.db) + + await vi.waitFor(() => + expect(b.db.listPendingFederationRelay(conversationId!, 'to_home')).toEqual([]) + ) + expect(mailFor(a, 'term_a')).toEqual([]) + }) + + it('keeps a queued reply when the server resets its tasks', async () => { + await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Ask' + }) + a.runtime.stopOrchestrationFederationRelay() + const [onB] = mailFor(b, 'term_b') + await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Kept.', from: 'term_b' }) + + b.db.resetTasks() + + a.runtime.ensureOrchestrationFederationRelay() + await vi.waitFor(() => + expect(mailFor(a, 'term_a').map((message) => message.body)).toEqual(['Kept.']) + ) + }) + + it('keeps pulling after a failed pull when the server list cannot be read', async () => { + await mutation(a, 'orchestration.send', { + from: 'term_a', + on: 'devB', + to: 'term_b', + subject: 'Ask' + }) + a.runtime.stopOrchestrationFederationRelay() + const [onB] = mailFor(b, 'term_b') + await mutation(b, 'orchestration.reply', { id: onB!.id, body: 'Later.', from: 'term_b' }) + const call = vi.spyOn(transport, 'call') + call.mockRejectedValueOnce(new Error('offline')) + hasEnvironment = () => { + hasEnvironment = () => true + throw new Error('registry unreadable') + } + + a.runtime.ensureOrchestrationFederationRelay() + + await vi.waitFor(() => + expect(mailFor(a, 'term_a').map((message) => message.body)).toEqual(['Later.']) + ) + call.mockRestore() + }) +}) diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts new file mode 100644 index 00000000000..e78a9abda6a --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-reply.ts @@ -0,0 +1,106 @@ +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { PeerMailMessageRow } from '../../../../orchestration/db/federation/peer-mail-store' +import type { MessageRow } from '../../../../orchestration/db/orchestration-records' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { + deliverPeerMail, + peerMailMessageId, + peerMailPairing, + peerMailSenderLabel, + requirePeerMailServer +} from '../../../../orchestration/federation/peer-mail/peer-mail-delivery' +import { notifyPeerMailQueued } from '../../../../orchestration/federation/peer-mail/peer-mail-waiters' +import { recordReceiptBeforeNudge } from './mutation-replay-nudge' + +const NOTHING_SENT = { effectsApplied: false } as const + +/** A reply to mail that came from another Orca goes back over that mail's conversation. */ +export async function replyOverPeerMail(args: { + runtime: OrcaRuntimeService + original: MessageRow + route: PeerMailMessageRow + params: { body: string; from?: string; on?: string } + orchestrationCaller: OrchestrationSessionCaller | undefined + orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined + recordMutationReceipt: ((receipt: unknown) => void) | undefined +}): Promise { + const { runtime, original, route, params } = args + const db = runtime.getOrchestrationDb() + const conversation = db.getPeerMailConversation(route.conversation_id) + if (!conversation) { + throw new OrchestrationError( + 'request_mismatch', + `The conversation ${original.id} came on is gone from this Orca. No reply was sent.`, + NOTHING_SENT + ) + } + const replier = args.orchestrationCaller?.address ?? params.from ?? original.to_handle + const id = peerMailMessageId(args.orchestrationMutation) + const subject = original.subject.startsWith('Re: ') ? original.subject : `Re: ${original.subject}` + const threadId = original.thread_id ?? original.id + const senderLabel = peerMailSenderLabel(runtime, replier) + + if (params.on !== undefined) { + throw new OrchestrationError( + 'request_mismatch', + `${original.id} came from ${original.from_handle}; its reply goes back there by itself. Drop --on. No reply was sent.`, + NOTHING_SENT + ) + } + + if (conversation.role === 'peer') { + db.enqueueFederationRelay({ + dispatchId: conversation.conversation_id, + direction: 'to_home', + kind: 'peer_mail', + messageId: id, + payload: JSON.stringify({ + senderLabel, + fromAddress: replier, + subject, + body: params.body, + threadId + }) + }) + db.markAsRead([original.id]) + return recordReceiptBeforeNudge( + args.recordMutationReceipt, + { message: { id, subject }, to: original.from_handle }, + () => notifyPeerMailQueued(db), + { kind: 'messages', targets: [] } + ) + } + + const environmentId = conversation.environment_id ?? '' + if (!route.remote_party) { + throw new OrchestrationError( + 'request_mismatch', + `${original.id} does not say who sent it. No reply was sent.`, + NOTHING_SENT + ) + } + const server = await requirePeerMailServer(runtime, environmentId) + // After a re-pair the server no longer knows the old conversation; continue it under the new pairing. + const current = db.openHomePeerMailConversation({ + environmentId, + peerFingerprint: peerMailPairing(server), + localParty: conversation.local_party ?? '', + localPaneKey: conversation.local_pane_key + }) + await deliverPeerMail(runtime, server, current, { + id, + to: route.remote_party, + senderLabel, + subject, + body: params.body, + threadId + }) + db.markAsRead([original.id]) + return recordReceiptBeforeNudge( + args.recordMutationReceipt, + { message: { id, subject }, to: original.from_handle, server: server.name }, + () => runtime.ensureOrchestrationFederationRelay(), + { kind: 'federation' } + ) +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts new file mode 100644 index 00000000000..9001cb57a7d --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/messaging/peer-mail-send.ts @@ -0,0 +1,133 @@ +import type { z } from 'zod' +import type { OrcaRuntimeService } from '../../../../orca-runtime' +import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity' +import type { OrchestrationCompatibilityCallerAuthority } from '../../../../orchestration/terminal-authority/orchestration-compatibility-authority' +import { OrchestrationError } from '../../../../orchestration/orchestration-error' +import { + deliverPeerMail, + peerMailMessageId, + peerMailPairing, + peerMailSenderLabel, + requirePeerMailServer +} from '../../../../orchestration/federation/peer-mail/peer-mail-delivery' +import type { RpcContext } from '../../../core' +import { recordReceiptBeforeNudge } from './mutation-replay-nudge' +import type { SendParams } from './send-params' +import type { ORCHESTRATION_SEND_METHODS } from './send-methods' + +const NOTHING_SENT = { effectsApplied: false } as const + +/** The agent on this Orca that mail sent elsewhere answers to: a chat by its session, a terminal by its live pane. */ +export function peerMailLocalCaller(args: { + runtime: OrcaRuntimeService + from: string | undefined + orchestrationCaller: OrchestrationSessionCaller | undefined + attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined +}): { address: string; paneKey: string | null } { + if (args.orchestrationCaller) { + return { address: args.orchestrationCaller.address, paneKey: null } + } + const paneKey = + args.from === undefined + ? null + : (args.attestedCaller?.paneKey ?? args.runtime.getLiveTerminalPaneKey(args.from)) + if (!args.from || !paneKey) { + throw new OrchestrationError( + 'invalid_argument', + '--on needs a terminal or chat agent on this Orca to receive the replies. Run it from that agent. Nothing was sent.', + NOTHING_SENT + ) + } + if (args.runtime.getOrchestrationDb().findActiveRemoteAttachmentForPane(paneKey)) { + throw new OrchestrationError( + 'invalid_argument', + "This terminal is a worker for another Orca's Run; its mail goes to that Run's coordinator, not to other servers. Nothing was sent.", + NOTHING_SENT + ) + } + return { address: args.from, paneKey } +} + +/** `send --on `: this Orca carries the mail and keeps the conversation the replies come back on. */ +export async function sendPeerMail(args: { + params: z.infer & { on: string } + runtime: OrcaRuntimeService + orchestrationCaller: OrchestrationSessionCaller | undefined + attestedCaller: OrchestrationCompatibilityCallerAuthority | undefined + orchestrationMutation: { callerFingerprint: string; requestId: string } | undefined + recordMutationReceipt: ((receipt: unknown) => void) | undefined +}): Promise { + const { params, runtime } = args + const to = params.to + if (!to || /^(run|dispatch|task):/.test(to) || to.startsWith('@')) { + throw new OrchestrationError( + 'invalid_argument', + `--on sends to one terminal or chat agent on that server: --to term_… or --to orca_session_id:…${to ? `, not ${to}` : ''}. Nothing was sent.`, + NOTHING_SENT + ) + } + const type = params.type ?? 'status' + if (type !== 'status' && type !== 'handoff') { + throw new OrchestrationError( + 'invalid_argument', + `--on carries --type status or handoff, not ${type}. Nothing was sent.`, + NOTHING_SENT + ) + } + if (params.payload !== undefined) { + throw new OrchestrationError( + 'invalid_argument', + '--on carries a subject and body; payload fields such as --task-id or --report-path name work on this Orca only. Nothing was sent.', + NOTHING_SENT + ) + } + const caller = peerMailLocalCaller({ ...args, from: params.from }) + const server = await requirePeerMailServer(runtime, params.on) + const conversation = runtime.getOrchestrationDb().openHomePeerMailConversation({ + environmentId: server.environmentId, + peerFingerprint: peerMailPairing(server), + localParty: caller.address, + localPaneKey: caller.paneKey + }) + const id = peerMailMessageId(args.orchestrationMutation) + await deliverPeerMail(runtime, server, conversation, { + id, + to, + senderLabel: peerMailSenderLabel(runtime, caller.address), + subject: params.subject, + body: params.body, + type, + priority: params.priority, + threadId: params.threadId + }) + return recordReceiptBeforeNudge( + args.recordMutationReceipt, + { message: { id, to }, server: server.name }, + () => runtime.ensureOrchestrationFederationRelay(), + { kind: 'federation' } + ) +} + +/** `orchestration.send` with `on` set goes to the paired server; every other send runs unchanged. */ +export function withPeerMailSend( + methods: typeof ORCHESTRATION_SEND_METHODS +): typeof ORCHESTRATION_SEND_METHODS { + return methods.map((method) => ({ + ...method, + handler: (params: Parameters[0], ctx: RpcContext) => { + const on = params.on + if (on === undefined || ctx.replayedMutationReceipt !== undefined) { + return method.handler(params, ctx) + } + const attested = ctx.orchestrationCompatibilityCallerAuthority + return sendPeerMail({ + params: { ...params, on }, + runtime: ctx.runtime, + orchestrationCaller: ctx.orchestrationCaller, + attestedCaller: attested?.terminalHandle === params.from ? attested : undefined, + orchestrationMutation: ctx.orchestrationMutation, + recordMutationReceipt: ctx.recordMutationReceipt + }) + } + })) +} diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts index b0bd4ec708f..f0ea51d87e7 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/reply-method.ts @@ -14,6 +14,7 @@ import { recordReceiptBeforeNudge, replayMutationNudge } from './mutation-replay import { resolveReplyRecipient } from './recipient-routing' import { helperQuestionAnswerer } from './helper-question-answerer' import { replyToRemoteRunHome } from './reply-remote' +import { replyOverPeerMail } from './peer-mail-reply' import { withAnswerNext } from '../receipt-next' import { ReplyParams } from '../../../../../../shared/rpc-contract/orchestration-params' import { @@ -35,6 +36,7 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({ legacyCoordinatorRunId, recordMutationReceipt, replayedMutationReceipt, + orchestrationMutation, signal } ) => { @@ -157,6 +159,25 @@ export const ORCHESTRATION_REPLY_METHOD = defineMethod({ ) } + const peerRoute = db.getPeerMailMessage(original.id) + if (peerRoute) { + return await replyOverPeerMail({ + runtime, + original, + route: peerRoute, + params, + orchestrationCaller, + orchestrationMutation, + recordMutationReceipt + }) + } + if (params.on !== undefined) { + throw new OrchestrationError( + 'invalid_argument', + `${params.id} did not come from another server, so its reply stays on this Orca. Drop --on. No reply was sent.`, + { effectsApplied: false } + ) + } if (db.getRun(original.run_id)?.home_database === 'remote') { return await replyToRemoteRunHome({ runtime, db, original, params, signal }) } diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts index c9ba10ffe59..4c40eac6996 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-methods.ts @@ -38,6 +38,7 @@ import { settledDispatchId } from './settled-worker-follow-through' +// `send --on ` is carried by withPeerMailSend (peer-mail-send.ts) before this handler runs. export const ORCHESTRATION_SEND_METHODS = [ defineMethod({ name: 'orchestration.send', diff --git a/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts b/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts index 27bed5c0e56..cce983c33e3 100644 --- a/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts +++ b/src/main/runtime/rpc/methods/orchestration/messaging/send-params.ts @@ -33,6 +33,8 @@ export const SendParams = z // Use remint-stable pane keys to attest worker_done/heartbeat; from handles only route. senderPaneKey: OptionalString, run: OptionalString, + // A paired server: this Orca carries the mail there and the replies back (`send --on`). + on: OptionalString, waitForLifecycleSettlement: OptionalBoolean, devMode: OptionalBoolean }) diff --git a/src/main/runtime/rpc/methods/orchestration/orchestration.ts b/src/main/runtime/rpc/methods/orchestration/orchestration.ts index 57ab816b30d..a9d551e8555 100644 --- a/src/main/runtime/rpc/methods/orchestration/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration/orchestration.ts @@ -5,6 +5,7 @@ import { ORCHESTRATION_WORKER_METHODS } from './worker/worker-methods' import { ORCHESTRATION_FEDERATION_METHODS } from './federation/federation-methods' import { ORCHESTRATION_MUTATION_REQUEST_METHODS } from './runs/mutation-request-show' import { ORCHESTRATION_SEND_METHODS } from './messaging/send-methods' +import { withPeerMailSend } from './messaging/peer-mail-send' import { ORCHESTRATION_CHECK_METHODS } from './messaging/check-methods' import { ORCHESTRATION_MESSAGE_METHODS } from './messaging/message-methods' import { ORCHESTRATION_DISPATCH_METHODS } from './runs/dispatch-methods' @@ -20,7 +21,7 @@ export const ORCHESTRATION_METHODS = requiringOrcadFeature('orchestration', [ ...ORCHESTRATION_WORKER_METHODS, ...ORCHESTRATION_FEDERATION_METHODS, ...ORCHESTRATION_MUTATION_REQUEST_METHODS, - ...ORCHESTRATION_SEND_METHODS, + ...withPeerMailSend(ORCHESTRATION_SEND_METHODS), ...ORCHESTRATION_CHECK_METHODS, ...ORCHESTRATION_MESSAGE_METHODS, ...ORCHESTRATION_DISPATCH_METHODS, diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts index 7fb0f1e2889..f21da18e24b 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-follow-up-placement.ts @@ -10,6 +10,7 @@ import { structuredWorkerSession } from '../../../../orchestration/terminal-authority/structured-sessions/structured-worker-authority' import type { WorkerFollowUpPlacement } from './worker-follow-up-choice' +import { publishChatTabInBackground } from '../../../../session-tabs/background-chat-tab-publication' /** What a follow-up continues, and for a closed worker how it comes back once the follow-up holds its Dispatch. */ export type WorkerFollowUp = { @@ -128,13 +129,7 @@ export async function reopenWorkerChat( const running = structuredWorkerSession(identity) const sessionId = running.kind === 'here' ? running.sessionId : identity.sessionId const userOpened = host.isSessionTabVisible(sessionId) - const revealed = await host.revealSession(sessionId) - await runtime.publishStructuredAgentSessionTab({ - workspaceId: revealed.workspaceId, - sessionId: revealed.sessionId, - agent: revealed.agent, - activate: false - }) + await publishChatTabInBackground(runtime, host, sessionId) return { handle, chat: true, diff --git a/src/main/runtime/rpc/methods/projects/project-group-rpc-methods.ts b/src/main/runtime/rpc/methods/projects/project-group-rpc-methods.ts new file mode 100644 index 00000000000..4b1f86d9b2c --- /dev/null +++ b/src/main/runtime/rpc/methods/projects/project-group-rpc-methods.ts @@ -0,0 +1,78 @@ +import { defineMethod } from '../../core' +import { projectRepoVisibilityForClient } from '../../repo-visibility-projection' +import { + ProjectGroupCreate, + ProjectGroupImportNested, + ProjectGroupMoveProject, + ProjectGroupScanNested, + ProjectGroupSelector, + ProjectGroupUpdate, + ProjectGroupUpdateMany +} from '../../../../../shared/rpc-contract/repo-params' + +export const PROJECT_GROUP_METHODS = [ + defineMethod({ + name: 'projectGroup.list', + permission: 'workspace', + params: null, + handler: (_params, { runtime }) => ({ groups: runtime.listVisibleProjectGroups() }) + }), + defineMethod({ + name: 'projectGroup.create', + permission: 'workspace', + params: ProjectGroupCreate, + handler: async (params, { runtime }) => ({ + group: await runtime.createProjectGroup(params) + }) + }), + defineMethod({ + name: 'projectGroup.update', + permission: 'workspace', + params: ProjectGroupUpdate, + handler: async (params, { runtime }) => ({ + group: await runtime.updateProjectGroup(params.groupId, params.updates) + }) + }), + defineMethod({ + name: 'projectGroup.delete', + permission: 'workspace', + params: ProjectGroupSelector, + handler: async (params, { runtime }) => runtime.deleteProjectGroup(params.groupId) + }), + defineMethod({ + name: 'projectGroup.updateMany', + permission: 'workspace', + params: ProjectGroupUpdateMany, + handler: async (params, { runtime }) => ({ + groups: await runtime.updateProjectGroups(params.mutations) + }) + }), + defineMethod({ + name: 'projectGroup.moveProject', + permission: 'workspace', + params: ProjectGroupMoveProject, + handler: async (params, context) => ({ + repo: projectRepoVisibilityForClient( + await context.runtime.moveProjectToGroup( + params.repo, + params.groupId ?? null, + params.order, + params.connectionId + ), + context + ) + }) + }), + defineMethod({ + name: 'projectGroup.scanNested', + permission: 'workspace', + params: ProjectGroupScanNested, + handler: async (params, { runtime }) => runtime.scanNestedRepos(params.path) + }), + defineMethod({ + name: 'projectGroup.importNested', + permission: 'workspace', + params: ProjectGroupImportNested, + handler: async (params, { runtime }) => runtime.importNestedRepos(params) + }) +] diff --git a/src/main/runtime/rpc/methods/projects/repo.ts b/src/main/runtime/rpc/methods/projects/repo.ts index e3987d8a38d..dd1bfdbb411 100644 --- a/src/main/runtime/rpc/methods/projects/repo.ts +++ b/src/main/runtime/rpc/methods/projects/repo.ts @@ -1,5 +1,6 @@ import { defineMethod } from '../../core' import { resolveReplySnapshot } from '../../content-snapshot-id' +import { PROJECT_GROUP_METHODS } from './project-group-rpc-methods' import { PROJECT_RUNTIME_METHODS } from './project-runtime-rpc-methods' import { FOLDER_WORKSPACE_METHODS } from '../workspaces/folder-workspace' import { @@ -18,12 +19,6 @@ import { projectRepoVisibilityForClient } from '../../repo-visibility-projection' import { - ProjectGroupCreate, - ProjectGroupImportNested, - ProjectGroupMoveProject, - ProjectGroupScanNested, - ProjectGroupSelector, - ProjectGroupUpdate, RepoClone, RepoCreate, RepoHooksCheck, @@ -54,63 +49,8 @@ export const REPO_METHODS = [ } }), ...PROJECT_RUNTIME_METHODS, - defineMethod({ - name: 'projectGroup.list', - permission: 'workspace', - params: null, - handler: (_params, { runtime }) => ({ groups: runtime.listVisibleProjectGroups() }) - }), - defineMethod({ - name: 'projectGroup.create', - permission: 'workspace', - params: ProjectGroupCreate, - handler: async (params, { runtime }) => ({ - group: await runtime.createProjectGroup(params) - }) - }), - defineMethod({ - name: 'projectGroup.update', - permission: 'workspace', - params: ProjectGroupUpdate, - handler: async (params, { runtime }) => ({ - group: await runtime.updateProjectGroup(params.groupId, params.updates) - }) - }), - defineMethod({ - name: 'projectGroup.delete', - permission: 'workspace', - params: ProjectGroupSelector, - handler: async (params, { runtime }) => runtime.deleteProjectGroup(params.groupId) - }), - defineMethod({ - name: 'projectGroup.moveProject', - permission: 'workspace', - params: ProjectGroupMoveProject, - handler: async (params, context) => ({ - repo: projectRepoVisibilityForClient( - await context.runtime.moveProjectToGroup( - params.repo, - params.groupId ?? null, - params.order, - params.connectionId - ), - context - ) - }) - }), + ...PROJECT_GROUP_METHODS, ...FOLDER_WORKSPACE_METHODS, - defineMethod({ - name: 'projectGroup.scanNested', - permission: 'workspace', - params: ProjectGroupScanNested, - handler: async (params, { runtime }) => runtime.scanNestedRepos(params.path) - }), - defineMethod({ - name: 'projectGroup.importNested', - permission: 'workspace', - params: ProjectGroupImportNested, - handler: async (params, { runtime }) => runtime.importNestedRepos(params) - }), defineMethod({ name: 'repo.sparsePresets', permission: 'workspace', diff --git a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts index b3b93c31f96..55191be8241 100644 --- a/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts +++ b/src/main/runtime/rpc/methods/source-control/github/github-pull-request-methods.ts @@ -16,7 +16,7 @@ export const GITHUB_PULL_REQUEST_METHODS = [ name: 'github.prForBranch', permission: 'workspace', params: PrForBranch, - handler: async (params, { runtime }) => + handler: async (params, { runtime, clientKind }) => runtime.getRepoPRForBranch( params.repo, params.branch, @@ -25,7 +25,8 @@ export const GITHUB_PULL_REQUEST_METHODS = [ params.acceptMergedFallbackPR, params.currentHeadOid, params.reason, - params.userRefresh + params.userRefresh, + clientKind ) }), defineMethod({ diff --git a/src/main/runtime/rpc/methods/speech/speech.ts b/src/main/runtime/rpc/methods/speech/speech.ts index 352dc1357d7..3d4154c1258 100644 --- a/src/main/runtime/rpc/methods/speech/speech.ts +++ b/src/main/runtime/rpc/methods/speech/speech.ts @@ -5,15 +5,16 @@ import { DictationSetup, DictationStart, OpenAiSpeechKeySet, - SpeechModelAction + SpeechModelAction, + SpeechSetupRead } from '../../../../../shared/rpc-contract/speech-params' export const SPEECH_METHODS = [ defineMethod({ name: 'speech.models.list', permission: 'workspace', - params: null, - handler: async (_params, { runtime }) => runtime.listMobileSpeechModels() + params: SpeechSetupRead, + handler: async (params, { runtime }) => runtime.listMobileSpeechModels(params?.worktreeId) }), defineMethod({ name: 'speech.models.download', diff --git a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts index fdab266aaf1..441bff0acff 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/creation/structured-agent-session-precommit-refusal.test.ts @@ -1,3 +1,6 @@ +import { copyCodexConversation } from '../../../../../codex/codex-conversation-copy' +import type * as AppServerSession from '../../../../../codex/app-server/codex-app-server-session' +import { tmpdir } from 'node:os' import { createRestTestRig } from '../../../../../native-chat/agent-session-wire/host/testing/structured-agent-session-rest-test-rig' import { forkTestSource } from '../../../../../native-chat/agent-session-wire/acquisition/testing/structured-agent-session-fork.test-fixture' import { agentSessionRecordFixture } from '../../../../../native-chat/agent-session-record-test-fixture' @@ -21,6 +24,15 @@ import { RpcDispatcher } from '../../../dispatcher' import { STRUCTURED_AGENT_SESSION_METHODS } from '../structured-agent-session' import './structured-agent-session-create' +const codex = vi.hoisted(() => ({ request: vi.fn() })) +vi.mock('../../../../../codex/app-server/codex-app-server-session', async (importOriginal) => ({ + ...(await importOriginal()), + runCodexAppServerSession: async ( + _launch: unknown, + body: (rpc: AppServerSession.CodexAppServerRpc) => Promise + ) => body({ request: codex.request, notify: () => {} }) +})) + const SESSION = 'session-alpha' const OPERATION = '1800000000000-00000000000000000000000000000001' const WORKTREE = 'id:workspace-1' @@ -310,3 +322,52 @@ it('does not prove no copy when source revalidation fails after the native copy' await rig.dispose() } }) + +it('settles a redirected Codex preparation refusal but not a dispatched child-read failure', async () => { + const { rig, test, createFork } = await forkHost() + test.record.conversationName = ' Release notes ' + try { + test.copy.mockImplementation((input) => + copyCodexConversation(input, { + resolveLaunchArgs: () => [], + resolveWorkspacePath: async () => tmpdir(), + resolveCommand: () => ({ command: 'codex', prefixArgs: [] }) + }) + ) + codex.request.mockRejectedValue(new Error('source read failed')) + expect(refusalOf(await createFork('codex_source_read_failed'))).toMatchObject({ + code: 'agent_session_identity_required', + details: { reason: 'transcriptUnreadable' }, + createAttemptRefusedBeforeCommit: true + }) + expect(rig.store.getRecord('codex_source_read_failed')).toBeNull() + codex.request.mockImplementation(async (method: string) => { + if (method === 'thread/read') { + return { thread: { id: '019e6b26-18e2-7103-b7a0-7ba6bb071123', historyMode: 'paginated' } } + } + if (method === 'thread/fork') { + return { thread: { id: '01a1bde0-5ded-7f03-a1bf-3dae1613d8c7' } } + } + throw new Error('child read failed') + }) + // Source listing succeeds before the child read fails. + codex.request + .mockImplementationOnce(async () => ({ + thread: { id: '019e6b26-18e2-7103-b7a0-7ba6bb071123', historyMode: 'paginated' } + })) + .mockImplementationOnce(async () => ({ + data: [{ id: 'completed-turn', status: 'completed' }], + nextCursor: null + })) + const refusal = refusalOf(await createFork('codex_child_read_failed')) + expect(refusal).toMatchObject({ + code: 'agent_session_operation_invalid', + details: { reason: 'providerRejected' } + }) + expect(refusal).not.toHaveProperty('createAttemptRefusedBeforeCommit') + expect(rig.store.getRecord('codex_child_read_failed')).toBeNull() + } finally { + setStructuredAgentSessionHost(null) + await rig.dispose() + } +}) diff --git a/src/main/runtime/rpc/server/runtime-rpc-pairing.ts b/src/main/runtime/rpc/server/runtime-rpc-pairing.ts index cd23340f166..0887c8c2bb8 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-pairing.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-pairing.ts @@ -30,6 +30,10 @@ import { type MobileRelayPairingProvider, type PairingOfferUnavailable } from './runtime-rpc-pairing-types' +import { + pendingVmCheckouts, + publishPendingVmCheckoutRepoChanges +} from '../../../ephemeral-vm/pending-vm-checkouts' export class RuntimeRpcPairing extends RuntimeRpcNetworkExposure { getDeviceRegistry(): DeviceRegistry | null { @@ -126,9 +130,30 @@ export class RuntimeRpcPairing extends RuntimeRpcNetworkExposure { getHostDisplayLabelOverrides(this.runtime.requireStore().getSettings()), getWorkspaceSession: (hostId) => this.runtime.getWorkspaceSessionForHost(hostId), recipeEnvironmentsFor: (hostId) => - this.runtime.describeRecipeWorkspaceEnvironments(hostId) + this.runtime.describeRecipeWorkspaceEnvironments(hostId), + pendingVmCheckouts: () => pendingVmCheckouts.current() }) : null + this.detachRelayHostsChanges?.() + const detachListChanges = + this.mobileRelayHostCatalog?.publishListChanges({ + onClientEvent: (listener) => + this.runtime.onClientEvent(listener, { consumesTerminalSideEffects: false }), + changed: () => this.runtime.notifyRelayHostsChanged() + }) ?? null + // Phones filter pending VM checkouts when they read; a change makes them read again. + const detachPendingVmChanges = this.mobileRelayHostCatalog + ? publishPendingVmCheckoutRepoChanges(pendingVmCheckouts, (repoId) => + this.runtime.notifyWorktreesChangedForRemoteClients(repoId) + ) + : null + this.detachRelayHostsChanges = + detachListChanges || detachPendingVmChanges + ? () => { + detachListChanges?.() + detachPendingVmChanges?.() + } + : null this.runtime.setPairedWorkspaceContextSource(this.mobileRelayHostCatalog) } diff --git a/src/main/runtime/rpc/server/runtime-rpc-state.ts b/src/main/runtime/rpc/server/runtime-rpc-state.ts index 3f6f5d6894e..8edc4ff2ef8 100644 --- a/src/main/runtime/rpc/server/runtime-rpc-state.ts +++ b/src/main/runtime/rpc/server/runtime-rpc-state.ts @@ -86,6 +86,7 @@ export class RuntimeRpcState { protected mobileDesktopRelay: MobileDesktopRelay | null = null protected mobileRelayHostCatalog: MobileRelayHostCatalog | null = null protected detachPairedServerRows: (() => void) | null = null + protected detachRelayHostsChanges: (() => void) | null = null protected readonly declaredDesktopClients = new DeclaredDesktopClients() protected readonly authenticatedSourceRecorder: AuthenticatedSourceRecorder // Why: lets an automatic mint install a provider whose launch-time construction failed. diff --git a/src/main/runtime/rpc/server/runtime-rpc.ts b/src/main/runtime/rpc/server/runtime-rpc.ts index 628d7a20455..2e0a732be19 100644 --- a/src/main/runtime/rpc/server/runtime-rpc.ts +++ b/src/main/runtime/rpc/server/runtime-rpc.ts @@ -49,6 +49,8 @@ export class OrcaRuntimeRpcServer extends RuntimeRpcMobilePairing { this.mobileSocketWiring = null this.detachPairedServerRows?.() this.detachPairedServerRows = null + this.detachRelayHostsChanges?.() + this.detachRelayHostsChanges = null this.detachWebSocketWiring = null const stopResults = await Promise.allSettled( transports.map(async (transport) => transport.stop()) diff --git a/src/main/runtime/session-lifecycle/projection/codex-async-question-title-hold.ts b/src/main/runtime/session-lifecycle/projection/codex-async-question-title-hold.ts new file mode 100644 index 00000000000..846a071b2c1 --- /dev/null +++ b/src/main/runtime/session-lifecycle/projection/codex-async-question-title-hold.ts @@ -0,0 +1,18 @@ +import { agentStatusAuthorityObservedAt } from '../../../../shared/agent-status/contracts/agent-status-freshness' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' +import { CODEX_ASYNC_QUESTION_TOOL } from '../../../../shared/codex-async-question-input' +import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' + +/** Codex's title stays working while its async question waits; only the hook sees the question. */ +export function codexAsyncQuestionOutlivesWorkingTitle( + status: AgentStatusEntry, + pty: RuntimePtyWorktreeRecord +): boolean { + return ( + status.state === 'waiting' && + status.toolName === CODEX_ASYNC_QUESTION_TOOL && + status.interactivePrompt != null && + pty.lastAgentStatus === 'working' && + agentStatusAuthorityObservedAt(status) > (pty.providerGenerationResetAtEpochMs ?? 0) + ) +} diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts index 6529fe2eb65..17761ac1130 100644 --- a/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection.ts @@ -13,6 +13,7 @@ import type { AgentProviderSessionMetadata } from '../../../../shared/agent-sess import { terminalTitleBlocksExplicitAgentStatus } from '../../workspaces/process-listing/runtime-worktree-status-projection' import type { HookLiveAgentRow } from '../../workspaces/process-listing/hook-live-agent-row' import type { RuntimePtyWorktreeRecord } from '../../terminal/records/runtime-terminal-state-records' +import { codexAsyncQuestionOutlivesWorkingTitle } from './codex-async-question-title-hold' type HookTurnFacts = Pick< AgentStatusEntry, @@ -120,9 +121,10 @@ export function renewRuntimeMobileAgentStatusFromPtyTitle( // Same-class Claude title repaints can postdate a fresh permission hook without // contradicting it; only a working or released-pane title retires the question (#11761). if ( - (status.state === 'waiting' || status.state === 'blocked') && - pty.lastAgentStatus === 'idle' && - Date.now() - agentStatusAuthorityObservedAt(status) <= AGENT_STATUS_STALE_AFTER_MS + ((status.state === 'waiting' || status.state === 'blocked') && + pty.lastAgentStatus === 'idle' && + Date.now() - agentStatusAuthorityObservedAt(status) <= AGENT_STATUS_STALE_AFTER_MS) || + codexAsyncQuestionOutlivesWorkingTitle(status, pty) ) { return status } diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-codex-async-question-status.test.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-codex-async-question-status.test.ts new file mode 100644 index 00000000000..37ead87f35a --- /dev/null +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-codex-async-question-status.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' +import { renewRuntimeMobileAgentStatusFromPtyTitle } from './runtime-mobile-agent-status-projection' +import { makeTuiIdlePty } from '../../terminal/wait/tui-idle-wait-test-harness' + +const QUESTION = '{"questions":[{"title":"Which database should the probe use?"}]}' + +function waitingOnAsyncQuestion(hookAt: number): AgentStatusEntry { + return { + state: 'waiting', + prompt: 'Set up a db', + updatedAt: hookAt, + stateStartedAt: hookAt, + agentType: 'codex', + toolName: 'request_user_input_async', + interactivePrompt: QUESTION, + mainAgent: { state: 'waiting', stateStartedAt: hookAt }, + paneKey: 'tab-1:leaf-1', + stateHistory: [] + } +} + +describe('paired/mobile Codex status while an async question waits', () => { + it('keeps the question when Codex repaints its working title after the hook', () => { + const hookAt = 1_700_000_000_000 + const out = renewRuntimeMobileAgentStatusFromPtyTitle( + waitingOnAsyncQuestion(hookAt), + makeTuiIdlePty({ + lastOscTitle: '⠋ repo', + lastOscTitleEpochMs: hookAt + 2_000, + lastAgentStatus: 'working', + lastAgentStatusStartedAtEpochMs: hookAt - 10_000, + lastAgentStatusRichInvalidatedAtEpochMs: hookAt - 10_000 + }) + ) + expect(out).toMatchObject({ state: 'waiting', interactivePrompt: QUESTION }) + }) +}) diff --git a/src/main/runtime/session-tabs/background-chat-tab-publication.ts b/src/main/runtime/session-tabs/background-chat-tab-publication.ts new file mode 100644 index 00000000000..9c2c82336c9 --- /dev/null +++ b/src/main/runtime/session-tabs/background-chat-tab-publication.ts @@ -0,0 +1,17 @@ +import type { OrcaRuntimeService } from '../orca-runtime' +import type { StructuredAgentSessionHost } from '../../native-chat/agent-session-wire/host/structured-agent-session-host' + +/** Reveals a chat session and publishes its tab without taking focus. */ +export async function publishChatTabInBackground( + runtime: Pick, + host: Pick, + sessionId: string +): Promise { + const revealed = await host.revealSession(sessionId) + await runtime.publishStructuredAgentSessionTab({ + workspaceId: revealed.workspaceId, + sessionId: revealed.sessionId, + agent: revealed.agent, + activate: false + }) +} diff --git a/src/main/runtime/speech/runtime-dictation-terms.ts b/src/main/runtime/speech/runtime-dictation-terms.ts new file mode 100644 index 00000000000..63838db9179 --- /dev/null +++ b/src/main/runtime/speech/runtime-dictation-terms.ts @@ -0,0 +1,12 @@ +import { dictationTermsFor, type DictationTerm } from '../../../shared/dictation-dictionary' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' +import type { RuntimeStore } from '../construction/runtime-store-contract' + +/** This host's dictionary for a worktree; a folder workspace has no repo row, so it gets the personal terms. */ +export function hostDictationTerms( + store: RuntimeStore, + worktreeId: string | undefined +): DictationTerm[] { + const repo = worktreeId ? store.getRepo(getRepoIdFromWorktreeId(worktreeId)) : undefined + return dictationTermsFor(store.getSettings().voice, repo) +} diff --git a/src/main/runtime/speech/runtime-mobile-dictation-controller.ts b/src/main/runtime/speech/runtime-mobile-dictation-controller.ts index 07c02fdc24d..2bbf14ed4ed 100644 --- a/src/main/runtime/speech/runtime-mobile-dictation-controller.ts +++ b/src/main/runtime/speech/runtime-mobile-dictation-controller.ts @@ -1,5 +1,6 @@ import { getDefaultVoiceSettings } from '../../../shared/constants' import { MOBILE_DICTATION_RECONNECT_GRACE_MS } from '../../../shared/rpc-contract/speech-params' +import { speechModelNotReadyError } from '../../../shared/speech-model-retirement' import { getSpeechModelManager, getSpeechSttService } from '../../speech/speech-runtime-service' import { getCatalogModel, isLocalSpeechModel } from '../../speech/model-catalog' import { @@ -11,10 +12,11 @@ import { type MobileDictationChunk } from './mobile-dictation-chunk-order' import type { RuntimeStore } from '../construction/runtime-store-contract' +import { hostDictationTerms } from './runtime-dictation-terms' import { DictationTranscript, type DictationTranscriptSnapshot -} from './mobile-dictation-transcript' +} from '../../../shared/dictation-transcript' type MobileDictationSession = { id: string @@ -41,6 +43,7 @@ export class RuntimeMobileDictationController { async start(params: { dictationId: string modelId?: string + worktreeId?: string clientId?: string }): Promise<{ dictationId: string; modelId: string; dedupesResentChunks: true }> { const store = this.requireStore() @@ -58,7 +61,7 @@ export class RuntimeMobileDictationController { } const modelState = await getSpeechModelManager(store).getModelState(modelId) if (modelState.status !== 'ready') { - throw new Error(`voice_model_not_ready:${modelState.status}`) + throw new Error(speechModelNotReadyError(modelState)) } const clientId = params.clientId if (!clientId) { @@ -88,7 +91,7 @@ export class RuntimeMobileDictationController { await getSpeechSttService(store).startDictation( modelId, (event) => acceptEvent(session, event), - undefined, + hostDictationTerms(store, params.worktreeId), owner, voice ) diff --git a/src/main/runtime/speech/runtime-mobile-speech-catalog.ts b/src/main/runtime/speech/runtime-mobile-speech-catalog.ts index 3c8185e2ea3..6619e4f7e0b 100644 --- a/src/main/runtime/speech/runtime-mobile-speech-catalog.ts +++ b/src/main/runtime/speech/runtime-mobile-speech-catalog.ts @@ -18,6 +18,7 @@ import { getSpeechModelDeletionErrorCode } from '../../speech/speech-model-deletion' import type { RuntimeStore } from '../construction/runtime-store-contract' +import { hostDictationTerms } from './runtime-dictation-terms' import { clearOpenAiSpeechApiKey, getOpenAiSpeechApiKeyProtection, @@ -34,23 +35,28 @@ export type OpenAiSpeechKeyStatus = { export class RuntimeMobileSpeechCatalog { constructor(private readonly getStore: () => RuntimeStore | null) {} - async list(): Promise { + /** `worktreeId` picks the repo terms a phone recognizing on its own spells with. */ + async list(worktreeId?: string): Promise { const store = this.requireStore() const voice = store.getSettings().voice ?? getDefaultVoiceSettings() const states = await getSpeechModelManager(store).getModelStates() const stateById = new Map(states.map((state) => [state.id, state])) // Omit unsupported status variants; older phones could treat them as pickable models. - const localRunnable = hasLocalSpeechRecognizer() const runnable = SPEECH_MODEL_CATALOG.filter( (manifest) => - isOfferedSpeechModel(manifest) && (localRunnable || !isLocalSpeechModel(manifest)) + isOfferedSpeechModel(manifest) && + (!isLocalSpeechModel(manifest) || hasLocalSpeechRecognizer()) && + // Phones offer an unready cloud row as "add an OpenAI key", which can't set this one up. + (manifest.provider !== 'openai-compatible' || + stateById.get(manifest.id)?.status === 'ready') ) const models: RuntimeSpeechModelSummary[] = runnable.map((manifest) => { const state = stateById.get(manifest.id) return { id: manifest.id, label: manifest.label, - provider: manifest.provider === 'openai' ? 'openai' : 'local', + // Older phones know only these two; both cloud providers transcribe on this host. + provider: isLocalSpeechModel(manifest) ? 'local' : 'openai', sizeBytes: manifest.sizeBytes ?? null, recommended: manifest.recommended === true, status: state?.status ?? 'not-downloaded', @@ -63,6 +69,9 @@ export class RuntimeMobileSpeechCatalog { dictationMode: voice.dictationMode === 'hold' ? 'hold' : 'toggle', dictationHoldToRecord: voice.dictationHoldToRecord !== false, removeFillerWords: voice.removeFillerWords !== false, + // The phone has no Whisper prompt to bias, and its text pass would only join the name; keeping the + // hint out also spares a phone page from before hints, which would treat the name as a full term. + dictationTerms: hostDictationTerms(store, worktreeId).filter((entry) => !entry.hint), models } } diff --git a/src/main/runtime/terminal/wait/screen-ruled-agent-transcript-suite.ts b/src/main/runtime/terminal/wait/screen-ruled-agent-transcript-suite.ts index 21d7b488783..43f4d71c54d 100644 --- a/src/main/runtime/terminal/wait/screen-ruled-agent-transcript-suite.ts +++ b/src/main/runtime/terminal/wait/screen-ruled-agent-transcript-suite.ts @@ -11,7 +11,7 @@ import { readRuntimeFixture, type TranscriptReplayResize } from './agent-transcript-replay-test-harness' -import { isKnownReadyPromptBody, isQuietReadyScreenBody } from './terminal-wait-detection' +import { isQuietReadyScreenBody } from './terminal-wait-detection' import { evaluateAgentStateRules } from '../../agent-state-rules/agent-state-rules-engine' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' @@ -246,16 +246,4 @@ export function describeScreenRuledAgentTranscripts(suite: ScreenRuledAgentSuite } }) }) - - it('never reads the screen for another agent', async () => { - const { ruledScreenLines, waitText } = await finalReplayFrame( - firstReady.name, - firstReady.cols, - firstReady.rows - ) - const readScreenLines = vi.fn(() => ruledScreenLines) - isKnownReadyPromptBody(waitText, 'claude', readScreenLines, false) - expect(isQuietReadyScreenBody(waitText, 'claude', readScreenLines)).toBe(false) - expect(readScreenLines).not.toHaveBeenCalled() - }) } diff --git a/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts b/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts index 5759e90d503..c32fb362212 100644 --- a/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts +++ b/src/main/runtime/workspaces/catalog/runtime-workspace-catalog-events.ts @@ -5,6 +5,7 @@ import { import type { Repo } from '../../../../shared/repo-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { composeWorktreeId } from '../../../../shared/worktree/id' +import type { PullRequestChange } from '../../../github/pull-request-changed-events' import { OrcaRuntimeWithGetStatus } from '../../hosts/runtime-status' export abstract class RuntimeWorkspaceCatalogEvents extends OrcaRuntimeWithGetStatus { @@ -77,4 +78,9 @@ export abstract class RuntimeWorkspaceCatalogEvents extends OrcaRuntimeWithGetSt notifyReposChangedForRemoteClients(): void { this.emitClientEvent({ type: 'reposChanged' }) } + + // The PR coordinator is fed by desktop IPC, so its refreshes reach paired clients only through here. + notifyPullRequestChangedForRemoteClients(change: PullRequestChange): void { + this.emitClientEvent({ type: 'pullRequestChanged', ...change }) + } } diff --git a/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts b/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts index cb1a161ffd6..69c4825efa5 100644 --- a/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts +++ b/src/main/runtime/workspaces/sleep/runtime-workspace-sleep-operations.ts @@ -146,6 +146,11 @@ export abstract class RuntimeWorkspaceSleepOperations extends OrcaRuntimeWithRes ) } + /** The user's Suspend VM, serialised with any wake of the same VM. */ + suspendWorkspaceVm(worktreeId: string): Promise { + return this.workspaceSleep.suspendVm(worktreeId) + } + /** Where this workspace's recipe VM stands for a client about to reach its server. */ workspaceVmState(worktreeId: string, recordSuspended: boolean): RecipeVmState { return this.workspaceSleep.vmState(worktreeId, recordSuspended) diff --git a/src/main/runtime/workspaces/sleep/workspace-sleep-runtime.ts b/src/main/runtime/workspaces/sleep/workspace-sleep-runtime.ts index 8bd911b0526..49b038d774b 100644 --- a/src/main/runtime/workspaces/sleep/workspace-sleep-runtime.ts +++ b/src/main/runtime/workspaces/sleep/workspace-sleep-runtime.ts @@ -209,6 +209,47 @@ export class WorkspaceSleepCoordinator { } } + /** The user's Suspend VM on a workspace with nothing open to sleep: queued like a sleep's + * suspend, so it never runs beside a wake of the same VM, and skipped if the workspace is + * opened before its turn. */ + suspendVm(worktreeId: string): Promise { + const platform = this.runtime.workspaceSleepPlatform + if (!platform?.ownsVm(worktreeId)) { + return Promise.resolve() + } + // A second Suspend VM while one is queued or running would rerun the recipe's suspend on a + // VM already going to sleep. + const pending = (this.pendingVmOperations.get(worktreeId) ?? []).at(-1) + if (pending?.kind === 'suspend') { + return Promise.resolve() + } + // Opening the workspace while this waits its turn keeps the VM up, as it does for a Sleep. + const at = this.reopenings.get(worktreeId) ?? 0 + return this.queueVmSuspend( + platform, + worktreeId, + () => (this.reopenings.get(worktreeId) ?? 0) === at + ) + } + + private queueVmSuspend( + platform: WorkspaceSleepPlatform, + worktreeId: string, + wanted: () => boolean + ): Promise { + const operation: VmOperation = { kind: 'suspend', suspending: false } + return this.trackVmOperation( + worktreeId, + operation, + this.afterVmOperations(worktreeId, async () => { + if (wanted()) { + operation.suspending = true + await platform.suspendVm(worktreeId) + } + }) + ) + } + private trackVmOperation(worktreeId: string, operation: VmOperation, run: Promise) { return trackPendingVmOperation(this.pendingVmOperations, worktreeId, operation, run) } @@ -256,19 +297,7 @@ export class WorkspaceSleepCoordinator { return host.sleepWorkspace(worktreeId, markAsleep) }, suspendVm: platform - ? (worktreeId, wanted) => { - const operation: VmOperation = { kind: 'suspend', suspending: false } - return this.trackVmOperation( - worktreeId, - operation, - this.afterVmOperations(worktreeId, async () => { - if (wanted()) { - operation.suspending = true - await platform.suspendVm(worktreeId) - } - }) - ) - } + ? (worktreeId, wanted) => this.queueVmSuspend(platform, worktreeId, wanted) : null, vmWakeSettled: (worktreeId) => pendingVmWake(this.pendingVmOperations.get(worktreeId) ?? []).catch(() => {}), diff --git a/src/main/runtime/workspaces/sleep/workspace-sleep-vm-wake.test.ts b/src/main/runtime/workspaces/sleep/workspace-sleep-vm-wake.test.ts index 04e3c822fbc..8e58b572b57 100644 --- a/src/main/runtime/workspaces/sleep/workspace-sleep-vm-wake.test.ts +++ b/src/main/runtime/workspaces/sleep/workspace-sleep-vm-wake.test.ts @@ -130,6 +130,79 @@ describe('WorkspaceSleepCoordinator VM wake', () => { expect(order).toEqual(['resume']) }) + it("runs the user's Suspend VM after a wake already running, and reads it as asleep meanwhile", async () => { + const order: string[] = [] + const resuming = gate() + const workspaceSleep = coordinator({ + suspendVm: async () => { + order.push('suspend') + }, + resumeVm: async () => { + await resuming.opened + order.push('resume') + return null + } + }) + + const woke = workspaceSleep.wakeVm(WORKTREE_ID) + const suspended = workspaceSleep.suspendVm(WORKTREE_ID) + expect(workspaceSleep.vmState(WORKTREE_ID, false)).toBe('waking') + resuming.open() + await woke + expect(workspaceSleep.vmState(WORKTREE_ID, false)).toBe('asleep') + await suspended + + expect(order).toEqual(['resume', 'suspend']) + expect(workspaceSleep.vmState(WORKTREE_ID, true)).toBe('asleep') + }) + + it('drops a queued Suspend VM when the workspace is opened before its turn', async () => { + const order: string[] = [] + const resuming = gate() + const workspaceSleep = coordinator({ + suspendVm: async () => { + order.push('suspend') + }, + resumeVm: async () => { + await resuming.opened + order.push('resume') + return null + } + }) + + const woke = workspaceSleep.wakeVm(WORKTREE_ID) + const suspended = workspaceSleep.suspendVm(WORKTREE_ID) + workspaceSleep.noteReopened(WORKTREE_ID) + resuming.open() + await Promise.all([woke, suspended]) + + expect(order).toEqual(['resume']) + }) + + it('runs one suspend for a Suspend VM chosen twice before the first finishes', async () => { + const suspending = gate() + const suspendVm = vi.fn(async () => { + await suspending.opened + }) + const workspaceSleep = coordinator({ suspendVm, resumeVm: async () => null }) + + const first = workspaceSleep.suspendVm(WORKTREE_ID) + const second = workspaceSleep.suspendVm(WORKTREE_ID) + suspending.open() + await Promise.all([first, second]) + + expect(suspendVm).toHaveBeenCalledTimes(1) + }) + + it('skips Suspend VM for a workspace without a VM', async () => { + const suspendVm = vi.fn(async () => {}) + const workspaceSleep = coordinator({ suspendVm, resumeVm: async () => null }) + + await workspaceSleep.suspendVm('repo-1::/tmp/plain') + + expect(suspendVm).not.toHaveBeenCalled() + }) + // #36923: clients reaching the VM's server learn where it stands from its pending operations, // which outrank a stored record that lags them. it('reports a VM waking from its wake until the resume settles, even when it fails', async () => { diff --git a/src/main/speech/cloud-transcription-target.ts b/src/main/speech/cloud-transcription-target.ts new file mode 100644 index 00000000000..929cfe6377e --- /dev/null +++ b/src/main/speech/cloud-transcription-target.ts @@ -0,0 +1,59 @@ +import type { SpeechModelProvider } from '../../shared/speech-types' +import { getCatalogModel, replaceRetiredSpeechModelId } from './model-catalog' +import { + canReadOpenAiSpeechApiKey, + hasOpenAiSpeechApiKey, + readOpenAiSpeechApiKey +} from './openai-api-key-store' +import { + canReadOpenAiCompatibleSpeechProvider, + hasOpenAiCompatibleSpeechProvider, + openAiCompatibleTranscriptionUrl, + readOpenAiCompatibleSpeechProvider +} from './openai-compatible-speech-provider-store' + +export const OPENAI_TRANSCRIPTION_URL = 'https://api.openai.com/v1/audio/transcriptions' + +const OPENAI_TRANSCRIPTION_MODEL_BY_ID: Record = { + 'openai-gpt-transcribe': 'gpt-transcribe' +} + +export type CloudTranscriptionTarget = { + url: string + model: string + /** Empty when the server takes no key. */ + apiKey: string + /** Names the service in errors. */ + label: string +} + +export function hasCloudSpeechCredentials(provider: SpeechModelProvider): boolean { + return provider === 'openai-compatible' + ? hasOpenAiCompatibleSpeechProvider() + : hasOpenAiSpeechApiKey() +} + +/** Headless hosts can't raise keychain prompts, so their readiness verifies decryption. */ +export function canReadCloudSpeechCredentials(provider: SpeechModelProvider): boolean { + return provider === 'openai-compatible' + ? canReadOpenAiCompatibleSpeechProvider() + : canReadOpenAiSpeechApiKey() +} + +/** Reads the key (and the compatible provider's URL) only when audio is ready to upload. */ +export function resolveCloudTranscriptionTarget(modelId: string): CloudTranscriptionTarget { + if (getCatalogModel(modelId)?.provider === 'openai-compatible') { + const provider = readOpenAiCompatibleSpeechProvider() + if (!provider) { + throw new Error('The OpenAI-compatible speech provider is not set up') + } + const url = openAiCompatibleTranscriptionUrl(provider.baseUrl) + return { url, model: provider.model, apiKey: provider.apiKey, label: new URL(url).host } + } + // Settings load already moves retired ids; this catches a caller still holding one. + const model = OPENAI_TRANSCRIPTION_MODEL_BY_ID[replaceRetiredSpeechModelId(modelId)] + if (!model) { + throw new Error(`Unknown OpenAI transcription model: ${modelId}`) + } + return { url: OPENAI_TRANSCRIPTION_URL, model, apiKey: readOpenAiSpeechApiKey(), label: 'OpenAI' } +} diff --git a/src/main/speech/model-cache-path.ts b/src/main/speech/model-cache-path.ts index 8af6e92a1b7..05c4876e87c 100644 --- a/src/main/speech/model-cache-path.ts +++ b/src/main/speech/model-cache-path.ts @@ -59,7 +59,7 @@ export function getSpeechModelCacheDirCandidates( .filter((modelsDir) => !hasNonAsciiCharacters(modelsDir)) .map((modelsDir) => ({ modelsDir, migrationSourceDir: requestedModelsDir })) - // sherpa-onnx 1.12.x needs ASCII Windows paths; retain the requested path if shared caches fail. + // Native speech libraries may open paths with ANSI Windows APIs; retain the requested path if shared caches fail. return [...candidates, { modelsDir: requestedModelsDir, migrationSourceDir: null }] } diff --git a/src/main/speech/model-catalog.ts b/src/main/speech/model-catalog.ts index 0d6f595db05..258a129f940 100644 --- a/src/main/speech/model-catalog.ts +++ b/src/main/speech/model-catalog.ts @@ -1,156 +1,216 @@ import type { SpeechModelManifest } from '../../shared/speech-types' import { DICTATION_LANGUAGES, - SENSE_VOICE_DICTATION_LANGUAGES + NEMOTRON_DICTATION_LANGUAGES, + PARAKEET_V3_LANGUAGES, + SENSE_VOICE_DICTATION_LANGUAGES, + WHISPER_LANGUAGES } from '../../shared/dictation-language' import { getSpeechModelDownloadMetadata } from './model-download-catalog' +import { getGgufSpeechModelDownload } from './speech-model-gguf-downloads' +import { getSpeechModelErrorRates } from './speech-model-error-rates' + +const legacy = (id: Parameters[0]) => ({ + legacyDownloadFiles: getSpeechModelDownloadMetadata(id).downloadFiles +}) export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [ { id: 'parakeet-tdt-0.6b-v3-int8', label: 'Parakeet TDT v3', - description: - 'Highest accuracy for 25 European languages. Punctuation, capitalization, and word-level timestamps.', type: 'transducer', provider: 'local', language: 'multilingual', - ...getSpeechModelDownloadMetadata('parakeet-tdt-0.6b-v3-int8'), + ...getGgufSpeechModelDownload('parakeet-tdt-0.6b-v3-int8'), + ...legacy('parakeet-tdt-0.6b-v3-int8'), + languages: PARAKEET_V3_LANGUAGES, + ...getSpeechModelErrorRates('parakeet-tdt-0.6b-v3-int8'), + licence: 'CC-BY-4.0', sampleRate: 16000, streaming: false, - modelingUnit: 'bpe', recommended: true }, { id: 'parakeet-tdt-0.6b-v2-int8', label: 'Parakeet TDT v2', - description: - 'English only. Faster than v3 with similar accuracy. Punctuation and capitalization.', type: 'transducer', provider: 'local', language: 'en', - ...getSpeechModelDownloadMetadata('parakeet-tdt-0.6b-v2-int8'), + ...getGgufSpeechModelDownload('parakeet-tdt-0.6b-v2-int8'), + ...legacy('parakeet-tdt-0.6b-v2-int8'), + languages: ['en'], + ...getSpeechModelErrorRates('parakeet-tdt-0.6b-v2-int8'), + licence: 'CC-BY-4.0', sampleRate: 16000, - streaming: false, - modelingUnit: 'bpe' + streaming: false }, { id: 'zipformer-bilingual-zh-en', label: 'Zipformer Bilingual', - description: 'Chinese + English with code-switching. Low-latency real-time streaming.', type: 'transducer', provider: 'local', language: 'zh-en', ...getSpeechModelDownloadMetadata('zipformer-bilingual-zh-en'), + languages: ['zh', 'en'], sampleRate: 16000, streaming: true, - modelingUnit: 'cjkchar+bpe' + // transcribe-cpp has no zipformer; SenseVoice covers Chinese and English. + replacedBy: 'sense-voice-zh-en-ja-ko-yue' }, { id: 'paraformer-bilingual-zh-en', label: 'Paraformer Bilingual', - description: - 'Chinese (Mandarin + dialects) + English. Strong on accented and regional Chinese.', type: 'paraformer', provider: 'local', language: 'zh-en', ...getSpeechModelDownloadMetadata('paraformer-bilingual-zh-en'), + languages: ['zh', 'en'], sampleRate: 16000, - streaming: true + streaming: true, + // transcribe-cpp has no paraformer; SenseVoice covers Chinese and English. + replacedBy: 'sense-voice-zh-en-ja-ko-yue' }, { id: 'zipformer-streaming-en-20m', label: 'Zipformer Streaming EN', - description: 'English only. Lightweight 20M-param model, good balance of speed and size.', type: 'transducer', provider: 'local', language: 'en', ...getSpeechModelDownloadMetadata('zipformer-streaming-en-20m'), + languages: ['en'], sampleRate: 16000, streaming: true, - modelingUnit: 'bpe', // The model itself loses the first words of every utterance. replacedBy: 'parakeet-tdt-0.6b-v2-int8' }, { id: 'zipformer-streaming-zh-14m', label: 'Zipformer Streaming ZH', - description: 'Chinese only. Ultra-lightweight 14M-param model, ideal for low-resource devices.', type: 'transducer', provider: 'local', language: 'zh', ...getSpeechModelDownloadMetadata('zipformer-streaming-zh-14m'), + languages: ['zh'], sampleRate: 16000, streaming: true, - modelingUnit: 'cjkchar' + // transcribe-cpp has no zipformer; SenseVoice beat Nemotron 3.5 on Korean and Chinese. + replacedBy: 'sense-voice-zh-en-ja-ko-yue' }, { id: 'zipformer-streaming-korean', label: 'Zipformer Streaming KO', - description: 'Korean only. Low-latency real-time streaming.', type: 'transducer', provider: 'local', language: 'ko', ...getSpeechModelDownloadMetadata('zipformer-streaming-korean'), + languages: ['ko'], sampleRate: 16000, streaming: true, - modelingUnit: 'bpe' + // transcribe-cpp has no zipformer; SenseVoice beat Nemotron 3.5 on Korean and Chinese. + replacedBy: 'sense-voice-zh-en-ja-ko-yue' }, { id: 'parakeet-tdt-ctc-0.6b-ja-int8', label: 'Parakeet TDT-CTC JA', - description: 'Japanese only. Trained on 35k+ hours of natural speech. Punctuation included.', type: 'nemo-ctc', provider: 'local', language: 'ja', ...getSpeechModelDownloadMetadata('parakeet-tdt-ctc-0.6b-ja-int8'), + languages: ['ja'], sampleRate: 16000, - streaming: false + streaming: false, + // No GGUF conversion exists; SenseVoice covers Japanese. + replacedBy: 'sense-voice-zh-en-ja-ko-yue' }, { id: 'whisper-tiny', label: 'Whisper Tiny', - description: '90+ languages. Lower accuracy than Parakeet but broadest language coverage.', type: 'whisper', provider: 'local', language: 'multilingual', - ...getSpeechModelDownloadMetadata('whisper-tiny'), + ...getGgufSpeechModelDownload('whisper-tiny'), + ...legacy('whisper-tiny'), dictationLanguages: DICTATION_LANGUAGES, + languages: WHISPER_LANGUAGES, + ...getSpeechModelErrorRates('whisper-tiny'), + licence: 'Apache-2.0', + sampleRate: 16000, + streaming: false + }, + { + id: 'whisper-large-v3-turbo', + label: 'Whisper Large v3 Turbo', + type: 'whisper', + provider: 'local', + language: 'multilingual', + ...getGgufSpeechModelDownload('whisper-large-v3-turbo'), + dictationLanguages: DICTATION_LANGUAGES, + languages: [...WHISPER_LANGUAGES, 'yue'], + ...getSpeechModelErrorRates('whisper-large-v3-turbo'), + licence: 'MIT', sampleRate: 16000, streaming: false }, { id: 'sense-voice-zh-en-ja-ko-yue', label: 'SenseVoice', - description: - 'Chinese, English, Japanese, Korean, and Cantonese with automatic language detection.', type: 'senseVoice', provider: 'local', language: 'multilingual', - ...getSpeechModelDownloadMetadata('sense-voice-zh-en-ja-ko-yue'), + ...getGgufSpeechModelDownload('sense-voice-zh-en-ja-ko-yue'), + ...legacy('sense-voice-zh-en-ja-ko-yue'), dictationLanguages: SENSE_VOICE_DICTATION_LANGUAGES, + languages: SENSE_VOICE_DICTATION_LANGUAGES, + ...getSpeechModelErrorRates('sense-voice-zh-en-ja-ko-yue'), + licence: 'FunASR Model License', sampleRate: 16000, streaming: false }, + { + id: 'nemotron-3.5-asr-streaming-0.6b', + label: 'Nemotron 3.5', + type: 'transducer', + provider: 'local', + language: 'multilingual', + ...getGgufSpeechModelDownload('nemotron-3.5-asr-streaming-0.6b'), + dictationLanguages: NEMOTRON_DICTATION_LANGUAGES, + languages: NEMOTRON_DICTATION_LANGUAGES, + ...getSpeechModelErrorRates('nemotron-3.5-asr-streaming-0.6b'), + licence: 'OpenMDW-1.1', + sampleRate: 16000, + // Decoded per chunk for now; live text arrives with the streaming engine path. + streaming: false + }, { id: 'openai-gpt-transcribe', label: 'GPT Transcribe', - description: 'Cloud transcription with high accuracy. Requires an OpenAI API key.', type: 'openai', provider: 'openai', language: 'multilingual', dictationLanguages: DICTATION_LANGUAGES, + languages: DICTATION_LANGUAGES, + sampleRate: 16000, + streaming: false + }, + { + id: 'openai-compatible', + label: 'OpenAI-compatible', + type: 'openai', + provider: 'openai-compatible', + language: 'multilingual', + dictationLanguages: DICTATION_LANGUAGES, + languages: DICTATION_LANGUAGES, sampleRate: 16000, streaming: false }, { id: 'openai-gpt-4o-mini-transcribe', label: 'GPT-4o mini Transcribe', - description: - 'Cloud transcription with strong accuracy and low cost. Requires an OpenAI API key.', type: 'openai', provider: 'openai', language: 'multilingual', dictationLanguages: DICTATION_LANGUAGES, + languages: DICTATION_LANGUAGES, sampleRate: 16000, streaming: false, // OpenAI shuts the gpt-4o transcribe models down on 2027-02-26. @@ -159,11 +219,11 @@ export const SPEECH_MODEL_CATALOG: SpeechModelManifest[] = [ { id: 'openai-gpt-4o-transcribe', label: 'GPT-4o Transcribe', - description: 'Cloud transcription with higher accuracy. Requires an OpenAI API key.', type: 'openai', provider: 'openai', language: 'multilingual', dictationLanguages: DICTATION_LANGUAGES, + languages: DICTATION_LANGUAGES, sampleRate: 16000, streaming: false, replacedBy: 'openai-gpt-transcribe' diff --git a/src/main/speech/model-download-catalog.ts b/src/main/speech/model-download-catalog.ts index 0c5e4e73968..6d4b740976a 100644 --- a/src/main/speech/model-download-catalog.ts +++ b/src/main/speech/model-download-catalog.ts @@ -1,4 +1,4 @@ -import type { SpeechModelDownloadFile } from '../../shared/speech-types' +import type { SpeechModelDownloadFile, SpeechModelManifest } from '../../shared/speech-types' type DownloadFileSpec = readonly [name: string, sizeBytes: number, sha256: string] @@ -216,6 +216,32 @@ const MODEL_DOWNLOAD_FILES = { export type DownloadableSpeechModelId = keyof typeof MODEL_DOWNLOAD_FILES +/** What the model manager needs to download, verify and place one model's files. */ +export type SpeechModelDownload = Pick< + SpeechModelManifest, + 'id' | 'provider' | 'downloadFiles' | 'legacyDownloadFiles' | 'sizeBytes' +> + +const SILERO_VAD_FILES = huggingFaceFiles( + 'handy-computer/silero-vad-v6.2-gguf', + '97bbd75179f535e4708bccdf61e9278b8b60dfc7', + [ + [ + 'silero-vad-v6.2-F32.gguf', + 1_241_056, + '0d871a800c420fdd5d1b17a3aea4296d1c39608f0ff4a9295eb76457eb1c88e6' + ] + ] +) + +/** Silero VAD (MIT), which transcribe-cpp uses to find pauses; a helper download, never a dictation model. */ +export const SILERO_VAD_MODEL = { + id: 'silero-vad-v6.2', + provider: 'local', + downloadFiles: SILERO_VAD_FILES, + sizeBytes: SILERO_VAD_FILES.reduce((total, { sizeBytes }) => total + sizeBytes, 0) +} satisfies SpeechModelDownload + export function getSpeechModelDownloadMetadata(modelId: DownloadableSpeechModelId): { downloadFiles: SpeechModelDownloadFile[] files: string[] diff --git a/src/main/speech/model-manager-progress-callback.test.ts b/src/main/speech/model-manager-progress-callback.test.ts deleted file mode 100644 index 49cff109461..00000000000 --- a/src/main/speech/model-manager-progress-callback.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { ModelManager } from './model-manager' -import { openElectronSpeechDownloadRequest } from '../host/electron-speech-services' - -vi.mock('electron', () => ({ - app: { - getPath: () => '/tmp/orca-speech-models-test' - } -})) - -type ModelManagerInternals = { - updateState: ( - modelId: string, - status: 'not-downloaded' | 'downloading' | 'extracting' | 'ready' | 'error', - progress?: number, - error?: string - ) => void -} - -describe('ModelManager progress callbacks', () => { - it('unsubscribes progress callbacks without replacing other listeners', () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) - try { - const manager = new ModelManager(dir, openElectronSpeechDownloadRequest) - const internals = manager as unknown as ModelManagerInternals - const first = vi.fn() - const second = vi.fn() - const clearFirst = manager.setProgressCallback(first) - const clearSecond = manager.setProgressCallback(second) - - internals.updateState('model-a', 'downloading', 0.25) - clearFirst() - internals.updateState('model-a', 'extracting') - clearSecond() - internals.updateState('model-a', 'ready') - - expect(first).toHaveBeenCalledTimes(1) - expect(first).toHaveBeenCalledWith('model-a', 0.25) - expect(second).toHaveBeenCalledTimes(2) - expect(second).toHaveBeenNthCalledWith(1, 'model-a', 0.25) - expect(second).toHaveBeenNthCalledWith(2, 'model-a', 0.95) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) - - it('coalesces per-chunk download progress to whole percent', () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) - try { - const manager = new ModelManager(dir, openElectronSpeechDownloadRequest) - const internals = manager as unknown as ModelManagerInternals - const listener = vi.fn() - manager.setProgressCallback(listener) - - // A 500MB model over a 64KB chunk stream reports this many times. - for (let chunk = 0; chunk < 8_000; chunk += 1) { - internals.updateState('model-a', 'downloading', chunk / 8_000) - } - - expect(listener.mock.calls.map(([, progress]) => progress)).toEqual( - Array.from({ length: 101 }, (_unused, percent) => percent / 100) - ) - const afterDownload = listener.mock.calls.length - internals.updateState('model-a', 'extracting') - internals.updateState('model-a', 'ready') - internals.updateState('model-a', 'ready') - expect(listener.mock.calls.length).toBe(afterDownload + 3) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) -}) diff --git a/src/main/speech/model-manager.test.ts b/src/main/speech/model-manager.test.ts index d374b2b0bc0..ddcd490e104 100644 --- a/src/main/speech/model-manager.test.ts +++ b/src/main/speech/model-manager.test.ts @@ -1,7 +1,6 @@ -import 'node:crypto' -import { existsSync, mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' +import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' import { SPEECH_MODEL_CATALOG } from './model-catalog' import { ModelManager } from './model-manager' @@ -26,17 +25,6 @@ vi.mock('./openai-api-key-store', () => ({ })) type ModelManagerInternals = { - verifyFileSha256: (filePath: string, expectedSha256: string) => Promise - downloadFileWithRetry: ( - url: string, - filePath: string, - expectedSize: number, - modelId: string, - isAborted: () => boolean, - signal: AbortSignal, - completedBytes?: number, - modelTotalBytes?: number - ) => Promise downloadFile: ( url: string, dest: string, @@ -62,72 +50,26 @@ describe('ModelManager', () => { hasOpenAiSpeechApiKeyMock.mockReturnValue(false) }) - it('installs individually verified model files through a staging directory', async () => { + it('reports a model downloaded in the old sherpa-onnx format as needing an update', async () => { const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) try { - const manifest = SPEECH_MODEL_CATALOG.find( - (model) => model.id === 'zipformer-streaming-zh-14m' - )! const manager = new ModelManager(dir, openElectronSpeechDownloadRequest) - const internals = manager as unknown as ModelManagerInternals - const downloadMock = vi - .spyOn(internals, 'downloadFileWithRetry') - .mockImplementation(async (_url, filePath, expectedSize) => { - writeFileSync(filePath, '') - truncateSync(filePath, expectedSize) - }) - const verifyMock = vi.spyOn(internals, 'verifyFileSha256').mockResolvedValue() - - await manager.downloadModel(manifest.id) - - const modelDir = manager.getModelDir(manifest.id) - expect(downloadMock).toHaveBeenCalledTimes(manifest.downloadFiles?.length ?? 0) - expect(verifyMock).toHaveBeenCalledTimes(manifest.downloadFiles?.length ?? 0) - let expectedOffset = 0 - for (const [index, file] of (manifest.downloadFiles ?? []).entries()) { - expect(downloadMock.mock.calls[index]?.slice(6)).toEqual([ - expectedOffset, - manifest.sizeBytes - ]) - expectedOffset += file.sizeBytes - expect(existsSync(join(modelDir, file.name))).toBe(true) - } - expect(existsSync(`${modelDir}.partial`)).toBe(false) - await expect(manager.getModelState(manifest.id)).resolves.toEqual({ - id: manifest.id, - status: 'ready' - }) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) - - it('deletes a ready local model and reports it as not downloaded', async () => { - const dir = mkdtempSync(join(tmpdir(), 'orca-model-manager-')) - try { - const manifest = SPEECH_MODEL_CATALOG.find( - (model) => model.id === 'zipformer-streaming-zh-14m' - ) - expect(manifest?.files).toBeDefined() - const manager = new ModelManager(dir, openElectronSpeechDownloadRequest) - const modelDir = manager.getModelDir(manifest!.id) - for (const file of manifest!.downloadFiles ?? []) { - const path = join(modelDir, file.name) - mkdirSync(dirname(path), { recursive: true }) - writeFileSync(path, '') - truncateSync(path, file.sizeBytes) + const modelDir = manager.getModelDir('parakeet-tdt-0.6b-v2-int8') + mkdirSync(modelDir, { recursive: true }) + for (const [name, size] of [ + ['encoder.int8.onnx', 652_184_296], + ['decoder.int8.onnx', 7_257_753], + ['joiner.int8.onnx', 1_739_080], + ['tokens.txt', 9_384] + ] as const) { + writeFileSync(join(modelDir, name), '') + truncateSync(join(modelDir, name), size) } - await expect(manager.getModelState(manifest!.id)).resolves.toEqual({ - id: manifest!.id, - status: 'ready' - }) - await manager.deleteModel(manifest!.id) - - expect(existsSync(modelDir)).toBe(false) - await expect(manager.getModelState(manifest!.id)).resolves.toEqual({ - id: manifest!.id, - status: 'not-downloaded' + await expect(manager.getModelState('parakeet-tdt-0.6b-v2-int8')).resolves.toEqual({ + id: 'parakeet-tdt-0.6b-v2-int8', + status: 'not-downloaded', + needsUpdate: true }) } finally { rmSync(dir, { recursive: true, force: true }) diff --git a/src/main/speech/model-manager.ts b/src/main/speech/model-manager.ts index 00e3b0de910..8e530065f6d 100644 --- a/src/main/speech/model-manager.ts +++ b/src/main/speech/model-manager.ts @@ -1,19 +1,18 @@ -import { existsSync, mkdirSync, rmSync, statSync } from 'node:fs' +import { existsSync, mkdirSync, rmSync } from 'node:fs' import { rename, rm } from 'node:fs/promises' import { join, relative, resolve } from 'node:path' -import type { - SpeechModelManifest, - SpeechModelState, - SpeechModelStatus -} from '../../shared/speech-types' +import type { SpeechModelState, SpeechModelStatus } from '../../shared/speech-types' import { SPEECH_MODEL_CATALOG, getCatalogModel, isLocalSpeechModel } from './model-catalog' -import { hasOpenAiSpeechApiKey } from './openai-api-key-store' +import type { SpeechModelDownload } from './model-download-catalog' +import { downloadSileroVadInBackground, speechModelDownload } from './speech-vad-model' +import { hasCloudSpeechCredentials } from './cloud-transcription-target' import { getSpeechModelCacheDirCandidates, migrateSpeechModelCacheIfNeeded, type SpeechModelCacheDir } from './model-cache-path' import { SpeechModelDownloadTransport } from './speech-model-download-transport' +import { hasSpeechModelFiles } from './speech-model-files' import type { OpenSpeechDownloadRequest } from './speech-model-download-response' import { getAppEnvironment } from '../../shared/app-environment' import { @@ -38,7 +37,7 @@ export class ModelManager extends SpeechModelDownloadTransport { constructor( customModelsDir: string | undefined, openRequest: OpenSpeechDownloadRequest, - private readonly hasOpenAiKey: () => boolean = hasOpenAiSpeechApiKey + private readonly hasCloudCredentials = hasCloudSpeechCredentials ) { super(openRequest) const requestedModelsDir = @@ -98,21 +97,25 @@ export class ModelManager extends SpeechModelDownloadTransport { return cached } - const manifest = getCatalogModel(modelId) + const manifest = speechModelDownload(modelId) if (!manifest) { return { id: modelId, status: 'error', error: 'Unknown model' } } - if (manifest.provider === 'openai') { - return { id: modelId, status: this.hasOpenAiKey() ? 'ready' : 'not-downloaded' } + if (manifest.provider !== 'local') { + const ready = this.hasCloudCredentials(manifest.provider) + return { id: modelId, status: ready ? 'ready' : 'not-downloaded' } } const modelDir = this.getModelDir(modelId) - if (existsSync(modelDir) && this.validateModelFiles(manifest, modelDir)) { + if (existsSync(modelDir) && hasSpeechModelFiles(manifest.downloadFiles, modelDir)) { const state: SpeechModelState = { id: modelId, status: 'ready' } this.modelStates.set(modelId, state) return state } + if (existsSync(modelDir) && hasSpeechModelFiles(manifest.legacyDownloadFiles, modelDir)) { + return { id: modelId, status: 'not-downloaded', needsUpdate: true } + } return { id: modelId, status: 'not-downloaded' } } @@ -122,7 +125,7 @@ export class ModelManager extends SpeechModelDownloadTransport { } private getSafeModelDir(modelId: string, root: string = this.modelsDir): string { - const manifest = getCatalogModel(modelId) + const manifest = speechModelDownload(modelId) if (!manifest) { throw new Error(`Unknown model: ${modelId}`) } @@ -135,30 +138,17 @@ export class ModelManager extends SpeechModelDownloadTransport { return modelDir } - private validateModelFiles(manifest: SpeechModelManifest, modelDir: string): boolean { - if (!manifest.downloadFiles) { - return false - } - return manifest.downloadFiles.every(({ name, sizeBytes }) => { - try { - return statSync(join(modelDir, name)).size === sizeBytes - } catch { - return false - } - }) - } - async downloadModel(modelId: string): Promise { // Do not await migration: downloads cannot race it, and cancellation needs synchronous setup. if (this.activeDownloads.has(modelId)) { return } - const manifest = getCatalogModel(modelId) + const manifest = speechModelDownload(modelId) if (!manifest) { throw new Error(`Unknown model: ${modelId}`) } - if (!isLocalSpeechModel(manifest)) { + if (manifest.provider !== 'local') { throw new Error(`Model does not support downloads: ${modelId}`) } if (!manifest.downloadFiles?.length || !manifest.sizeBytes) { @@ -166,7 +156,7 @@ export class ModelManager extends SpeechModelDownloadTransport { } const modelDir = this.getModelDir(modelId) - if (existsSync(modelDir) && this.validateModelFiles(manifest, modelDir)) { + if (existsSync(modelDir) && hasSpeechModelFiles(manifest.downloadFiles, modelDir)) { this.updateState(modelId, 'ready') return } @@ -211,6 +201,9 @@ export class ModelManager extends SpeechModelDownloadTransport { await rm(modelDir, { recursive: true, force: true }) await rename(stagingDir, modelDir) this.updateState(modelId, 'ready') + if (getCatalogModel(modelId)?.files?.some((file) => file.endsWith('.gguf'))) { + downloadSileroVadInBackground(this) + } } catch (err) { if (!aborted) { console.error('[speech] Model download failed:', modelId, err) @@ -291,7 +284,7 @@ export class ModelManager extends SpeechModelDownloadTransport { } private async downloadModelFiles( - manifest: SpeechModelManifest, + manifest: SpeechModelDownload, stagingDir: string, modelId: string, isAborted: () => boolean, @@ -330,7 +323,7 @@ export class ModelManager extends SpeechModelDownloadTransport { completedBytes += file.sizeBytes } - if (!this.validateModelFiles(manifest, stagingDir)) { + if (!hasSpeechModelFiles(manifest.downloadFiles, stagingDir)) { throw new Error('Model files missing after download') } } diff --git a/src/main/speech/node-speech-download-request.test.ts b/src/main/speech/node-speech-download-request.test.ts index 394f7802ccf..1ace63cedfa 100644 --- a/src/main/speech/node-speech-download-request.test.ts +++ b/src/main/speech/node-speech-download-request.test.ts @@ -64,15 +64,6 @@ describe('openNodeSpeechDownloadRequest', () => { expect(listeners.response).not.toHaveBeenCalled() }) - it('hands any other response to the download', () => { - const handle = openNodeSpeechDownloadRequest('https://models.example/a.tar.bz2') - const listeners = { error: vi.fn(), response: vi.fn(), redirect: vi.fn() } - handle.listen(listeners) - const ok = incoming(206, { 'content-range': 'bytes 10-19/20' }) - lastRequest().emit('response', ok) - expect(listeners.response).toHaveBeenCalledWith(ok) - }) - // Abort emits after detach; an unhandled ClientRequest error crashes orcad. it('swallows the error abort raises after the download detached', () => { const handle = openNodeSpeechDownloadRequest('https://models.example/a.tar.bz2') diff --git a/src/main/speech/openai-api-key-store.test.ts b/src/main/speech/openai-api-key-store.test.ts index 73dd4ff7ce0..26a2dfc56e1 100644 --- a/src/main/speech/openai-api-key-store.test.ts +++ b/src/main/speech/openai-api-key-store.test.ts @@ -46,15 +46,6 @@ function writeStoredOpenAiKey(value: string): void { } describe('OpenAI speech API key store', () => { - it('checks configured status without decrypting or touching safeStorage', async () => { - writeStoredOpenAiKey('encrypted-key') - const store = await loadStoreModule() - - expect(store.hasOpenAiSpeechApiKey()).toBe(true) - expect(safeStorageMock.isEncryptionAvailable).not.toHaveBeenCalled() - expect(safeStorageMock.decryptString).not.toHaveBeenCalled() - }) - // #31174: orcad cannot open a key the desktop sealed with safeStorage, so it must not say ready. it('reports a stored key this host cannot decrypt as unusable', async () => { writeStoredOpenAiKey('v10\u0000ÿþ sealed by another store') @@ -77,13 +68,4 @@ describe('OpenAI speech API key store', () => { expect(store.canReadOpenAiSpeechApiKey()).toBe(false) expect(() => store.readOpenAiSpeechApiKey()).toThrow('OpenAI API key could not be decrypted') }) - - it('caches the decrypted key so repeated dictations do not repeatedly touch safeStorage', async () => { - writeStoredOpenAiKey('encrypted-key') - const store = await loadStoreModule() - - expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key') - expect(store.readOpenAiSpeechApiKey()).toBe('encrypted-key') - expect(safeStorageMock.decryptString).toHaveBeenCalledOnce() - }) }) diff --git a/src/main/speech/openai-api-key-verification.ts b/src/main/speech/openai-api-key-verification.ts index d7fe69a1710..6249026b8ba 100644 --- a/src/main/speech/openai-api-key-verification.ts +++ b/src/main/speech/openai-api-key-verification.ts @@ -1,4 +1,11 @@ import { saveOpenAiSpeechApiKey } from './openai-api-key-store' +import { OPENAI_TRANSCRIPTION_URL } from './cloud-transcription-target' +import { + openAiCompatibleTranscriptionUrl, + resolveOpenAiCompatibleSpeechProviderInput, + saveOpenAiCompatibleSpeechProvider +} from './openai-compatible-speech-provider-store' +import type { OpenAiCompatibleSpeechProvider } from '../../shared/speech-types' import { postOpenAiTranscription, readOpenAiErrorMessage, @@ -11,16 +18,27 @@ const KEY_CHECK_TIMEOUT_MS = 10_000 export async function saveVerifiedOpenAiSpeechApiKey(apiKey: string): Promise { const trimmed = apiKey.trim() if (trimmed) { - await rejectUnauthorizedOpenAiKey(trimmed) + await rejectUnauthorizedKey(OPENAI_TRANSCRIPTION_URL, trimmed, 'OpenAI') } saveOpenAiSpeechApiKey(apiKey) } -async function rejectUnauthorizedOpenAiKey(apiKey: string): Promise { +/** Same check against the provider's own endpoint, which also catches a wrong base URL. */ +export async function saveVerifiedOpenAiCompatibleSpeechProvider( + input: OpenAiCompatibleSpeechProvider +): Promise { + const provider = resolveOpenAiCompatibleSpeechProviderInput(input) + const url = openAiCompatibleTranscriptionUrl(provider.baseUrl) + await rejectUnauthorizedKey(url, provider.apiKey, new URL(url).host) + saveOpenAiCompatibleSpeechProvider(provider) +} + +async function rejectUnauthorizedKey(url: string, apiKey: string, label: string): Promise { let response: Response try { - // An empty form is refused before any transcription, but only after OpenAI checks the key. + // An empty form is refused before any transcription, but only after the server checks the key. response = await postOpenAiTranscription( + url, apiKey, new FormData(), AbortSignal.timeout(KEY_CHECK_TIMEOUT_MS) @@ -28,10 +46,15 @@ async function rejectUnauthorizedOpenAiKey(apiKey: string): Promise { } catch { return } + if (response.status === 404 || response.status === 405) { + void response.body?.cancel().catch(() => undefined) + throw new Error(`${label} has no transcription endpoint at ${url}. Check the base URL.`) + } if (response.status !== 401) { void response.body?.cancel().catch(() => undefined) return } const data: OpenAiTranscriptionResponse = await response.json().catch(() => ({})) - throw new Error(readOpenAiErrorMessage(data) ?? 'OpenAI rejected this API key.') + const fallback = apiKey ? `${label} rejected this API key.` : `${label} needs an API key.` + throw new Error(readOpenAiErrorMessage(data, apiKey) ?? fallback) } diff --git a/src/main/speech/openai-compatible-speech-provider-store.test.ts b/src/main/speech/openai-compatible-speech-provider-store.test.ts new file mode 100644 index 00000000000..8821eb525b3 --- /dev/null +++ b/src/main/speech/openai-compatible-speech-provider-store.test.ts @@ -0,0 +1,66 @@ +import { mkdtempSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +async function loadStoreModule() { + vi.resetModules() + const { setSecretStore } = await import('../../shared/secret-store') + setSecretStore({ + decryptString: (value: Buffer) => value.toString('utf8'), + encryptString: (value: string) => Buffer.from(value), + isEncryptionAvailable: () => true, + describeProtectionGap: () => null + }) + return import('./openai-compatible-speech-provider-store') +} + +beforeEach(() => { + const home = mkdtempSync(join(tmpdir(), 'orca-compatible-speech-')) + vi.stubEnv('HOME', home) + vi.stubEnv('USERPROFILE', home) +}) + +describe('openAiCompatibleTranscriptionUrl', () => { + it('appends the transcriptions path to a base URL and keeps a full one', async () => { + const { openAiCompatibleTranscriptionUrl } = await loadStoreModule() + expect(openAiCompatibleTranscriptionUrl(' https://api.groq.com/openai/v1/ ')).toBe( + 'https://api.groq.com/openai/v1/audio/transcriptions' + ) + expect(openAiCompatibleTranscriptionUrl('https://api.mistral.ai/v1/audio/transcriptions')).toBe( + 'https://api.mistral.ai/v1/audio/transcriptions' + ) + expect(openAiCompatibleTranscriptionUrl('http://127.0.0.1:8000/v1')).toBe( + 'http://127.0.0.1:8000/v1/audio/transcriptions' + ) + expect(() => openAiCompatibleTranscriptionUrl('file:///etc/passwd')).toThrow() + expect(() => openAiCompatibleTranscriptionUrl('api.groq.com')).toThrow() + expect(() => openAiCompatibleTranscriptionUrl('https://user:pw@host.example/v1')).toThrow() + }) +}) + +describe('resolveOpenAiCompatibleSpeechProviderInput', () => { + it('keeps a saved key for a blank field only while the base URL is unchanged', async () => { + const store = await loadStoreModule() + store.saveOpenAiCompatibleSpeechProvider({ + baseUrl: 'https://api.groq.com/openai/v1', + model: 'whisper-large-v3-turbo', + apiKey: 'gsk_saved' + }) + + expect( + store.resolveOpenAiCompatibleSpeechProviderInput({ + baseUrl: 'https://api.groq.com/openai/v1/', + model: 'whisper-large-v3', + apiKey: '' + }).apiKey + ).toBe('gsk_saved') + expect( + store.resolveOpenAiCompatibleSpeechProviderInput({ + baseUrl: 'https://evil.example/v1', + model: 'whisper-large-v3', + apiKey: '' + }).apiKey + ).toBe('') + }) +}) diff --git a/src/main/speech/openai-compatible-speech-provider-store.ts b/src/main/speech/openai-compatible-speech-provider-store.ts new file mode 100644 index 00000000000..b634d9b26ea --- /dev/null +++ b/src/main/speech/openai-compatible-speech-provider-store.ts @@ -0,0 +1,98 @@ +import { z } from 'zod' +import { createEncryptedApiKeyFileStore } from '../credentials/encrypted-api-key-file-store' +import { savedCredentialUnreadable } from '../credentials/saved-credential-readability' +import type { + OpenAiCompatibleSpeechProvider, + OpenAiCompatibleSpeechProviderSummary +} from '../../shared/speech-types' + +// URL, model and key are sealed together so a key can never be sent to a host it wasn't saved for. +const store = createEncryptedApiKeyFileStore({ + fileName: 'openai-compatible-speech-provider.enc', + envelopePrefix: 'orca-openai-compatible-speech:v1:', + providerLabel: 'OpenAI-compatible speech provider', + logScope: 'speech' +}) + +export const hasOpenAiCompatibleSpeechProvider = store.has +export const clearOpenAiCompatibleSpeechProvider = store.clear +export const openAiCompatibleSpeechProviderEnvelopeFile = store.envelopeFile + +const TRANSCRIPTION_PATH = '/audio/transcriptions' + +const providerSchema = z.object({ + baseUrl: z.string().catch(''), + model: z.string().catch(''), + apiKey: z.string().catch('') +}) satisfies z.ZodType + +/** Accepts a base like `https://api.groq.com/openai/v1` or the full transcriptions URL. */ +export function openAiCompatibleTranscriptionUrl(baseUrl: string): string { + let url: URL + try { + url = new URL(baseUrl.trim()) + } catch { + throw new Error('Enter a full base URL, such as https://api.groq.com/openai/v1') + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + throw new Error('The base URL must start with https:// or http://') + } + // fetch refuses these, and its error would echo the password. + if (url.username || url.password) { + throw new Error('Put the key in the API Key field, not in the base URL') + } + const path = url.pathname.replace(/\/+$/, '') + url.pathname = path.endsWith(TRANSCRIPTION_PATH) ? path : `${path}${TRANSCRIPTION_PATH}` + return url.toString() +} + +export function readOpenAiCompatibleSpeechProvider(): OpenAiCompatibleSpeechProvider | null { + // The store caches what it read; another process (desktop vs orca serve) may have removed the file since. + const raw = store.has() ? store.read() : null + if (raw === null) { + return null + } + return providerSchema.parse(JSON.parse(raw)) +} + +/** Headless hosts may not open a desktop-sealed file; checks the disk quietly, since readiness is polled. */ +export function canReadOpenAiCompatibleSpeechProvider(): boolean { + return store.has() && savedCredentialUnreadable(store.envelopeFile()) === undefined +} + +export function summarizeOpenAiCompatibleSpeechProvider(): OpenAiCompatibleSpeechProviderSummary | null { + const provider = readOpenAiCompatibleSpeechProvider() + return provider + ? { baseUrl: provider.baseUrl, model: provider.model, hasApiKey: provider.apiKey !== '' } + : null +} + +/** A blank key keeps the saved one only while the base URL is unchanged. */ +export function resolveOpenAiCompatibleSpeechProviderInput( + input: OpenAiCompatibleSpeechProvider +): OpenAiCompatibleSpeechProvider { + const baseUrl = input.baseUrl.trim() + const model = input.model.trim() + openAiCompatibleTranscriptionUrl(baseUrl) + if (!model) { + throw new Error('Enter the model name the provider expects') + } + return { baseUrl, model, apiKey: input.apiKey.trim() || savedKeyFor(baseUrl) } +} + +function savedKeyFor(baseUrl: string): string { + try { + const saved = readOpenAiCompatibleSpeechProvider() + const sameEndpoint = + saved !== null && + openAiCompatibleTranscriptionUrl(saved.baseUrl) === openAiCompatibleTranscriptionUrl(baseUrl) + return sameEndpoint ? saved.apiKey : '' + } catch { + // An unreadable or invalid saved provider has no key worth keeping. + return '' + } +} + +export function saveOpenAiCompatibleSpeechProvider(provider: OpenAiCompatibleSpeechProvider): void { + store.save(JSON.stringify(provider)) +} diff --git a/src/main/speech/openai-transcription-client.test.ts b/src/main/speech/openai-transcription-client.test.ts index abec63f2854..c74b8afaf91 100644 --- a/src/main/speech/openai-transcription-client.test.ts +++ b/src/main/speech/openai-transcription-client.test.ts @@ -47,7 +47,15 @@ describe('OpenAiTranscriptionSession', () => { uploads.push(Buffer.from(await file.arrayBuffer())) return new Response(JSON.stringify({ text: ' complete dictation ' })) }) - const session = new OpenAiTranscriptionSession('openai-gpt-transcribe', () => 'test-key', 'de') + const session = new OpenAiTranscriptionSession( + () => ({ + url: 'https://api.openai.com/v1/audio/transcriptions', + model: 'gpt-transcribe', + apiKey: 'test-key', + label: 'OpenAI' + }), + 'de' + ) const input = new Float32Array([ -2, -1, @@ -76,4 +84,31 @@ describe('OpenAiTranscriptionSession', () => { -32768, -32768, -16384, 0, 0, 16384, 32767, 32767, 0, 32767, -32768, 0, 24575 ]) }) + + it('sends a keyless server the singular language field and no Authorization header', async () => { + let sent: RequestInit | undefined + vi.stubGlobal('fetch', async (_url: string, init: RequestInit) => { + sent = init + return new Response(JSON.stringify({ text: 'hola' })) + }) + const session = new OpenAiTranscriptionSession( + () => ({ + url: 'http://127.0.0.1:8000/v1/audio/transcriptions', + model: 'whisper-large-v3-turbo', + apiKey: '', + label: '127.0.0.1:8000' + }), + 'es' + ) + session.feedAudio(new Float32Array(160), 16000) + + expect(await session.finish()).toBe('hola') + const form = sent?.body + if (!(form instanceof FormData)) { + throw new Error('Expected multipart body') + } + expect(form.get('language')).toBe('es') + expect(form.has('languages[]')).toBe(false) + expect(sent?.headers).toEqual({}) + }) }) diff --git a/src/main/speech/openai-transcription-client.ts b/src/main/speech/openai-transcription-client.ts index 452685c9b29..3f18309beb6 100644 --- a/src/main/speech/openai-transcription-client.ts +++ b/src/main/speech/openai-transcription-client.ts @@ -1,17 +1,12 @@ import { getMainHttpClient } from '../network/http-client' import { resampleToRate } from './stt-audio-resample' -import { replaceRetiredSpeechModelId } from './model-catalog' +import type { CloudTranscriptionTarget } from './cloud-transcription-target' import { CLOUD_TRANSCRIPTION_SAMPLE_RATE, MAX_CLOUD_TRANSCRIPTION_SECONDS, cloudTranscriptionTimeoutMs } from '../../shared/dictation-finish-deadlines' -export const OPENAI_TRANSCRIPTION_MODEL_BY_ID: Record = { - 'openai-gpt-transcribe': 'gpt-transcribe' -} - -export const OPENAI_TRANSCRIPTION_URL = 'https://api.openai.com/v1/audio/transcriptions' const MAX_CLOUD_AUDIO_SAMPLES = MAX_CLOUD_TRANSCRIPTION_SECONDS * CLOUD_TRANSCRIPTION_SAMPLE_RATE export type OpenAiTranscriptionResponse = { @@ -21,17 +16,18 @@ export type OpenAiTranscriptionResponse = { } } -export function sanitizeOpenAiTranscriptionErrorMessage(message: string): string { +export function sanitizeOpenAiTranscriptionErrorMessage(message: string, apiKey = ''): string { if (/incorrect api key provided:/i.test(message)) { return 'Incorrect OpenAI API key provided.' } - const sanitized = message + // Other providers' keys have other shapes, so also redact the exact key sent (unless it's a placeholder like "x"). + const sanitized = (apiKey.length >= 8 ? message.split(apiKey).join('[redacted]') : message) .replace(/\bsk-[A-Za-z0-9_-]+/g, '[redacted]') .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [redacted]') .trim() - return sanitized || 'OpenAI transcription request failed' + return sanitized || 'Transcription request failed' } function writePcm16Samples(view: DataView, samples: Float32Array, offset: number): void { @@ -72,33 +68,34 @@ function encodePcm16Wav(chunks: Float32Array[], sampleRate: number): Buffer { - return getMainHttpClient().fetch(OPENAI_TRANSCRIPTION_URL, { + return getMainHttpClient().fetch(url, { method: 'POST', - // Bearer auth only: keep OpenAI's cookies out of the shared desktop session. + // Bearer auth only: keep the provider's cookies out of the shared desktop session. credentials: 'omit', signal, - headers: { Authorization: `Bearer ${apiKey}` }, + // Local servers that take no key get no Authorization header. + headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : {}, body: form }) } -export function readOpenAiErrorMessage(data: OpenAiTranscriptionResponse): string | undefined { +export function readOpenAiErrorMessage( + data: OpenAiTranscriptionResponse, + apiKey = '' +): string | undefined { return typeof data.error?.message === 'string' - ? sanitizeOpenAiTranscriptionErrorMessage(data.error.message) + ? sanitizeOpenAiTranscriptionErrorMessage(data.error.message, apiKey) : undefined } -function parseOpenAiTranscriptionResponse(data: OpenAiTranscriptionResponse): string { - if (typeof data.text === 'string') { - return data.text.trim() - } - throw new Error( - readOpenAiErrorMessage(data) ?? 'OpenAI transcription response did not include text' - ) +// gpt-transcribe takes a list of expected languages in place of the singular field others use. +function languageField(model: string): string { + return /^gpt-(live-)?transcribe/.test(model) ? 'languages[]' : 'language' } export class OpenAiTranscriptionSession { @@ -107,8 +104,7 @@ export class OpenAiTranscriptionSession { private readonly abortController = new AbortController() constructor( - private readonly modelId: string, - private readonly readApiKey: () => string, + private readonly readTarget: () => CloudTranscriptionTarget, private readonly language?: string ) {} @@ -136,46 +132,46 @@ export class OpenAiTranscriptionSession { return '' } - // Settings load already moves retired ids; this catches a caller still holding one. - const apiModel = OPENAI_TRANSCRIPTION_MODEL_BY_ID[replaceRetiredSpeechModelId(this.modelId)] - if (!apiModel) { - throw new Error(`Unknown OpenAI transcription model: ${this.modelId}`) - } - + const target = this.readTarget() const chunks = this.chunks this.chunks = [] const wav = encodePcm16Wav(chunks, CLOUD_TRANSCRIPTION_SAMPLE_RATE) + // No response_format: JSON is the default everywhere, and not every provider accepts the field. const form = new FormData() - // No response_format: JSON is the default, and gpt-transcribe documents no other. - form.append('model', apiModel) + form.append('model', target.model) if (this.language) { - // gpt-transcribe takes a list of expected languages in place of the singular `language`. - form.append('languages[]', this.language) + form.append(languageField(target.model), this.language) } // A named WAV blob satisfies multipart uploads without temporary files. form.append('file', new Blob([wav], { type: 'audio/wav' }), 'dictation.wav') const timeout = AbortSignal.timeout(cloudTranscriptionTimeoutMs(this.audioSamples)) try { - return await this.upload(form, AbortSignal.any([this.abortController.signal, timeout])) + return await upload(target, form, AbortSignal.any([this.abortController.signal, timeout])) } catch (error) { if (timeout.aborted && !this.abortController.signal.aborted) { - throw new Error('OpenAI transcription timed out. Check your connection and try again.') + throw new Error( + `${target.label} transcription timed out. Check your connection and try again.` + ) } throw error } } +} - private async upload(form: FormData, signal: AbortSignal): Promise { - const response = await postOpenAiTranscription(this.readApiKey(), form, signal) - - const data = (await response.json().catch(() => ({}))) as OpenAiTranscriptionResponse - if (!response.ok) { - throw new Error( - `OpenAI transcription failed: ${readOpenAiErrorMessage(data) ?? response.statusText}` - ) - } - - return parseOpenAiTranscriptionResponse(data) +async function upload( + target: CloudTranscriptionTarget, + form: FormData, + signal: AbortSignal +): Promise { + const response = await postOpenAiTranscription(target.url, target.apiKey, form, signal) + const data = (await response.json().catch(() => ({}))) as OpenAiTranscriptionResponse + const error = readOpenAiErrorMessage(data, target.apiKey) + if (!response.ok) { + throw new Error(`${target.label} transcription failed: ${error ?? response.statusText}`) + } + if (typeof data.text === 'string') { + return data.text.trim() } + throw new Error(error ?? `${target.label} transcription response did not include text`) } diff --git a/src/main/speech/speech-model-error-rates.ts b/src/main/speech/speech-model-error-rates.ts new file mode 100644 index 00000000000..9418e179081 --- /dev/null +++ b/src/main/speech/speech-model-error-rates.ts @@ -0,0 +1,79 @@ +import type { SpeechModelErrorRate } from '../../shared/speech-types' + +type Measured = readonly [language: string, percent: number, measuredOn: string] + +const LIBRISPEECH_CLIPS = 73 +const FLEURS_CLIPS = 5 +const CHARACTER_SCORED = new Set(['ja', 'ko', 'zh']) + +// Orca's speech bench: transcribe-cpp 0.4.1 with Metal on an M4 Max, the catalog's pinned GGUF +// files, one run per clip. English is LibriSpeech (73 clips); other languages are FLEURS dev +// (5 clips each, so rough). Each clip's language was sent the way Orca sends it; Parakeet ignores it. +const MEASURED = { + 'parakeet-tdt-0.6b-v3-int8': [ + ['en', 3.7, '2026-11-06'], + ['de', 2.2, '2026-11-06'], + ['es', 1.7, '2026-11-06'], + ['fr', 8.3, '2026-11-09'], + ['pt', 11.3, '2026-11-09'], + ['ru', 3.4, '2026-11-06'] + ], + 'parakeet-tdt-0.6b-v2-int8': [['en', 2.8, '2026-11-06']], + 'whisper-tiny': [ + ['en', 13, '2026-11-09'], + ['de', 10, '2026-11-09'], + ['es', 13.6, '2026-11-09'], + ['fr', 52.3, '2026-11-09'], + ['ja', 69.3, '2026-11-09'], + ['ko', 24.9, '2026-11-09'], + ['pt', 31.1, '2026-11-09'], + ['ru', 38.2, '2026-11-09'], + ['tr', 49.5, '2026-11-09'], + ['zh', 47.5, '2026-11-09'] + ], + 'whisper-large-v3-turbo': [ + ['en', 4.5, '2026-11-09'], + ['de', 1.1, '2026-11-09'], + ['es', 1.7, '2026-11-09'], + ['fr', 5.3, '2026-11-09'], + ['ja', 7.4, '2026-11-09'], + ['ko', 2.6, '2026-11-09'], + ['pt', 8.5, '2026-11-09'], + ['ru', 3.4, '2026-11-09'], + ['tr', 7.7, '2026-11-09'], + ['zh', 9.4, '2026-11-09'] + ], + 'sense-voice-zh-en-ja-ko-yue': [ + ['en', 6.9, '2026-11-09'], + ['ja', 10.7, '2026-11-09'], + ['ko', 10, '2026-11-09'], + ['zh', 12.9, '2026-11-09'] + ], + 'nemotron-3.5-asr-streaming-0.6b': [ + ['en', 5.3, '2026-11-09'], + ['de', 5.6, '2026-11-09'], + ['es', 2.5, '2026-11-09'], + ['fr', 9.8, '2026-11-09'], + ['ja', 17.2, '2026-11-09'], + ['ko', 11.8, '2026-11-09'], + ['pt', 13.2, '2026-11-09'], + ['ru', 14.6, '2026-11-09'], + ['tr', 14.3, '2026-11-09'], + ['zh', 17.3, '2026-11-09'] + ] +} satisfies Record + +export function getSpeechModelErrorRates(modelId: keyof typeof MEASURED): { + errorRates: SpeechModelErrorRate[] +} { + return { + errorRates: MEASURED[modelId].map(([language, percent, measuredOn]) => ({ + language, + percent, + metric: CHARACTER_SCORED.has(language) ? 'cer' : 'wer', + test: language === 'en' ? 'librispeech' : 'fleurs', + clips: language === 'en' ? LIBRISPEECH_CLIPS : FLEURS_CLIPS, + measuredOn + })) + } +} diff --git a/src/main/speech/speech-model-files.ts b/src/main/speech/speech-model-files.ts new file mode 100644 index 00000000000..7e454c142b1 --- /dev/null +++ b/src/main/speech/speech-model-files.ts @@ -0,0 +1,20 @@ +import { statSync } from 'node:fs' +import { join } from 'node:path' +import type { SpeechModelDownloadFile } from '../../shared/speech-types' + +/** Whether every listed file is in `modelDir` at its expected size. */ +export function hasSpeechModelFiles( + files: readonly SpeechModelDownloadFile[] | undefined, + modelDir: string +): boolean { + if (!files) { + return false + } + return files.every(({ name, sizeBytes }) => { + try { + return statSync(join(modelDir, name)).size === sizeBytes + } catch { + return false + } + }) +} diff --git a/src/main/speech/speech-model-gguf-downloads.ts b/src/main/speech/speech-model-gguf-downloads.ts new file mode 100644 index 00000000000..c8b1c9c0c2a --- /dev/null +++ b/src/main/speech/speech-model-gguf-downloads.ts @@ -0,0 +1,67 @@ +import type { SpeechModelDownloadFile } from '../../shared/speech-types' + +type GgufDownload = readonly [ + repository: string, + revision: string, + name: string, + sizeBytes: number, + sha256: string +] + +// handy-computer's GGUF conversions for transcribe-cpp 0.4.x, pinned by revision and hash. +const GGUF_DOWNLOADS = { + 'parakeet-tdt-0.6b-v3-int8': [ + 'handy-computer/parakeet-tdt-0.6b-v3-gguf', + '85ac09ea12fc4b1112fa76810059364bc6adc9de', + 'parakeet-tdt-0.6b-v3-Q8_0.gguf', + 739_508_576, + '5859f77944efcd8eafa23a6350731960b2b55b2203df51f319665c807d802cc7' + ], + 'parakeet-tdt-0.6b-v2-int8': [ + 'handy-computer/parakeet-tdt-0.6b-v2-gguf', + '07cee0616125a08ef619729bb47f40ef747e4bc4', + 'parakeet-tdt-0.6b-v2-Q8_0.gguf', + 729_574_912, + 'f0d0e99cebb6d3b83f1f7069b82b5d3c2e39a54545b0da039cb4bafd9c4e5caa' + ], + 'whisper-tiny': [ + 'handy-computer/whisper-tiny-gguf', + '6687f30c99641ee265df421e582354adbc8848fc', + 'whisper-tiny-Q8_0.gguf', + 45_981_088, + '325b9c7997cd1eff81ef709d55766565e71be696130cc3a3d444713798706834' + ], + 'whisper-large-v3-turbo': [ + 'handy-computer/whisper-large-v3-turbo-gguf', + '5eaf945c7978e564bae5b28a5b1639dd93c2bfb1', + 'whisper-large-v3-turbo-Q8_0.gguf', + 886_381_760, + 'b2e30cc286bc9f3aba4db9099fc7403543497c05ce7100d0d83091ddfd25a183' + ], + 'sense-voice-zh-en-ja-ko-yue': [ + 'handy-computer/SenseVoiceSmall-gguf', + '4a08b8e900b38a977e32eb08d5d0697d6e72ba04', + 'SenseVoiceSmall-Q8_0.gguf', + 252_684_608, + '6c759ee4c9748c9b3f7a5a60ca74f0f7e685fb9d45d1378fce7cfd62f59adf29' + ], + 'nemotron-3.5-asr-streaming-0.6b': [ + 'handy-computer/nemotron-3.5-asr-streaming-0.6b-gguf', + '6d44e540bc31b0de1dbe174a3cea87f53a7f22fb', + 'nemotron-3.5-asr-streaming-0.6b-Q8_0.gguf', + 751_094_240, + 'b94545b313b3223fda7b2857a52681da813935c2127643d1e9ff0c23d988089c' + ] +} satisfies Record + +export type GgufSpeechModelId = keyof typeof GGUF_DOWNLOADS + +export function getGgufSpeechModelDownload(modelId: GgufSpeechModelId): { + downloadFiles: SpeechModelDownloadFile[] + files: string[] + sizeBytes: number +} { + const [repository, revision, name, sizeBytes, sha256] = GGUF_DOWNLOADS[modelId] + const url = `https://huggingface.co/${repository}/resolve/${revision}/${encodeURIComponent(name)}?download=true` + return { downloadFiles: [{ name, url, sizeBytes, sha256 }], files: [name], sizeBytes } +} diff --git a/src/main/speech/speech-model-warmup.ts b/src/main/speech/speech-model-warmup.ts index 347e4e8c7ca..ac8429fec2a 100644 --- a/src/main/speech/speech-model-warmup.ts +++ b/src/main/speech/speech-model-warmup.ts @@ -12,6 +12,7 @@ type SpeechWarmupStore = { * does not wait for it. Returns a call that re-warms it when the user is likely to dictate. */ export function startSpeechModelWarmup(store: SpeechWarmupStore): () => void { + let speechGpu = store.getSettings().voice?.speechGpu // A settings change retries a model that failed to load; a window focus does not. const sync = (retryFailed: boolean): void => { const voice = store.getSettings().voice @@ -22,7 +23,19 @@ export function startSpeechModelWarmup(store: SpeechWarmupStore): () => void { try { const stt = getSpeechSttService(store) stt.setIdleUnloadDelay(voiceModelUnloadDelayMs(voice)) - void stt.prewarm(voice.sttModel, voice.dictationLanguage, retryFailed) + const prewarm = (): void => { + const current = store.getSettings().voice + if (current?.enabled && current.sttModel) { + void stt.prewarm(current.sttModel, current.dictationLanguage, retryFailed) + } + } + // A loaded recognizer keeps the GPU choice it started with; reload it once no dictation uses it. + if (voice.speechGpu !== speechGpu) { + speechGpu = voice.speechGpu + void stt.unloadModelWhenIdle().then(prewarm) + } else { + prewarm() + } } catch (error) { // Runs inside settings writes; an unusable models folder must not fail the write. console.warn('[speech] Could not pre-warm the speech model:', error) diff --git a/src/main/speech/speech-runtime-service.ts b/src/main/speech/speech-runtime-service.ts index 1943e188f59..3174271e7f1 100644 --- a/src/main/speech/speech-runtime-service.ts +++ b/src/main/speech/speech-runtime-service.ts @@ -12,7 +12,8 @@ type SpeechSettingsStore = { export type SpeechServiceFactories = { createModelManager(customModelsDir: string | undefined): ModelManager - createSttService(models: ModelManager): SttService + /** `gpuEnabled` reads the user's Voice setting at each recognizer start. */ + createSttService(models: ModelManager, gpuEnabled: () => boolean): SttService } let factories: SpeechServiceFactories | null = null @@ -43,7 +44,10 @@ export function getSpeechModelManager(store: SpeechSettingsStore): ModelManager export function getSpeechSttService(store: SpeechSettingsStore): SttService { if (!sttService) { - sttService = requireFactories().createSttService(getSpeechModelManager(store)) + sttService = requireFactories().createSttService( + getSpeechModelManager(store), + () => store.getSettings().voice?.speechGpu !== 'off' + ) } return sttService } diff --git a/src/main/speech/speech-vad-model.ts b/src/main/speech/speech-vad-model.ts new file mode 100644 index 00000000000..12403954e06 --- /dev/null +++ b/src/main/speech/speech-vad-model.ts @@ -0,0 +1,56 @@ +import { statSync } from 'node:fs' +import { join } from 'node:path' +import { getCatalogModel } from './model-catalog' +import { SILERO_VAD_MODEL, type SpeechModelDownload } from './model-download-catalog' +import type { ModelManager } from './model-manager' + +/** A catalog model, or the VAD helper the model manager downloads the same way but never lists. */ +export function speechModelDownload(modelId: string): SpeechModelDownload | undefined { + return modelId === SILERO_VAD_MODEL.id ? SILERO_VAD_MODEL : getCatalogModel(modelId) +} + +/** Fetch the VAD for later dictations; until it lands, offline text arrives at stop as before. */ +export function downloadSileroVadInBackground(models: Pick): void { + models.downloadModel(SILERO_VAD_MODEL.id).catch((error: unknown) => { + console.warn('[speech] Silero VAD download failed:', error) + }) +} + +// Settings never lists the VAD, so once its file is in place it stays; only a new models folder rechecks. +let verifiedVadPath: string | undefined + +function placedSileroVadPath(models: Pick): string | undefined { + const [file] = SILERO_VAD_MODEL.downloadFiles + const path = join(models.getModelDir(SILERO_VAD_MODEL.id), file.name) + if (path === verifiedVadPath) { + return path + } + try { + if (statSync(path).size === file.sizeBytes) { + verifiedVadPath = path + return path + } + } catch { + // Not downloaded yet, e.g. the model came before VAD support. + } + return undefined +} + +/** Whether a model-state change for `modelId` means the Silero VAD file is now in place. */ +export function sileroVadLanded( + models: Pick, + modelId: string +): boolean { + return modelId === SILERO_VAD_MODEL.id && placedSileroVadPath(models) !== undefined +} + +/** The downloaded Silero VAD file; when it's missing, starts fetching it and returns undefined. */ +export function sileroVadModelPath( + models: Pick +): string | undefined { + const path = placedSileroVadPath(models) + if (!path) { + downloadSileroVadInBackground(models) + } + return path +} diff --git a/src/main/speech/stt-gpu-failure-marker.ts b/src/main/speech/stt-gpu-failure-marker.ts new file mode 100644 index 00000000000..5320a34967d --- /dev/null +++ b/src/main/speech/stt-gpu-failure-marker.ts @@ -0,0 +1,62 @@ +import { readFileSync } from 'node:fs' +import { writeFile } from 'node:fs/promises' +import { release } from 'node:os' +import { join } from 'node:path' +import type { SttGpuPolicy } from './stt-worker-cpu-fallback' +import { getSpeechEngineModulesDir } from './stt-worker-paths' + +const GPU_FAILURE_MARKER_FILE = 'speech-gpu-failed.json' + +let cachedGpuFailureKey: string | null = null + +// The GPU is retried once transcribe-cpp or the OS (on macOS, also the GPU driver) changes. +function gpuFailureKey(): string { + if (cachedGpuFailureKey) { + return cachedGpuFailureKey + } + let version = 'unknown' + const modulesDir = getSpeechEngineModulesDir() + if (modulesDir) { + try { + version = JSON.parse( + readFileSync(join(modulesDir, 'transcribe-cpp', 'package.json'), 'utf8') + ).version + } catch { + // An unreadable version keys the marker as 'unknown'; the next good read retries the GPU. + } + } + cachedGpuFailureKey = `${version}|${process.platform}|${process.arch}|${release()}` + return cachedGpuFailureKey +} + +function readMarkerKey(file: string): string | null { + try { + return JSON.parse(readFileSync(file, 'utf8')).key ?? null + } catch { + return null + } +} + +/** `gpuEnabled` is the user's Voice setting; the marker records a GPU that failed on this machine. */ +export function createSttGpuPolicy(modelsDir: string, gpuEnabled: () => boolean): SttGpuPolicy { + const file = join(modelsDir, GPU_FAILURE_MARKER_FILE) + // Read once per process; this process's own failures update it in memory. + let failedKey: string | null | undefined + return { + allowGpu: () => { + if (!gpuEnabled()) { + return false + } + if (failedKey === undefined) { + failedKey = readMarkerKey(file) + } + return failedKey !== gpuFailureKey() + }, + markGpuFailed: () => { + failedKey = gpuFailureKey() + writeFile(file, JSON.stringify({ key: failedKey })).catch((error: unknown) => { + console.warn('[speech] Could not record the GPU failure:', error) + }) + } + } +} diff --git a/src/main/speech/stt-offline-audio-chunker.ts b/src/main/speech/stt-offline-audio-chunker.ts index 935e6921cb7..d34be24ec33 100644 --- a/src/main/speech/stt-offline-audio-chunker.ts +++ b/src/main/speech/stt-offline-audio-chunker.ts @@ -1,4 +1,4 @@ -// Bound ONNX allocations: Chromium kills the app on a single allocation >=2GiB (#7925). +// Parakeet has no long-form mode, and bounded chunks keep the decode left for stop short. export const OFFLINE_DECODE_CHUNK_SECONDS = 30 // Split near quiet tail pauses to avoid mid-word cuts; ~100ms windows exclude short intra-word closures. @@ -18,6 +18,11 @@ export class OfflineAudioChunker { this.energyWindowSamples = Math.max(1, Math.round(SPLIT_ENERGY_WINDOW_SECONDS * sampleRate)) } + /** Samples pushed but not yet returned. */ + get heldSamples(): number { + return this.bufferedSamples + } + /** Return complete bounded chunks as samples arrive. */ push(samples: Float32Array): Float32Array[] { if (samples.length === 0) { diff --git a/src/main/speech/stt-recognizer.ts b/src/main/speech/stt-recognizer.ts new file mode 100644 index 00000000000..fb440a87295 --- /dev/null +++ b/src/main/speech/stt-recognizer.ts @@ -0,0 +1,34 @@ +export type SttRecognizerInit = { + /** The node_modules directory holding transcribe-cpp. */ + speechModulesDir: string + modelDir: string + files: string[] + sampleRate: number + /** Absent = auto-detect. */ + language?: string + /** Silero VAD GGUF; when present, offline models commit text at each pause. */ + vadModelPath?: string +} + +export type SttRecognizerEvent = + /** One decoded offline chunk; `samples` counts the stream's input-rate samples decoded so far. */ + | { type: 'chunk'; streamId: string; text: string; samples: number } + /** Pause-cut streams only: speech was heard that no chunk has committed yet. */ + | { type: 'speech-pending'; streamId: string; pending: boolean } + /** A load step finished, so a slow load is told apart from a hung GPU. */ + | { type: 'loading' } + +export type SttRecognizerPost = (event: SttRecognizerEvent) => void + +/** One loaded model in the speech host child, shared by every dictation stream; calls never overlap. */ +export type SttRecognizer = { + /** Starts a stream that expects these spellings; a stream fed without one expects none. */ + open(streamId: string, vocabulary: readonly string[]): void + feed(streamId: string, samples: Float32Array, sampleRate: number): Promise + /** Decode the stream's buffered audio, post its text and drop the stream; may throw after posting. */ + finish(streamId: string): Promise + /** Drop the stream's audio undecoded. */ + discard(streamId: string): void + /** Called on a cancel's arrival, ahead of the queue: skip the stream's remaining chunks; the running decode finishes. */ + cancel(streamId: string): void +} diff --git a/src/main/speech/stt-service.test.ts b/src/main/speech/stt-service.test.ts index 39b4ade9f76..e3864b1e8a0 100644 --- a/src/main/speech/stt-service.test.ts +++ b/src/main/speech/stt-service.test.ts @@ -1,16 +1,11 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import type { ModelManager } from './model-manager' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { SpeechModelState } from '../../shared/speech-types' +import { beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' -const { - MockOpenAiTranscriptionSession, - MockWorker, - getCloudSessions, - getCreatedWorkerCount, - getLastWorker, - readOpenAiSpeechApiKeyMock, - resetCloudSessions, - resetWorkers -} = vi.hoisted(() => { +const { MockWorker, getCreatedWorkerCount, getLastWorker, resetWorkers } = vi.hoisted(() => { class HoistedMockWorker extends EventTarget { static created = 0 static instances: HoistedMockWorker[] = [] @@ -18,6 +13,8 @@ const { terminated = false emitStoppedOnStop = true answerDiscard = true + /** False: a decode for the canceled stream never ends, so the queue never reaches its discard. */ + reachDiscard = true emitReadyOnInit = HoistedMockWorker.emitReadyOnInit emitExitOnTerminate = true terminatePromise: Promise | null = null @@ -69,6 +66,11 @@ const { ) { queueMicrotask(() => this.emit('message', { type: 'stopped', streamId: message.streamId })) } + if (message.type === 'discard' && this.answerDiscard && this.reachDiscard) { + queueMicrotask(() => + this.emit('message', { type: 'discarded', streamId: message.streamId }) + ) + } } attachAudioPort(streamId: string, port: unknown): boolean { @@ -85,36 +87,10 @@ const { } } - class HoistedMockOpenAiTranscriptionSession { - static instances: HoistedMockOpenAiTranscriptionSession[] = [] - feedCalls: { samples: Float32Array; sampleRate: number }[] = [] - - constructor( - readonly modelId: string, - readonly readApiKey: () => string - ) { - HoistedMockOpenAiTranscriptionSession.instances.push(this) - } - - feedAudio(samples: Float32Array, sampleRate: number): void { - this.feedCalls.push({ samples, sampleRate }) - } - - finish(): Promise { - return Promise.resolve(`${this.modelId}:${this.readApiKey()}`) - } - } - return { - MockOpenAiTranscriptionSession: HoistedMockOpenAiTranscriptionSession, MockWorker: HoistedMockWorker, - getCloudSessions: () => HoistedMockOpenAiTranscriptionSession.instances, getCreatedWorkerCount: () => HoistedMockWorker.created, getLastWorker: () => HoistedMockWorker.instances.at(-1), - readOpenAiSpeechApiKeyMock: vi.fn(() => 'test-openai-key'), - resetCloudSessions: () => { - HoistedMockOpenAiTranscriptionSession.instances = [] - }, resetWorkers: () => { HoistedMockWorker.created = 0 HoistedMockWorker.instances = [] @@ -138,12 +114,22 @@ const stoppedReply = (worker: InstanceType) => ({ streamId: worker.messages.findLast((message) => message.type === 'stop')?.streamId }) -const readyModels = (): ModelManager => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SttService reads only getModelState and getModelDir. +const testModels = ( + models: Pick, + onModelStateChange: ModelManager['setProgressCallback'] = () => () => {} +): ModelManager => + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: SttService reads getModelState and getModelDir, fetches the VAD with downloadModel and watches it land. ({ + ...models, + downloadModel: vi.fn().mockResolvedValue(undefined), + setProgressCallback: onModelStateChange + }) as never + +const readyModels = (): ModelManager => + testModels({ getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - }) as never + }) // Starting a session awaits the model check before it spawns the process. async function flushMicrotasks(): Promise { @@ -153,6 +139,7 @@ async function flushMicrotasks(): Promise { } vi.mock('./model-catalog', () => ({ + isLocalSpeechModel: (manifest: { provider: string }) => manifest.provider === 'local', getCatalogModel: (id: string) => id === 'openai-model' ? { @@ -185,12 +172,15 @@ vi.mock('./model-catalog', () => ({ } })) -vi.mock('./openai-api-key-store', () => ({ - readOpenAiSpeechApiKey: readOpenAiSpeechApiKeyMock +vi.mock('./cloud-transcription-target', () => ({ + resolveCloudTranscriptionTarget: (modelId: string) => ({ + model: modelId, + apiKey: 'test-openai-key' + }) })) vi.mock('./openai-transcription-client', () => ({ - OpenAiTranscriptionSession: MockOpenAiTranscriptionSession + OpenAiTranscriptionSession: class {} })) import { START_DICTATION_TIMEOUT_MS, SttService, type SttEventSink } from './stt-service' @@ -199,9 +189,32 @@ const DEFAULT_IDLE_UNLOAD_MS = 15 * 60 * 1000 describe('SttService', () => { beforeEach(() => { - resetCloudSessions() resetWorkers() - readOpenAiSpeechApiKeyMock.mockClear() + }) + + it('reloads a recognizer loaded before the VAD landed once the dictation using it ends', async () => { + const modelsDir = mkdtempSync(join(tmpdir(), 'stt-vad-')) + onTestFinished(() => rmSync(modelsDir, { recursive: true, force: true })) + const watchModels = vi.fn(() => () => {}) + const models = testModels( + { getModelState: readyModels().getModelState, getModelDir: (id) => join(modelsDir, id) }, + watchModels + ) + const service = new SttService(models, spawnMockWorker) + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + const initOf = (worker = getLastWorker()) => worker?.messages.find((m) => m.type === 'init') + expect(initOf()).toMatchObject({ vadModelPath: undefined }) + + const vadPath = join(modelsDir, 'silero-vad-v6.2', 'silero-vad-v6.2-F32.gguf') + mkdirSync(join(modelsDir, 'silero-vad-v6.2')) + writeFileSync(vadPath, Buffer.alloc(1_241_056)) + watchModels.mock.calls[0]?.[0]('silero-vad-v6.2', -1) + await flushMicrotasks() + expect(getCreatedWorkerCount()).toBe(1) + + await service.stopDictation('desktop') + await vi.waitFor(() => expect(getCreatedWorkerCount()).toBe(2)) + expect(initOf()).toMatchObject({ vadModelPath: vadPath }) }) it('gives each device dictating at once only its own text from one recognizer', async () => { @@ -268,6 +281,35 @@ describe('SttService', () => { ]) }) + it('spells each dictation with its own terms on one shared recognizer', async () => { + const service = new SttService(readyModels(), spawnMockWorker) + const desktop = vi.fn() + const phone = vi.fn() + + await service.startDictation('model-a', desktop, [{ term: 'pnpm' }], 'desktop') + await service.startDictation( + 'model-a', + phone, + [{ term: 'kubectl', heardAs: 'cube control' }], + 'mobile:phone-a:1' + ) + const worker = getLastWorker()! + const opens = worker.messages.filter((message) => message.type === 'open') + for (const { streamId } of opens) { + worker.emit('message', { type: 'final', streamId, text: 'Run PNPM and cube control.' }) + } + + expect(getCreatedWorkerCount()).toBe(1) + expect(opens).toEqual([ + { type: 'open', streamId: opens[0].streamId, vocabulary: ['pnpm'] }, + { type: 'open', streamId: opens[1].streamId, vocabulary: ['kubectl'] } + ]) + expect(desktop.mock.calls.at(-1)).toEqual([ + { type: 'final', text: 'Run pnpm and cube control.' } + ]) + expect(phone.mock.calls.at(-1)).toEqual([{ type: 'final', text: 'Run PNPM and kubectl.' }]) + }) + it("hands a renderer's audio port only to its own on-device stream", async () => { const service = new SttService(readyModels(), spawnMockWorker) await service.startDictation('model-a', vi.fn(), undefined, 'mobile:phone-a:1') @@ -320,12 +362,11 @@ describe('SttService', () => { }) it('rebuilds the warm worker when the dictation language changes', async () => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a local start reads only getModelState and getModelDir. const service = new SttService( - { + testModels({ getModelState: vi.fn().mockResolvedValue({ id: 'whisper-model', status: 'ready' }), getModelDir: vi.fn().mockReturnValue('/tmp/whisper-model') - } as never, + }), spawnMockWorker ) @@ -343,16 +384,22 @@ describe('SttService', () => { }) }) - it('frees the warm worker at once when a local dictation is discarded', async () => { + it('keeps a recognizer marked for unload until its dictation ends, then unloads it', async () => { const service = new SttService(readyModels(), spawnMockWorker) - await service.startDictation('model-a', vi.fn(), undefined, 'mobile:1') - // Decoding the rest of the audio would hold the worker; a discard must not wait for it. - getLastWorker()!.emitStoppedOnStop = false - await service.stopDictation('mobile:1', { discard: true }) - await service.startDictation('model-a', vi.fn(), undefined, 'mobile:2') + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + const worker = getLastWorker()! + let unloaded = false + const unload = service.unloadModelWhenIdle().then(() => { + unloaded = true + }) + await Promise.resolve() + expect(worker.terminated).toBe(false) + expect(unloaded).toBe(false) - expect(getCreatedWorkerCount()).toBe(1) + await service.stopDictation('desktop') + await unload + expect(worker.terminated).toBe(true) }) it('kills a worker stuck in a decode instead of making a cancel wait for it', async () => { @@ -424,6 +471,41 @@ describe('SttService', () => { expect(worker!.messages.filter((message) => message.type === 'feed')).toHaveLength(0) }) + it('ends a finishing dictation at once when it is canceled, without waiting for its decode', async () => { + const service = new SttService(readyModels(), spawnMockWorker) + const sink = vi.fn() + await service.startDictation('model-a', sink, undefined, 'desktop') + const worker = getLastWorker()! + worker.emitStoppedOnStop = false + + const finishing = service.stopDictation('desktop') + await service.stopDictation('desktop', { discard: true }) + await finishing + + expect(worker.terminated).toBe(false) + expect(sink).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' })) + }) + + it('restarts the speech process when a canceled decode is still running as the next dictation starts', async () => { + vi.useFakeTimers() + try { + const service = new SttService(readyModels(), spawnMockWorker) + await service.startDictation('model-a', vi.fn(), undefined, 'desktop') + const hung = getLastWorker()! + hung.reachDiscard = false + await service.stopDictation('desktop', { discard: true }) + + const next = service.startDictation('model-a', vi.fn(), undefined, 'desktop') + await vi.advanceTimersByTimeAsync(2_000) + await next + + expect(hung.terminated).toBe(true) + expect(getLastWorker()).not.toBe(hung) + } finally { + vi.useRealTimers() + } + }) + it('drops in-flight audio while stop is waiting for the worker', async () => { const service = new SttService(readyModels(), spawnMockWorker) @@ -442,15 +524,15 @@ describe('SttService', () => { }) it('rejects deletion prep while the target model is starting', async () => { - let resolveModelState: (state: { id: string; status: string }) => void = () => {} - const modelStatePromise = new Promise<{ id: string; status: string }>((resolve) => { + let resolveModelState: (state: SpeechModelState) => void = () => {} + const modelStatePromise = new Promise((resolve) => { resolveModelState = resolve }) const service = new SttService( - { + testModels({ getModelState: vi.fn(() => modelStatePromise), getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - } as never, + }), spawnMockWorker ) @@ -477,41 +559,6 @@ describe('SttService', () => { expect(worker!.terminated).toBe(true) }) - it('uses the OpenAI transcription session without creating a worker', async () => { - const sink = vi.fn() - const service = new SttService( - { - getModelState: vi.fn().mockResolvedValue({ id: 'openai-model', status: 'ready' }), - getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - } as never, - spawnMockWorker - ) - - await service.startDictation('openai-model', sink, undefined, 'desktop') - service.feedAudio(new Float32Array([0.25, -0.25]), 48000, 'desktop') - await service.stopDictation('desktop') - - expect(getCreatedWorkerCount()).toBe(0) - expect(getCloudSessions()).toHaveLength(1) - expect(getCloudSessions()[0].feedCalls).toHaveLength(1) - expect(sink).toHaveBeenCalledWith({ type: 'ready' }) - expect(sink).toHaveBeenCalledWith({ - type: 'final', - text: 'openai-model:test-openai-key' - }) - expect(sink).toHaveBeenCalledWith({ type: 'stopped' }) - }) - - it('frees an idle local recognizer when a cloud dictation starts', async () => { - const service = new SttService(readyModels(), spawnMockWorker) - await service.startDictation('model-a', vi.fn(), undefined, 'desktop') - await service.stopDictation('desktop') - - await service.startDictation('openai-model', vi.fn(), undefined, 'desktop') - - expect(getLastWorker()!.terminated).toBe(true) - }) - it('lets a model that is still loading finish when its dictation is canceled', async () => { vi.useFakeTimers() try { @@ -584,39 +631,6 @@ describe('SttService', () => { } }) - it('does not treat internal warm-worker replacement as startup cancellation', async () => { - const service = new SttService(readyModels(), spawnMockWorker) - - await service.startDictation('model-a', vi.fn(), '/tmp/hotwords-a.txt', 'desktop:1') - await service.stopDictation('desktop:1') - - await expect( - service.startDictation('model-a', vi.fn(), '/tmp/hotwords-b.txt', 'desktop:1') - ).resolves.toBe(undefined) - }) - - it('removes lifecycle listeners when the active worker errors', async () => { - const sink = vi.fn() - const service = new SttService(readyModels(), spawnMockWorker) - - await service.startDictation('model-a', sink, undefined, 'desktop') - const worker = getLastWorker() - expect(worker).toBeDefined() - expect(worker!.listenerCount('message')).toBe(1) - expect(worker!.listenerCount('error')).toBe(1) - expect(worker!.listenerCount('exit')).toBe(1) - - worker!.emit('error', new Error('worker failed')) - - expect(sink).toHaveBeenCalledWith({ - type: 'error', - error: 'Error: worker failed' - }) - expect(worker!.listenerCount('message')).toBe(0) - expect(worker!.listenerCount('error')).toBe(0) - expect(worker!.listenerCount('exit')).toBe(0) - }) - it('allows slow offline stop decoding before terminating the worker', async () => { vi.useFakeTimers() try { @@ -639,6 +653,33 @@ describe('SttService', () => { } }) + it('lets a finish run past the stop timeout while the engine keeps sending its text', async () => { + vi.useFakeTimers() + try { + const service = new SttService(readyModels(), spawnMockWorker) + const sink = vi.fn() + await service.startDictation('model-a', sink, undefined, 'desktop') + const worker = getLastWorker()! + worker.emitStoppedOnStop = false + + const stopPromise = service.stopDictation('desktop') + const { streamId } = stoppedReply(worker) + await vi.advanceTimersByTimeAsync(50_000) + worker.emit('message', { type: 'final', streamId, text: 'first phrase' }) + await vi.advanceTimersByTimeAsync(50_000) + worker.emit('message', { type: 'final', streamId, text: 'second phrase' }) + await vi.advanceTimersByTimeAsync(50_000) + worker.emit('message', stoppedReply(worker)) + await stopPromise + + expect(worker.terminated).toBe(false) + expect(sink).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' })) + expect(sink).toHaveBeenCalledWith({ type: 'final', text: 'second phrase' }) + } finally { + vi.useRealTimers() + } + }) + it('settles stop when the worker exits during stop and does not reuse it', async () => { const service = new SttService(readyModels(), spawnMockWorker) const events: { type: string }[] = [] @@ -690,22 +731,6 @@ describe('SttService', () => { expect(events).toContainEqual({ type: 'stopped' }) }) - it('shares one stop message across concurrent stop callers', async () => { - const service = new SttService(readyModels(), spawnMockWorker) - - await service.startDictation('model-a', vi.fn(), undefined, 'desktop') - const worker = getLastWorker() - expect(worker).toBeDefined() - worker!.emitStoppedOnStop = false - - const firstStop = service.stopDictation('desktop') - const secondStop = service.stopDictation('desktop') - expect(worker!.messages.filter((message) => message.type === 'stop')).toHaveLength(1) - - worker!.emit('message', stoppedReply(worker!)) - await Promise.all([firstStop, secondStop]) - }) - it('does not retain or reuse a worker that timed out while stopping', async () => { vi.useFakeTimers() try { @@ -762,10 +787,10 @@ describe('SttService', () => { status: modelStatus })) const service = new SttService( - { + testModels({ getModelState, getModelDir: vi.fn().mockReturnValue('/tmp/model-a') - } as never, + }), spawnMockWorker ) @@ -792,14 +817,19 @@ describe('SttService', () => { async (event) => { vi.useFakeTimers() try { - const models: Pick = { + const models: Pick< + ModelManager, + 'getModelState' | 'getModelDir' | 'downloadModel' | 'setProgressCallback' + > = { getModelState: vi.fn().mockResolvedValue({ id: 'model-a', status: 'ready' }), - getModelDir: vi.fn().mockReturnValue('/tmp/model-a') + getModelDir: vi.fn().mockReturnValue('/tmp/model-a'), + downloadModel: vi.fn().mockResolvedValue(undefined), + setProgressCallback: () => () => {} } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This lifecycle reads only getModelState/getModelDir on the model manager. + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This lifecycle reads getModelState/getModelDir, downloadModel (VAD) and setProgressCallback on the model manager. const service = new SttService(models as ModelManager, spawnMockWorker) const sink = vi.fn() await service.startDictation('model-a', sink, undefined, 'desktop') diff --git a/src/main/speech/stt-service.ts b/src/main/speech/stt-service.ts index c7228ff6bfd..bacc4b753ed 100644 --- a/src/main/speech/stt-service.ts +++ b/src/main/speech/stt-service.ts @@ -1,10 +1,12 @@ import type { MessagePortMain } from 'electron' +import { dictationVocabulary, type DictationTerm } from '../../shared/dictation-dictionary' import { createDictationTextPipeline, type DictationTextSettings } from '../../shared/dictation-text-pipeline' import { getCatalogModel } from './model-catalog' import type { ModelManager } from './model-manager' +import { sileroVadLanded } from './speech-vad-model' import type { SpawnSttWorkerProcess } from './stt-worker-process' import { prewarmSttModel } from './stt-session-prewarm' import { startSttDictation } from './stt-session-start' @@ -16,12 +18,14 @@ import { teardownIdleSttEngine } from './stt-session-stop' -export { START_DICTATION_TIMEOUT_MS } from './stt-session-timeouts' +export { START_DICTATION_TIMEOUT_MS } from '../../shared/dictation-finish-deadlines' export type SttEvent = | { type: 'ready' } | { type: 'partial'; text?: string } | { type: 'final'; text?: string } + /** Speech was heard that no final has committed yet; only from pause-cut on-device models. */ + | { type: 'speech-pending'; pending: boolean } | { type: 'stopped' } | { type: 'error'; error?: string } @@ -42,21 +46,43 @@ export class SttService { constructor(modelManager: ModelManager, spawnWorker: SpawnSttWorkerProcess) { this.state = createSttSessionState(modelManager, spawnWorker) + modelManager.setProgressCallback((modelId) => { + if (sileroVadLanded(modelManager, modelId)) { + void this.reloadForVad() + } + }) } + /** A recognizer loaded before the VAD landed cuts text only at stop; reload it once no dictation uses it. */ + private async reloadForVad(): Promise { + const engine = this.state.engine + if (!engine || engine.retired || engine.vadModelPath) { + return + } + const { modelId, language } = engine + const unloaded = this.unloadModelWhenIdle() + const generation = this.state.prewarmGeneration + await unloaded + // A newer pre-warm or a dictation took over; loading is theirs now. + if (this.state.prewarmGeneration === generation && !this.state.engine) { + await this.prewarm(modelId, language) + } + } + + /** `terms`: the dictionary for where this dictation goes, repo terms first (dictationTermsFor). */ startDictation( modelId: string, sink: SttEventSink, - hotwordsFilePath?: string, + terms: readonly DictationTerm[] = [], owner = 'desktop', voice?: Partial ): Promise { - const clean = createDictationTextPipeline(getCatalogModel(modelId), voice) + const clean = createDictationTextPipeline(getCatalogModel(modelId), voice, terms) return startSttDictation( this.state, modelId, clean ? cleanTranscriptEvents(sink, clean) : sink, - hotwordsFilePath, + dictationVocabulary(terms), owner, voice?.dictationLanguage ) @@ -121,4 +147,14 @@ export class SttService { this.state.prewarmGeneration += 1 return teardownIdleSttEngine(this.state) } + + /** Unloads the recognizer now, or when the dictations using it end; resolves once it is gone. */ + unloadModelWhenIdle(): Promise { + this.state.prewarmGeneration += 1 + const engine = this.state.engine + if (!engine || sttEngineUsers(this.state, engine).length === 0) { + return teardownIdleSttEngine(this.state) + } + return new Promise((resolve) => engine.onUnloaded.push(resolve)) + } } diff --git a/src/main/speech/stt-session-prewarm.ts b/src/main/speech/stt-session-prewarm.ts index 11a617657ef..a4c0b6451e2 100644 --- a/src/main/speech/stt-session-prewarm.ts +++ b/src/main/speech/stt-session-prewarm.ts @@ -30,19 +30,15 @@ export async function prewarmSttModel( return } const manifest = getCatalogModel(modelId) - // Desktop and phone starts pass no hotwords, so this matches the recognizer they would load. const config: SttRecognizerConfig | null = manifest && isLocalSpeechModel(manifest) - ? { - modelId, - hotwordsFilePath: undefined, - language: engineDictationLanguage(manifest, language) - } + ? { modelId, language: engineDictationLanguage(manifest, language) } : null if (config && state.engine && sameSttRecognizerConfig(state.engine, config)) { return } const ready = + manifest !== undefined && config !== null && hasLocalSpeechRecognizer() && (await state.modelManager.getModelState(modelId)).status === 'ready' diff --git a/src/main/speech/stt-session-start.ts b/src/main/speech/stt-session-start.ts index adc272ae3c0..fad17af1f9d 100644 --- a/src/main/speech/stt-session-start.ts +++ b/src/main/speech/stt-session-start.ts @@ -1,8 +1,9 @@ +import { SPEECH_MODEL_NEEDS_UPDATE_ERROR } from '../../shared/speech-model-retirement' import { engineDictationLanguage } from '../../shared/dictation-language' import type { SpeechModelManifest } from '../../shared/speech-types' import { getCatalogModel } from './model-catalog' import { OpenAiTranscriptionSession } from './openai-transcription-client' -import { readOpenAiSpeechApiKey } from './openai-api-key-store' +import { resolveCloudTranscriptionTarget } from './cloud-transcription-target' import type { SttEventSink } from './stt-service' import { MAX_STT_SESSIONS, @@ -19,20 +20,21 @@ import { teardownIdleSttEngine, teardownSttEngine } from './stt-session-stop' -import { getSherpaModulePath, LOCAL_SPEECH_UNAVAILABLE_ERROR } from './stt-worker-paths' +import { getSpeechEngineModulesDir, LOCAL_SPEECH_UNAVAILABLE_ERROR } from './stt-worker-paths' import { attachSttWorkerLifecycle, initializeSttWorker, waitForSttWorkerReady } from './stt-worker-startup' -import { START_DICTATION_TIMEOUT_MS } from './stt-session-timeouts' +import { START_DICTATION_TIMEOUT_MS } from '../../shared/dictation-finish-deadlines' import { STT_WORKER_EXITED_ERROR } from './stt-worker-process' +import { sileroVadModelPath } from './speech-vad-model' export async function startSttDictation( state: SttSessionState, modelId: string, sink: SttEventSink, - hotwordsFilePath?: string, + vocabulary: string[] = [], owner = 'desktop', language?: string ): Promise { @@ -47,7 +49,7 @@ export async function startSttDictation( } if (existing?.phase === 'stopping') { await existing.stopPromise - return startSttDictation(state, modelId, sink, hotwordsFilePath, owner, language) + return startSttDictation(state, modelId, sink, vocabulary, owner, language) } const manifest = getCatalogModel(modelId) @@ -55,9 +57,9 @@ export async function startSttDictation( throw new Error(`Unknown model: ${modelId}`) } const config: SttRecognizerConfig | null = - manifest.provider === 'openai' + manifest.provider !== 'local' ? null - : { modelId, hotwordsFilePath, language: engineDictationLanguage(manifest, language) } + : { modelId, language: engineDictationLanguage(manifest, language) } if (state.sessions.size >= MAX_STT_SESSIONS) { throw new Error('dictation_session_limit') } @@ -71,6 +73,7 @@ export async function startSttDictation( sink, config, modelId, + vocabulary, engine: null, cloud: null, phase: 'starting', @@ -90,8 +93,7 @@ export async function startSttDictation( // A cloud dictation needs no recognizer; free one nobody else uses. await teardownIdleSttEngine(state) session.cloud = new OpenAiTranscriptionSession( - modelId, - readOpenAiSpeechApiKey, + () => resolveCloudTranscriptionTarget(modelId), engineDictationLanguage(manifest, language) ) } @@ -124,7 +126,11 @@ async function requireModelReady(state: SttSessionState, modelId: string): Promi const modelState = await state.modelManager.getModelState(modelId) if (modelState.status !== 'ready') { await teardownIdleSttEngine(state, modelId) - throw new Error(`Model not ready: ${modelState.status}`) + throw new Error( + modelState.needsUpdate + ? SPEECH_MODEL_NEEDS_UPDATE_ERROR + : `Model not ready: ${modelState.status}` + ) } } @@ -148,28 +154,45 @@ async function acquireSttEngine( const current = state.engine // Bound in the same step it is chosen, so an idle teardown never sees it unused. if (current && sameSttRecognizerConfig(current, config)) { + if (current.draining) { + await current.draining + continue + } clearSttIdleTeardownTimer(state) - session.engine = current - return current + return bindSttEngine(session, current) } if (!current) { - session.engine = spawnSttEngine(state, config, manifest) - return session.engine + return bindSttEngine(session, spawnSttEngine(state, config, manifest)) } // No session uses a recognizer with another config, so it is idle. await teardownSttEngine(state, current) } } +// The stream opens before this session can feed it, so all of its audio decodes with its vocabulary. +function bindSttEngine(session: SttSession, engine: SttEngine): SttEngine { + session.engine = engine + if (session.vocabulary.length > 0) { + engine.worker.postMessage({ + type: 'open', + streamId: session.streamId, + vocabulary: session.vocabulary + }) + } + return engine +} + export function spawnSttEngine( state: SttSessionState, config: SttRecognizerConfig, manifest: SpeechModelManifest ): SttEngine { - const sherpaModulePath = getSherpaModulePath() - if (!sherpaModulePath) { + const speechModulesDir = getSpeechEngineModulesDir() + if (!speechModulesDir) { throw new Error(LOCAL_SPEECH_UNAVAILABLE_ERROR) } + // A VAD fetched now reloads this engine once it is idle (SttService). + const vadModelPath = sileroVadModelPath(state.modelManager) clearSttIdleTeardownTimer(state) const worker = state.spawnWorker() const readyPromise = waitForSttWorkerReady(worker, START_DICTATION_TIMEOUT_MS) @@ -191,6 +214,9 @@ export function spawnSttEngine( worker, detach, retired: false, + vadModelPath, + onUnloaded: [], + draining: null, ready: readyPromise.catch((error: unknown) => { failSttEngine(state, engine, STT_WORKER_EXITED_ERROR) throw error @@ -200,15 +226,12 @@ export function spawnSttEngine( engine.ready.catch(() => undefined) state.engine = engine initializeSttWorker(worker, { - sherpaModulePath, + speechModulesDir, modelDir: state.modelManager.getModelDir(config.modelId), - modelType: manifest.type, - streaming: manifest.streaming, sampleRate: manifest.sampleRate, files: manifest.files ?? [], - hotwordsFilePath: config.hotwordsFilePath, - modelingUnit: manifest.modelingUnit, - language: config.language + language: config.language, + vadModelPath }) return engine } diff --git a/src/main/speech/stt-session-state.ts b/src/main/speech/stt-session-state.ts index 236809d1bc6..2bdd8a022f9 100644 --- a/src/main/speech/stt-session-state.ts +++ b/src/main/speech/stt-session-state.ts @@ -9,7 +9,6 @@ export const MAX_STT_SESSIONS = 4 export type SttRecognizerConfig = { modelId: string - hotwordsFilePath: string | undefined language: string | undefined } @@ -20,6 +19,12 @@ export type SttEngine = SttRecognizerConfig & { detach: () => void /** Torn down on purpose, so a load it cut short is not a failure of the model. */ retired: boolean + /** Absent when the VAD wasn't downloaded yet at load, so this process cuts text only at stop. */ + vadModelPath: string | undefined + /** Called once this process is gone; set when it must not outlive its last dictation. */ + onUnloaded: (() => void)[] + /** Set while a canceled stream's last decode finishes; a new dictation waits for it before reusing this process. */ + draining: Promise | null } export type SttSession = { @@ -29,6 +34,8 @@ export type SttSession = { /** null for cloud models, which load no recognizer. */ config: SttRecognizerConfig | null modelId: string + /** Spellings this dictation's stream tells the engine to expect. */ + vocabulary: string[] engine: SttEngine | null cloud: OpenAiTranscriptionSession | null phase: 'starting' | 'active' | 'stopping' @@ -68,11 +75,7 @@ export function createSttSessionState( } export function sameSttRecognizerConfig(a: SttRecognizerConfig, b: SttRecognizerConfig): boolean { - return ( - a.modelId === b.modelId && - a.hotwordsFilePath === b.hotwordsFilePath && - a.language === b.language - ) + return a.modelId === b.modelId && a.language === b.language } export function sttEngineUsers(state: SttSessionState, engine: SttEngine): SttSession[] { diff --git a/src/main/speech/stt-session-stop.ts b/src/main/speech/stt-session-stop.ts index 29a4e55820c..12d5c77976f 100644 --- a/src/main/speech/stt-session-stop.ts +++ b/src/main/speech/stt-session-stop.ts @@ -27,9 +27,12 @@ export function stopSttDictation( return Promise.resolve() } if (session.phase === 'stopping') { - // A cancel after Finish still aborts the cloud upload whose text it would throw away. + // A cancel after Finish still drops the work whose text it would throw away. if (options.discard) { session.cloud?.cancel() + if (session.engine) { + discardLocalStream(state, session.engine, session.streamId) + } } return session.stopPromise ?? Promise.resolve() } @@ -78,10 +81,69 @@ function stopLocalSession( discard, finish: (outcome) => finishLocalStop(state, session, engine, outcome, discard) }) - engine.worker.postMessage({ type: discard ? 'discard' : 'stop', streamId: session.streamId }) + if (discard) { + discardLocalStream(state, engine, session.streamId) + } else { + engine.worker.postMessage({ type: 'stop', streamId: session.streamId }) + } return stopped } +/** + * The speech process answers a cancel at once and skips the stream's queued work, but a decode already running + * finishes first. One that outlasts the grace (hung in native code, or just long) restarts the process, as a + * cancel always did, so the next dictation isn't stuck behind it. + */ +function discardLocalStream(state: SttSessionState, engine: SttEngine, streamId: string): void { + const reached = waitForSttWorkerMessage( + engine.worker, + (message) => message.type === 'discarded' && message.streamId === streamId, + DISCARD_DICTATION_TIMEOUT_MS + ) + engine.worker.postMessage({ type: 'discard', streamId }) + const draining = reached.then(async (inTime) => { + // Another device's decode may hold the queue; never kill its dictation. + if (!inTime && state.engine === engine && sttEngineUsers(state, engine).length === 0) { + // A failed kill must not fail the dictation waiting on this; it starts on a fresh process either way. + await teardownSttEngine(state, engine).catch((error: unknown) => + console.warn('[speech] Could not stop the busy speech process after a cancel:', error) + ) + } + }) + engine.draining = draining + void draining.finally(() => { + if (engine.draining === draining) { + engine.draining = null + } + }) +} + +/** Resolves true when the worker sends a matching message (or exits), false after `timeoutMs`. */ +function waitForSttWorkerMessage( + worker: SttEngine['worker'], + matches: (message: { type: string; streamId?: string }) => boolean, + timeoutMs: number +): Promise { + return new Promise((resolve) => { + const settle = (inTime: boolean): void => { + clearTimeout(timer) + worker.off('message', onMessage) + worker.off('exit', onExit) + resolve(inTime) + } + const onMessage = (message: { type: string; streamId?: string }): void => { + if (matches(message)) { + settle(true) + } + } + const onExit = (): void => settle(true) + const timer = setTimeout(() => settle(false), timeoutMs) + timer.unref?.() + worker.on('message', onMessage) + worker.on('exit', onExit) + }) +} + function finishLocalStop( state: SttSessionState, session: SttSession, @@ -113,7 +175,17 @@ export function releaseSttSession(state: SttSessionState, session: SttSession): engine.worker.postMessage({ type: 'discard', streamId: session.streamId }) } if (sttEngineUsers(state, engine).length === 0) { - scheduleSttIdleTeardown(state) + if (engine.onUnloaded.length > 0) { + void teardownSttEngine(state, engine) + } else { + scheduleSttIdleTeardown(state) + } + } +} + +function notifyUnloaded(engine: SttEngine): void { + for (const unloaded of engine.onUnloaded.splice(0)) { + unloaded() } } @@ -133,7 +205,7 @@ export function failSttEngine(state: SttSessionState, engine: SttEngine, error: session.sink({ type: 'error', error }) session.sink({ type: 'stopped' }) } - void engine.worker.terminate() + void engine.worker.terminate().finally(() => notifyUnloaded(engine)) } export async function prepareSttModelForDeletion( @@ -196,4 +268,5 @@ export async function teardownSttEngine(state: SttSessionState, engine: SttEngin engine.detach() // Resolves once the process is gone, so its model files are free to delete. await engine.worker.terminate() + notifyUnloaded(engine) } diff --git a/src/main/speech/stt-session-timeouts.ts b/src/main/speech/stt-session-timeouts.ts deleted file mode 100644 index 1e9b06f7e10..00000000000 --- a/src/main/speech/stt-session-timeouts.ts +++ /dev/null @@ -1 +0,0 @@ -export const START_DICTATION_TIMEOUT_MS = 60_000 diff --git a/src/main/speech/stt-stop-tail-padding.ts b/src/main/speech/stt-stop-tail-padding.ts deleted file mode 100644 index 77981589252..00000000000 --- a/src/main/speech/stt-stop-tail-padding.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Streaming encoders emit a word only once lookahead frames follow it; sherpa-onnx's own decoders pad 0.66 s before inputFinished. -const STOP_TAIL_PADDING_SECONDS = 0.66 - -export function createStopTailPadding(sampleRate: number): Float32Array { - return new Float32Array(Math.round(STOP_TAIL_PADDING_SECONDS * sampleRate)) -} diff --git a/src/main/speech/stt-transcribe-cpp-recognizer.ts b/src/main/speech/stt-transcribe-cpp-recognizer.ts new file mode 100644 index 00000000000..f292db59403 --- /dev/null +++ b/src/main/speech/stt-transcribe-cpp-recognizer.ts @@ -0,0 +1,270 @@ +import { availableParallelism } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import type * as TranscribeCpp from 'transcribe-cpp' +import { resampleToRate } from './stt-audio-resample' +import { OfflineAudioChunker } from './stt-offline-audio-chunker' +import { VadPauseSegmenter } from './stt-vad-pause-segmenter' +import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer' + +// Past ~8 threads decode slowed 2-4x under load in the 2026-11 benchmark; E-cores and SMT siblings +// don't help. Half the logical CPUs is close to the performance cores on Apple silicon and SMT x86. +function performanceCoreThreads(): number { + const logical = availableParallelism() + return Math.min(logical, 8, Math.max(4, Math.floor(logical / 2))) +} + +// Without the detector, audio is still cut at the decode bound, just not at pauses. +type AudioSegmenter = { + readonly heldSamples: number + readonly phraseOpen?: boolean + push(samples: Float32Array): Float32Array[] | Promise + flush(): Float32Array[] | Promise +} + +function boundedChunks(sampleRate: number): AudioSegmenter { + const chunker = new OfflineAudioChunker(sampleRate) + return { + get heldSamples() { + return chunker.heldSamples + }, + push: (samples) => chunker.push(samples), + flush: () => { + const rest = chunker.flush() + return rest ? [rest] : [] + } + } +} + +// Totals, not the nominal rate ratio: per-feed resampling rounds, and the drift would replay decoded audio. +type StreamCoverage = { + options: TranscribeCpp.TranscribeOptions + segmenter: AudioSegmenter + vad: TranscribeCpp.VadSession | null + inputSamples: number + resampledSamples: number + reportedSamples: number + slowPhraseDecodes: number + speechPending: boolean +} + +// Whisper pads every decode to a 30 s window, so each phrase costs a full decode. Where that takes longer than the +// speech (and silence) it covers, per-pause decodes queue up behind the speaker, so that dictation stops cutting. +// Two in a row, so one slow first run or load spike doesn't. +const SLOW_PHRASE_DECODES_BEFORE_NO_CUTS = 2 + +// Dropped silence still counts as covered; report it so the host's replay buffer and stall watch don't grow through long pauses. +const SILENCE_COVERAGE_REPORT_SECONDS = 5 + +// Optional: without it dictation still works, with text only at the decode bound and at stop. +async function loadSileroVad( + transcribe: typeof TranscribeCpp, + path: string | undefined, + sampleRate: number +): Promise { + if (!path) { + return null + } + try { + // Tiny and per-frame; the CPU keeps it off a GPU that may fail over. + const model = await transcribe.TranscribeModel.load(path, { backend: 'cpu' }) + if (model.vadInfo.sampleRate === sampleRate) { + return model + } + console.warn( + `[speech] Silero VAD needs ${model.vadInfo.sampleRate} Hz; this model takes ${sampleRate} Hz` + ) + model.dispose() + } catch (error) { + console.warn('[speech] Silero VAD unavailable; text arrives at stop:', error) + } + return null +} + +export async function createTranscribeCppRecognizer( + init: SttRecognizerInit, + post: SttRecognizerPost +): Promise { + const entry = join(init.speechModulesDir, 'transcribe-cpp', 'dist', 'index.js') + const transcribe: typeof TranscribeCpp = await import(pathToFileURL(entry).href) + const gguf = init.files.find((file) => file.endsWith('.gguf')) + if (!gguf) { + throw new Error(`No .gguf model file in: ${init.files.join(', ')}`) + } + // Device setup (Metal shader library, Vulkan drivers) and reading the weights each report done, + // so a cold disk or a busy machine isn't taken for a GPU that hung. + await transcribe.initialize() + post({ type: 'loading' }) + const model = await transcribe.TranscribeModel.load(join(init.modelDir, gguf)) + post({ type: 'loading' }) + // The child runs one call at a time, so every stream can share one session. + const session = model.createSession({ nThreads: performanceCoreThreads() }) + const { languages } = model.capabilities + // The setting is ISO-639-1; Nemotron names locales (ko-KR) and rejects the bare code. + const language = init.language + ? (languages.find((code) => code === init.language) ?? + languages.find((code) => code.startsWith(`${init.language}-`))) + : undefined + const baseOptions: TranscribeCpp.TranscribeOptions = { + timestamps: 'none', + ...(language ? { language } : {}) + } + // A plain list as context, not the `vocabulary` option: in the 2026-11 dev bench that dropped + // Whisper's sentence-final periods. Whisper keeps a long prompt's end, so the first terms go last. + const streamOptions = (vocabulary: readonly string[]): TranscribeCpp.TranscribeOptions => + vocabulary.length > 0 && model.supports('context_prompt') + ? { ...baseOptions, prompt: `${vocabulary.toReversed().join(', ')}.` } + : baseOptions + const modelRate = model.capabilities.nativeSampleRate || init.sampleRate + const vadModel = await loadSileroVad(transcribe, init.vadModelPath, modelRate) + const streams = new Map() + const openStream = (streamId: string, vocabulary: readonly string[]): StreamCoverage => { + // A VAD stream is per-dictation state, so each dictation gets its own session. + const vad = vadModel?.createVadSession({ nThreads: 1 }) ?? null + const stream: StreamCoverage = { + options: streamOptions(vocabulary), + segmenter: boundedChunks(modelRate), + vad, + inputSamples: 0, + resampledSamples: 0, + reportedSamples: 0, + slowPhraseDecodes: 0, + speechPending: false + } + if (vad && vadModel) { + stream.segmenter = new VadPauseSegmenter( + vad, + modelRate, + vadModel.vadInfo.frameSamples, + () => stream.slowPhraseDecodes < SLOW_PHRASE_DECODES_BEFORE_NO_CUTS + ) + } + streams.get(streamId)?.vad?.dispose() + streams.set(streamId, stream) + return stream + } + + const transcribeChunk = async ( + chunk: Float32Array, + options: TranscribeCpp.TranscribeOptions + ): Promise => { + try { + return (await session.run(chunk, options)).text + } catch (error) { + // Repetition loops (Whisper on noise) and length caps are about this audio, not the GPU; keep what decoded. + if (error instanceof transcribe.OutputTruncated) { + return error.partialResult?.text ?? '' + } + throw error + } + } + + // The first run compiles GPU pipelines (seconds on Metal); pay it while loading, not on the first stop. + await transcribeChunk(new Float32Array(Math.round(modelRate / 2)), baseOptions) + + // Coverage is in input-rate samples so the host can trim the audio it keeps for a CPU replay. + const report = (streamId: string, stream: StreamCoverage, text: string, undecoded: number) => { + const covered = stream.resampledSamples - stream.segmenter.heldSamples - undecoded + stream.reportedSamples = covered + post({ + type: 'chunk', + streamId, + text, + samples: Math.round((covered * stream.inputSamples) / stream.resampledSamples) + }) + } + + // Canceled streams, until their queued discard runs; also covers a finish that already closed its stream. + const canceled = new Set() + + const decode = async (streamId: string, stream: StreamCoverage, chunks: Float32Array[]) => { + let undecoded = chunks.reduce((total, chunk) => total + chunk.length, 0) + for (const chunk of chunks) { + if (canceled.has(streamId)) { + return + } + const startedAt = performance.now() + const text = await transcribeChunk(chunk, stream.options) + const decodeMs = performance.now() - startedAt + const spokenSince = stream.reportedSamples + undecoded -= chunk.length + report(streamId, stream, text.trim(), undecoded) + if (stream.vad) { + noteDecodeSpeed( + stream, + decodeMs, + ((stream.reportedSamples - spokenSince) / modelRate) * 1000 + ) + } + } + const dropped = stream.resampledSamples - stream.segmenter.heldSamples - stream.reportedSamples + if (dropped >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate) { + report(streamId, stream, '', 0) + } + } + + const noteDecodeSpeed = (stream: StreamCoverage, decodeMs: number, spokenMs: number) => { + if (stream.slowPhraseDecodes >= SLOW_PHRASE_DECODES_BEFORE_NO_CUTS) { + return + } + stream.slowPhraseDecodes = decodeMs > spokenMs ? stream.slowPhraseDecodes + 1 : 0 + if (stream.slowPhraseDecodes === SLOW_PHRASE_DECODES_BEFORE_NO_CUTS) { + console.warn( + '[speech] Phrases decode slower than they are spoken; this dictation cuts only at 30 s' + ) + } + } + + // Only pause-cut streams report it: without the detector, nothing tells speech from silence. + const notePendingSpeech = (streamId: string, stream: StreamCoverage, pending: boolean) => { + if (stream.vad && stream.speechPending !== pending) { + stream.speechPending = pending + post({ type: 'speech-pending', streamId, pending }) + } + } + + const closeStream = (streamId: string): StreamCoverage | undefined => { + const stream = streams.get(streamId) + streams.delete(streamId) + return stream + } + + return { + open(streamId, vocabulary) { + openStream(streamId, vocabulary) + }, + async feed(streamId, samples, sampleRate) { + const stream = streams.get(streamId) ?? openStream(streamId, []) + // The binding borrows PCM until the run settles; resampleToRate may return the caller's buffer. + const resampled = new Float32Array( + resampleToRate(samples, sampleRate || modelRate, modelRate) + ) + stream.inputSamples += samples.length + stream.resampledSamples += resampled.length + const phrases = await stream.segmenter.push(resampled) + // A cut phrase stays pending until its text is posted. + notePendingSpeech(streamId, stream, phrases.length > 0 || !!stream.segmenter.phraseOpen) + await decode(streamId, stream, phrases) + notePendingSpeech(streamId, stream, !!stream.segmenter.phraseOpen) + }, + async finish(streamId) { + const stream = closeStream(streamId) + if (!stream) { + return + } + try { + await decode(streamId, stream, await stream.segmenter.flush()) + notePendingSpeech(streamId, stream, false) + } finally { + stream.vad?.dispose() + } + }, + discard(streamId) { + canceled.delete(streamId) + closeStream(streamId)?.vad?.dispose() + }, + cancel(streamId) { + canceled.add(streamId) + } + } +} diff --git a/src/main/speech/stt-vad-pause-segmenter.test.ts b/src/main/speech/stt-vad-pause-segmenter.test.ts new file mode 100644 index 00000000000..4ad6cd1efdb --- /dev/null +++ b/src/main/speech/stt-vad-pause-segmenter.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from 'vitest' +import { VadPauseSegmenter, type VadStream } from './stt-vad-pause-segmenter' + +// 100 Hz audio in 10-sample (0.1 s) frames; each sample holds its frame's speech probability, so outputs show which frames survived. +const RATE = 100 +const FRAME = 10 + +function fakeVad(): VadStream { + let pending: number[] = [] + let frames = 0 + const score = (flush: boolean) => { + const probs: number[] = [] + while (pending.length >= FRAME || (flush && pending.length > 0)) { + probs.push(pending[0]) + pending = pending.slice(FRAME) + } + const firstFrame = frames + frames = flush ? 0 : frames + probs.length + return { probs, firstFrame, segments: [] } + } + return { + streamFeed: async (pcm) => { + if (!(pcm instanceof Float32Array)) { + throw new Error('the segmenter feeds Float32Array') + } + pending.push(...pcm) + return score(false) + }, + streamFlush: async () => score(true) + } +} + +function audio(frames: number[]): Float32Array { + return Float32Array.from(frames.flatMap((probability) => Array(FRAME).fill(probability))) +} + +function framesOf(chunks: Float32Array[]): number[][] { + return chunks.map((chunk) => + Array.from( + chunk.filter((_, index) => index % FRAME === 0), + (value) => Math.round(value * 100) / 100 + ) + ) +} + +describe('VadPauseSegmenter', () => { + it('commits a phrase at a 0.6 s pause, keeps 0.4 s ahead of the next, and drops the silence between', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + const first = await segmenter.push(audio([0.1, 0.9, 0.8, 0.7, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2])) + expect(framesOf(first)).toEqual([[0.1, 0.9, 0.8, 0.7, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2]]) + expect(segmenter.heldSamples).toBe(0) + + const second = await segmenter.push(audio([0.1, 0.1, 0.1, 0.1, 0.1, 0.11, 0.12, 0.13, 0.14])) + expect(second).toEqual([]) + // Only the last 0.4 s of that silence is held as the next phrase's lead-in. + expect(segmenter.heldSamples).toBe(4 * FRAME) + + expect(await segmenter.push(audio([0.7, 0.6]))).toEqual([]) + expect(framesOf(await segmenter.flush())).toEqual([[0.11, 0.12, 0.13, 0.14, 0.7, 0.6]]) + }) + + it('keeps a phrase whole across a pause shorter than 0.6 s', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + const ready = await segmenter.push( + audio([0.9, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2]) + ) + expect(framesOf(ready)).toEqual([ + [0.9, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2] + ]) + }) + + it('holds a click shorter than 0.25 s of speech until real speech joins it, without opening a phrase', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + expect(await segmenter.push(audio([0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2]))).toEqual([]) + expect(segmenter.phraseOpen).toBe(false) + expect(await segmenter.push(audio([0.8, 0.8]))).toEqual([]) + expect(segmenter.phraseOpen).toBe(true) + const ready = await segmenter.push(audio([0.2, 0.2, 0.2, 0.2, 0.2, 0.2])) + expect(framesOf(ready)).toEqual([ + [0.9, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.8, 0.8, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2] + ]) + expect(segmenter.phraseOpen).toBe(false) + }) + + it('returns nothing for a dictation that never had speech', async () => { + const segmenter = new VadPauseSegmenter(fakeVad(), RATE, FRAME) + expect(await segmenter.push(audio([0.1, 0.2, 0.3, 0.1]))).toEqual([]) + expect(await segmenter.flush()).toEqual([]) + expect(segmenter.heldSamples).toBe(0) + }) + + it('keeps every held sample when the detector fails mid-dictation', async () => { + const vad = fakeVad() + const segmenter = new VadPauseSegmenter( + { + streamFeed: async (pcm) => { + if (pcm instanceof Float32Array && pcm[0] === 0.5) { + throw new Error('vad failed') + } + return vad.streamFeed(pcm) + }, + streamFlush: vad.streamFlush + }, + RATE, + FRAME + ) + expect(await segmenter.push(audio([0.1, 0.2, 0.1, 0.1, 0.1, 0.9]))).toEqual([]) + expect(await segmenter.push(audio([0.5, 0.1]))).toEqual([]) + expect(await segmenter.push(audio([0.2]))).toEqual([]) + expect(framesOf(await segmenter.flush())).toEqual([[0.2, 0.1, 0.1, 0.1, 0.9, 0.5, 0.1, 0.2]]) + }) +}) diff --git a/src/main/speech/stt-vad-pause-segmenter.ts b/src/main/speech/stt-vad-pause-segmenter.ts new file mode 100644 index 00000000000..8e7fc3b3d33 --- /dev/null +++ b/src/main/speech/stt-vad-pause-segmenter.ts @@ -0,0 +1,164 @@ +import type * as TranscribeCpp from 'transcribe-cpp' +import { OfflineAudioChunker } from './stt-offline-audio-chunker' + +// Silero's own defaults: a frame at or above this is speech; inside speech, one below the second is silence. +const SPEECH_PROBABILITY = 0.5 +const SILENCE_PROBABILITY = 0.35 +// A pause this long commits the phrase before it. Shorter cuts split phrases, and each piece gets its own capital and full stop. +export const VAD_PAUSE_SECONDS = 0.6 +// Silence kept ahead of detected speech so a soft first syllable isn't clipped. +const SPEECH_PREROLL_SECONDS = 0.4 +// Silero's minimum speech: a click or cough alone doesn't end a phrase; it waits for the speech after it, as without a detector. +const MIN_PHRASE_SPEECH_SECONDS = 0.25 + +export type VadStream = Pick + +/** + * Cuts one dictation's audio at pauses so an offline model can decode each phrase as it ends, and drops the + * silence between phrases. Phrases longer than the decode bound still split at their quietest point. + */ +export class VadPauseSegmenter { + private readonly phrase: OfflineAudioChunker + private readonly pauseFrames: number + private readonly minSpeechFrames: number + private readonly prerollSamples: number + private unscored: Float32Array = new Float32Array(0) + private preroll: Float32Array[] = [] + private prerollLength = 0 + private inSpeech = false + private speechFrames = 0 + private silentFrames = 0 + private vadFailed = false + + /** `cutsAtPauses` false: phrases end only at the decode bound and at stop, as without a detector. */ + constructor( + private readonly vad: VadStream, + sampleRate: number, + private readonly frameSamples: number, + private readonly cutsAtPauses: () => boolean = () => true + ) { + this.phrase = new OfflineAudioChunker(sampleRate) + this.pauseFrames = Math.ceil((VAD_PAUSE_SECONDS * sampleRate) / frameSamples) + this.minSpeechFrames = Math.ceil((MIN_PHRASE_SPEECH_SECONDS * sampleRate) / frameSamples) + this.prerollSamples = Math.round(SPEECH_PREROLL_SECONDS * sampleRate) + } + + /** Samples pushed but neither returned nor dropped as silence. */ + get heldSamples(): number { + return this.unscored.length + this.prerollLength + this.phrase.heldSamples + } + + /** At least a phrase's worth of speech not cut yet (a lone click isn't); after a detector error, until stop. */ + get phraseOpen(): boolean { + return this.inSpeech && (this.vadFailed || this.speechFrames >= this.minSpeechFrames) + } + + /** Return the phrases that ended (or reached the decode bound) within these samples. */ + async push(samples: Float32Array): Promise { + if (this.vadFailed) { + return this.phrase.push(samples) + } + this.unscored = concat(this.unscored, samples) + try { + // The binding borrows the PCM until the call settles, so it gets its own copy. + return this.route((await this.vad.streamFeed(new Float32Array(samples))).probs) + } catch (error) { + return this.stopSegmenting(error) + } + } + + /** Return the rest of an open phrase; trailing silence is dropped. */ + async flush(): Promise { + let ready: Float32Array[] = [] + if (!this.vadFailed) { + try { + ready = this.route((await this.vad.streamFlush()).probs, true) + } catch (error) { + ready = this.stopSegmenting(error) + } + } + const rest = this.inSpeech ? this.phrase.flush() : null + this.inSpeech = false + this.preroll = [] + this.prerollLength = 0 + return rest ? [...ready, rest] : ready + } + + // A detector error must not cost the dictation: keep every held sample and finish as bounded chunks. + private stopSegmenting(error: unknown): Float32Array[] { + console.warn('[speech] Silero VAD failed mid-dictation; text arrives at stop:', error) + this.vadFailed = true + this.inSpeech = true + const ready: Float32Array[] = [] + for (const held of [...this.preroll, this.unscored]) { + ready.push(...this.phrase.push(held)) + } + this.preroll = [] + this.prerollLength = 0 + this.unscored = new Float32Array(0) + return ready + } + + private route(probs: readonly number[], last = false): Float32Array[] { + const ready: Float32Array[] = [] + let offset = 0 + for (const probability of probs) { + // The flushed last frame is zero padded past the real audio. + const end = Math.min(this.unscored.length, offset + this.frameSamples) + const frame = this.unscored.subarray(offset, end) + offset = end + if (!this.inSpeech && probability >= SPEECH_PROBABILITY) { + this.inSpeech = true + this.speechFrames = 0 + this.silentFrames = 0 + for (const held of this.preroll) { + ready.push(...this.phrase.push(held)) + } + this.preroll = [] + this.prerollLength = 0 + } + if (!this.inSpeech) { + this.holdPreroll(frame) + continue + } + ready.push(...this.phrase.push(frame)) + this.speechFrames += probability >= SPEECH_PROBABILITY ? 1 : 0 + this.silentFrames = probability < SILENCE_PROBABILITY ? this.silentFrames + 1 : 0 + if ( + this.silentFrames >= this.pauseFrames && + this.speechFrames >= this.minSpeechFrames && + this.cutsAtPauses() + ) { + this.inSpeech = false + const rest = this.phrase.flush() + if (rest) { + ready.push(rest) + } + } + } + this.unscored = last ? new Float32Array(0) : this.unscored.slice(offset) + return ready + } + + private holdPreroll(frame: Float32Array): void { + this.preroll.push(frame.slice()) + this.prerollLength += frame.length + while ( + this.preroll.length > 1 && + this.prerollLength - this.preroll[0].length >= this.prerollSamples + ) { + this.prerollLength -= this.preroll[0].length + this.preroll.shift() + } + } +} + +function concat(a: Float32Array, b: Float32Array): Float32Array { + if (a.length === 0) { + return b.slice() + } + const out = new Float32Array(a.length + b.length) + out.set(a) + out.set(b, a.length) + return out +} diff --git a/src/main/speech/stt-worker-cpu-fallback.test.ts b/src/main/speech/stt-worker-cpu-fallback.test.ts new file mode 100644 index 00000000000..ffc7a6cb42c --- /dev/null +++ b/src/main/speech/stt-worker-cpu-fallback.test.ts @@ -0,0 +1,153 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { spawnSttWorkerWithCpuFallback } from './stt-worker-cpu-fallback' + +class FakeChild extends EventEmitter { + readonly posted: { type: string; samples?: Float32Array }[] = [] + constructor(readonly cpuOnly: boolean) { + super() + } + postMessage(message: { type: string; samples?: Float32Array }): void { + this.posted.push(message) + } + terminate(): Promise { + return Promise.resolve(0) + } + attachAudioPort(): boolean { + return true + } +} + +function setup(): { + worker: ReturnType + children: FakeChild[] + events: unknown[] + marks: () => number +} { + const children: FakeChild[] = [] + let marks = 0 + const worker = spawnSttWorkerWithCpuFallback( + ({ cpuOnly }) => { + const child = new FakeChild(cpuOnly) + children.push(child) + return child + }, + { allowGpu: () => true, markGpuFailed: () => void (marks += 1) } + ) + const events: unknown[] = [] + worker.on('message', (event: unknown) => events.push(event)) + worker.postMessage({ + type: 'init', + speechModulesDir: '/app/node_modules', + modelDir: '/models/parakeet', + sampleRate: 16000, + files: ['model-Q8_0.gguf'] + }) + return { worker, children, events, marks: () => marks } +} + +const feed = ( + n: number +): { type: 'feed'; streamId: string; samples: Float32Array; sampleRate: number } => ({ + type: 'feed', + streamId: '1', + samples: new Float32Array(n), + sampleRate: 16000 +}) + +describe('GPU speech process falling back to the CPU', () => { + it('replays only the audio the GPU had not decoded when it crashes mid-stop', () => { + const { worker, children, events, marks } = setup() + const [gpu] = children + gpu.emit('message', { type: 'ready' }) + worker.postMessage(feed(300)) + worker.postMessage(feed(300)) + gpu.emit('message', { type: 'chunk', streamId: '1', text: 'first', samples: 400 }) + worker.postMessage(feed(300)) + worker.postMessage({ type: 'stop', streamId: '1' }) + gpu.emit('exit', 1) + // The dead process's late messages must not settle the stop or duplicate text. + gpu.emit('message', { type: 'chunk', streamId: '1', text: 'late', samples: 900 }) + gpu.emit('message', { type: 'stopped', streamId: '1' }) + + const cpu = children[1] + expect(cpu.cpuOnly).toBe(true) + expect(cpu.posted.map((m) => [m.type, m.samples?.length])).toEqual([ + ['init', undefined], + ['feed', 200], + ['feed', 300], + ['stop', undefined] + ]) + expect(marks()).toBe(0) + cpu.emit('message', { type: 'ready' }) + expect(marks()).toBe(1) + cpu.emit('message', { type: 'chunk', streamId: '1', text: 'second', samples: 500 }) + cpu.emit('message', { type: 'stopped', streamId: '1' }) + expect(events).toEqual([ + { type: 'ready' }, + { type: 'final', streamId: '1', text: 'first' }, + { type: 'final', streamId: '1', text: 'second' }, + { type: 'stopped', streamId: '1' } + ]) + }) + + it('does not replay a canceled dictation', () => { + const { worker, children } = setup() + const [gpu] = children + gpu.emit('message', { type: 'ready' }) + worker.postMessage(feed(100)) + worker.postMessage({ type: 'discard', streamId: '1' }) + gpu.emit('exit', 1) + expect(children[1].posted.map((m) => m.type)).toEqual(['init', 'discard']) + }) + + it('reports an idle GPU process killed between dictations instead of moving it to the CPU', () => { + const { worker, children, marks } = setup() + const [gpu] = children + const exits: number[] = [] + worker.on('exit', (code: number) => exits.push(code)) + gpu.emit('message', { type: 'ready' }) + worker.postMessage({ type: 'stop', streamId: '1' }) + gpu.emit('message', { type: 'stopped', streamId: '1' }) + gpu.emit('exit', 137) + expect(children).toHaveLength(1) + expect(exits).toEqual([137]) + expect(marks()).toBe(0) + }) + + it('keeps a slow GPU load that still finishes its steps, and moves a silent one to the CPU', () => { + vi.useFakeTimers() + try { + const { children, events } = setup() + const [gpu] = children + vi.advanceTimersByTime(20_000) + gpu.emit('message', { type: 'loading' }) + vi.advanceTimersByTime(20_000) + gpu.emit('message', { type: 'loading' }) + vi.advanceTimersByTime(20_000) + gpu.emit('message', { type: 'ready' }) + expect(children).toHaveLength(1) + expect(events).toEqual([{ type: 'ready' }]) + + const silent = setup() + vi.advanceTimersByTime(20_000) + silent.children[0].emit('message', { type: 'loading' }) + vi.advanceTimersByTime(25_000) + expect(silent.children).toHaveLength(2) + expect(silent.children[1].cpuOnly).toBe(true) + } finally { + vi.useRealTimers() + } + }) + + it('fails the worker when the CPU replacement cannot load the model mid-dictation', () => { + const { worker, children } = setup() + const exits: number[] = [] + worker.on('exit', (code: number) => exits.push(code)) + children[0].emit('message', { type: 'ready' }) + worker.postMessage(feed(100)) + children[0].emit('exit', 1) + children[1].emit('message', { type: 'error', error: 'model load failed' }) + expect(exits).toEqual([1]) + }) +}) diff --git a/src/main/speech/stt-worker-cpu-fallback.ts b/src/main/speech/stt-worker-cpu-fallback.ts new file mode 100644 index 00000000000..ede1d976006 --- /dev/null +++ b/src/main/speech/stt-worker-cpu-fallback.ts @@ -0,0 +1,253 @@ +import { EventEmitter } from 'node:events' +import type { MessagePortMain } from 'electron' +import { OFFLINE_DECODE_CHUNK_SECONDS } from './stt-offline-audio-chunker' +import type { SttWorkerProcess, SttWorkerRequest } from './stt-worker-process' + +export type SpawnSttChild = (options: { cpuOnly: boolean }) => SttWorkerProcess + +export type SttGpuPolicy = { + /** False when the user turned the GPU off or this machine's GPU already failed. */ + allowGpu(): boolean + markGpuFailed(): void +} + +type Feed = Extract +type Open = Extract +type ChildMessage = + | { type: 'chunk'; streamId: string; text: string; samples: number } + | { type: 'speech-pending'; streamId: string; pending: boolean } + | { + type: 'ready' | 'loading' | 'stopped' | 'discarded' | 'error' | 'partial' | 'final' + streamId?: string + text?: string + error?: string + } + +/** A dictation's audio the GPU has not decoded yet, kept for a CPU replay. */ +type StreamBacklog = { + open: Open | null + feeds: Feed[] + /** Input samples before feeds[0], in the stream's own count. */ + start: number + seconds: number + pending: 'stop' | 'discard' | null +} + +// Per load step or decode. Well under the session's 60 s start and stop timeouts, so a CPU replay still fits; +// covers first-run shader compiles. +const GPU_STALL_TIMEOUT_MS = 25_000 + +/** + * Runs transcribe-cpp on the GPU and, when the GPU fails to load, errors, stalls or crashes the + * process, moves every dictation to a CPU-only process and replays the audio not yet decoded. + * Session code sees one worker throughout. + */ +class SttCpuFallbackWorker extends EventEmitter implements SttWorkerProcess { + private child!: SttWorkerProcess + private detachChild: () => void = () => undefined + private cpuOnly: boolean + private init: Extract | null = null + private ready = false + private exitRequested = false + private markOnCpuReady = false + private readonly streams = new Map() + private stallTimer: ReturnType | null = null + + constructor( + private readonly spawn: SpawnSttChild, + private readonly gpu: SttGpuPolicy + ) { + super() + this.cpuOnly = !gpu.allowGpu() + this.attach(spawn({ cpuOnly: this.cpuOnly })) + } + + postMessage(msg: SttWorkerRequest): void { + if (msg.type === 'init') { + this.init = msg + } else if (msg.type === 'open' && this.canFallBack()) { + this.backlog(msg.streamId).open = msg + } else if (msg.type === 'feed' && this.canFallBack()) { + const stream = this.backlog(msg.streamId) + stream.feeds.push(msg) + stream.seconds += msg.samples.length / msg.sampleRate + } else if ((msg.type === 'stop' || msg.type === 'discard') && this.canFallBack()) { + this.backlog(msg.streamId).pending = msg.type + } + this.watchForStall(false) + this.child.postMessage(msg) + } + + /** A GPU process keeps audio on IPC, where this wrapper can hold it for a CPU replay. */ + attachAudioPort(streamId: string, port: MessagePortMain): boolean { + return !this.canFallBack() && this.child.attachAudioPort(streamId, port) + } + + terminate(): Promise { + this.exitRequested = true + this.clearStallTimer() + return this.child.terminate() + } + + private canFallBack(): boolean { + return this.init !== null && !this.cpuOnly && !this.exitRequested + } + + private backlog(streamId: string): StreamBacklog { + let stream = this.streams.get(streamId) + if (!stream) { + stream = { open: null, feeds: [], start: 0, seconds: 0, pending: null } + this.streams.set(streamId, stream) + } + return stream + } + + private attach(child: SttWorkerProcess): void { + const onMessage = (message: ChildMessage): void => this.receive(message) + const onExit = (code: number): void => { + // An idle process killed from outside (OOM, Activity Monitor) is not a GPU failure. + if (this.canFallBack() && (!this.ready || this.streams.size > 0)) { + this.fallBack(true) + } else { + this.emit('exit', code) + } + } + child.on('message', onMessage) + child.on('exit', onExit) + this.child = child + this.detachChild = () => { + child.off('message', onMessage) + child.off('exit', onExit) + } + } + + private receive(message: ChildMessage): void { + if (message.type === 'error' && this.canFallBack()) { + this.fallBack(!this.ready) + return + } + if (message.type === 'error' && !message.streamId && this.ready) { + // The CPU replacement could not load: fail every dictation now rather than answer them empty. + this.detachChild() + void this.child.terminate().catch(() => undefined) + this.emit('exit', 1) + return + } + if (message.type === 'loading') { + this.watchForStall(true) + return + } + if (message.type === 'chunk') { + const { streamId, text, samples } = message + const stream = this.streams.get(streamId) + if (stream) { + this.trimBacklog(stream, samples) + } + this.watchForStall(true) + if (text) { + this.emit('message', { type: 'final', streamId, text }) + } + return + } + if (message.type === 'ready') { + if (this.markOnCpuReady) { + this.markOnCpuReady = false + this.gpu.markGpuFailed() + } + if (this.ready) { + return + } + this.ready = true + this.watchForStall(true) + } else if (message.type === 'stopped' && message.streamId) { + this.streams.delete(message.streamId) + this.watchForStall(true) + } + this.emit('message', message) + } + + /** `persist`: the GPU itself failed (crash or load error), not just this audio. */ + private fallBack(persist: boolean): void { + this.clearStallTimer() + this.detachChild() + void this.child.terminate().catch(() => undefined) + // Persist only once CPU loads the model: a broken model must not turn the GPU off. + this.markOnCpuReady = persist + this.cpuOnly = true + this.attach(this.spawn({ cpuOnly: true })) + if (this.init) { + this.child.postMessage(this.init) + } + for (const [streamId, stream] of this.streams) { + // A canceled dictation wants no text, so its audio is not replayed. + if (stream.pending !== 'discard') { + if (stream.open) { + this.child.postMessage(stream.open) + } + for (const feed of stream.feeds) { + this.child.postMessage(feed) + } + } + if (stream.pending) { + this.child.postMessage({ type: stream.pending, streamId }) + } + } + this.streams.clear() + } + + private trimBacklog(stream: StreamBacklog, decodedSamples: number): void { + while (stream.feeds.length > 0) { + const first = stream.feeds[0] + const end = stream.start + first.samples.length + const dropped = Math.min(first.samples.length, decodedSamples - stream.start) + stream.seconds -= dropped / first.sampleRate + if (end > decodedSamples) { + stream.feeds[0] = { ...first, samples: first.samples.subarray(dropped) } + stream.start = decodedSamples + return + } + stream.feeds.shift() + stream.start = end + } + } + + /** The GPU owes progress while loading, finishing a stop, or once a full chunk waits undecoded. */ + private owesProgress(): boolean { + if (!this.ready) { + return this.init !== null + } + for (const stream of this.streams.values()) { + if (stream.pending === 'stop' || stream.seconds > OFFLINE_DECODE_CHUNK_SECONDS) { + return true + } + } + return false + } + + /** `progressed`: the GPU just answered, so a running timer restarts. */ + private watchForStall(progressed: boolean): void { + if (progressed || !this.canFallBack() || !this.owesProgress()) { + this.clearStallTimer() + } + if (this.stallTimer || !this.canFallBack() || !this.owesProgress()) { + return + } + // Not persisted: a first-run shader compile or cold model read can be slow once and fine after. + this.stallTimer = setTimeout(() => this.fallBack(false), GPU_STALL_TIMEOUT_MS) + this.stallTimer.unref?.() + } + + private clearStallTimer(): void { + if (this.stallTimer) { + clearTimeout(this.stallTimer) + this.stallTimer = null + } + } +} + +export function spawnSttWorkerWithCpuFallback( + spawn: SpawnSttChild, + gpu: SttGpuPolicy +): SttWorkerProcess { + return new SttCpuFallbackWorker(spawn, gpu) +} diff --git a/src/main/speech/stt-worker-forked-process.ts b/src/main/speech/stt-worker-forked-process.ts index ef5624408cc..6c87e9c8a95 100644 --- a/src/main/speech/stt-worker-forked-process.ts +++ b/src/main/speech/stt-worker-forked-process.ts @@ -2,19 +2,20 @@ import { forkProcess } from '@orca/process-host/fork-process' import { getSttWorkerPath } from './stt-worker-paths' import { logSttWorkerStderr, + sttWorkerEnv, SttWorkerChildProcess, type SttWorkerProcess } from './stt-worker-process' /** For orcad, which has no Electron utility processes. */ -export function spawnSttForkedProcess(): SttWorkerProcess { +export function spawnSttForkedProcess(options: { cpuOnly: boolean }): SttWorkerProcess { const child = forkProcess({ modulePath: getSttWorkerPath(), // Structured clone keeps feed audio a Float32Array. serialization: 'advanced', execArgv: [], stdio: ['ignore', 'ignore', 'pipe', 'ipc'], - env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' } + env: { ...sttWorkerEnv(options), ELECTRON_RUN_AS_NODE: '1' } }) const kill = (): void => { child.kill('SIGKILL') diff --git a/src/main/speech/stt-worker-model-config.ts b/src/main/speech/stt-worker-model-config.ts deleted file mode 100644 index b441ff745c2..00000000000 --- a/src/main/speech/stt-worker-model-config.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { readdirSync } from 'node:fs' -import { availableParallelism } from 'node:os' -import { join } from 'node:path' - -// ONNX filenames vary by model; find each role in the manifest. -export function resolveFile( - files: string[], - role: string, - modelDir: string, - ext = '.onnx' -): string { - const match = files.find((f) => f.includes(role) && f.endsWith(ext)) - if (!match) { - throw new Error(`No *${role}*${ext} found in model files: ${files.join(', ')}`) - } - return join(modelDir, match) -} - -export function resolveTokens(files: string[], modelDir: string): string { - const match = files.find((f) => f.endsWith('tokens.txt')) - if (!match) { - throw new Error(`No *tokens.txt found in model files: ${files.join(', ')}`) - } - return join(modelDir, match) -} - -// BPE hotword matching needs a vocab file that older caches may lack. -function discoverBpeVocab(modelDir: string): string | undefined { - try { - const entries = readdirSync(modelDir) - const vocabFile = entries.find((f) => f.endsWith('.vocab')) - return vocabFile ? join(modelDir, vocabFile) : undefined - } catch { - return undefined - } -} - -export type HotwordsConfig = { - decodingMethod: string - hotwordsFile?: string - hotwordsScore?: number - modelingUnit?: string - bpeVocab?: string -} - -export function buildHotwordsConfig(opts: { - modelDir: string - modelType: string - hotwordsFilePath?: string - modelingUnit?: string -}): HotwordsConfig { - if (opts.modelType !== 'transducer' || !opts.hotwordsFilePath) { - return { decodingMethod: 'greedy_search' } - } - - const unit = opts.modelingUnit - if (unit?.includes('bpe')) { - const bpeVocab = discoverBpeVocab(opts.modelDir) - if (!bpeVocab) { - return { decodingMethod: 'greedy_search' } - } - return { - decodingMethod: 'modified_beam_search', - hotwordsFile: opts.hotwordsFilePath, - hotwordsScore: 1.5, - modelingUnit: unit, - bpeVocab - } - } - - return { - decodingMethod: 'modified_beam_search', - hotwordsFile: opts.hotwordsFilePath, - hotwordsScore: 1.5, - modelingUnit: unit - } -} - -export type RecognizerConfigInput = { - modelDir: string - modelType: string - streaming: boolean - sampleRate: number - files: string[] - hotwordsFilePath?: string - modelingUnit?: string - // Absent = auto-detect; only Whisper and SenseVoice read it. - language?: string -} - -// The user waits on offline decode at stop (and per 30 s chunk); 4 threads cut it ~35% at equal memory. -const OFFLINE_NUM_THREADS = Math.min(4, availableParallelism()) - -// Online configs go to createOnlineRecognizer, the rest to createOfflineRecognizer. -export function buildRecognizerConfig(msg: RecognizerConfigInput): { - online: boolean - config: Record -} { - const { modelDir, modelType, streaming, sampleRate, files } = msg - const tokens = resolveTokens(files, modelDir) - const hotwords = buildHotwordsConfig(msg) - - if (streaming && modelType === 'transducer') { - const config = { - featConfig: { sampleRate, featureDim: 80 }, - modelConfig: { - transducer: { - encoder: resolveFile(files, 'encoder', modelDir), - decoder: resolveFile(files, 'decoder', modelDir), - joiner: resolveFile(files, 'joiner', modelDir) - }, - tokens, - numThreads: 1, - provider: 'cpu', - debug: 0 - }, - ...hotwords, - enableEndpoint: 1, - rule1MinTrailingSilence: 2.4, - rule2MinTrailingSilence: 1.2, - rule3MinUtteranceLength: 20 - } - return { online: true, config } - } - if (streaming && modelType === 'paraformer') { - const config = { - featConfig: { sampleRate, featureDim: 80 }, - modelConfig: { - paraformer: { - encoder: resolveFile(files, 'encoder', modelDir), - decoder: resolveFile(files, 'decoder', modelDir) - }, - tokens, - numThreads: 1, - provider: 'cpu', - debug: 0 - }, - decodingMethod: 'greedy_search', - enableEndpoint: 1, - rule1MinTrailingSilence: 2.4, - rule2MinTrailingSilence: 1.2, - rule3MinUtteranceLength: 20 - } - return { online: true, config } - } - if (modelType === 'whisper') { - const config = { - featConfig: { sampleRate, featureDim: 80 }, - modelConfig: { - whisper: { - encoder: resolveFile(files, 'encoder', modelDir), - decoder: resolveFile(files, 'decoder', modelDir), - language: msg.language ?? '' - }, - tokens, - numThreads: OFFLINE_NUM_THREADS, - provider: 'cpu', - debug: 0 - }, - decodingMethod: 'greedy_search' - } - return { online: false, config } - } - if (modelType === 'nemo-ctc') { - const config = { - featConfig: { sampleRate, featureDim: 80 }, - modelConfig: { - nemoCtc: { - model: resolveFile(files, 'model', modelDir) - }, - tokens, - numThreads: OFFLINE_NUM_THREADS, - provider: 'cpu', - debug: 0 - }, - decodingMethod: 'greedy_search' - } - return { online: false, config } - } - if (modelType === 'senseVoice') { - const config = { - featConfig: { sampleRate, featureDim: 80 }, - modelConfig: { - senseVoice: { - model: resolveFile(files, 'model', modelDir), - language: msg.language ?? '', - useInverseTextNormalization: 1 - }, - tokens, - numThreads: OFFLINE_NUM_THREADS, - provider: 'cpu', - debug: 0 - }, - decodingMethod: 'greedy_search' - } - return { online: false, config } - } - const config = { - featConfig: { sampleRate, featureDim: 80 }, - modelConfig: { - transducer: { - encoder: resolveFile(files, 'encoder', modelDir), - decoder: resolveFile(files, 'decoder', modelDir), - joiner: resolveFile(files, 'joiner', modelDir) - }, - tokens, - numThreads: OFFLINE_NUM_THREADS, - provider: 'cpu', - debug: 0 - }, - ...hotwords - } - return { online: false, config } -} diff --git a/src/main/speech/stt-worker-paths.ts b/src/main/speech/stt-worker-paths.ts index 90a6c8432f0..4fa7d3a3f1d 100644 --- a/src/main/speech/stt-worker-paths.ts +++ b/src/main/speech/stt-worker-paths.ts @@ -1,9 +1,8 @@ -import { existsSync } from 'node:fs' import { join } from 'node:path' import { getAppEnvironment } from '../../shared/app-environment' import { - SPEECH_RECOGNIZER_DIR_ENV, - speechRecognizerPackageName + hasSpeechEnginePackage, + SPEECH_RECOGNIZER_DIR_ENV } from '../../shared/speech-recognizer-package' import { currentWorkerEntryLayout, @@ -17,34 +16,34 @@ export function getSttWorkerPath(): string { return resolveWorkerThreadEntryPath(currentWorkerEntryLayout(__dirname), 'stt-worker.js') } -/** Recognizer directory, or null on hosts without one. */ -export function getSherpaModulePath(): string | null { - const nativePackage = speechRecognizerPackageName(process.platform, process.arch) +function speechNodeModulesDirCandidates(): string[] { const resourcesPath = 'resourcesPath' in process && typeof process.resourcesPath === 'string' ? process.resourcesPath : undefined - if (getAppEnvironment().isPackaged() && resourcesPath) { - const resourcesNodeModule = join(resourcesPath, 'node_modules', nativePackage) - if (existsSync(resourcesNodeModule)) { - return resourcesNodeModule - } - return join(resourcesPath, 'app.asar.unpacked', 'node_modules', nativePackage) + return [join(resourcesPath, 'node_modules')] } if (getAppEnvironment().isPackaged()) { // orcad: only the installed app's copy, which `orca serve` names. const handed = process.env[SPEECH_RECOGNIZER_DIR_ENV] - return handed && existsSync(join(handed, 'sherpa-onnx.node')) ? handed : null + return handed ? [handed] : [] } + return require.resolve.paths('transcribe-cpp') ?? [] +} - try { - return join(require.resolve(nativePackage), '..') - } catch { - return null +// The app's engine packages don't change while it runs, so they are looked up once. +let speechEngineModulesDir: string | null | undefined + +/** The node_modules directory holding transcribe-cpp, or null on hosts without it. */ +export function getSpeechEngineModulesDir(): string | null { + if (speechEngineModulesDir === undefined) { + speechEngineModulesDir = + speechNodeModulesDirCandidates().find((dir) => hasSpeechEnginePackage(dir)) ?? null } + return speechEngineModulesDir } export function hasLocalSpeechRecognizer(): boolean { - return getSherpaModulePath() !== null + return getSpeechEngineModulesDir() !== null } diff --git a/src/main/speech/stt-worker-process.ts b/src/main/speech/stt-worker-process.ts index bfa17341bef..b9a4eadea93 100644 --- a/src/main/speech/stt-worker-process.ts +++ b/src/main/speech/stt-worker-process.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'node:events' import type { MessagePortMain } from 'electron' import type { WorkerRequestTransport } from '../worker-threads/worker-thread-transport' -import type { RecognizerConfigInput } from './stt-worker-model-config' +import type { SttRecognizerInit } from './stt-recognizer' /** Electron reports it as the utility process's name when it exits. */ export const STT_UTILITY_PROCESS_NAME = 'Orca Speech' @@ -10,7 +10,8 @@ export const STT_WORKER_EXITED_ERROR = 'The speech engine stopped unexpectedly. export const STT_WORKER_HUNG_ERROR = 'The speech engine stopped responding. Try again.' export type SttWorkerRequest = - | ({ type: 'init'; sherpaModulePath: string } & RecognizerConfigInput) + | ({ type: 'init' } & SttRecognizerInit) + | { type: 'open'; streamId: string; vocabulary: string[] } | { type: 'feed'; streamId: string; samples: Float32Array; sampleRate: number } | { type: 'stop'; streamId: string } | { type: 'discard'; streamId: string } @@ -73,6 +74,16 @@ export class SttWorkerChildProcess extends EventEmitter implements SttWorkerProc } } +/** Env for a speech child: CPU-only skips GPU backend registration, which can itself crash a driver. */ +export function sttWorkerEnv(options: { cpuOnly: boolean }): NodeJS.ProcessEnv { + return { + ...process.env, + ...(options.cpuOnly ? { TRANSCRIBE_BACKENDS: 'cpu' } : {}), + // Implicit Vulkan layers (overlays, capture tools) crash some drivers' compute (Handy #2049). + ...(process.platform === 'win32' ? { VK_LOADER_LAYERS_DISABLE: '~implicit~' } : {}) + } +} + export function logSttWorkerStderr(stderr: NodeJS.ReadableStream | null | undefined): void { stderr?.on('data', (chunk: Buffer) => { console.error('[speech-worker]', String(chunk).trimEnd()) diff --git a/src/main/speech/stt-worker-startup.ts b/src/main/speech/stt-worker-startup.ts index 85762c66c5b..fcb1fdb1b77 100644 --- a/src/main/speech/stt-worker-startup.ts +++ b/src/main/speech/stt-worker-startup.ts @@ -1,4 +1,5 @@ import type { SttEvent } from './stt-service' +import type { SttRecognizerInit } from './stt-recognizer' import type { SttWorkerProcess } from './stt-worker-process' /** Session events carry the stream they belong to. */ @@ -84,19 +85,6 @@ export function attachSttWorkerLifecycle(args: { } } -export function initializeSttWorker( - worker: SttWorkerProcess, - input: { - sherpaModulePath: string - modelDir: string - modelType: string - streaming: boolean - sampleRate: number - files: readonly string[] - hotwordsFilePath?: string - modelingUnit?: string - language?: string - } -): void { +export function initializeSttWorker(worker: SttWorkerProcess, input: SttRecognizerInit): void { worker.postMessage({ type: 'init', ...input }) } diff --git a/src/main/speech/stt-worker-stop.ts b/src/main/speech/stt-worker-stop.ts index 8f47829911a..79b93ea5766 100644 --- a/src/main/speech/stt-worker-stop.ts +++ b/src/main/speech/stt-worker-stop.ts @@ -50,6 +50,12 @@ export function waitForSttWorkerStop(args: { if (message.type === 'stopped' && message.streamId === args.streamId) { receivedStopped = true finish('stopped') + return + } + // Sessions share one queue, so any answer means the engine is still working toward this stream, not hung. + // A cancel keeps its short deadline. + if (!args.discard) { + timeout?.refresh() } } const onError = (error: Error): void => finish('error', error) diff --git a/src/main/speech/stt-worker-utility-process.ts b/src/main/speech/stt-worker-utility-process.ts index 871fad4f841..a254140e9e4 100644 --- a/src/main/speech/stt-worker-utility-process.ts +++ b/src/main/speech/stt-worker-utility-process.ts @@ -3,15 +3,17 @@ import { getSttWorkerPath } from './stt-worker-paths' import { logSttWorkerStderr, STT_UTILITY_PROCESS_NAME, + sttWorkerEnv, SttWorkerChildProcess, type SttWorkerProcess } from './stt-worker-process' /** A native crash or hang in the recognizer stays out of the app's main process. */ -export function spawnSttUtilityProcess(): SttWorkerProcess { +export function spawnSttUtilityProcess(options: { cpuOnly: boolean }): SttWorkerProcess { const child = utilityProcess.fork(getSttWorkerPath(), [], { serviceName: STT_UTILITY_PROCESS_NAME, - stdio: ['ignore', 'ignore', 'pipe'] + stdio: ['ignore', 'ignore', 'pipe'], + env: sttWorkerEnv(options) }) const worker = new SttWorkerChildProcess({ send: (message) => child.postMessage(message), diff --git a/src/main/speech/stt-worker.test.ts b/src/main/speech/stt-worker.test.ts index 588ab88be72..91f5c8c5031 100644 --- a/src/main/speech/stt-worker.test.ts +++ b/src/main/speech/stt-worker.test.ts @@ -21,10 +21,4 @@ describe('resampleToRate', () => { expect(second[1]).toBeCloseTo(0.00625, 6) expect(second[80]).toBeCloseTo(0.5, 6) }) - - it('keeps same-rate chunks unchanged', () => { - const samples = new Float32Array([0, 0.5, -0.5]) - - expect(resampleToRate(samples, 16000, 16000)).toBe(samples) - }) }) diff --git a/src/main/speech/stt-worker.ts b/src/main/speech/stt-worker.ts index 5f406e684c4..ebcbdcc64b4 100644 --- a/src/main/speech/stt-worker.ts +++ b/src/main/speech/stt-worker.ts @@ -1,175 +1,64 @@ -/* oxlint-disable typescript-eslint/no-explicit-any -- sherpa-onnx native addon has no type definitions */ import type { MessagePortMain } from 'electron' import type { SpeechAudioPortMessage } from '../../shared/speech-types' -import { resampleToRate } from './stt-audio-resample' -import { OfflineAudioChunker } from './stt-offline-audio-chunker' -import { buildRecognizerConfig } from './stt-worker-model-config' -import { createStopTailPadding } from './stt-stop-tail-padding' +import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer' +import { createTranscribeCppRecognizer } from './stt-transcribe-cpp-recognizer' import { connectSttWorkerParentPort } from './stt-worker-parent-port' -import type { SttWorkerRequest as WorkerMessage } from './stt-worker-process' - -// One per dictation session; every session shares the one loaded recognizer. -type SessionStream = { - // Online streams live for the session; offline ones are made per decode. - online: any - offlineChunker: OfflineAudioChunker | null - // Primed on the session's first feed so stop never waits on another session's stream. - primed: boolean - // Streaming models report the same hypothesis on most 100 ms feeds; only changes are posted. - lastPartialText: string -} +import type { SttWorkerRequest } from './stt-worker-process' // A desktop renderer's audio for one stream, posted straight here instead of through main. type AudioPortInput = { port: MessagePortMain onEnded: (() => void) | null + /** 'end' arrived; its frames may still wait behind a decode. */ + ending: boolean } const parentPort = connectSttWorkerParentPort() -// Use the platform native addon: the main sherpa-onnx WASM package cannot load host model files. Main supplies its resolved path. -let sherpa: any = null -let recognizer: any = null -let isStreaming = false -let modelSampleRate = 16000 -const streams = new Map() +let recognizer: SttRecognizer | null = null const audioPorts = new Map() +// Canceled streams whose queued work is skipped instead of decoded; cleared when their discard runs. +const discarded = new Set() -function loadSherpa(modulePath: string | undefined): any { - if (!modulePath) { - throw new Error('init.sherpaModulePath is required') - } - return require(modulePath) +// transcribe-cpp decodes off the event loop; one queue keeps feeds behind init and stop behind feeds. +let queue: Promise = Promise.resolve() +function enqueue(task: () => void | Promise): void { + // A task that throws must not stop every later one; the session's timeouts report the stream. + queue = queue.then(task).catch((err: unknown) => { + console.error('[speech-worker] task failed:', err) + }) } -function handleInit(msg: Extract): void { +async function handleInit(init: SttRecognizerInit): Promise { try { - sherpa = loadSherpa(msg.sherpaModulePath) - isStreaming = msg.streaming - modelSampleRate = msg.sampleRate - const { online, config } = buildRecognizerConfig(msg) - recognizer = online - ? sherpa.createOnlineRecognizer(config) - : sherpa.createOfflineRecognizer(config) + const post: SttRecognizerPost = (event) => parentPort.post(event) + recognizer = await createTranscribeCppRecognizer(init, post) parentPort.post({ type: 'ready' }) } catch (err) { parentPort.post({ type: 'error', error: String(err) }) } } -function openStream(streamId: string): SessionStream { - const existing = streams.get(streamId) - if (existing) { - return existing - } - const stream: SessionStream = { - online: isStreaming ? sherpa.createOnlineStream(recognizer) : null, - offlineChunker: isStreaming ? null : new OfflineAudioChunker(modelSampleRate), - primed: false, - lastPartialText: '' - } - streams.set(streamId, stream) - return stream -} - -function decodeOfflineChunk(samples: Float32Array): string { - const stream = sherpa.createOfflineStream(recognizer) - sherpa.acceptWaveformOffline(stream, { sampleRate: modelSampleRate, samples }) - sherpa.decodeOfflineStream(recognizer, stream) - const result = JSON.parse(sherpa.getOfflineStreamResultAsJson(stream)) - return result?.text?.trim() ?? '' -} - -function feedOnline(streamId: string, stream: SessionStream, samples: Float32Array): void { - if (!stream.primed) { - // New streams start with empty encoder caches; zipformer en-20M dropped most of the first second - // (first word wrong on 71 of 73 LibriSpeech clips). A second of silence fills them first. - sherpa.acceptWaveformOnline(stream.online, { - sampleRate: modelSampleRate, - samples: new Float32Array(modelSampleRate) - }) - stream.primed = true - } - sherpa.acceptWaveformOnline(stream.online, { sampleRate: modelSampleRate, samples }) - while (sherpa.isOnlineStreamReady(recognizer, stream.online)) { - sherpa.decodeOnlineStream(recognizer, stream.online) - } - const result = JSON.parse(sherpa.getOnlineStreamResultAsJson(recognizer, stream.online)) - const text = result?.text?.trim() - if (text && text !== stream.lastPartialText) { - stream.lastPartialText = text - parentPort.post({ type: 'partial', streamId, text }) - } - if (sherpa.isEndpoint(recognizer, stream.online)) { - if (text) { - parentPort.post({ type: 'final', streamId, text }) - } - sherpa.reset(recognizer, stream.online) - stream.lastPartialText = '' - } -} - -function feedOffline(streamId: string, stream: SessionStream, samples: Float32Array): void { - // Bound ONNX allocations below Chromium's >=2GiB crash threshold (#7925); consumers append final segments. - const readyChunks = stream.offlineChunker?.push(new Float32Array(samples)) ?? [] - // push() already consumed these windows; keep decoding later ones after a failure. - let firstError: unknown = null - for (const chunk of readyChunks) { - try { - const text = decodeOfflineChunk(chunk) - if (text) { - parentPort.post({ type: 'final', streamId, text }) - } - } catch (err) { - firstError ??= err - } - } - if (firstError) { - throw firstError - } -} - -function handleFeed(msg: Extract): void { - if (!recognizer) { +async function handleFeed(msg: Extract): Promise { + if (discarded.has(msg.streamId)) { return } try { - const stream = openStream(msg.streamId) - // Normalize rates before native decode: mixed rates on one recognizer abort the process. - const samples = resampleToRate(msg.samples, msg.sampleRate || modelSampleRate, modelSampleRate) - if (isStreaming) { - feedOnline(msg.streamId, stream, samples) - } else { - feedOffline(msg.streamId, stream, samples) - } + await recognizer?.feed(msg.streamId, msg.samples, msg.sampleRate) } catch (err) { parentPort.post({ type: 'error', streamId: msg.streamId, error: String(err) }) } } -function finishStream(stream: SessionStream): string { - if (stream.online) { - sherpa.acceptWaveformOnline(stream.online, { - sampleRate: modelSampleRate, - samples: createStopTailPadding(modelSampleRate) - }) - sherpa.inputFinished(stream.online) - while (sherpa.isOnlineStreamReady(recognizer, stream.online)) { - sherpa.decodeOnlineStream(recognizer, stream.online) - } - const result = JSON.parse(sherpa.getOnlineStreamResultAsJson(recognizer, stream.online)) - return result?.text?.trim() ?? '' - } - // flush() leaves less than one bounded chunk. - const remaining = stream.offlineChunker?.flush() - return remaining && remaining.length > 0 ? decodeOfflineChunk(remaining) : '' -} - function attachAudioPort(streamId: string, port: MessagePortMain | undefined): void { if (!port) { return } - const input: AudioPortInput = { port, onEnded: null } - // The renderer closes its end after 'end'; a close alone means it went away. + // A cancel that arrived while this attach waited in line must not let the port's frames reopen the stream. + if (discarded.has(streamId)) { + port.close() + return + } + const input: AudioPortInput = { port, onEnded: null, ending: false } const end = (): void => { if (audioPorts.get(streamId) !== input) { return @@ -181,31 +70,40 @@ function attachAudioPort(streamId: string, port: MessagePortMain | undefined): v port.on('message', ({ data }) => { // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the desktop preload holds the other end, and it sends SpeechAudioPortMessage. const msg = data as SpeechAudioPortMessage - if (msg.type === 'end') { + input.ending ||= msg.type === 'end' + enqueue(() => { + // A discard or end ran first; a late frame must not reopen the stream. + if (audioPorts.get(streamId) !== input) { + return + } + return msg.type === 'end' + ? end() + : handleFeed({ type: 'feed', streamId, samples: msg.samples, sampleRate: msg.sampleRate }) + }) + }) + // The renderer closes its end right after 'end', so that close must leave the queued frames to decode. + // A close alone means it canceled or went away. + port.on('close', () => { + if (!input.ending) { end() - } else { - handleFeed({ type: 'feed', streamId, samples: msg.samples, sampleRate: msg.sampleRate }) } }) - port.on('close', end) audioPorts.set(streamId, input) port.start() } -function handleStop(streamId: string): void { +async function handleStop(streamId: string): Promise { + if (discarded.has(streamId)) { + return + } const input = audioPorts.get(streamId) // Main's stop can overtake the renderer's last frames on the port; finish only after them. if (input) { - input.onEnded = () => handleStop(streamId) + input.onEnded = () => enqueue(() => handleStop(streamId)) return } - const stream = streams.get(streamId) - streams.delete(streamId) try { - const text = stream && recognizer ? finishStream(stream) : '' - if (text) { - parentPort.post({ type: 'final', streamId, text }) - } + await recognizer?.finish(streamId) } catch (err) { parentPort.post({ type: 'error', streamId, error: String(err) }) } finally { @@ -213,33 +111,48 @@ function handleStop(streamId: string): void { } } -// A canceled dictation drops its audio undecoded. -function handleDiscard(streamId: string): void { +// A cancel answers at once, even during Finish, and the stream's queued audio is skipped rather than decoded. +function cancelStream(streamId: string): void { + discarded.add(streamId) + recognizer?.cancel(streamId) const input = audioPorts.get(streamId) audioPorts.delete(streamId) input?.port.close() - streams.delete(streamId) parentPort.post({ type: 'stopped', streamId }) } -parentPort.onMessage((message, ports) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the session host posts here, and it sends WorkerMessage. - const msg = message as WorkerMessage +// Runs in queue order, after everything queued for the stream before the cancel; the host waits for it. +function handleDiscard(streamId: string): void { + discarded.delete(streamId) + recognizer?.discard(streamId) + parentPort.post({ type: 'discarded', streamId }) +} + +function handleMessage( + msg: SttWorkerRequest, + ports: readonly MessagePortMain[] +): void | Promise { switch (msg.type) { case 'init': - handleInit(msg) - break + return handleInit(msg) + case 'open': + return recognizer?.open(msg.streamId, msg.vocabulary) case 'feed': - handleFeed(msg) - break + return handleFeed(msg) case 'stop': - handleStop(msg.streamId) - break + return handleStop(msg.streamId) case 'discard': - handleDiscard(msg.streamId) - break + return handleDiscard(msg.streamId) case 'attach-audio': - attachAudioPort(msg.streamId, ports[0]) - break + return attachAudioPort(msg.streamId, ports[0]) } +} + +parentPort.onMessage((message, ports) => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the session host posts here, and it sends SttWorkerRequest. + const msg = message as SttWorkerRequest + if (msg.type === 'discard') { + cancelStream(msg.streamId) + } + enqueue(() => handleMessage(msg, ports)) }) diff --git a/src/main/ssh/authentication/ssh-multi-key-authentication.test.ts b/src/main/ssh/authentication/ssh-multi-key-authentication.test.ts index d4c8289439d..ab4b2e4de05 100644 --- a/src/main/ssh/authentication/ssh-multi-key-authentication.test.ts +++ b/src/main/ssh/authentication/ssh-multi-key-authentication.test.ts @@ -5,8 +5,7 @@ import { type AnyAuthMethod, type AuthenticationType, type AuthHandlerMiddleware, - type ConnectConfig, - type ParsedKey + type ConnectConfig } from 'ssh2' vi.mock('os', () => ({ @@ -31,7 +30,6 @@ vi.mock('./ssh-identity-file-read', () => ({ })) import { buildConnectConfig } from '../connection/ssh-connect-config' -import { getPassphrasePrivateKeyPath } from './ssh-private-key-authentication' import '../system-transport/system-ssh-args' import { walkInitialAuthLadder } from '../connection/testing/ssh-connection-test-fixtures' import type { SshTarget } from '../../../shared/ssh-types' @@ -144,33 +142,6 @@ describe('ordered SSH private-key authentication', () => { expect(nextAuth(config, false)).toBe('keyboard-interactive') }) - it('keeps explicit manual keys and unresolved imported keys as singular overrides', () => { - const manual = buildConnectConfig( - makeTarget({ - source: 'manual', - configHost: 'manual.example.com', - host: 'manual.example.com', - identityFile: '/keys/manual' - }), - makeResolved(), - { includeAgent: false, includePrivateKey: true } - ) - const unresolvedImport = buildConnectConfig(makeTarget(), null, { - includeAgent: false, - includePrivateKey: true - }) - - expect(manual.privateKey).toEqual(Buffer.from('/keys/manual')) - expect(unresolvedImport.privateKey).toEqual(Buffer.from('/keys/stale-imported')) - // Single-key targets also need per-stage keyboard-interactive restart for MFA. - expect(nextAuth(manual, true)).toMatchObject({ type: 'none' }) - expect(nextAuth(manual, false)).toMatchObject({ - type: 'publickey', - key: Buffer.from('/keys/manual') - }) - expect(nextAuth(manual, false)).toBe('keyboard-interactive') - }) - it('keeps the password challenge on an agent attempt that carries a key, because no key retry follows it', () => { vi.stubEnv('SSH_AUTH_SOCK', '/tmp/agent.sock') // Real key bytes, so '/keys/explicit' counts as unencrypted and IdentitiesOnly builds its agent. @@ -216,35 +187,11 @@ describe('ordered SSH private-key authentication', () => { expect(partialSuccessAuth(config, ['keyboard-interactive'])).toBe(false) }) - it('offers every resolved key for a manually owned config-picker target', () => { - const config = buildConnectConfig( - makeTarget({ - source: 'manual', - configHost: 'prod', - host: 'prod.internal', - identityFile: undefined - }), - makeResolved(), - { includeAgent: false, includePrivateKey: true } - ) - - expect(nextAuth(config, true)).toMatchObject({ type: 'none' }) - expect(nextAuth(config, false)).toMatchObject({ - type: 'publickey', - key: Buffer.from('/keys/unauthorized-first') - }) - expect(nextAuth(config, false)).toMatchObject({ - type: 'publickey', - key: Buffer.from('/keys/authorized-second') - }) - }) - - it('resets ordered authentication for credential retries without extra key reads', () => { + it('resets ordered authentication for credential retries', () => { const config = buildConnectConfig(makeTarget(), makeResolved(), { includeAgent: false, includePrivateKey: true }) - const readsAfterResolution = mockReadFileSync.mock.calls.length expect(nextAuth(config, true)).toMatchObject({ type: 'none' }) config.password = 'retry-password' @@ -257,26 +204,5 @@ describe('ordered SSH private-key authentication', () => { type: 'publickey', key: Buffer.from('/keys/unauthorized-first') }) - expect(mockReadFileSync).toHaveBeenCalledTimes(readsAfterResolution) - }) - - it('keeps encrypted-key prompts tied to the matching fresh identity path', () => { - vi.spyOn(utils, 'parseKey').mockImplementation((key) => { - if ( - Buffer.from(key as Buffer) - .toString() - .includes('encrypted-second') - ) { - return new Error('Encrypted private OpenSSH key detected, but no passphrase given') - } - return { isPrivateKey: () => true } as ParsedKey - }) - const config = buildConnectConfig( - makeTarget(), - makeResolved({ identityFile: ['/keys/first', '/keys/encrypted-second'] }), - { includeAgent: false, includePrivateKey: true } - ) - - expect(getPassphrasePrivateKeyPath(config)).toBe('/keys/encrypted-second') }) }) diff --git a/src/main/ssh/authentication/ssh-security-key-identity.test.ts b/src/main/ssh/authentication/ssh-security-key-identity.test.ts index 0ba4f9642d8..705e8bda8da 100644 --- a/src/main/ssh/authentication/ssh-security-key-identity.test.ts +++ b/src/main/ssh/authentication/ssh-security-key-identity.test.ts @@ -3,14 +3,8 @@ import 'node:os' import 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - isOpenSshSecurityKeyPrivateKey, - isOpenSshSecurityKeyPublicKey -} from './ssh-security-key-identity' -import { - createOpenSshPrivateKeyFixture, - createOpenSshPublicKeyFixture -} from './testing/ssh-security-key-identity.test-fixture' +import { isOpenSshSecurityKeyPrivateKey } from './ssh-security-key-identity' +import { createOpenSshPrivateKeyFixture } from './testing/ssh-security-key-identity.test-fixture' import '../system-transport/ssh-transport-selection' const { findSystemSshMock } = vi.hoisted(() => ({ findSystemSshMock: vi.fn() })) @@ -56,27 +50,4 @@ describe('isOpenSshSecurityKeyPrivateKey', () => { isOpenSshSecurityKeyPrivateKey(Buffer.from(`${ED25519_SECURITY_KEY} AAAA comment`)) ).toBe(false) }) - - it('rejects regular or mismatched OpenSSH public key blobs', () => { - expect(isOpenSshSecurityKeyPublicKey(createOpenSshPublicKeyFixture('ssh-ed25519'))).toBe(false) - expect( - isOpenSshSecurityKeyPublicKey( - Buffer.from(`${ED25519_SECURITY_KEY} ${Buffer.from('ssh-ed25519').toString('base64')}`) - ) - ).toBe(false) - }) - - it('rejects malformed and truncated OpenSSH envelopes without throwing', () => { - const key = createOpenSshPrivateKeyFixture([ED25519_SECURITY_KEY]) - const malformedLength = Buffer.concat([ - Buffer.from('openssh-key-v1\0', 'ascii'), - Buffer.from([0xff, 0xff, 0xff, 0xff]) - ]).toString('base64') - const malformedKey = Buffer.from( - `-----BEGIN OPENSSH PRIVATE KEY-----\n${malformedLength}\n-----END OPENSSH PRIVATE KEY-----\n` - ) - expect(isOpenSshSecurityKeyPrivateKey(key.subarray(0, -20))).toBe(false) - expect(isOpenSshSecurityKeyPrivateKey(malformedKey)).toBe(false) - expect(isOpenSshSecurityKeyPrivateKey(Buffer.from('not a private key'))).toBe(false) - }) }) diff --git a/src/main/ssh/connection/ssh-connect-config.test.ts b/src/main/ssh/connection/ssh-connect-config.test.ts index 377a1923b8a..343966ae939 100644 --- a/src/main/ssh/connection/ssh-connect-config.test.ts +++ b/src/main/ssh/connection/ssh-connect-config.test.ts @@ -29,7 +29,6 @@ vi.mock('../authentication/ssh-identity-file-read', () => ({ import { buildConnectConfig } from './ssh-connect-config' import { findDefaultKeyFile } from '../authentication/ssh-auth-resolution' -import { resolveEffectiveProxy } from '../system-transport/ssh-proxy-command' import { walkInitialAuthLadder } from './testing/ssh-connection-test-fixtures' import type { SshTarget } from '../../../shared/ssh-types' import type { SshResolvedConfig } from '../config/ssh-g-config-resolution' @@ -120,70 +119,6 @@ describe('buildConnectConfig', () => { } }) - it('uses ssh -G HostName when a config-host target still points at its alias', () => { - const config = buildConnectConfig( - makeTarget({ label: 'workbox', configHost: 'workbox', host: 'workbox' }), - makeResolved({ hostname: 'workbox.internal' }) - ) - - expect(config.host).toBe('workbox.internal') - }) - - it('uses ssh -G Port when a config-host target still has the default port', () => { - const config = buildConnectConfig( - makeTarget({ configHost: 'workbox', host: 'workbox', port: 22 }), - makeResolved({ port: 2202 }) - ) - - expect(config.port).toBe(2202) - }) - - it('keeps explicit non-default target ports ahead of ssh -G Port', () => { - const config = buildConnectConfig( - makeTarget({ configHost: 'workbox', host: 'workbox', port: 2022 }), - makeResolved({ port: 2202 }) - ) - - expect(config.port).toBe(2022) - }) - - it('uses fresh OpenSSH endpoint authority for imported config targets', () => { - const config = buildConnectConfig( - makeTarget({ - source: 'ssh-config', - configHost: 'workbox', - host: 'stale.example.com', - port: 2022, - username: 'stale-user' - }), - makeResolved({ - hostname: 'current.example.com', - port: 2202, - user: 'current-user' - }) - ) - - expect(config.host).toBe('current.example.com') - expect(config.port).toBe(2202) - expect(config.username).toBe('current-user') - }) - - it('uses configured IdentityAgent before SSH_AUTH_SOCK', () => { - const config = buildConnectConfig( - makeTarget(), - makeResolved({ identityAgent: '/tmp/one-password.sock' }) - ) - expect(config.agent).toBe('/tmp/one-password.sock') - }) - - it('prefers ssh -G resolved IdentityAgent for config-host targets', () => { - const config = buildConnectConfig( - makeTarget({ configHost: 'work', identityAgent: '%d/.1password/agent.sock' }), - makeResolved({ identityAgent: testHomePath('.1password', 'agent.sock') }) - ) - expect(config.agent).toBe(testHomePath('.1password', 'agent.sock')) - }) - it('allows IdentityAgent none to disable agent auth', () => { const config = buildConnectConfig(makeTarget(), makeResolved({ identityAgent: 'none' })) expect(config.agent).toBeUndefined() @@ -200,32 +135,6 @@ describe('buildConnectConfig', () => { expect(config.privateKey).toEqual(Buffer.from('not-a-key')) }) - it('uses fresh OpenSSH IdentityFile authority for imported config targets', () => { - mockReadFileSync.mockImplementation((path: unknown) => Buffer.from(String(path))) - const config = buildConnectConfig( - makeTarget({ - source: 'ssh-config', - configHost: 'workbox', - identityFile: '/home/user/.ssh/stale' - }), - makeResolved({ identityFile: ['/home/user/.ssh/current'] }), - { includeAgent: false, includePrivateKey: true } - ) - - expect(config.privateKey).toEqual(Buffer.from('/home/user/.ssh/current')) - expect(mockReadFileSync).toHaveBeenCalledWith('/home/user/.ssh/current') - }) - - it('expands Windows-style target.identityFile before reading private key', () => { - mockReadFileSync.mockReturnValue(Buffer.from('key')) - const config = buildConnectConfig(makeTarget({ identityFile: '~\\.ssh\\custom' }), null, { - includeAgent: false, - includePrivateKey: true - }) - expect(config.privateKey).toEqual(Buffer.from('key')) - expect(mockReadFileSync).toHaveBeenCalledWith(testHomePath('.ssh', 'custom')) - }) - it('defers an existing default key file to the no-agent retry', () => { mockExistsSync.mockImplementation( (p: unknown) => String(p) === testHomePath('.ssh', 'id_ed25519') @@ -243,17 +152,6 @@ describe('buildConnectConfig', () => { ]) }) - it('reads a deferred default key only once the agent-first attempt reaches the challenge', () => { - const defaultKeyPath = testHomePath('.ssh', 'id_ed25519') - mockExistsSync.mockImplementation((p: unknown) => String(p) === defaultKeyPath) - mockReadFileSync.mockReturnValue(UNENCRYPTED_KEY) - const config = buildConnectConfig(makeTarget(), null) - // Agent-only success must not touch FIFO/slow-mount identity files. - expect(mockReadFileSync).not.toHaveBeenCalledWith(defaultKeyPath) - expect(walkInitialAuthLadder(config, PASSWORD_HOST_METHODS)).toEqual(['none', 'agent']) - expect(mockReadFileSync).toHaveBeenCalledWith(defaultKeyPath) - }) - it('keeps the challenge when several keys wait, which could spend the retry auth budget', () => { mockReadFileSync.mockReturnValue(UNENCRYPTED_KEY) const config = buildConnectConfig( @@ -303,31 +201,3 @@ describe('buildConnectConfig', () => { } }) }) - -describe('resolveEffectiveProxy', () => { - it('returns target.proxyCommand first', () => { - const target = { ...makeTarget(), proxyCommand: 'cloudflared access ssh --hostname %h' } - const resolved = makeResolved({ proxyCommand: 'other' }) - expect(resolveEffectiveProxy(target, resolved)).toEqual({ - kind: 'proxy-command', - command: 'cloudflared access ssh --hostname %h' - }) - }) - - it('uses fresh OpenSSH proxy authority for imported config targets', () => { - const target = { - ...makeTarget(), - source: 'ssh-config' as const, - configHost: 'workbox', - proxyCommand: 'ssh -W %h:%p stale-bastion' - } - - expect(resolveEffectiveProxy(target, makeResolved())).toBeUndefined() - expect( - resolveEffectiveProxy(target, makeResolved({ proxyCommand: 'ssh -W %h:%p current-bastion' })) - ).toEqual({ - kind: 'proxy-command', - command: 'ssh -W %h:%p current-bastion' - }) - }) -}) diff --git a/src/main/ssh/connection/ssh-connection-system-transport.test.ts b/src/main/ssh/connection/ssh-connection-system-transport.test.ts index 6daac261f7f..64e051880a8 100644 --- a/src/main/ssh/connection/ssh-connection-system-transport.test.ts +++ b/src/main/ssh/connection/ssh-connection-system-transport.test.ts @@ -1,10 +1,9 @@ import { describe, expect, it, vi, beforeEach } from 'vitest' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { clientInstances, ssh2Mock } from './testing/ssh-connection-test-client' +import { ssh2Mock } from './testing/ssh-connection-test-client' import { - findSystemSshMock, getOrcaControlSocketPathMock, removeControlSocketPathMock, resetSshConnectionMocks, @@ -25,10 +24,6 @@ import { writeFileViaSystemSsh } from '../system-transport/file-transfer/system- import { CONNECT_TIMEOUT_MS } from './ssh-connection-timing' import { initSshHostKeyStoreFile, trustHostKey } from '../host-keys/ssh-host-key-store' import type { SshTarget } from '../../../shared/ssh-types' -import { - createOpenSshPrivateKeyFixture, - createOpenSshPublicKeyFixture -} from '../authentication/testing/ssh-security-key-identity.test-fixture' vi.mock('../authentication/ssh2-module-load', async () => (await import('./testing/ssh-connection-test-client')).createSsh2LoaderModule() @@ -190,92 +185,6 @@ describe('SshConnection', () => { expect(removeControlSocketPathMock).toHaveBeenCalledWith('/tmp/orca-ssh-501/stale-socket') }) - it('uses system SSH before ssh2 parses a security-key private key', async () => { - findSystemSshMock.mockReturnValue('/usr/bin/ssh') - const directory = mkdtempSync(join(tmpdir(), 'orca-security-key-connect-')) - const keyPath = join(directory, 'id_ed25519_sk') - writeFileSync( - keyPath, - createOpenSshPrivateKeyFixture(['sk-ssh-ed25519@openssh.com'], { encrypted: true }) - ) - const conn = new SshConnection(createTarget({ identityFile: keyPath }), createCallbacks()) - - try { - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - expect(clientInstances).toHaveLength(0) - expect(spawnSystemSshCommandMock).toHaveBeenCalledTimes(1) - } finally { - rmSync(directory, { recursive: true }) - } - }) - - it('uses system SSH for an agent-backed security-key public identity', async () => { - findSystemSshMock.mockReturnValue('/usr/bin/ssh') - const directory = mkdtempSync(join(tmpdir(), 'orca-security-key-agent-connect-')) - const identityPath = join(directory, 'id_ed25519_sk') - writeFileSync( - `${identityPath}.pub`, - createOpenSshPublicKeyFixture('sk-ssh-ed25519@openssh.com') - ) - const conn = new SshConnection(createTarget({ identityFile: identityPath }), createCallbacks()) - - try { - await conn.connect() - - expect(conn.usesSystemSshTransport()).toBe(true) - expect(clientInstances).toHaveLength(0) - expect(spawnSystemSshCommandMock).toHaveBeenCalledTimes(1) - } finally { - rmSync(directory, { recursive: true }) - } - }) - - it('falls back to system SSH when ssh2 hits a local network policy reachability error', async () => { - ssh2Mock.connectBehavior = 'error' - ssh2Mock.connectErrorMessage = - 'connect EHOSTUNREACH 192.168.0.210:22 - Local (192.168.0.2:52112)' - ssh2Mock.connectErrorCode = 'EHOSTUNREACH' - const conn = new SshConnection( - createTarget({ host: '192.168.0.210', label: 'LAN Linux', username: 'hydra' }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - expect(clientInstances).toHaveLength(1) - expect(spawnSystemSshCommandMock).toHaveBeenCalledWith( - expect.objectContaining({ host: '192.168.0.210' }), - 'echo ORCA-SYSTEM-SSH-OK', - { wrapCommand: false } - ) - }) - - it.each([ - 'Handshake failed: no matching host key format', - 'Handshake failed: no matching key exchange algorithm', - 'Handshake failed: no matching C->S cipher' - ])( - 'falls back to system SSH when ssh2 shares no algorithm with the host (%s)', - async (message) => { - ssh2Mock.connectBehavior = 'error' - ssh2Mock.connectErrorMessage = message - const conn = new SshConnection( - createTarget({ host: 'cert.example.com', label: 'Cert host' }), - createCallbacks() - ) - - await conn.connect() - - expect(conn.getState().status).toBe('connected') - expect(conn.usesSystemSshTransport()).toBe(true) - } - ) - it('keeps a host pinned in the Orca key store on ssh2 when negotiation fails', async () => { const storeDir = mkdtempSync(join(tmpdir(), 'orca-ssh-pinned-store-')) try { diff --git a/src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts b/src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts index 60ab686b110..209a6d575f3 100644 --- a/src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts +++ b/src/main/ssh/file-transfer/sftp/sftp-stream-late-error.test.ts @@ -7,9 +7,6 @@ import type { SFTPWrapper } from 'ssh2' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { uploadBuffer, writeStringViaSftp } from './sftp-upload' import { uploadFile } from './sftp-file-upload' -import { writeRemoteInstallFile } from '../../../managed-server/install/remote-install-transfers' -import type { SshConnection } from '../../connection/ssh-connection' -import { getRemoteHostPlatform } from '../../remote-host/ssh-remote-platform' function sftpNoSuchFileError(): Error { return Object.assign(new Error('file does not exist'), { code: 2 }) @@ -78,25 +75,3 @@ describe('late SFTP stream errors', () => { ) }) }) - -describe('sandboxed SFTP subsystem diagnosis', () => { - it('leaves a permission refusal as itself rather than blaming a chroot', async () => { - // Permission denial names visible paths; mislabeling it as sandboxing sends users to fix ProxyJump for chmod. - const conn = { - writeFile: () => Promise.reject(Object.assign(new Error('permission denied'), { code: 3 })) - } as unknown as SshConnection - - const failure: unknown = await writeRemoteInstallFile( - conn, - getRemoteHostPlatform('linux-x64'), - '/home/user/.orca-remote/relay-1/.version', - 'v1' - ).then( - () => null, - (err: unknown) => err - ) - - expect((failure as Error).message).toBe('permission denied') - expect(failure).not.toHaveProperty('sandboxedSftpNamespace') - }) -}) diff --git a/src/main/ssh/host-keys/ssh-known-hosts-source.test.ts b/src/main/ssh/host-keys/ssh-known-hosts-source.test.ts index 176ed1feae4..48223e2627a 100644 --- a/src/main/ssh/host-keys/ssh-known-hosts-source.test.ts +++ b/src/main/ssh/host-keys/ssh-known-hosts-source.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import '../config/ssh-g-config-resolution' @@ -62,16 +62,6 @@ describe('the union of known_hosts entries', () => { expect(verdict(entries, 'shared.example', ED_C)).toBe('mismatch') }) - it('skips a missing file and keeps the rest', async () => { - const root = await createRoot() - const present = join(root, 'known_hosts') - await writeFile(present, hostLine('alpha.example', ED_A)) - - const entries = await loadKnownHostsEntries([join(root, 'absent'), present]) - - expect(verdict(entries, 'alpha.example', ED_A)).toBe('match') - }) - it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( 'skips an unreadable file and keeps the rest', async () => { @@ -118,15 +108,6 @@ describe('loadKnownHostsEvidence', () => { expect(evidence.unreadableFileCount).toBe(1) } ) - - it('counts a path that is a directory', async () => { - const root = await createRoot() - await mkdir(join(root, 'a_directory')) - - const evidence = await loadKnownHostsEvidence([join(root, 'a_directory')]) - - expect(evidence.unreadableFileCount).toBe(1) - }) }) /** OpenSSH10.2p1 prints spaced trust paths unquoted; splitting can hide existing changed-key evidence as absent files. */ diff --git a/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts index 1010b5b15dd..d10c4eed181 100644 --- a/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts +++ b/src/main/ssh/host-server/ssh-host-server-on-connect.test.ts @@ -31,76 +31,6 @@ describe('which server an SSH host runs on connect', () => { expect(d.autoUpdate).not.toHaveBeenCalled() }) - it('checks for an update right after pairing with a server another version runs', async () => { - const d = deps({ - isEmptyHost: () => true, - deploy: vi.fn(async () => ({ - outcome: 'already-current' as const, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the orchestrator reads only the environment id. - environment: { id: 'env-1' } as never, - activeVersion: '0.9' - })), - autoUpdate: vi.fn(async () => ({ - outcome: 'deferred' as const, - code: 'orcad_update_terminals_running', - reason: '3 terminals are running' - })) - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-1', - update: { state: 'deferred', detail: '3 terminals are running' } - }) - expect(d.autoUpdate).toHaveBeenCalledWith('env-1', expect.anything()) - expect(d.abandonDeploy).not.toHaveBeenCalled() - }) - - // COMPAT(legacy-relay-bridge): the census only reports; converting leaves relay terminals running. - it('converts anyway when the bridge takes the live or unproven relay terminals', async () => { - for (const verdict of ['live', 'unverifiable'] as const) { - const proof = { verdict, count: 2, bridged: true as const } - const d = deps({ relayTerminals: async () => proof }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toMatchObject({ - route: 'managed' - }) - expect(d.convert).toHaveBeenCalledWith(target, proof) - } - }) - - it('surfaces a refusal for any other reason, naming it', async () => { - const d = deps({ - convert: async () => ({ - outcome: 'refused', - verdict: 'live', - code: 'orcad_migration_preflight_blocked', - reason: 'An automation still runs on this host.' - }) - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'unserved', - reason: 'refused', - detail: 'An automation still runs on this host.' - }) - }) - - it('offers "Move anyway" when only saved state refuses', async () => { - const d = deps({ - convert: async () => ({ - outcome: 'refused', - verdict: 'live', - code: 'orcad_migration_preflight_blocked', - reason: 'This SSH host cannot move yet: saved tabs and panes (2).', - canLeaveBehind: true - }) - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'unserved', - reason: 'refused', - detail: 'This SSH host cannot move yet: saved tabs and panes (2).', - canLeaveBehind: true - }) - }) - it('falls back to the relay ladder for good when orcad cannot run, and remembers why', async () => { const d = deps({ isEmptyHost: () => true, @@ -168,32 +98,6 @@ describe('which server an SSH host runs on connect', () => { warn.mockRestore() }) - it('touches no host when this build carries no orcad template', async () => { - const d = deps({ hasTemplate: () => false, isEmptyHost: () => true }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'unserved', - reason: 'orcad_unavailable', - detail: 'artifacts_unavailable' - }) - expect(d.deploy).not.toHaveBeenCalled() - }) - - it('retries a transient failure on the next connect without recording it', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const d = deps({ - convert: async () => { - throw new Error('Connection lost') - } - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'unserved', - reason: 'failed', - detail: 'Connection lost' - }) - expect(d.recordUnavailable).not.toHaveBeenCalled() - warn.mockRestore() - }) - it('names a conflict the server will keep refusing, and the way out, instead of a retry', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const d = deps({ @@ -241,19 +145,6 @@ describe('which server an SSH host runs on connect', () => { warn.mockRestore() }) - it('keeps a staged claim of another desktop’s move a retry, since it expires', async () => { - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const d = deps({ - convert: async () => { - throw new Error('orcad_migration_staged_claim_conflict:repository-path:/root/migrepo') - } - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toMatchObject({ - reason: 'failed' - }) - warn.mockRestore() - }) - it('records why when even the stdio bridge cannot reach the deployed server', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) const d = deps({ @@ -341,36 +232,5 @@ describe('which server an SSH host runs on connect', () => { }) expect(order).toEqual(['start', 'update']) }) - - it('keeps the old version serving while terminals run, and retries on a later connect', async () => { - const reason = '2 terminals are running on this host.' - const d = managed({ - autoUpdate: async () => ({ - outcome: 'deferred', - code: 'orcad_update_terminals_running', - reason - }) - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-9', - update: { state: 'deferred', detail: reason } - }) - expect(d.recordUpdateFailure).not.toHaveBeenCalled() - }) - - it('still connects when the update check itself throws', async () => { - const d = managed({ - autoUpdate: async () => { - throw new Error('ssh dropped') - } - }) - await expect(resolveHostServerOnConnect(target, d)).resolves.toEqual({ - route: 'managed', - environmentId: 'env-9', - update: { state: 'check-failed', detail: 'ssh dropped' } - }) - expect(d.recordUpdateFailure).not.toHaveBeenCalled() - }) }) }) diff --git a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts index d56582aeb35..7cde14c097e 100644 --- a/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts +++ b/src/main/ssh/legacy-relay/cli/legacy-relay-cli-server.test.ts @@ -2,7 +2,6 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { CONNECTOR_REPLY_UNAVAILABLE } from '../../../../shared/rpc-contract/connector-params' import { toAppSshPtyId } from '../../../../shared/ssh-pty-id' import '../../../../shared/ssh-remote-cli-control' import { OrcaRuntimeService } from '../../../runtime/orca-runtime' @@ -12,11 +11,7 @@ import '../../../runtime/orchestration/db/messages/mailbox-routing-page' import '../../../runtime/orchestration/db/dispatch-row-writer' import '../../../runtime/orchestration/db/attempt-outcome-projection' import { LEGACY_RELAY_CLI_UNVERIFIED } from './legacy-relay-cli-caller' -import { - createLegacyRelayCliServer, - LEGACY_RELAY_CLI_CONTROL_OFF, - LEGACY_RELAY_CLI_UNSUPPORTED -} from './legacy-relay-cli-server' +import { createLegacyRelayCliServer, LEGACY_RELAY_CLI_CONTROL_OFF } from './legacy-relay-cli-server' import type { LegacyRelayLivePane } from '../bridge/legacy-relay-bridge-leases' const TARGET = 'target-1' @@ -143,16 +138,6 @@ describe('the relay-era orca CLI on the desktop runtime', () => { expect(db.getTask(ids.taskId)?.status).toBe('dispatched') }) - it('refuses commands outside orchestration', async () => { - await expect(run(['worktree', 'list'])).rejects.toThrow(LEGACY_RELAY_CLI_UNSUPPORTED) - await expect(run(['terminal', 'send', '--terminal', COORDINATOR])).rejects.toThrow( - LEGACY_RELAY_CLI_UNSUPPORTED - ) - await expect(run(['connector', 'reply', '--text', 'done'])).rejects.toThrow( - CONNECTOR_REPLY_UNAVAILABLE - ) - }) - it.each([ ['a pane the bridge does not run', () => panes.clear(), ENV], [ diff --git a/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts index ab23d5622cc..4a24bdf0326 100644 --- a/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts +++ b/src/main/ssh/legacy-relay/endpoints/ssh-host-relay-windows-census.test.ts @@ -82,11 +82,6 @@ describe('the connect-time relay census on a Windows host', () => { countRelayPtysOverBridge.mockReset().mockResolvedValue(0) }) - it('finds none on a host that never ran a relay', async () => { - listing = '' - await expect(census()).resolves.toEqual({ verdict: 'none', count: 0 }) - }) - // Two desktops, two target ids, one Windows account: B's live shell must block A's conversion. it("asks another desktop's relay on this account, with that relay's own credential", async () => { const [bPrimary] = pipesOf('desktop-b') @@ -105,22 +100,6 @@ describe('the connect-time relay census on a Windows host', () => { ) }) - it('maps a pipe through its active-pipe marker when its credential is gone', async () => { - const [, bFallback] = pipesOf('desktop-b') - inventory = { - pipes: [bare(bFallback)], - dirs: { - [VERSION]: { - credentials: [], - markers: { [`.windows-active-pipe-${sockOf('desktop-b')}`]: bFallback } - } - } - } - countRelayPtysOverBridge.mockResolvedValue(2) - - await expect(census()).resolves.toEqual({ verdict: 'live', count: 1 }) - }) - it("is unverifiable for a pipe no directory here accounts for, unless it is another account's", async () => { inventory = { pipes: ['orca-relay-0123456789abcdef0123', 'orca-relay-fedcba9876543210fedc'], @@ -136,27 +115,6 @@ describe('the connect-time relay census on a Windows host', () => { await expect(census()).resolves.toEqual({ verdict: 'idle', count: 0 }) }) - it.each([ - [ - 'the inventory could not run', - () => - execCommand.mockImplementation(async (_conn: unknown, command: string) => { - if (command === 'LIST') { - return listing - } - throw new Error('channel closed') - }) - ], - ['the pipe listing failed', () => (inventory = { pipes: null, dirs: {} })], - [ - 'a version directory could not be read', - () => (inventory = { pipes: [], dirs: { [VERSION]: null } }) - ] - ])('is unverifiable when %s', async (_label, arrange) => { - arrange() - await expect(census()).resolves.toMatchObject({ verdict: 'unverifiable' }) - }) - it('never converts under an owned pipe it cannot ask', async () => { const [aPrimary] = pipesOf('desktop-a') inventory = { pipes: [bare(aPrimary)], dirs: { [VERSION]: { credentials: [], markers: {} } } } @@ -164,13 +122,4 @@ describe('the connect-time relay census on a Windows host', () => { await expect(census()).resolves.toEqual({ verdict: 'unverifiable', count: 1 }) }) - - it('reads relays that answer with no PTYs, or no relay pipes at all, as idle', async () => { - const [aPrimary] = pipesOf('desktop-a') - inventory = { pipes: [bare(aPrimary)], dirs: { [VERSION]: { credentials: [], markers: {} } } } - await expect(census()).resolves.toEqual({ verdict: 'idle', count: 0 }) - - inventory = { pipes: [], dirs: { [VERSION]: { credentials: [], markers: {} } } } - await expect(census()).resolves.toEqual({ verdict: 'idle', count: 0 }) - }) }) diff --git a/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts index ba5d82ceb3a..76ab7a30888 100644 --- a/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts +++ b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel.test.ts @@ -34,19 +34,6 @@ describe('waitForSentinel', () => { expect(chunks).toEqual(['first-frame-after-sentinel']) }) - it('buffers post-sentinel bytes from the sentinel chunk', async () => { - const channel = createMockChannel() - const transportPromise = waitForSentinel(channel) - - channel.emit('data', Buffer.from(`${RELAY_SENTINEL}same-chunk-frame`)) - - const transport = await transportPromise - const chunks: string[] = [] - transport.onData((chunk) => chunks.push(chunk.toString('utf-8'))) - - expect(chunks).toEqual(['same-chunk-frame']) - }) - it('does not count same-chunk post-sentinel payload against the startup buffer cap', async () => { const channel = createMockChannel() const transportPromise = waitForSentinel(channel) diff --git a/src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts b/src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts deleted file mode 100644 index 27e000e4856..00000000000 --- a/src/main/ssh/migration-source/orcad-migration-bridged-panes.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - DORMANT_LEAF_ID, - DORMANT_WORKTREE_ID, - dormantState, - manifest -} from '../../persistence/migrating-orcad-catalog/persistence-orcad-migration-catalog-fixture' -import type { SshRemotePtyLease } from '../../../shared/ssh-types' -import { preservesOrcadMigrationBridgedPanes } from './orcad-migration-bridged-panes' -import { isBridgeableLease } from '../legacy-relay/bridge/legacy-relay-bridge-leases' - -const LEASE: SshRemotePtyLease = { - targetId: 'ssh-prod', - ptyId: 'relay-pty', - tabId: 'tab-dormant', - leafId: DORMANT_LEAF_ID, - worktreeId: DORMANT_WORKTREE_ID, - state: 'detached', - createdAt: 1, - updatedAt: 1 -} - -describe('preserving the relay bridge when skipping saved state', () => { - it('refuses when a tab survives but the running split pane is omitted', () => { - const payload = { ...manifest().payload, dormantState: dormantState() } - const session = payload.dormantState!.workspaceSession! - session.terminalLayoutsByTabId[LEASE.tabId!]!.root = { type: 'leaf', leafId: 'other-leaf' } - session.terminalLayoutsByTabId[LEASE.tabId!]!.activeLeafId = 'other-leaf' - expect( - preservesOrcadMigrationBridgedPanes(payload, [LEASE], [LEASE.ptyId], isBridgeableLease) - ).toBe(false) - }) - - it('refuses a tab that moved to another workspace or whose lease identity is unknown', () => { - const payload = { ...manifest().payload, dormantState: dormantState() } - expect( - preservesOrcadMigrationBridgedPanes( - payload, - [ - { - ...LEASE, - worktreeId: 'folder:other-folder' - } - ], - [LEASE.ptyId], - isBridgeableLease - ) - ).toBe(false) - expect(preservesOrcadMigrationBridgedPanes(payload, [], [LEASE.ptyId], isBridgeableLease)).toBe( - false - ) - }) -}) diff --git a/src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts b/src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts deleted file mode 100644 index d0ef3f5e2a5..00000000000 --- a/src/main/ssh/migration-source/orcad-migration-ssh-relay-source.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import type { SshTarget } from '../../../shared/ssh-types' -import { closeTestStores, createSqliteTestStore } from '../../persistence/persistence-test-harness' -import { Store } from '../../persistence/loading-store/store' -import { listOrcadMigrationSourceCutovers } from '../../persistence/migrating-orcad-catalog/orcad-migration-cutover-journal' - -import { createSshRelayMigrationSource } from './orcad-migration-ssh-relay-source' -import { SshTargetOrcadClaims } from '../targets/ssh-target-orcad-claims' - -const TARGET: SshTarget = { - id: 'ssh-prod', - label: 'Production', - host: 'prod.example.com', - port: 22, - username: 'deploy', - generation: 2 -} - -const directories: string[] = [] -afterEach(async () => { - await closeTestStores() - for (const directory of directories.splice(0)) { - rmSync(directory, { recursive: true, force: true }) - } -}) - -function setup() { - const userDataPath = mkdtempSync(join(tmpdir(), 'orcad-ssh-relay-source-')) - directories.push(userDataPath) - const store = createSqliteTestStore(Store, { dataFile: join(userDataPath, 'orca-data.json') }) - store.addSshTarget(TARGET) - store.addRepo({ - id: 'repo-1', - path: '/srv/app', - displayName: 'App', - badgeColor: '#737373', - addedAt: 1, - kind: 'git', - connectionId: TARGET.id - }) - const claims = new SshTargetOrcadClaims(store) - const source = createSshRelayMigrationSource({ - userDataPath, - store, - claims, - target: store.getSshTarget(TARGET.id)! - }) - return { userDataPath, store, source } -} - -describe('relay-era SSH migration source', () => { - it('never proves exit without a host-wide census', async () => { - await expect(setup().source.assessTerminals()).resolves.toMatchObject({ - verdict: 'unverifiable' - }) - }) - - it('acquires, verifies, and releases its fence through the journal it is keyed by', async () => { - const { userDataPath, source } = setup() - expect(source.resolveFence()).toEqual({ state: 'none' }) - const fenced = await source.acquireFence({ - destinationEnvironmentId: 'env-1', - destinationName: 'Managed', - terminalProof: { verdict: 'exited', provenPtyIds: [] } - }) - expect(fenced.outcome).toBe('fenced') - const cutover = listOrcadMigrationSourceCutovers(userDataPath)[0] - expect(cutover.sshTargetId).toBe(source.journalKey) - expect(() => source.verifyFence(cutover)).not.toThrow() - await source.releaseFence(cutover) - expect(listOrcadMigrationSourceCutovers(userDataPath)).toEqual([]) - }) -}) diff --git a/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts b/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts index 3800702be8d..0068739f460 100644 --- a/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts +++ b/src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.test.ts @@ -51,11 +51,4 @@ describe('forward channel check (system SSH)', () => { }) await expect(checkForwardChannel(forward)).resolves.toBe('allowed') }) - - it('reads reply bytes through the channel as allowed', async () => { - const forward = await forwardAnswering((socket) => { - socket.once('data', () => socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')) - }) - await expect(checkForwardChannel(forward)).resolves.toBe('allowed') - }) }) diff --git a/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.test.ts b/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.test.ts index d8e23894f67..37ccfbeb69c 100644 --- a/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.test.ts +++ b/src/main/ssh/remote-host/node-toolchain/ssh-remote-node-resolution.test.ts @@ -38,14 +38,6 @@ function loginShellProbe(shell: string, mode: string) { ) } -function decodePowerShellCommand(command: string): string { - const match = command.match(/-EncodedCommand\s+([A-Za-z0-9+/=]+)/) - if (!match) { - throw new Error(`No encoded PowerShell command found in: ${command}`) - } - return Buffer.from(match[1]!, 'base64').toString('utf16le') -} - describe('resolveRemoteNodePath', () => { beforeEach(() => { execCommandMock.mockReset() @@ -60,46 +52,36 @@ describe('resolveRemoteNodePath', () => { await expect(resolveRemoteNodePath(conn)).resolves.toBe( '/home/u/.nvm/versions/node/v22.22.0/bin/node' ) - - expect(execCommandMock.mock.calls[1]![1]).toContain("PATH='/usr/bin':$PATH npm --version") - expect(execCommandMock.mock.calls[2]![1]).toContain( - "PATH='/home/u/.nvm/versions/node/v22.22.0/bin':$PATH npm --version" - ) }) - it.runIf(process.platform !== 'win32')( - 'accepts npm elsewhere on PATH without probing another Node candidate', - async () => { - const root = mkdtempSync(path.join(os.tmpdir(), 'orca-split-node-npm-')) - try { - const nodePath = path.join(root, 'selected node', 'bin', 'node') - const npmBinDir = path.join(root, 'npm elsewhere', 'bin') - mkdirSync(path.dirname(nodePath), { recursive: true }) - mkdirSync(npmBinDir, { recursive: true }) - writeFileSync(nodePath, '#!/bin/sh\nprintf "v22.22.0\\n"\n') - writeFileSync(path.join(npmBinDir, 'npm'), '#!/bin/sh\nprintf "11.13.0\\n"\n') - chmodSync(nodePath, 0o755) - chmodSync(path.join(npmBinDir, 'npm'), 0o755) + it.runIf(process.platform !== 'win32')('accepts npm elsewhere on PATH', async () => { + const root = mkdtempSync(path.join(os.tmpdir(), 'orca-split-node-npm-')) + try { + const nodePath = path.join(root, 'selected node', 'bin', 'node') + const npmBinDir = path.join(root, 'npm elsewhere', 'bin') + mkdirSync(path.dirname(nodePath), { recursive: true }) + mkdirSync(npmBinDir, { recursive: true }) + writeFileSync(nodePath, '#!/bin/sh\nprintf "v22.22.0\\n"\n') + writeFileSync(path.join(npmBinDir, 'npm'), '#!/bin/sh\nprintf "11.13.0\\n"\n') + chmodSync(nodePath, 0o755) + chmodSync(path.join(npmBinDir, 'npm'), 0o755) - execCommandMock - .mockResolvedValueOnce(`${nodePath}\n${path.join(root, 'fallback', 'bin', 'node')}\n`) - .mockImplementationOnce((_conn: SshConnection, command: string) => - Promise.resolve( - execFileSync('/bin/sh', ['-c', command], { - encoding: 'utf8', - env: { HOME: root, PATH: npmBinDir } - }) - ) + execCommandMock + .mockResolvedValueOnce(`${nodePath}\n${path.join(root, 'fallback', 'bin', 'node')}\n`) + .mockImplementationOnce((_conn: SshConnection, command: string) => + Promise.resolve( + execFileSync('/bin/sh', ['-c', command], { + encoding: 'utf8', + env: { HOME: root, PATH: npmBinDir } + }) ) + ) - await expect(resolveRemoteNodePath(conn)).resolves.toBe(nodePath) - // One inventory exec plus one candidate probe keeps SSH startup work bounded. - expect(execCommandMock).toHaveBeenCalledTimes(2) - } finally { - rmSync(root, { recursive: true, force: true }) - } + await expect(resolveRemoteNodePath(conn)).resolves.toBe(nodePath) + } finally { + rmSync(root, { recursive: true, force: true }) } - ) + }) it('finds node under a MISE_DATA_DIR exported from a shell dotfile', async () => { execCommandMock @@ -290,14 +272,6 @@ describe('resolveRemoteNodePath', () => { ) }) - it('accepts Node 18 (the exact minimum) as valid', async () => { - execCommandMock - .mockResolvedValueOnce('/usr/local/bin/node\n') - .mockResolvedValueOnce('v18.0.0\n') - - await expect(resolveRemoteNodePath(conn)).resolves.toBe('/usr/local/bin/node') - }) - it('falls back to the login shell when path probes find nothing', async () => { execCommandMock .mockResolvedValueOnce('\n') @@ -328,37 +302,6 @@ describe('resolveRemoteNodePath', () => { ) }) - it('respects a non-default $SHELL instead of hardcoding bash', async () => { - execCommandMock - .mockResolvedValueOnce('\n') - .mockResolvedValueOnce('/usr/bin/fish') - .mockImplementationOnce(loginShellAnswer('/opt/homebrew/bin/node\n')) - .mockResolvedValueOnce('v22.0.0\n') - - await resolveRemoteNodePath(conn) - - expect(execCommandMock).toHaveBeenNthCalledWith( - 3, - conn, - loginShellProbe('/usr/bin/fish', '-lc'), - { wrapCommand: false, timeoutMs: 8_000 } - ) - }) - - it('uses /bin/sh when the remote shell expansion falls back to it', async () => { - execCommandMock - .mockResolvedValueOnce('\n') - .mockResolvedValueOnce('/bin/sh\n') - .mockImplementationOnce(loginShellAnswer('/usr/local/bin/node\n')) - .mockResolvedValueOnce('v20.0.0\n') - - await expect(resolveRemoteNodePath(conn)).resolves.toBe('/usr/local/bin/node') - expect(execCommandMock).toHaveBeenNthCalledWith(3, conn, loginShellProbe('/bin/sh', '-c'), { - wrapCommand: false, - timeoutMs: 8_000 - }) - }) - it('uses -c (not -lc) for a csh login shell, which rejects combined -lc', async () => { // csh/tcsh require plain -c; -lc/-l can fail with Bad modifier (#8701). execCommandMock @@ -374,25 +317,6 @@ describe('resolveRemoteNodePath', () => { }) }) - it('uses -c (not -lc) for a tcsh login shell', async () => { - execCommandMock - .mockResolvedValueOnce('\n') - .mockResolvedValueOnce('/usr/bin/tcsh\n') - .mockImplementationOnce(loginShellAnswer('/usr/local/bin/node\n')) - .mockResolvedValueOnce('v20.0.0\n') - - await expect(resolveRemoteNodePath(conn)).resolves.toBe('/usr/local/bin/node') - expect(execCommandMock).toHaveBeenNthCalledWith( - 3, - conn, - loginShellProbe('/usr/bin/tcsh', '-c'), - { - wrapCommand: false, - timeoutMs: 8_000 - } - ) - }) - it('keeps the default path-probe fallback for SSH session-limit-shaped errors', async () => { const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 4 @@ -416,73 +340,6 @@ describe('resolveRemoteNodePath', () => { ).rejects.toBe(sessionLimitError) }) - it('rethrows SSH session-limit errors from candidate version checks in strict mode', async () => { - const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { - reason: 4 - }) - execCommandMock - .mockResolvedValueOnce('/usr/local/bin/node\n') - .mockRejectedValueOnce(sessionLimitError) - - await expect( - resolveRemoteNodePath(conn, undefined, { rethrowSessionLimitErrors: true }) - ).rejects.toBe(sessionLimitError) - }) - - it('rethrows SSH session-limit errors from login-shell resolution in strict mode', async () => { - const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { - reason: 4 - }) - execCommandMock.mockResolvedValueOnce('\n').mockRejectedValueOnce(sessionLimitError) - - await expect( - resolveRemoteNodePath(conn, undefined, { rethrowSessionLimitErrors: true }) - ).rejects.toBe(sessionLimitError) - }) - - it('rethrows SSH session-limit errors from package-manager hint probing in strict mode', async () => { - const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { - reason: 4 - }) - execCommandMock - .mockResolvedValueOnce('\n') - .mockResolvedValueOnce('/bin/bash') - .mockResolvedValueOnce('\n') - .mockRejectedValueOnce(sessionLimitError) - - await expect( - resolveRemoteNodePath(conn, undefined, { rethrowSessionLimitErrors: true }) - ).rejects.toBe(sessionLimitError) - }) - - it('rethrows SSH session-limit errors from Windows node resolution in strict mode', async () => { - const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { - reason: 4 - }) - execCommandMock.mockRejectedValueOnce(sessionLimitError) - - await expect( - resolveRemoteNodePath(conn, getRemoteHostPlatform('win32-x64'), { - rethrowSessionLimitErrors: true - }) - ).rejects.toBe(sessionLimitError) - }) - - it('rethrows SSH session-limit errors from Windows version checks in strict mode', async () => { - const sessionLimitError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { - reason: 4 - }) - execCommandMock - .mockResolvedValueOnce('C:\\Program Files\\nodejs\\node.exe\n') - .mockRejectedValueOnce(sessionLimitError) - - await expect( - resolveRemoteNodePath(conn, getRemoteHostPlatform('win32-x64'), { - rethrowSessionLimitErrors: true - }) - ).rejects.toBe(sessionLimitError) - }) - it('surfaces an AbortError instead of not-found when the shared signal is aborted', async () => { // Shared bootstrap abort must remain cancellation; swallowing it as Node-not-found defeats sequential fallback. const controller = new AbortController() @@ -508,9 +365,6 @@ describe('resolveRemoteNodePath', () => { await expect(resolveRemoteNodePath(conn, getRemoteHostPlatform('win32-x64'))).resolves.toBe( 'C:/Program Files/nodejs/node.exe' ) - - const discoveryScript = decodePowerShellCommand(execCommandMock.mock.calls[0]![1] as string) - expect(discoveryScript).not.toMatch(/Write-Output \$path\s+exit 0/) }) describe('strict resolution, which settles rung D only on an answered "no Node"', () => { diff --git a/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts index 0585a3f5820..b9e823ca9e9 100644 --- a/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-args.test.ts @@ -1,6 +1,6 @@ /** SSH flags can silently change meaning in SFTP; unknown translations must decline to another transport. */ import { describe, expect, it } from 'vitest' -import { SftpArgTranslationError, translateSshArgsToSftpArgs } from './system-ssh-sftp-args' +import { translateSshArgsToSftpArgs } from './system-ssh-sftp-args' describe('translateSshArgsToSftpArgs', () => { it('translates the whole unclaimed-alias shape buildSshArgs emits', () => { @@ -35,24 +35,4 @@ describe('translateSshArgsToSftpArgs', () => { 'awin' ]) }) - - it('refuses any other -S, which would hand sftp an ssh binary Orca did not choose', () => { - expect(() => translateSshArgsToSftpArgs(['-S', '/tmp/ctl.sock'])).toThrow( - SftpArgTranslationError - ) - }) - - it('takes everything after -- as the destination without reinterpreting it', () => { - // A host literally named `-p` is not a flag once `--` has been seen. - expect(translateSshArgsToSftpArgs(['--', '-p'])).toEqual(['--', '-p']) - }) - - it('refuses an unknown flag rather than guessing what sftp would do with it', () => { - // Future SSH flags must fall back safely instead of inheriting SFTP's different meaning. - expect(() => translateSshArgsToSftpArgs(['-A', '--', 'host'])).toThrow(SftpArgTranslationError) - }) - - it('refuses a value flag with no value', () => { - expect(() => translateSshArgsToSftpArgs(['-o'])).toThrow(SftpArgTranslationError) - }) }) diff --git a/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts index 8392f41cba9..0c7395df839 100644 --- a/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts +++ b/src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts @@ -146,19 +146,6 @@ describe('system SSH forward process', () => { expect(spawnMock).not.toHaveBeenCalled() }) - it('rejects startup when ssh exits early with stderr', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - const socket = createFakeSocket() - connectMock.mockReturnValue(socket) - - const pending = waitForSystemSshForwardStartup(child as never, 3000) - child.stderr.emit('data', Buffer.from('bind: Address already in use\n')) - child.emit('exit', 255) - - await expect(pending).rejects.toThrow('bind: Address already in use') - }) - it("rejects startup and stops ssh when it cannot listen on this forward's own port", async () => { const child = createFakeProcess() spawnMock.mockReturnValue(child) @@ -201,17 +188,6 @@ describe('system SSH forward process', () => { expect(child.kill).not.toHaveBeenCalled() }) - it('rejects startup when the ssh process emits an error', async () => { - vi.useFakeTimers() - const child = createFakeProcess() - connectMock.mockReturnValue(createFakeSocket()) - - const pending = waitForSystemSshForwardStartup(child as never, 3000) - child.emit('error', new Error('spawn failed')) - - await expect(pending).rejects.toThrow('spawn failed') - }) - it('rejects when no listener appears within the listener timeout', async () => { vi.useFakeTimers() const child = createFakeProcess() diff --git a/src/main/ssh/system-transport/system-ssh-operations.test.ts b/src/main/ssh/system-transport/system-ssh-operations.test.ts index 9469a873f71..d9cebf806a2 100644 --- a/src/main/ssh/system-transport/system-ssh-operations.test.ts +++ b/src/main/ssh/system-transport/system-ssh-operations.test.ts @@ -1,7 +1,6 @@ import { EventEmitter } from 'node:events' import { PassThrough } from 'node:stream' import { describe, expect, it, vi, beforeEach } from 'vitest' -import { createFakeSpawnedChild } from '../../../shared/__fixtures__/fake-spawned-child' const { existsSyncMock, spawnMock } = vi.hoisted(() => ({ existsSyncMock: vi.fn(), @@ -20,14 +19,12 @@ vi.mock('child_process', () => ({ spawn: spawnMock })) -import { buildSshArgs } from './system-ssh-args' import { spawnSystemSshCommand } from './system-ssh-command' import { uploadDirectoryViaSystemSsh, writeFileViaSystemSsh } from './file-transfer/system-ssh-file-transfer' import type { SshTarget } from '../../../shared/ssh-types' -import type { SystemSshResolvedConfig } from './ssh-control-socket' const SYSTEM_SSH_PATH = process.platform === 'win32' ? 'C:\\Windows\\System32\\OpenSSH\\ssh.exe' : '/usr/bin/ssh' @@ -47,37 +44,6 @@ function createTarget(overrides?: Partial): SshTarget { } } -function createResolvedConfig( - overrides?: Partial -): SystemSshResolvedConfig { - return { - hostname: 'example.com', - port: 22, - identityFile: [], - forwardAgent: false, - identitiesOnly: false, - proxyUseFdpass: false, - controlMaster: 'no', - controlPersist: 'no', - ...overrides - } -} - -function expectNoOrcaControlMasterArgs(args: string[]): void { - expect(args).not.toContain('ControlMaster=auto') - expect(args.some((arg) => arg.startsWith('ControlPath='))).toBe(false) - expect(args).not.toContain('ControlPersist=300') -} - -function createEventedProcess() { - const proc = createFakeSpawnedChild(12345) - const stdin = Object.assign(proc.stdin, { - write: vi.spyOn(proc.stdin, 'write'), - end: vi.spyOn(proc.stdin, 'end') - }) - return Object.assign(proc, { stdin }) -} - function createMockChildProcess(): EventEmitter & { stdin: PassThrough stdout: PassThrough @@ -110,159 +76,12 @@ function createMockChildProcess(): EventEmitter & { } describe('spawnSystemSsh', () => { - let mockProc: { - stdin: { - write: ReturnType - end: ReturnType - on: ReturnType - } - stdout: { on: ReturnType } - stderr: { on: ReturnType } - pid: number - on: ReturnType - kill: ReturnType - } - beforeEach(() => { existsSyncMock.mockReset() spawnMock.mockReset() - - mockProc = { - stdin: { write: vi.fn(), end: vi.fn(), on: vi.fn() }, - stdout: { on: vi.fn() }, - stderr: { on: vi.fn() }, - pid: 12345, - on: vi.fn(), - kill: vi.fn() - } - spawnMock.mockReturnValue(mockProc) mockSystemSshExists() }) - it('uses configHost without resolved field overrides so OpenSSH sees the Host block', () => { - const args = buildSshArgs( - createTarget({ - configHost: 'fdpass-host', - host: 'resolved.example.com', - port: 2222, - username: 'deploy', - identityFile: '/tmp/key', - identityAgent: '/tmp/agent.sock', - proxyCommand: 'ignored' - }) - ) - - expect(args).toContain('fdpass-host') - expect(args).not.toContain('deploy@fdpass-host') - expect(args).not.toContain('resolved.example.com') - expect(args).not.toContain('-p') - expect(args).not.toContain('-i') - expect(args).not.toContain('IdentityAgent=/tmp/agent.sock') - expect(args).not.toContain('ProxyCommand=ignored') - }) - - it('states the stored endpoint when no Host block claims the alias', () => { - // #11746: Host * can retain a deleted alias's proxy, making it appear config-backed. - const args = buildSshArgs( - createTarget({ - source: 'ssh-config', - configHost: 'prod', - host: '10.0.0.5', - port: 2222, - username: 'deploy' - }), - { aliasClaimedByConfig: false } - ) - - expect(args).toContain('Hostname=10.0.0.5') - expect(args.slice(args.indexOf('-p'))).toContain('2222') - expect(args.slice(args.indexOf('-l'))).toContain('deploy') - expect(args.at(-1)).toBe('prod') - expect(args).not.toContain('deploy@prod') - expect(args).not.toContain('-i') - expect(args).not.toContain('-J') - }) - - it('restricts Kerberos probes to non-interactive GSSAPI authentication', () => { - spawnSystemSshCommand( - createTarget({ - configHost: 'krb-host; touch /tmp/not-run', - source: 'ssh-config', - gssapiAuthentication: true - }), - 'echo ready', - { gssapiOnly: true, wrapCommand: false } - ) - - const args = spawnMock.mock.calls[0][1] as string[] - expect(args).toEqual( - expect.arrayContaining([ - '-o', - 'BatchMode=yes', - '-o', - 'GSSAPIAuthentication=yes', - '-o', - 'PreferredAuthentications=gssapi-with-mic' - ]) - ) - expect(args).not.toContain('BatchMode=no') - const standaloneControlIdx = args.indexOf('-S') - expect(standaloneControlIdx).toBeGreaterThan(-1) - expect(args[standaloneControlIdx + 1]).toBe('none') - expect(args.at(-2)).toBe('krb-host; touch /tmp/not-run') - expect(args.at(-1)).toBe('echo ready') - }) - - it('does not inject Orca ControlMaster flags when ssh config already owns muxing', () => { - const args = buildSshArgs(createTarget({ configHost: 'workbox', source: 'ssh-config' }), { - resolvedConfig: createResolvedConfig({ - controlMaster: 'auto', - controlPath: '/Users/me/.ssh/cm/%r@%h:%p', - controlPersist: '10m' - }) - }) - - expectNoOrcaControlMasterArgs(args) - expect(args).not.toContain('-S') - expect(args).toContain('workbox') - }) - - it('does not inject Orca ControlMaster flags for unresolved ssh-config targets', () => { - const args = buildSshArgs(createTarget({ configHost: 'workbox', source: 'ssh-config' })) - - expectNoOrcaControlMasterArgs(args) - expect(args).not.toContain('-S') - expect(args).toContain('workbox') - }) - - it('forces standalone SSH when target connection reuse is disabled', () => { - const args = buildSshArgs(createTarget({ systemSshConnectionReuse: false })) - const standaloneControlIdx = args.indexOf('-S') - - expect(standaloneControlIdx).toBeGreaterThan(-1) - expect(args[standaloneControlIdx + 1]).toBe('none') - expectNoOrcaControlMasterArgs(args) - }) - - it('removes wrapped process listeners after command close', () => { - const proc = createEventedProcess() - spawnMock.mockReturnValue(proc) - - const channel = spawnSystemSshCommand(createTarget(), 'echo hello') - const onClose = vi.fn() - channel.on('close', onClose) - proc.emit('close', 0, null) - - expect(onClose).toHaveBeenCalledWith(0, null) - expect(proc.stdout.listenerCount('data')).toBe(0) - expect(proc.stdout.listenerCount('end')).toBe(0) - expect(proc.stdout.listenerCount('error')).toBe(0) - expect(proc.stdin.listenerCount('error')).toBe(0) - expect(proc.listenerCount('exit')).toBe(0) - expect(proc.listenerCount('close')).toBe(0) - expect(proc.listenerCount('error')).toBe(0) - }) - it('pauses command stdout under backpressure and resumes when the channel reads', async () => { const proc = createMockChildProcess() const pause = vi.spyOn(proc.stdout, 'pause') diff --git a/src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts b/src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts deleted file mode 100644 index 20f991ab7f5..00000000000 --- a/src/main/ssh/targets/ssh-connection-store-orcad-ownership.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' - -import { SshConnectionStore } from './ssh-connection-store' -import { createMockStore } from './testing/ssh-connection-store-test-fixture' -import { emptyDependentStateStore } from './testing/ssh-target-orcad-dependents-fixture' - -const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ - loadUserSshConfigMock: vi.fn(), - sshConfigHostsToTargetsMock: vi.fn() -})) - -vi.mock('../config/ssh-config-parser', () => ({ - loadUserSshConfig: loadUserSshConfigMock, - loadUserSshConfigWithText: () => ({ hosts: loadUserSshConfigMock(), text: '' }), - sshConfigHostsToTargets: sshConfigHostsToTargetsMock -})) - -const base = { label: 'cluster', host: 'cluster.example.com', port: 22, username: 'dev' } - -describe('managed orcad ownership of SSH targets', () => { - let mockStore: ReturnType - let sshStore: SshConnectionStore - - beforeEach(() => { - mockStore = Object.assign(createMockStore(), emptyDependentStateStore()) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the fixture implements the store methods SshConnectionStore calls. - sshStore = new SshConnectionStore(mockStore as never, { config: async () => null }) - loadUserSshConfigMock.mockReset() - sshConfigHostsToTargetsMock.mockReset() - }) - - it('lists managed and provisioning hosts with their status, and hides only runtime-owned ones', () => { - sshStore.addTarget(base) - sshStore.addTarget({ - ...base, - label: 'provisioning', - orcadProvisioning: { requestId: 'r', name: 'n' } - }) - const claimed = sshStore.addTarget({ ...base, label: 'claimed' }) - sshStore.getOrcadRuntimeClaims().claim(claimed.id, 'environment-1', { ownerRecorded: false }) - mockStore.addSshTarget({ - ...base, - id: 'runtime-ssh-vm', - label: 'vm', - owner: { type: 'on-demand-runtime', runtimeId: 'vm-1' } - }) - - expect(sshStore.listTargets().map((target) => target.label)).toEqual([ - 'cluster', - 'provisioning', - 'claimed' - ]) - expect(sshStore.getTarget(claimed.id)?.owner).toBeUndefined() - }) - - it('keeps ~/.ssh/config sync from rewriting a claimed config-sourced host', async () => { - mockStore.addSshTarget({ - ...base, - id: 'ssh-config-host', - configHost: 'cluster', - source: 'ssh-config', - orcadFence: { environmentId: 'environment-1' } - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'cluster' }]) - sshConfigHostsToTargetsMock.mockReturnValue([ - { ...base, id: 'tmp', configHost: 'cluster', host: '10.0.0.9', port: 2222 } - ]) - - expect((await sshStore.importFromSshConfig()).targets).toEqual([]) - expect(mockStore.updateSshTarget).not.toHaveBeenCalled() - }) -}) diff --git a/src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts b/src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts index e670fcdea7e..76987608be6 100644 --- a/src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts +++ b/src/main/ssh/targets/ssh-connection-store-route-dedupe.test.ts @@ -105,56 +105,6 @@ describe('SshConnectionStore import route de-duplication', () => { loadUserSshConfigMock.mockReturnValue([]) }) - it('never matches a saved target whose own jump host conflicts with the one it inherits', async () => { - mockStore.addSshTarget({ - id: 'ssh-own-jump', - label: 'Own jump', - configHost: 'saved-own-jump', - host: '172.16.203.131', - port: 22, - username: 'chanmuzi', - jumpHost: 'bastion-b', - source: 'manual' - }) - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('via-a')]) - - expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1) - }) - - // Saved from the picker when prod was 10.0.0.1; system ssh now follows the config to 10.0.0.9, ssh2 keeps 10.0.0.1. - it('never matches a saved target whose host the two transports resolve differently', async () => { - mockStore.addSshTarget({ - id: 'ssh-prod', - label: 'prod', - configHost: 'prod', - host: '10.0.0.1', - port: 22, - username: 'chanmuzi', - jumpHost: 'b', - source: 'manual' - }) - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('old')]) - - expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1) - }) - - // Its Host block is gone, so system ssh still dials the saved 192.0.2.10, not the name `fresh` points at. - it('never matches a saved config target whose alias the config no longer claims', async () => { - mockStore.addSshTarget({ - id: 'ssh-removed-block', - label: 'removed-block', - configHost: 'removed-block', - host: '192.0.2.10', - port: 22, - username: 'chanmuzi', - source: 'ssh-config' - }) - unclaimedAliases.add('removed-block') - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('fresh')]) - - expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1) - }) - it('keeps a route match when this import itself updates the matched target', async () => { mockStore.addSshTarget({ ...configCandidate('moved'), @@ -202,18 +152,6 @@ describe('SshConnectionStore import route de-duplication', () => { ) }) - it('imports the same address behind a different jump host', async () => { - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('via-b')]) - - expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1) - }) - - it('falls back to alias-only when ssh -G fails, rather than guessing', async () => { - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('unresolvable')]) - - expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1) - }) - it('lets Restore bring back a removed alias that shares a saved route, as its dialog promised', async () => { sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('aimp')]) mockStore.addDeletedSshConfigAlias('aimp') @@ -221,11 +159,4 @@ describe('SshConnectionStore import route de-duplication', () => { expect((await sshStore.importFromSshConfig()).targets).toEqual([]) expect((await sshStore.importFromSshConfig({ reAdopt: true })).targets).toHaveLength(1) }) - - // #15478's own config: without HostName, OpenSSH connects to the alias name, which only DNS ties to the IP. - it('does not match a HostName-less alias to an IP target by name resolution', async () => { - sshConfigHostsToTargetsMock.mockReturnValue([configCandidate('aimp-no-hostname')]) - - expect((await sshStore.importFromSshConfig()).targets).toHaveLength(1) - }) }) diff --git a/src/main/ssh/targets/ssh-connection-store.test.ts b/src/main/ssh/targets/ssh-connection-store.test.ts index e2212b0bb6c..72704ff7c61 100644 --- a/src/main/ssh/targets/ssh-connection-store.test.ts +++ b/src/main/ssh/targets/ssh-connection-store.test.ts @@ -41,72 +41,6 @@ describe('SshConnectionStore', () => { } } - it('adopts a legacy unsourced target into config-sync', async () => { - mockStore.addSshTarget({ - id: 'ssh-legacy', - label: 'cluster', - configHost: 'cluster', - host: '10.0.0.5', - port: 2200, - username: 'dev' - // no source — predates the field - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'cluster' }]) - sshConfigHostsToTargetsMock.mockReturnValue([ - candidate({ configHost: 'cluster', host: '10.0.0.5', port: 2222, username: 'dev' }) - ]) - - const result = (await sshStore.importFromSshConfig()).targets - - expect(mockStore.updateSshTarget).toHaveBeenCalledWith( - 'ssh-legacy', - expect.objectContaining({ port: 2222, source: 'ssh-config' }) - ) - expect(result[0].source).toBe('ssh-config') - }) - - it('does not overwrite a legacy unsourced manual target with the same alias', async () => { - mockStore.addSshTarget({ - id: 'ssh-legacy-manual', - label: 'cluster', - configHost: 'cluster', - host: 'cluster', - port: 2200, - username: 'me' - // no source — predates the field, but does not look like a config import - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'cluster' }]) - sshConfigHostsToTargetsMock.mockReturnValue([ - candidate({ configHost: 'cluster', host: '10.0.0.5', port: 2222, username: 'dev' }) - ]) - - const result = (await sshStore.importFromSshConfig()).targets - - expect(mockStore.updateSshTarget).not.toHaveBeenCalled() - expect(mockStore.addSshTarget).toHaveBeenCalledTimes(1) - expect(result).toEqual([]) - }) - - // Import alias ownership must use the picker's case-insensitive Host matching. - it('treats a case-only alias variant as owned by the existing manual target', async () => { - mockStore.addSshTarget({ - id: 'ssh-m', - label: 'Prod', - configHost: 'Prod', - host: 'manual.example.com', - port: 22, - username: 'me', - source: 'manual' - }) - loadUserSshConfigMock.mockReturnValue([{ host: 'prod' }]) - sshConfigHostsToTargetsMock.mockReturnValue([candidate({ configHost: 'prod' })]) - - const result = (await sshStore.importFromSshConfig()).targets - - expect(mockStore.addSshTarget).toHaveBeenCalledTimes(1) - expect(result).toEqual([]) - }) - it('keeps a case-only alias variant suppressed after the host was deleted', async () => { const added = sshStore.addTarget({ label: 'Prod', @@ -172,27 +106,4 @@ describe('SshConnectionStore', () => { expect(result).toHaveLength(1) }) }) - - describe('re-adoption of orphaned workspaces', () => { - it('does not re-adopt when the re-added host identity differs', () => { - mockStore.addRemovedSshTargetTombstone({ - oldTargetId: 'ssh-old', - host: 'other.example.com', - port: 22, - username: 'root', - label: 'Other', - removedAt: 1 - }) - - sshStore.addTarget({ - label: 'Dev', - host: 'dev.example.com', - port: 22, - username: 'tim' - }) - - expect(mockStore.reassignSshTargetId).not.toHaveBeenCalled() - expect(sshStore.lastRepoReadoptions).toEqual([]) - }) - }) }) diff --git a/src/main/text-generation/codex-model-list-discovery.ts b/src/main/text-generation/codex-model-list-discovery.ts new file mode 100644 index 00000000000..688de29c597 --- /dev/null +++ b/src/main/text-generation/codex-model-list-discovery.ts @@ -0,0 +1,175 @@ +import { StringDecoder } from 'node:string_decoder' +import type { Writable } from 'node:stream' +import type { AgentSessionModelOption } from '../../shared/agent-session/agent-session-wire' +import type { CommitMessageModel } from '../../shared/source-control/ai/generation/commit-message-agent-spec' +import { createIncrementalNdjsonFramer } from '../../shared/main-process-ndjson-framer' +import { createCodexAppServerRecordDispatcher } from '../codex/app-server/codex-app-server-record-dispatch' +import { isProviderRecord } from '../provider-process/provider-json-record' +import { listCodexModelPages } from '../codex/structured/catalog/codex-structured-model-catalog' +import type { AgentModelProbeSpec } from '../../shared/agent-model-probe-spec' +import { discoveredModelsResult } from './commit-message-model-discovery-policy' +import type { + DiscoverCommitMessageModelsResult, + SpawnedSourceControlAgentProcess +} from './source-control-text-generation-types' + +const APP_SERVER_EXIT_GRACE_MS = 1_500 + +export type CodexModelListDiscovery = { + /** Feed raw stdout; the caller owns the byte budget. */ + receive: (chunk: Buffer) => void + /** Rejects every waiting request, e.g. once the process closed. */ + fail: (error: Error) => void + /** Visible models, or null when the listing was incomplete or empty. */ + models: Promise +} + +// The default must be one of the listed levels; Codex's own default is low. +function listedDefaultEffort(model: AgentSessionModelOption): string { + const listed = model.efforts.map((effort) => effort.value) + return ( + [model.defaultEffort, 'low'].find((effort) => effort && listed.includes(effort)) ?? listed[0] + ) +} + +/** `model/list` over an app-server child the caller spawned, owns and stops. */ +export function startCodexModelListDiscovery(stdin: Writable): CodexModelListDiscovery { + let nextRequestId = 1 + let failure: Error | null = null + const write = (payload: Record): void => { + stdin.write(`${JSON.stringify(payload)}\n`) + } + const fail = (error: Error): void => { + failure ??= error + dispatcher.failPending(error) + } + const dispatcher = createCodexAppServerRecordDispatcher({ + handlers: {}, + writeResponse: (payload) => { + try { + write(payload) + } catch { + // A closed stdin fails the next request. + } + }, + onProtocolFailure: fail + }) + const decoder = new StringDecoder('utf8') + const framer = createIncrementalNdjsonFramer( + (record) => { + if (isProviderRecord(record)) { + dispatcher.dispatch(record) + } + }, + (rejected) => { + if (rejected.kind === 'line-too-long') { + dispatcher.rejectOversized(rejected) + } + } + ) + const request = (method: string, params?: Record): Promise => + failure + ? Promise.reject(failure) + : new Promise((resolve, reject) => { + const id = nextRequestId++ + // The caller's process deadline bounds every request. + dispatcher.addPending(id, { method, resolve, reject, timer: undefined }) + try { + write(params === undefined ? { method, id } : { method, id, params }) + } catch (error) { + dispatcher.deletePending(id) + reject(error instanceof Error ? error : new Error(String(error))) + } + }) + + const models = (async (): Promise => { + await request('initialize', { + clientInfo: { name: 'orca_desktop', title: 'Orca', version: '0.0.0' } + }) + write({ method: 'initialized' }) + const listing = await listCodexModelPages((params) => request('model/list', params)) + if (!listing.complete || listing.models.length === 0) { + return null + } + return listing.models.map((model) => ({ + id: model.id, + label: model.label, + ...(model.description ? { description: model.description } : {}), + ...(model.efforts.length + ? { + thinkingLevels: model.efforts.map((effort) => ({ + id: effort.value, + label: effort.label + })), + defaultThinkingLevel: listedDefaultEffort(model) + } + : {}), + ...(model.isDefault ? { isDefault: true } : {}) + })) + })() + + return { + receive: (chunk) => { + try { + framer.feed(decoder.write(chunk)) + } catch (error) { + fail(error instanceof Error ? error : new Error(String(error))) + } + }, + fail, + models + } +} + +/** Settles discovery from the listing, then ends the app-server, which would otherwise wait on stdin + * forever. Codex rewrites its shared models cache at startup, so stdin EOF gets a grace before any kill. */ +export function settleCodexModelListing(input: { + listing: CodexModelListDiscovery + spec: AgentModelProbeSpec + child: SpawnedSourceControlAgentProcess + isSettled: () => boolean + stop: () => void + finish: (result: DiscoverCommitMessageModelsResult) => void +}): void { + const { child, spec } = input + let exited = false + child.once('exit', () => { + exited = true + }) + const endAppServer = (): void => { + try { + child.stdin?.end() + } catch { + // A destroyed stdin still leaves the kill below. + } + if (exited) { + return + } + const grace = setTimeout(input.stop, APP_SERVER_EXIT_GRACE_MS) + child.once('exit', () => clearTimeout(grace)) + } + void input.listing.models.then( + (models) => { + if (input.isSettled()) { + return + } + endAppServer() + input.finish( + models + ? discoveredModelsResult(spec, models) + : { success: false, error: `${spec.label} returned an incomplete model list.` } + ) + }, + (error: unknown) => { + if (input.isSettled()) { + return + } + endAppServer() + console.error('[commit-message] Model discovery failed:', error) + input.finish({ + success: false, + error: `${spec.label} model discovery failed. Check the agent CLI configuration and try again.` + }) + } + ) +} diff --git a/src/main/text-generation/commit-message-model-discovery-policy.ts b/src/main/text-generation/commit-message-model-discovery-policy.ts index 5a18527cb1f..1c4f8d4d5fa 100644 --- a/src/main/text-generation/commit-message-model-discovery-policy.ts +++ b/src/main/text-generation/commit-message-model-discovery-policy.ts @@ -1,4 +1,6 @@ import { buildClaudeModelListArgs } from '../../shared/claude-model-list-probe' +import type { CommitMessageModel } from '../../shared/source-control/ai/generation/commit-message-agent-spec' +import { CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS } from '../codex-cli/codex-read-only-app-server-args' import type { CommandTemplateBackslash } from '../../shared/source-control/ai/generation/commit-message-prompt' import type { CommitMessagePlan } from '../../shared/source-control/ai/generation/commit-message-plan' import { planAgentBinary } from '../../shared/agent-launch/startup/agent-command-plan' @@ -45,10 +47,21 @@ export function finalizeModelDiscoveryOutput( error: formatAgentCliFailureMessage(spec.label, stdout, stderr, code) } } - let models = spec.modelDiscovery?.parse(stdout) ?? [] + const parse = + spec.modelDiscovery && 'parse' in spec.modelDiscovery ? spec.modelDiscovery.parse : null + let models = parse?.(stdout) ?? [] if (models.length === 0 && stderr.trim()) { - models = spec.modelDiscovery?.parse(stderr) ?? [] + models = parse?.(stderr) ?? [] } + return discoveredModelsResult(spec, models) +} + +/** Wraps a probe's models, falling back to the spec's list when it found none. */ +export function discoveredModelsResult( + spec: AgentModelProbeSpec, + discovered: CommitMessageModel[] +): DiscoverCommitMessageModelsResult { + let models = discovered if (models.length === 0) { if (spec.models.length > 0) { console.warn('[commit-message] Model discovery returned no models; using static fallback:', { @@ -87,15 +100,17 @@ export function planModelDiscovery( return command } const args = - spec.id === 'claude' - ? buildClaudeModelListArgs(strictMcp, command.prefixArgs) - : modelDiscovery.args + 'listing' in modelDiscovery + ? CODEX_SHORT_LIVED_PROBE_APP_SERVER_ARGS + : spec.id === 'claude' + ? buildClaudeModelListArgs(strictMcp, command.prefixArgs) + : modelDiscovery.args return { ok: true, plan: { binary: command.binary, args: [...command.prefixArgs, ...args], - stdinPayload: modelDiscovery.stdinPayload ?? null, + stdinPayload: 'stdinPayload' in modelDiscovery ? (modelDiscovery.stdinPayload ?? null) : null, label: spec.label, ...(command.env ? { env: command.env } : {}) } diff --git a/src/main/text-generation/commit-message-model-discovery.ts b/src/main/text-generation/commit-message-model-discovery.ts index 22146fe06a9..636320651e9 100644 --- a/src/main/text-generation/commit-message-model-discovery.ts +++ b/src/main/text-generation/commit-message-model-discovery.ts @@ -23,6 +23,12 @@ import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from './source-control-generation-limits' import { runCodexProcessWithHomeLock } from './source-control-local-generation' +import { formatAgentCliFailureMessage } from './source-control-agent-failure' +import { + settleCodexModelListing, + startCodexModelListDiscovery, + type CodexModelListDiscovery +} from './codex-model-list-discovery' import { killSourceControlAgentProcess } from './source-control-local-process' import type { DiscoverCommitMessageModelsResult, @@ -99,6 +105,8 @@ async function discoverModelsOnce( : {}), error: couldNotStart }) + // The app-server answers `model/list` over the stdin it must keep open. + const appServer = spec.modelDiscovery !== undefined && 'listing' in spec.modelDiscovery const startDiscovery = (): LocalProcessExecution => { let markProcessClosed!: () => void const processClosed = new Promise((resolve) => { @@ -106,6 +114,7 @@ async function discoverModelsOnce( }) const result = new Promise((resolve) => { let child: SpawnedSourceControlAgentProcess + let listing: CodexModelListDiscovery | null = null try { child = input.spawnAgent({ binary, @@ -114,10 +123,14 @@ async function discoverModelsOnce( env: input.options.wslDistro ? input.env : env, commandEnv: plan.env, wslDistro: input.options.wslDistro, - stdinMode: plan.stdinPayload === null ? 'ignore' : 'pipe', + stdinMode: plan.stdinPayload === null && !appServer ? 'ignore' : 'pipe', useCwdForNative: false }) - if (plan.stdinPayload !== null) { + if (appServer && child.stdin) { + const stdin = child.stdin + listing = startCodexModelListDiscovery(stdin) + stdin.on('error', (error) => listing?.fail(error)) + } else if (plan.stdinPayload !== null) { child.stdin?.on?.('error', () => {}) child.stdin?.end(plan.stdinPayload) } @@ -129,6 +142,8 @@ async function discoverModelsOnce( } let stdout = '' + // Count bytes read from both streams; the budget bounds raw input, not retained text. + let outputBytes = 0 let stderr = '' let outputLimitExceeded = false let settled = false @@ -151,6 +166,8 @@ async function discoverModelsOnce( timer = null } detachChildListeners() + // Waiting listing requests have no timers of their own. + listing?.fail(new Error(`${spec.label} model discovery ended`)) if (input.agentId !== 'codex') { markProcessClosed() } @@ -165,10 +182,8 @@ async function discoverModelsOnce( }, SOURCE_CONTROL_GENERATION_TIMEOUT_MS) const onData = (chunk: Buffer, append: (text: string) => void): void => { - if ( - stdout.length + stderr.length + chunk.byteLength > - MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES - ) { + outputBytes += chunk.byteLength + if (outputBytes > MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES) { outputLimitExceeded = true startTermination() finish({ success: false, error: `${spec.label} returned too much model data.` }) @@ -176,7 +191,10 @@ async function discoverModelsOnce( } append(chunk.toString('utf-8')) } - const onStdoutData = (chunk: Buffer): void => onData(chunk, (text) => (stdout += text)) + const onStdoutData = (chunk: Buffer): void => + listing + ? onData(chunk, () => listing?.receive(chunk)) + : onData(chunk, (text) => (stdout += text)) const onStderrData = (chunk: Buffer): void => onData(chunk, (text) => (stderr += text)) const onError = (error: Error): void => { if (!child.pid) { @@ -195,6 +213,7 @@ async function discoverModelsOnce( } const onClose = (code: number | null): void => { markClosedAfterTermination() + listing?.fail(new Error(`${spec.label} app-server exited`)) const spawnFailure = outputLimitExceeded ? null : supervisedProviderSpawnFailure(code, stderr) @@ -213,9 +232,32 @@ async function discoverModelsOnce( finish( outputLimitExceeded ? { success: false, error: `${spec.label} returned too much model data.` } - : finalizeModelDiscoveryOutput(spec, stdout, stderr, code) + : listing + ? listingFailure(code) + : finalizeModelDiscoveryOutput(spec, stdout, stderr, code) ) } + const listingFailure = (code: number | null): DiscoverCommitMessageModelsResult => { + console.error('[commit-message] Model discovery failed:', { + label: spec.label, + exitCode: code, + stderr + }) + return { + success: false, + error: formatAgentCliFailureMessage(spec.label, '', stderr, code) + } + } + if (listing) { + settleCodexModelListing({ + listing, + spec, + child, + isSettled: () => settled, + stop: startTermination, + finish + }) + } child.stdout?.on('data', onStdoutData) child.stderr?.on('data', onStderrData) if (input.agentId === 'codex') { diff --git a/src/main/text-generation/commit-message-text-generation-cancellation.test.ts b/src/main/text-generation/commit-message-text-generation-cancellation.test.ts index bcd900a3728..e48b5ed84a1 100644 --- a/src/main/text-generation/commit-message-text-generation-cancellation.test.ts +++ b/src/main/text-generation/commit-message-text-generation-cancellation.test.ts @@ -10,6 +10,7 @@ import { generatePullRequestFieldsFromContext } from './commit-message-text-generation' import { + answerCodexAppServer, createChildTerminationExpectation, createMockDiscoveryChild, spawnedAgentArgv, @@ -627,12 +628,11 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', () }) expect(generationSpawns()).toHaveLength(1) - discoveryChild.stdout.emit( - 'data', - Buffer.from(JSON.stringify({ models: [{ slug: 'gpt-5.5', display_name: 'GPT-5.5' }] })) - ) - discoveryChild.emit('close', 0) + answerCodexAppServer(discoveryChild, [ + { data: [{ id: 'gpt-5.5', model: 'gpt-5.5', displayName: 'GPT-5.5' }], nextCursor: null } + ]) await expect(blocker).resolves.toMatchObject({ success: true }) + discoveryChild.emit('close', 0) const later = generateCommitMessageFromContext( { branch: 'main', stagedSummary: 'M\tREADME.md', stagedPatch: '+later' }, diff --git a/src/main/text-generation/commit-message-text-generation-model-discovery.test.ts b/src/main/text-generation/commit-message-text-generation-model-discovery.test.ts index 46ec400d597..98e2782de8b 100644 --- a/src/main/text-generation/commit-message-text-generation-model-discovery.test.ts +++ b/src/main/text-generation/commit-message-text-generation-model-discovery.test.ts @@ -3,9 +3,11 @@ import type * as ChildProcess from 'node:child_process' import type * as CliCommandResolution from '../../shared/node-cli-command-resolution' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { discoverCommitMessageModelsLocal } from './commit-message-text-generation' +import agentPickerCliRecordings from '../../shared/fixtures/agent-picker-cli-recordings.json' import { PROVIDER_SPAWN_FAILURE_MARKER } from '../provider-process/provider-spawn-failure-report' import { createChildTerminationExpectation, + answerCodexAppServer, createMockDiscoveryChild, spawnedAgentArgv, withPlatform @@ -35,6 +37,13 @@ vi.mock('child_process', async (importOriginal) => { const spawnMock = vi.mocked(spawn) +function spawnChildren(...children: ReturnType[]): void { + for (const child of children) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: discovery reads only the pid, kill, stdio streams and events the mock child implements. + spawnMock.mockReturnValueOnce(child as unknown as ReturnType) + } +} + function spawnError(errno: string): Error { return Object.assign(new Error(`spawn claude ${errno}`), { code: errno }) } @@ -336,6 +345,113 @@ describe('discoverCommitMessageModelsLocal on the Windows direct-child path', () } }) + it('lists Codex models from app-server model/list without hidden rows, then releases the home once it stops', async () => { + vi.useFakeTimers() + const child = createMockDiscoveryChild() + const nextChild = createMockDiscoveryChild() + spawnChildren(child, nextChild) + const env = { CODEX_HOME: '/managed/codex-model-list-home' } + answerCodexAppServer(child, [ + { data: agentPickerCliRecordings.modelList.data, nextCursor: 'page-2' }, + { + data: [ + { + id: 'codex-auto-review', + model: 'codex-auto-review', + displayName: 'Codex Auto Review', + hidden: true + } + ], + nextCursor: null + } + ]) + + try { + const first = discoverCommitMessageModelsLocal('codex', env) + await vi.advanceTimersByTimeAsync(0) + await expect(first).resolves.toEqual({ + success: true, + catalogOrigin: 'probe', + defaultModelId: 'gpt-5.6-sol', + capability: expect.objectContaining({ defaultModelId: 'gpt-5.6-sol' }), + models: [ + { + id: 'gpt-5.6-sol', + label: 'GPT-5.6-Sol', + description: 'Latest frontier agentic coding model.', + thinkingLevels: [ + { id: 'low', label: 'Low' }, + { id: 'medium', label: 'Medium' }, + { id: 'high', label: 'High' }, + { id: 'xhigh', label: 'Extra high' }, + { id: 'max', label: 'Max' }, + { id: 'ultra', label: 'Ultra' } + ], + defaultThinkingLevel: 'low', + isDefault: true + } + ] + }) + expect(spawnedAgentArgv(spawnMock.mock.calls[0])).toContain('app-server') + expect(child.stdin.end).toHaveBeenCalled() + + // A different command shares the home lock but not the cached listing. + const next = discoverCommitMessageModelsLocal('codex', env, 'codex') + await vi.advanceTimersByTimeAsync(1_499) + expect(child.kill).not.toHaveBeenCalled() + expect(spawnMock).toHaveBeenCalledTimes(1) + // A child that ignores stdin EOF is stopped after the grace; its exit frees the home. + await vi.advanceTimersByTimeAsync(1) + await expectChildTerminated(child) + child.emit('exit', null, 'SIGKILL') + await vi.advanceTimersByTimeAsync(0) + expect(spawnMock).toHaveBeenCalledTimes(2) + + answerCodexAppServer(nextChild, [ + { data: [{ id: 'gpt-5.5', model: 'gpt-5.5', displayName: 'GPT-5.5' }], nextCursor: null } + ]) + await vi.advanceTimersByTimeAsync(0) + await expect(next).resolves.toMatchObject({ success: true, defaultModelId: 'gpt-5.5' }) + // An app-server that exits on stdin EOF is never killed. + nextChild.emit('exit', 0, null) + await vi.advanceTimersByTimeAsync(2_000) + expect(nextChild.kill).not.toHaveBeenCalled() + } finally { + vi.useRealTimers() + } + }) + + it('lists again for a different Codex home when Windows env names differ only in case', async () => { + const listing = { + data: [{ id: 'gpt-5.5', model: 'gpt-5.5', displayName: 'GPT-5.5' }], + nextCursor: null + } + for (const home of ['C:\\accounts\\a', 'C:\\accounts\\b']) { + const child = createMockDiscoveryChild() + spawnChildren(child) + answerCodexAppServer(child, [listing]) + await expect( + discoverCommitMessageModelsLocal('codex', { codex_home: 'C:\\shell', CODEX_HOME: home }) + ).resolves.toMatchObject({ success: true }) + child.emit('exit', 0, null) + } + expect(spawnMock).toHaveBeenCalledTimes(2) + }) + + it.each([ + ['an unsupported model/list', { rpcError: { code: -32601, message: 'Method not found' } }], + ['an unreadable page', { data: 'not-a-list', nextCursor: null }] + ])('keeps the built-in Codex list when the app-server returns %s', async (name, page) => { + const child = createMockDiscoveryChild() + spawnChildren(child) + answerCodexAppServer(child, [page]) + + await expect( + discoverCommitMessageModelsLocal('codex', { CODEX_HOME: `/managed/codex-${name}` }) + ).resolves.toMatchObject({ success: false }) + child.emit('exit', 0, null) + }) + it('keeps the Codex home locked after a discovery timeout until the child closes', async () => { vi.useFakeTimers() const firstChild = createMockDiscoveryChild() @@ -346,7 +462,8 @@ describe('discoverCommitMessageModelsLocal on the Windows direct-child path', () try { const first = discoverCommitMessageModelsLocal('codex', env) await vi.advanceTimersByTimeAsync(0) - const second = discoverCommitMessageModelsLocal('codex', env) + // A different command shares the home lock but not the in-flight listing. + const second = discoverCommitMessageModelsLocal('codex', env, 'codex') await vi.advanceTimersByTimeAsync(60_000) await expect(first).resolves.toMatchObject({ @@ -359,15 +476,9 @@ describe('discoverCommitMessageModelsLocal on the Windows direct-child path', () firstChild.emit('close', null) await vi.advanceTimersByTimeAsync(0) expect(spawnMock).toHaveBeenCalledTimes(2) - secondChild.stdout.emit( - 'data', - Buffer.from( - JSON.stringify({ - models: [{ slug: 'gpt-5.5', display_name: 'GPT-5.5' }] - }) - ) - ) - secondChild.emit('close', 0) + answerCodexAppServer(secondChild, [ + { data: [{ id: 'gpt-5.5', model: 'gpt-5.5', displayName: 'GPT-5.5' }], nextCursor: null } + ]) await expect(second).resolves.toMatchObject({ success: true, defaultModelId: 'gpt-5.5' @@ -387,7 +498,8 @@ describe('discoverCommitMessageModelsLocal on the Windows direct-child path', () try { const first = discoverCommitMessageModelsLocal('codex', env) await vi.advanceTimersByTimeAsync(0) - const second = discoverCommitMessageModelsLocal('codex', env) + // A different command shares the home lock but not the in-flight listing. + const second = discoverCommitMessageModelsLocal('codex', env, 'codex') await vi.advanceTimersByTimeAsync(60_000) await expect(first).resolves.toMatchObject({ success: false }) expect(spawnMock).toHaveBeenCalledTimes(1) @@ -397,15 +509,9 @@ describe('discoverCommitMessageModelsLocal on the Windows direct-child path', () await vi.advanceTimersByTimeAsync(0) expect(spawnMock).toHaveBeenCalledTimes(2) - secondChild.stdout.emit( - 'data', - Buffer.from( - JSON.stringify({ - models: [{ slug: 'gpt-5.5', display_name: 'GPT-5.5' }] - }) - ) - ) - secondChild.emit('close', 0) + answerCodexAppServer(secondChild, [ + { data: [{ id: 'gpt-5.5', model: 'gpt-5.5', displayName: 'GPT-5.5' }], nextCursor: null } + ]) await expect(second).resolves.toMatchObject({ success: true, defaultModelId: 'gpt-5.5' diff --git a/src/main/text-generation/commit-message-text-generation-test-harness.ts b/src/main/text-generation/commit-message-text-generation-test-harness.ts index 57194b937fd..948fb2e80c9 100644 --- a/src/main/text-generation/commit-message-text-generation-test-harness.ts +++ b/src/main/text-generation/commit-message-text-generation-test-harness.ts @@ -1,5 +1,6 @@ import { ChildProcess } from 'node:child_process' import { PassThrough } from 'node:stream' +import { isProviderRecord } from '../provider-process/provider-json-record' import { expect, vi } from 'vitest' export type MockDiscoveryChild = ChildProcess & { @@ -26,6 +27,32 @@ export function createMockDiscoveryChild(): MockDiscoveryChild { }) } +/** Answers initialize, then each `model/list` with the next page (`{ rpcError }` replies an error), as a Codex app-server child. */ +export function answerCodexAppServer( + child: { stdin: NodeJS.EventEmitter; stdout: NodeJS.EventEmitter }, + pages: unknown[] +): void { + let page = 0 + child.stdin.on('data', (chunk: Buffer) => { + for (const line of chunk.toString('utf8').split('\n').filter(Boolean)) { + const message: unknown = JSON.parse(line) + if (isProviderRecord(message) && typeof message.id === 'number') { + const answer = message.method === 'model/list' ? pages[page++] : {} + const error = isProviderRecord(answer) ? answer.rpcError : undefined + const reply = Buffer.from( + `${JSON.stringify(error ? { id: message.id, error } : { id: message.id, result: answer })}\n` + ) + // Real streams may be piped onward by the spawner; plain emitters only have listeners. + if (child.stdout instanceof PassThrough) { + child.stdout.write(reply) + } else { + child.stdout.emit('data', reply) + } + } + } + }) +} + export function withPlatform(platform: NodeJS.Platform, fn: () => T): T { const original = process.platform Object.defineProperty(process, 'platform', { configurable: true, value: platform }) diff --git a/src/main/text-generation/model-discovery-host-cache.ts b/src/main/text-generation/model-discovery-host-cache.ts index 762a5c4456a..96f82eac7ad 100644 --- a/src/main/text-generation/model-discovery-host-cache.ts +++ b/src/main/text-generation/model-discovery-host-cache.ts @@ -7,11 +7,12 @@ import type { CommitMessageModelDiscoveryLocalOptions } from './commit-message-m import { SOURCE_CONTROL_GENERATION_TIMEOUT_MS } from './source-control-generation-limits' import type { DiscoverCommitMessageModelsResult } from './source-control-text-generation-types' -// Phone and desktop chat pickers list these on open; other agents' lists have their own catalog owners. -// Each maps to the config-dir var that picks its login (mirrors prepareShellConfigDirEnv). +// Pickers list these on open; Codex's listing starts an app-server. Each maps to the config-dir var +// that picks its login (mirrors prepareShellConfigDirEnv). const ACCOUNT_DIR_VAR: Partial> = { omp: PRIMARY_AGENT_DIR_ENV_BY_KIND.omp, - grok: 'GROK_HOME' + grok: 'GROK_HOME', + codex: 'CODEX_HOME' } const TTL_MS = 10 * 60_000 const MAX_ENTRIES = 32 @@ -29,6 +30,17 @@ onAgentsRefreshedOnHost(() => { inFlight.clear() }) +// Windows environment names ignore case; like Node's spawn, the lexicographically first spelling wins. +function accountDir(env: NodeJS.ProcessEnv | undefined, name: string): string | null { + const key = + process.platform === 'win32' + ? Object.keys(env ?? {}) + .filter((entry) => entry.toUpperCase() === name) + .sort()[0] + : name + return (key && env?.[key]) ?? null +} + export type ModelDiscoveryCacheInput = { agentId: TuiAgent agentCommandOverride: string | undefined @@ -36,7 +48,7 @@ export type ModelDiscoveryCacheInput = { options: CommitMessageModelDiscoveryLocalOptions } -/** Runs the probe; a probe-confirmed OMP or Grok list is reused for 10 min. */ +/** Runs the probe; a probe-confirmed OMP, Grok or Codex list is reused for 10 min. */ export function discoverModelsWithHostCache( input: ModelDiscoveryCacheInput, probe: () => Promise @@ -52,7 +64,8 @@ export function discoverModelsWithHostCache( input.agentId, input.agentCommandOverride ?? null, wslDistro ? { cwd: cwd ?? '', wslDistro } : null, - input.env?.[accountDirVar] ?? null + // Why: a native probe without an env spawns with process.env; a WSL guest's env isn't ours to read. + accountDir(input.env ?? (wslDistro ? undefined : process.env), accountDirVar) ]) const cached = cache.get(key) if (cached && cached.expiresAt > Date.now()) { diff --git a/src/main/text-generation/source-control-local-process.test.ts b/src/main/text-generation/source-control-local-process.test.ts index 10ccd1133f5..6f1935eb202 100644 --- a/src/main/text-generation/source-control-local-process.test.ts +++ b/src/main/text-generation/source-control-local-process.test.ts @@ -1,5 +1,8 @@ import * as supervisedStop from '../provider-process/supervised-child-process-stop' -import { createMockDiscoveryChild } from './commit-message-text-generation-test-harness' +import { + answerCodexAppServer, + createMockDiscoveryChild +} from './commit-message-text-generation-test-harness' import { MAX_SOURCE_CONTROL_AGENT_OUTPUT_BYTES, SOURCE_CONTROL_GENERATION_TIMEOUT_MS @@ -7,6 +10,7 @@ import { import { cancelLocalGeneration } from './source-control-generation-lanes' import { generateConversationName } from './conversation-name-generation-request' import { EventEmitter } from 'node:events' +import { PassThrough } from 'node:stream' import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -60,12 +64,12 @@ function fakeSupervisor(exitsOn: NodeJS.Signals | null): FakeSupervisor { function fakeSupervisedAgent(stopMs: number): FakeSupervisor & { stdout: EventEmitter stderr: EventEmitter - stdin: { on: () => void; end: () => void } + stdin: PassThrough } { const child = Object.assign(fakeSupervisor(null), { stdout: new EventEmitter(), stderr: new EventEmitter(), - stdin: { on: vi.fn(), end: vi.fn() } + stdin: Object.assign(new PassThrough(), { end: vi.fn() }) }) child.kill.mockImplementation((signal?: NodeJS.Signals) => { if (signal === 'SIGTERM') { @@ -381,11 +385,9 @@ describe('a supervised Codex model discovery that runs out of time', () => { await vi.advanceTimersByTimeAsync(1) expect(spawnAgent).toHaveBeenCalledTimes(2) - agents[1]!.stdout.emit( - 'data', - Buffer.from(JSON.stringify({ models: [{ slug: 'gpt-5.5', display_name: 'GPT-5.5' }] })) - ) - agents[1]!.emit('close', 0) + answerCodexAppServer(agents[1]!, [ + { data: [{ id: 'gpt-5.5', model: 'gpt-5.5', displayName: 'GPT-5.5' }], nextCursor: null } + ]) await expect(second).resolves.toMatchObject({ success: true }) expect(agents[0]!.kill).not.toHaveBeenCalledWith('SIGKILL') expect(terminateTreeMock).not.toHaveBeenCalled() @@ -528,7 +530,15 @@ setInterval(() => {}, 60000) const lists = join(folder, 'lists.cjs') writeFileSync( lists, - "console.log(JSON.stringify({ models: [{ slug: 'gpt-5.5', display_name: 'GPT-5.5' }] }))\n" + `require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => { + const message = JSON.parse(line) + if (message.id === undefined) return + const result = message.method === 'model/list' + ? { data: [{ id: 'gpt-5.5', model: 'gpt-5.5', displayName: 'GPT-5.5' }], nextCursor: null } + : {} + console.log(JSON.stringify({ id: message.id, result })) +}) +` ) const floodAliveAtSecondSpawn: boolean[] = [] const spawnAgent = vi.fn((input: Parameters[0]) => { diff --git a/src/main/wsl/host-lifecycle/wsl-host-service-instance.ts b/src/main/wsl/host-lifecycle/wsl-host-service-instance.ts index bfbd1d1a626..be6db00b4df 100644 --- a/src/main/wsl/host-lifecycle/wsl-host-service-instance.ts +++ b/src/main/wsl/host-lifecycle/wsl-host-service-instance.ts @@ -8,8 +8,24 @@ export function getWslHostService(): WslHostService | null { return instance } +const statusListeners = new Set<() => void>() +let stopForwardingStatuses: (() => void) | null = null + export function setWslHostService(service: WslHostService | null): void { + stopForwardingStatuses?.() instance = service + stopForwardingStatuses = + service?.onStatusesChanged(() => { + for (const listener of statusListeners) { + listener() + } + }) ?? null +} + +/** Statuses of whichever service is installed, now or later. */ +export function onWslHostStatusesChanged(listener: () => void): () => void { + statusListeners.add(listener) + return () => statusListeners.delete(listener) } let phoneGate: WslHostPhoneGate | null = null diff --git a/src/packages/process-host/src/spawn-process-stdio.test.ts b/src/packages/process-host/src/spawn-process-stdio.test.ts deleted file mode 100644 index 501e0c5d63c..00000000000 --- a/src/packages/process-host/src/spawn-process-stdio.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { once } from 'node:events' -import { describe, expect, expectTypeOf, it } from 'vitest' -import { spawnProcess } from '@orca/process-host' -import type { ChildProcess, ChildProcessWithoutNullStreams } from 'node:child_process' -import type { ProcessSpec } from './process-spec' - -async function waitForClose(child: ChildProcess): Promise { - try { - await once(child, 'close', { signal: AbortSignal.timeout(5_000) }) - } finally { - if (child.exitCode === null && child.signalCode === null) { - const closing = once(child, 'close', { signal: AbortSignal.timeout(1_000) }) - child.kill('SIGKILL') - await closing - } - } -} - -describe('public spawn stream contracts', () => { - it('returns three pipes by default', async () => { - const child = spawnProcess({ program: process.execPath, args: ['-e', ''] }) - expectTypeOf(child).toEqualTypeOf() - await waitForClose(child) - expect(child.stdin).not.toBeNull() - expect(child.stdout).not.toBeNull() - expect(child.stderr).not.toBeNull() - }) - - it('returns three pipes for an explicit pipe mode', async () => { - const child = spawnProcess({ program: process.execPath, args: ['-e', ''], stdio: 'pipe' }) - expectTypeOf(child).toEqualTypeOf() - await waitForClose(child) - expect(child.stdin).not.toBeNull() - expect(child.stdout).not.toBeNull() - expect(child.stderr).not.toBeNull() - }) - - it('returns three pipes for an explicit pipe tuple', async () => { - const child = spawnProcess({ - program: process.execPath, - args: ['-e', ''], - stdio: ['pipe', 'pipe', 'pipe'] - }) - expectTypeOf(child).toEqualTypeOf() - await waitForClose(child) - expect(child.stdin).not.toBeNull() - expect(child.stdout).not.toBeNull() - expect(child.stderr).not.toBeNull() - }) - - it('keeps three pipes when the tuple adds an IPC channel', async () => { - const child = spawnProcess({ - program: process.execPath, - args: ['-e', 'process.disconnect()'], - stdio: ['pipe', 'pipe', 'pipe', 'ipc'] - }) - expectTypeOf(child).toEqualTypeOf() - await waitForClose(child) - expect(child.stdin).not.toBeNull() - expect(child.stdout).not.toBeNull() - expect(child.stderr).not.toBeNull() - }) - - it.each(['ignore', 'inherit'] as const)('returns nullable streams for %s', async (stdio) => { - const child = spawnProcess({ program: process.execPath, args: ['-e', ''], stdio }) - expectTypeOf(child).toEqualTypeOf() - await waitForClose(child) - expect(child.stdin).toBeNull() - expect(child.stdout).toBeNull() - expect(child.stderr).toBeNull() - }) - - it('does not promise a stdin pipe when only the output slots are piped', async () => { - const child = spawnProcess({ - program: process.execPath, - args: ['-e', ''], - stdio: ['ignore', 'pipe', 'pipe'] - }) - expectTypeOf(child).toEqualTypeOf() - await waitForClose(child) - expect(child.stdin).toBeNull() - expect(child.stdout).not.toBeNull() - expect(child.stderr).not.toBeNull() - }) - - it('keeps the general contract when the specification does not guarantee pipes', async () => { - const spec: ProcessSpec = { program: process.execPath, args: ['-e', ''] } - const child = spawnProcess(spec) - expectTypeOf(child).toEqualTypeOf() - await waitForClose(child) - }) -}) diff --git a/src/preload/api/ephemeral-vm-api.ts b/src/preload/api/ephemeral-vm-api.ts index 0b83d3f7157..f1aca3ee2f6 100644 --- a/src/preload/api/ephemeral-vm-api.ts +++ b/src/preload/api/ephemeral-vm-api.ts @@ -4,9 +4,11 @@ import type { EphemeralVmRecipeDoctorResult } from '../../shared/ephemeral-vm-re import type { EphemeralVmRecipeResultWarning } from '../../shared/ephemeral-vm-recipe-diagnostics' import type { EphemeralVmProvisionedRuntimeRecord, - EphemeralVmRuntimeRecord + EphemeralVmRuntimeRecord, + EphemeralVmWorkspaceLifecycleResult } from '../../shared/ephemeral-vm-runtimes' import type { EphemeralVmFailure } from '../../shared/ephemeral-vm-failure-copy' +import type { PendingVmCheckout } from '../../shared/pending-vm-checkouts' export type EphemeralVmApi = { listRecipes: (args: { repoId: string }) => Promise<{ @@ -68,7 +70,11 @@ export type EphemeralVmApi = { runtimeId: string workspaceId: string }) => Promise - resumeWorkspace: (args: { workspaceId: string }) => Promise + resumeWorkspace: (args: { workspaceId: string }) => Promise + /** Suspends the workspace's VM without closing panels; sleep closes them first. */ + suspendWorkspace: (args: { workspaceId: string }) => Promise + /** Fires after any runtime record write; re-list to read the new lifecycle status. */ + onRuntimesChanged: (callback: () => void) => () => void cleanup: (args: { runtimeId: string }) => Promise stopCleanup: (args: { runtimeId: string }) => Promise /** Drops an interrupted write-ahead record that never received a recipe result. */ @@ -80,4 +86,9 @@ export type EphemeralVmApi = { cleanupDisabled: boolean message?: string }> + /** This window's VM checkouts whose creates have not adopted them yet; replaces its last set. */ + publishPendingCheckouts: (checkouts: PendingVmCheckout[]) => void + listPendingCheckouts: () => Promise + /** Every window's pending VM checkouts, whenever any window's set changes. */ + onPendingCheckoutsChanged: (callback: (checkouts: PendingVmCheckout[]) => void) => () => void } diff --git a/src/preload/api/ephemeral-vm-bridge.ts b/src/preload/api/ephemeral-vm-bridge.ts index ee9748e499d..2eb8372bb79 100644 --- a/src/preload/api/ephemeral-vm-bridge.ts +++ b/src/preload/api/ephemeral-vm-bridge.ts @@ -1,5 +1,10 @@ import { ipcRenderer } from 'electron' import type { PreloadApi } from '../api-types' +import { EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL } from '../../shared/ephemeral-vm-runtime-store-events' +import { + PENDING_VM_CHECKOUTS_CHANGED_CHANNEL, + type PendingVmCheckout +} from '../../shared/pending-vm-checkouts' export const ephemeralVmApi = { listRecipes: (args) => ipcRenderer.invoke('ephemeralVm:listRecipes', args), @@ -18,8 +23,24 @@ export const ephemeralVmApi = { listRuntimes: () => ipcRenderer.invoke('ephemeralVm:listRuntimes'), attachWorkspace: (args) => ipcRenderer.invoke('ephemeralVm:attachWorkspace', args), resumeWorkspace: (args) => ipcRenderer.invoke('ephemeralVm:resumeWorkspace', args), + suspendWorkspace: (args) => ipcRenderer.invoke('ephemeralVm:suspendWorkspace', args), + onRuntimesChanged: (callback) => { + const listener = (): void => callback() + ipcRenderer.on(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, listener) + return () => ipcRenderer.removeListener(EPHEMERAL_VM_RUNTIMES_CHANGED_CHANNEL, listener) + }, cleanup: (args) => ipcRenderer.invoke('ephemeralVm:cleanup', args), stopCleanup: (args) => ipcRenderer.invoke('ephemeralVm:stopCleanup', args), forgetRuntime: (args) => ipcRenderer.invoke('ephemeralVm:forgetRuntime', args), - getCleanupCommand: (args) => ipcRenderer.invoke('ephemeralVm:getCleanupCommand', args) + getCleanupCommand: (args) => ipcRenderer.invoke('ephemeralVm:getCleanupCommand', args), + publishPendingCheckouts: (checkouts) => { + void ipcRenderer.invoke('ephemeralVm:publishPendingCheckouts', checkouts).catch(() => {}) + }, + listPendingCheckouts: () => ipcRenderer.invoke('ephemeralVm:listPendingCheckouts'), + onPendingCheckoutsChanged: (callback) => { + const listener = (_event: Electron.IpcRendererEvent, checkouts: PendingVmCheckout[]): void => + callback(checkouts) + ipcRenderer.on(PENDING_VM_CHECKOUTS_CHANGED_CHANNEL, listener) + return () => ipcRenderer.removeListener(PENDING_VM_CHECKOUTS_CHANGED_CHANNEL, listener) + } } satisfies PreloadApi['ephemeralVm'] diff --git a/src/preload/api/project-groups-bridge.ts b/src/preload/api/project-groups-bridge.ts index c14d58b7d00..b7748aca427 100644 --- a/src/preload/api/project-groups-bridge.ts +++ b/src/preload/api/project-groups-bridge.ts @@ -6,6 +6,7 @@ export const projectGroupsApi = { list: () => ipcRenderer.invoke('projectGroups:list'), create: (args) => ipcRenderer.invoke('projectGroups:create', args), update: (args) => ipcRenderer.invoke('projectGroups:update', args), + updateMany: (args) => ipcRenderer.invoke('projectGroups:updateMany', args), delete: (args) => ipcRenderer.invoke('projectGroups:delete', args), moveProject: (args) => ipcRenderer.invoke('projectGroups:moveProject', args), scanNested: (args) => ipcRenderer.invoke('projectGroups:scanNested', args), diff --git a/src/preload/api/repository-api.ts b/src/preload/api/repository-api.ts index e74b1a80af9..16c91ac61d3 100644 --- a/src/preload/api/repository-api.ts +++ b/src/preload/api/repository-api.ts @@ -6,6 +6,7 @@ import type { NestedRepoScanResult, ProjectGroup, ProjectGroupUpdate, + ProjectGroupMutation, ProjectGroupImportMode, ProjectGroupImportResult } from '../../shared/project-group-types' @@ -131,6 +132,9 @@ export type ProjectGroupsApi = { createdFrom?: ProjectGroup['createdFrom'] }) => Promise update: (args: { groupId: string; updates: ProjectGroupUpdate }) => Promise + updateMany: (args: { + mutations: readonly ProjectGroupMutation[] + }) => Promise delete: (args: { groupId: string }) => Promise moveProject: (args: { projectId: string diff --git a/src/preload/api/speech-api.ts b/src/preload/api/speech-api.ts index 8acba71dcc2..c7415932ba7 100644 --- a/src/preload/api/speech-api.ts +++ b/src/preload/api/speech-api.ts @@ -1,9 +1,13 @@ import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' import type { + DictationContext, + OpenAiCompatibleSpeechProvider, + OpenAiCompatibleSpeechProviderSummary, SpeechErrorEvent, SpeechLifecycleEvent, SpeechModelManifest, SpeechModelState, + SpeechPendingEvent, SpeechTranscriptEvent } from '../../shared/speech-types' @@ -16,12 +20,17 @@ export type SpeechApi = { }> saveOpenAiApiKey: (apiKey: string) => Promise<{ configured: boolean }> clearOpenAiApiKey: () => Promise<{ configured: boolean }> + /** Never returns the saved key. */ + getOpenAiCompatibleProvider: () => Promise + /** A blank key keeps the saved one while the base URL is unchanged. */ + saveOpenAiCompatibleProvider: (provider: OpenAiCompatibleSpeechProvider) => Promise + clearOpenAiCompatibleProvider: () => Promise downloadModel: (modelId: string) => Promise cancelDownload: (modelId: string) => Promise deleteModel: (modelId: string) => Promise startDictation: ( modelId: string, - hotwords: string[] | undefined, + context: DictationContext | undefined, sessionId: string ) => Promise /** Resolves true when this chunk filled a cloud session's upload cap. */ @@ -31,6 +40,7 @@ export type SpeechApi = { cancelDictation: (sessionId: string) => Promise onPartialTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void onFinalTranscript: (callback: (data: SpeechTranscriptEvent) => void) => () => void + onSpeechPending: (callback: (data: SpeechPendingEvent) => void) => () => void onDownloadProgress: ( callback: (data: { modelId: string; progress: number }) => void ) => () => void diff --git a/src/preload/api/speech-bridge.ts b/src/preload/api/speech-bridge.ts index a0b38154039..66acdfc0bac 100644 --- a/src/preload/api/speech-bridge.ts +++ b/src/preload/api/speech-bridge.ts @@ -1,11 +1,15 @@ import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection' import { ipcRenderer } from 'electron' import type { + DictationContext, + OpenAiCompatibleSpeechProvider, + OpenAiCompatibleSpeechProviderSummary, SpeechAudioPortMessage, SpeechErrorEvent, SpeechLifecycleEvent, SpeechModelManifest, SpeechModelState, + SpeechPendingEvent, SpeechTranscriptEvent } from '../../shared/speech-types' import type { PreloadApi } from '../api-types' @@ -24,6 +28,12 @@ export const speechApi = { ipcRenderer.invoke('speech:saveOpenAiApiKey', apiKey), clearOpenAiApiKey: (): Promise<{ configured: boolean }> => ipcRenderer.invoke('speech:clearOpenAiApiKey'), + getOpenAiCompatibleProvider: (): Promise => + ipcRenderer.invoke('speech:getOpenAiCompatibleProvider'), + saveOpenAiCompatibleProvider: (provider: OpenAiCompatibleSpeechProvider): Promise => + ipcRenderer.invoke('speech:saveOpenAiCompatibleProvider', provider), + clearOpenAiCompatibleProvider: (): Promise => + ipcRenderer.invoke('speech:clearOpenAiCompatibleProvider'), downloadModel: (modelId: string): Promise => ipcRenderer.invoke('speech:downloadModel', modelId), cancelDownload: (modelId: string): Promise => @@ -32,7 +42,7 @@ export const speechApi = { ipcRenderer.invoke('speech:deleteModel', modelId), startDictation: async ( modelId: string, - hotwords: string[] | undefined, + context: DictationContext | undefined, sessionId: string ): Promise => { const { port1, port2 } = new MessageChannel() @@ -43,7 +53,7 @@ export const speechApi = { const result: { directAudio?: boolean } | undefined = await ipcRenderer.invoke( 'speech:startDictation', modelId, - hotwords, + context, sessionId ) directAudio = result?.directAudio === true @@ -102,6 +112,12 @@ export const speechApi = { ipcRenderer.on('speech:final', listener) return () => ipcRenderer.removeListener('speech:final', listener) }, + onSpeechPending: (callback: (data: SpeechPendingEvent) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: SpeechPendingEvent): void => + callback(data) + ipcRenderer.on('speech:pending', listener) + return () => ipcRenderer.removeListener('speech:pending', listener) + }, onDownloadProgress: ( callback: (data: { modelId: string; progress: number }) => void ): (() => void) => { diff --git a/src/preload/browser-extension-preload.ts b/src/preload/browser-extension-preload.ts index d0f28a68532..43aa35d0415 100644 --- a/src/preload/browser-extension-preload.ts +++ b/src/preload/browser-extension-preload.ts @@ -28,7 +28,6 @@ import { installChromeWebStoreBridge } from './browser-extension-web-store-bridge' -// Why: raw require keeps the sandboxed preload standalone in the main-process CJS build. const electron: { contextBridge: ContextBridge; ipcRenderer: IpcRenderer } = require('electron') const { contextBridge, ipcRenderer } = electron diff --git a/src/preload/browser-extension-web-store-bridge.ts b/src/preload/browser-extension-web-store-bridge.ts index cddc88fcd0d..08266d7138c 100644 --- a/src/preload/browser-extension-web-store-bridge.ts +++ b/src/preload/browser-extension-web-store-bridge.ts @@ -20,7 +20,6 @@ export const PRELOAD_WEB_STORE_EVENT_CHANNEL = 'browserExtension:webStoreEvent' * Orca browser tab in a local profile) on every call; this side only relays. */ export function installChromeWebStoreBridge(): void { - // Why: raw require keeps the sandboxed preload standalone in the main-process CJS build. const electron: { contextBridge: ContextBridge; ipcRenderer: IpcRenderer } = require('electron') const { contextBridge, ipcRenderer } = electron let dispatch: ((event: string, args: unknown[]) => void) | null = null diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 2962535ef3b..b3eaaea1d6e 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -29,8 +29,8 @@ import { useAppSessionPersistence } from './app-shell/use-app-session-persistenc import { useAppShellServices } from './app-shell/use-app-shell-services' import { useAppStartupHydration } from './app-shell/use-app-startup-hydration' import { startNativeChatDraftLoad } from './app-shell/native-chat-draft-startup' -import { runWslMoveRendererStoreRewrites } from './lib/wsl-move-renderer-store-rewrites' -import { runWslDriveUncRendererStoreRewrites } from './lib/wsl-drive-unc-renderer-store-rewrites' +import { runWslMoveRendererStoreRewrites } from './lib/workspace/persistence/wsl-move-renderer-store-rewrites' +import { runWslDriveUncRendererStoreRewrites } from './lib/workspace/persistence/wsl-drive-unc-renderer-store-rewrites' import { useDocumentAppearance } from './app-shell/use-document-appearance' import { useFloatingWorkspacePanel } from './app-shell/use-floating-workspace-panel' import { useGlobalKeybindings } from './app-shell/use-global-keybindings' @@ -42,7 +42,7 @@ import { SpaceWindowStatePublisher } from './components/workspace-space/SpaceWin import { PlainSshTerminalPanels } from './components/plain-ssh-terminal/PlainSshTerminalPanels' import { PluginShotReplayMount } from './components/plugins/view/PluginShotReplayMount' import { AddToChatPointMenuHost } from './components/native-chat/selection-quotes/AddToChatMenu' -import { installActiveWorktreeRemovalSuccessor } from './lib/active-worktree-removal-successor' +import { installActiveWorktreeRemovalSuccessor } from './lib/workspace/activation/active-worktree-removal-successor' function App(): React.JSX.Element { const layout = useAppChromeLayout() diff --git a/src/renderer/src/app-shell/AppNotificationCards.tsx b/src/renderer/src/app-shell/AppNotificationCards.tsx index ea36809b65e..3db3a25dfea 100644 --- a/src/renderer/src/app-shell/AppNotificationCards.tsx +++ b/src/renderer/src/app-shell/AppNotificationCards.tsx @@ -4,6 +4,7 @@ import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' import { CodexSharedSettingsNoticeCard } from '../components/CodexSharedSettingsNoticeCard' import { NotificationCardStack } from '../components/NotificationCardStack' import { StarNagCard } from '../components/StarNagCard' +import { SpeechModelUpdateCard } from '../components/dictation/SpeechModelUpdateCard' import { OverlayBoundary } from './app-root-surface-boundaries' const ChatUiHereCornerCard = lazy(() => @@ -59,6 +60,9 @@ export function AppNotificationCards({ + + + ) } diff --git a/src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts b/src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts index cdc9c2dd7f4..ea6db592510 100644 --- a/src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts +++ b/src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts @@ -38,25 +38,6 @@ describe('createShutdownCheckpointPersist', () => { vi.restoreAllMocks() }) - it('degrades to durable-only staging when full staging fails again on retry (STA-5505)', () => { - vi.spyOn(console, 'error').mockImplementation(() => {}) - const stageBeforeUnloadSync = vi.fn((args: { sessions: unknown[] }) => { - if (args.sessions.length > 0) { - throw new Error('sync IPC staging failed') - } - }) - const { run: persist } = createShutdownCheckpointPersist(makeDeps({ stageBeforeUnloadSync })) - - expect(persist).toThrow('sync IPC staging failed') - expect(persist).not.toThrow() - expect(stageBeforeUnloadSync).toHaveBeenCalledTimes(3) - expect(stageBeforeUnloadSync).toHaveBeenLastCalledWith({ - sessions: [], - ui: { activeView: 'workspace' } - }) - vi.restoreAllMocks() - }) - it('stages the full snapshot when a retry after a transient staging failure succeeds', () => { let calls = 0 const stageBeforeUnloadSync = vi.fn(() => { diff --git a/src/renderer/src/app-shell/startup-window-parity.test.ts b/src/renderer/src/app-shell/startup-window-parity.test.ts index e06ff4428af..ad55364b52d 100644 --- a/src/renderer/src/app-shell/startup-window-parity.test.ts +++ b/src/renderer/src/app-shell/startup-window-parity.test.ts @@ -1,7 +1,7 @@ // Compare window startup from disk with the Loader round trip. Enumerate each divergence as a known defect or accepted difference with its reason. import { describe, expect, it, vi } from 'vitest' -import type * as AgentStatusModule from '@/lib/agent-status' +import type * as AgentStatusModule from '@/lib/agent-status/aggregation/worktree-agent-status' import type { ExecutionHostId } from '../../../shared/execution-host' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { LEGACY_WORKSPACE_LAYOUT_PROFILES } from '../../../shared/workspace-layout/workspace-layout-legacy-profile.test-fixture' @@ -24,7 +24,7 @@ vi.mock('../../../shared/layout-owner-switch', () => ({ } })) vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) -vi.mock('@/lib/agent-status', async (importOriginal) => { +vi.mock('@/lib/agent-status/aggregation/worktree-agent-status', async (importOriginal) => { const actual = await importOriginal() return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } }) diff --git a/src/renderer/src/app-shell/use-document-appearance.ts b/src/renderer/src/app-shell/use-document-appearance.ts index f726af1c036..53863ec5cfc 100644 --- a/src/renderer/src/app-shell/use-document-appearance.ts +++ b/src/renderer/src/app-shell/use-document-appearance.ts @@ -1,8 +1,8 @@ import { useEffect, useMemo, useRef } from 'react' import { useShallow } from 'zustand/react/shallow' import { buildAppFontFamily } from '@/lib/app-font-family' -import { applyCodeFontSmoothing } from '@/lib/code-font-smoothing' -import { applyMarkdownCodeFontFamily } from '@/lib/markdown-code-font' +import { applyCodeFontSmoothing } from '@/lib/editor/appearance/code-font-smoothing' +import { applyMarkdownCodeFontFamily } from '@/lib/editor/appearance/markdown-code-font' import { useSplitDividerSetting } from '@/hooks/use-split-divider-setting' import { rebuildAllTerminalWebglRenderers } from '@/lib/pane-manager/pane-manager-registry' import { applyDocumentTheme, applyPluginAppTheme } from '../lib/document-theme' @@ -15,7 +15,7 @@ import { findCodeEditorTheme, paintCodeEditorColors, resolveCodeEditorTheme -} from '../lib/code-editor-theme' +} from '../lib/editor/appearance/code-editor-theme' import { browserColorProbe } from '../lib/plugin-theme-tokens' import { TINTED_HOST_PILL_OUTLINE_MIX_TOKEN, diff --git a/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx b/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx index 32bf4fb7257..489294052e1 100644 --- a/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx +++ b/src/renderer/src/app-shell/workspace-view-cross-client-sync.test.tsx @@ -405,20 +405,4 @@ describe('workspace view preferences: cross-client persistence (STA-5781)', () = await flushDesktopDebounce() expect(authority.get().hideDefaultBranchWorkspace).toBe(true) }) - - it('desktop and another client changing the same field converge on the newest write', async () => { - act(() => { - store.getState().setHideDefaultBranchWorkspace(true) - }) - await flushDesktopDebounce() - deliverBroadcasts() - - // Another client flips the SAME field afterwards; last writer wins everywhere. - authority.set({ hideDefaultBranchWorkspace: false }) - deliverBroadcasts() - expect(authority.get().hideDefaultBranchWorkspace).toBe(false) - await flushDesktopDebounce() - expect(authority.get().hideDefaultBranchWorkspace).toBe(false) - expect(store.getState().hideDefaultBranchWorkspace).toBe(false) - }) }) diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index e6b560d0b4d..181e66ac5aa 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -65,6 +65,7 @@ --color-chat-foreground: var(--chat-foreground); --color-chat-foreground-strong: var(--chat-foreground-strong); --color-chat-foreground-faint: var(--chat-foreground-faint); + --color-chat-unread: var(--chat-unread); --color-chat-user-surface: var(--chat-user-surface); --color-chat-user-border: var(--chat-user-border); --color-chat-code-foreground: var(--chat-code-foreground); @@ -745,6 +746,8 @@ body[data-modal-overlay-open] /* Mixed toward the foreground so each clears text contrast on the canvas in either scheme. */ --chat-focus-ring: color-mix(in srgb, var(--chat-source-foreground) 50%, var(--chat-canvas)); --chat-warning: color-mix(in srgb, var(--status-warning) 70%, var(--chat-source-foreground)); + /* What the reader has not seen yet: the transcript's "New" marker, in the note hue. */ + --chat-unread: color-mix(in srgb, var(--callout-note) 70%, var(--chat-source-foreground)); --chat-diff-added: color-mix(in srgb, var(--diff-added) 70%, var(--chat-source-foreground)); --chat-diff-removed: color-mix(in srgb, var(--diff-removed) 70%, var(--chat-source-foreground)); --chat-link: color-mix( diff --git a/src/renderer/src/assets/markdown-preview.css b/src/renderer/src/assets/markdown-preview.css index c469ce93e0f..43743bcf1ec 100644 --- a/src/renderer/src/assets/markdown-preview.css +++ b/src/renderer/src/assets/markdown-preview.css @@ -582,7 +582,7 @@ cursor: pointer !important; text-decoration: underline; text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); - text-underline-offset: 2px; + text-underline-offset: 0.25em; transition: text-decoration-color 150ms; } diff --git a/src/renderer/src/assets/rich-markdown-editor.css b/src/renderer/src/assets/rich-markdown-editor.css index dda532e0c8d..d8acaf45e86 100644 --- a/src/renderer/src/assets/rich-markdown-editor.css +++ b/src/renderer/src/assets/rich-markdown-editor.css @@ -1143,7 +1143,7 @@ color: var(--text-link, #0969da); text-decoration: underline; text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); - text-underline-offset: 2px; + text-underline-offset: 0.25em; } /* Plain clicks place the caret; RichMarkdownEditor exposes link pointers only while Cmd/Ctrl is held. */ @@ -1164,7 +1164,7 @@ color: var(--text-link, #0969da); text-decoration: underline; text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); - text-underline-offset: 2px; + text-underline-offset: 0.25em; } .dark .rich-markdown-editor .rich-markdown-html-superscript-link { @@ -1462,7 +1462,7 @@ color: var(--text-link, #0969da); text-decoration: underline; text-decoration-color: color-mix(in srgb, currentColor 45%, transparent); - text-underline-offset: 2px; + text-underline-offset: 0.25em; } .dark .rich-markdown-editor .rich-markdown-doc-link { @@ -1489,7 +1489,7 @@ color: var(--text-link, #0969da); text-decoration: underline; text-decoration-color: color-mix(in srgb, currentColor 45%, transparent); - text-underline-offset: 2px; + text-underline-offset: 0.25em; } .dark .rich-markdown-editor .rich-markdown-doc-link-preview { diff --git a/src/renderer/src/assets/theme-token-contrast.test.ts b/src/renderer/src/assets/theme-token-contrast.test.ts index 95753fdc498..71538f350dc 100644 --- a/src/renderer/src/assets/theme-token-contrast.test.ts +++ b/src/renderer/src/assets/theme-token-contrast.test.ts @@ -1,7 +1,6 @@ import { readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' import { contrastRatio, type Rgba } from '../../../shared/color/rgba-contrast' -import { CHAT_SELECTION_MIX, chatSelectionMixOver } from '../lib/chat-selection-mix' const css = readFileSync(new URL('./main.css', import.meta.url), 'utf8').replace( /\/\*[\s\S]*?\*\//g, @@ -15,14 +14,6 @@ function themeBlocks(selector: ':root' | '.dark'): string[] { .map(([, , body]) => body) } -/** Last-wins percentage the blocks give `name`. */ -function themePercent(selector: ':root' | '.dark', name: string): number { - const values = themeBlocks(selector).flatMap((body) => - [...body.matchAll(new RegExp(`${name}:\\s*([\\d.]+)%;`, 'g'))].map(([, value]) => Number(value)) - ) - return values.at(-1) ?? Number.NaN -} - /** Last-wins hex tokens from every top-level block whose selector list starts with `selector`. */ function themeTokens(selector: ':root' | '.dark'): Map { const tokens = new Map() @@ -67,20 +58,6 @@ describe.each([':root', '.dark'] as const)('built-in %s token pairs', (selector) expect(contrastRatio(token(text), token(surface))).toBeGreaterThanOrEqual(4.5) }) - it('chat selection keeps selected text 4.5:1 at its full depth', () => { - const base = selector === '.dark' ? 'dark' : 'light' - const canvas = tint( - token('--foreground'), - themePercent(selector, '--chat-canvas-mix') / 100, - token('--background') - ) - const depth = themePercent(selector, '--chat-selection-mix') - expect(depth).toBe(CHAT_SELECTION_MIX[base]) - expect(chatSelectionMixOver(token('--foreground'), canvas, token('--callout-note'), base)).toBe( - depth - ) - }) - it.each(['--background', '--muted'])('success text on its tint over %s meets WCAG AA', (name) => { const surface = tint(token('--status-success'), successTint / 100, token(name)) expect(contrastRatio(token('--status-success'), surface)).toBeGreaterThanOrEqual(4.5) diff --git a/src/renderer/src/attention/agent-attention-policy.test.ts b/src/renderer/src/attention/agent-attention-policy.test.ts index 851ebc3c66c..deddebf04df 100644 --- a/src/renderer/src/attention/agent-attention-policy.test.ts +++ b/src/renderer/src/attention/agent-attention-policy.test.ts @@ -60,27 +60,6 @@ describe('resolveAgentAttention', () => { expect(sink.calls).toEqual([]) }) - it('admits a viewed surface for delivery but earns it no unread', () => { - const decision = resolveAgentAttention( - completion(), - makeSurface({ isSurfaceViewed: () => true }) - ) - expect(decision).toMatchObject({ admitted: true, unread: null }) - - const sink = makeSink() - applyAgentAttention(decision, sink) - expect(sink.calls).toEqual([`deliver:${WORKSPACE}:${SUBJECT}`]) - }) - - it('hands the unread write, with its admitted group and reason, to the sink', () => { - const sink = makeSink() - applyAgentAttention(resolveAgentAttention(completion(), makeSurface()), sink) - expect(sink.calls).toEqual([ - `unread:${WORKSPACE}:${SUBJECT}:${GROUP}:agent-completion`, - `deliver:${WORKSPACE}:${SUBJECT}` - ]) - }) - it('delivers a bell without validating the surface address or writing unread', () => { const admitSurface = vi.fn() const isSurfaceViewed = vi.fn() diff --git a/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts b/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts index 7d73a64894a..e8e5944834f 100644 --- a/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts +++ b/src/renderer/src/attention/hidden-workspace-notification-mute.test.ts @@ -3,9 +3,6 @@ import { getDefaultSettings } from '../../../shared/constants' import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' import { folderWorkspaceKey } from '../../../shared/workspace-scope' import { getDefaultNotificationSettings } from '../../../shared/notification-settings-defaults' -import { resolveAgentAttention } from '@/attention/agent-attention-policy' -import { createTerminalAttentionSurface } from '@/components/terminal-pane/notifications/terminal-attention-surface' -import { createStructuredAttentionSurface } from '@/components/native-chat/session/attention/structured-attention-surface' import { createTabsSliceMockApi } from '../store/slices/tabs/tabs-slice-test-harness' import { createTestStore } from '../store/testing/app-store-test-fixture' import { makeWorktree } from '../store/slices/worktrees/worktree.test-fixture' @@ -128,20 +125,6 @@ describe('isWorkspaceNotificationMutedBySidebarFilters', () => { }) describe('muted workspace attention', () => { - it('earns no unread and no delivery request from the attention policy', () => { - const decision = resolveAgentAttention( - { - subject: { workspaceId: CLI_ID, surfaceKey: 'tab-1:leaf-1' }, - reason: 'agent-completion', - settlesTurn: true, - hasFreshActivityEvidence: true - }, - createTerminalAttentionSurface(store.getState()) - ) - expect(decision).toEqual({ admitted: false, cause: 'muted-workspace' }) - expect(createStructuredAttentionSurface(store.getState()).isWorkspaceMuted(CLI_ID)).toBe(true) - }) - it('writes no bell marker for a muted workspace, and still does for a visible one', () => { const terminalTab = (id: string, worktreeId: string) => ({ id, diff --git a/src/renderer/src/attention/notification-subject-owner.ts b/src/renderer/src/attention/notification-subject-owner.ts index 4d9a8896891..2658f034f30 100644 --- a/src/renderer/src/attention/notification-subject-owner.ts +++ b/src/renderer/src/attention/notification-subject-owner.ts @@ -1,4 +1,8 @@ -import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import { + getRepoExecutionHostId, + parseExecutionHostId, + type ExecutionHostId +} from '../../../shared/execution-host' import type { NotificationWorkspaceOwner } from '../../../shared/notification-source' import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { parseWorkspaceKey } from '../../../shared/workspace-scope' @@ -7,7 +11,10 @@ import type { Tab } from '../../../shared/tab-types' import type { AppState } from '@/store/types' import type { PtyTransport } from '@/components/terminal-pane/pty-transport/pty-transport-types' import { resolveTerminalTabPtyOwnership } from '@/lib/terminal-tab-for-pty-id' -import { resolveExactWorktreeRoute, routeForOwner } from '@/lib/worktree-owner-route' +import { + resolveExactWorktreeRoute, + routeForOwner +} from '@/lib/workspace/ownership/worktree-owner-route' import { findIndexedWorktreeOwner, findIndexedWorktreeOwnerForHost, @@ -15,7 +22,7 @@ import { findIndexedProjectGroupOwner } from '@/lib/workspace/ownership/worktree-runtime-owner-index' import { findIndexedRepoOwner } from '@/lib/workspace/ownership/repo-owner-index' -import { getCatalogOwnerHostId } from '@/lib/workspace/ownership/workspace-catalog-owner-index' +import '@/lib/workspace/ownership/workspace-catalog-owner-index' import type { WorktreeRuntimeOwnerState } from '@/lib/workspace/ownership/worktree-runtime-owner-state' type SubjectOwnerState = WorktreeRuntimeOwnerState & @@ -47,7 +54,7 @@ export function resolveNotificationTabOwner( } const group = findIndexedProjectGroupOwner(state.projectGroups, folder.projectGroupId, hostId) return routeForOwner({ - hostId: getCatalogOwnerHostId({ + hostId: getRepoExecutionHostId({ executionHostId: folder.executionHostId ?? group?.executionHostId, connectionId: folder.connectionId ?? group?.connectionId }) @@ -63,7 +70,7 @@ export function resolveNotificationTabOwner( const repo = !owner.hostId ? findIndexedRepoOwner(state.repos, owner.repoId) : null const resolution = resolveExactWorktreeRoute(state, { ...owner, - hostId: owner.hostId ?? (repo ? getCatalogOwnerHostId(repo) : hostId) + hostId: owner.hostId ?? (repo ? getRepoExecutionHostId(repo) : hostId) }) return resolution.kind === 'resolved' ? resolution.route : null } diff --git a/src/renderer/src/attention/notification-workspace-labels.ts b/src/renderer/src/attention/notification-workspace-labels.ts index d16d5ab853f..b86c6836f1a 100644 --- a/src/renderer/src/attention/notification-workspace-labels.ts +++ b/src/renderer/src/attention/notification-workspace-labels.ts @@ -6,7 +6,7 @@ import { worktreeMatchesHost } from '../store/slices/worktrees/listing/worktree-host-ownership' import { getResolvedExecutionHostIdForWorktree } from '../lib/resolved-worktree-execution-host' -import { getActiveWorkspaceExecutionHostId } from '../lib/active-workspace-host' +import { getActiveWorkspaceExecutionHostId } from '../lib/workspace/ownership/active-workspace-host' import { findIndexedFolderWorkspaceOwner, findIndexedProjectGroupOwner @@ -15,8 +15,8 @@ import { findIndexedRepoOwnerForHost, resolveIndexedRepoOwner } from '../lib/workspace/ownership/repo-owner-index' -import { getCatalogOwnerHostId } from '../lib/workspace/ownership/workspace-catalog-owner-index' -import type { ExecutionHostId } from '../../../shared/execution-host' +import '../lib/workspace/ownership/workspace-catalog-owner-index' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' import type { Repo } from '../../../shared/repo-types' import type { Worktree } from '../../../shared/worktree/types' import { parseWorkspaceKey } from '../../../shared/workspace-scope' @@ -83,7 +83,7 @@ export function getNotificationWorkspaceLabels( findIndexedProjectGroupOwner( state.projectGroups, folder.projectGroupId, - getCatalogOwnerHostId(folder) + getRepoExecutionHostId(folder) ) return { repoLabel: group?.name, worktreeLabel: folder?.name || fallback } } diff --git a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx index be5f1670689..8b712f06a6a 100644 --- a/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx +++ b/src/renderer/src/components/ClaudeAccountSwitchSessionTree.tsx @@ -2,7 +2,7 @@ import { Fragment, useLayoutEffect, useRef, useState } from 'react' import { Folder, GitBranch } from 'lucide-react' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { formatAgentTypeLabel } from '../../../shared/agent-status/presentation/agent-type-label' import type { ClaudeAccountSwitchPromptSessions } from '@/lib/provider-accounts/claude-account-switch-sessions' import { diff --git a/src/renderer/src/components/FileTypeIcon.tsx b/src/renderer/src/components/FileTypeIcon.tsx index 1b4f7be889f..1451101b0fe 100644 --- a/src/renderer/src/components/FileTypeIcon.tsx +++ b/src/renderer/src/components/FileTypeIcon.tsx @@ -4,7 +4,7 @@ import { getFileTypeIcon, getPluginFileTypeIconIndex, getPluginFolderIconIndex -} from '@/lib/file-type-icons' +} from '@/lib/file-icons/file-type-icons' import { PLUGIN_ICON_ATTRIBUTE, useActivePluginIconTheme diff --git a/src/renderer/src/components/GitLabItemDialog.test.tsx b/src/renderer/src/components/GitLabItemDialog.test.tsx index 41efad984ca..1f9c3b90364 100644 --- a/src/renderer/src/components/GitLabItemDialog.test.tsx +++ b/src/renderer/src/components/GitLabItemDialog.test.tsx @@ -40,30 +40,12 @@ function detailsFor(item: GitLabWorkItem, reviewer: string): GitLabWorkItemDetai } } -function renderDialog(item: GitLabWorkItem) { - return render() -} - afterEach(() => { cleanup() vi.clearAllMocks() }) describe('GitLabItemDialog reconciliation', () => { - it('drops the previous MR details when another MR opens', async () => { - api.workItemDetails.mockResolvedValueOnce(detailsFor(mr(7), 'alice')) - const view = renderDialog(mr(7)) - await waitFor(() => expect(screen.getByText('alice')).toBeTruthy()) - - api.workItemDetails.mockReturnValueOnce(new Promise(() => {})) - view.rerender( - - ) - - expect(screen.queryByText('alice')).toBeNull() - expect(screen.queryByText('Reviewers')).toBeNull() - }) - it('drops the previous source details when only the task source changes', async () => { const source: TaskSourceContext = { kind: 'task-source', diff --git a/src/renderer/src/components/JiraIssueWorkspace.tsx b/src/renderer/src/components/JiraIssueWorkspace.tsx index aa280b752ff..6740918308b 100644 --- a/src/renderer/src/components/JiraIssueWorkspace.tsx +++ b/src/renderer/src/components/JiraIssueWorkspace.tsx @@ -19,7 +19,7 @@ import { JiraIssueMetadataBar, JiraIssueWorkspaceHeader } from './jira-issue-wor import { JiraIssueCommentComposer, JiraIssueWorkspaceContent } from './jira-issue-workspace-content' import { useJiraIssueWorkspaceActions } from './jira-issue-workspace-actions' import { getJiraReadIdentity } from '@/store/slices/jira/jira-read-coordination' -import { defaultScopeHost } from '@/lib/default-creation-host' +import { defaultScopeHost } from '@/runtime/hosts/selection/default-creation-host' import { taskSourceRuntimeTarget } from '@/lib/task-source-runtime-target' import { getEnvironmentRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context' import { runtimeTargetEnvironmentId } from '@/runtime/rpc/targets/runtime-client-target' diff --git a/src/renderer/src/components/LinearIssueTextEditor.tsx b/src/renderer/src/components/LinearIssueTextEditor.tsx index f991da7a5e9..595a2123c0c 100644 --- a/src/renderer/src/components/LinearIssueTextEditor.tsx +++ b/src/renderer/src/components/LinearIssueTextEditor.tsx @@ -23,7 +23,7 @@ import { } from './linear-issue-text-draft-state' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' -import { defaultScopeSource } from '@/lib/default-creation-host' +import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' type LinearIssueTextEditorProps = { issue: LinearIssue diff --git a/src/renderer/src/components/LinearIssueWorkspace.tsx b/src/renderer/src/components/LinearIssueWorkspace.tsx index ca62f2a8a1b..ba4bee4a91f 100644 --- a/src/renderer/src/components/LinearIssueWorkspace.tsx +++ b/src/renderer/src/components/LinearIssueWorkspace.tsx @@ -17,7 +17,7 @@ import { LinearIssueSubIssues } from './linear-issue-sub-issues' import { useLinearIssueWorkspaceDetail } from './linear-issue-workspace-detail-state' import { LinearIssueWorkspaceHeader } from './linear-issue-workspace-header' import { LinearIssueWorkspaceSidebar } from './linear-issue-workspace-sidebar' -import { defaultScopeSource } from '@/lib/default-creation-host' +import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-record-fields' type LinearIssueWorkspaceProps = { diff --git a/src/renderer/src/components/LinearItemDrawer.tsx b/src/renderer/src/components/LinearItemDrawer.tsx index d96aec5f0b7..a1c8fba8db4 100644 --- a/src/renderer/src/components/LinearItemDrawer.tsx +++ b/src/renderer/src/components/LinearItemDrawer.tsx @@ -20,7 +20,7 @@ import { } from '@/components/linear-item-drawer-types' import { renderLinearItemDrawerSheet } from '@/components/linear-item-drawer-sheet' import { selectFolderWorkspaces } from '@/store/workspaces/catalog/workspace-record-fields' -import { defaultScopeSource } from '@/lib/default-creation-host' +import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' export { LinearIssueEditSection } from '@/components/linear-item-drawer-edit-section' export { LinearIssueCommentFooter } from '@/components/linear-item-drawer-comment-footer' diff --git a/src/renderer/src/components/NativeChatResumeOnRestartAgentRow.tsx b/src/renderer/src/components/NativeChatResumeOnRestartAgentRow.tsx index f60e94e8c8c..b1ebf752d87 100644 --- a/src/renderer/src/components/NativeChatResumeOnRestartAgentRow.tsx +++ b/src/renderer/src/components/NativeChatResumeOnRestartAgentRow.tsx @@ -1,5 +1,5 @@ import { useContext } from 'react' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { agentTypeToIconAgent } from '../../../shared/agent-status/presentation/agent-type-icon-agent' import { formatAgentTypeLabel } from '../../../shared/agent-status/presentation/agent-type-label' import { formatShortTimeAgo } from '@/lib/short-time-ago' diff --git a/src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx b/src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx index 6e79187ecaf..f6c3909762a 100644 --- a/src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx +++ b/src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx @@ -132,16 +132,3 @@ it('starts expanded; collapsing hides a node’s rows and keeps their selection' expect(state(chatBox('in-child'))).toBe('false') expect(state(chatBox('also-in-child'))).toBe('true') }) - -it('toggles the chats of a collapsed node', () => { - render({ candidates: seedTree(), initiallySelected: [] }) - - act(() => disclosureOf('parent').click()) - act(() => nodeBox('parent').click()) - expect(countOf('parent')).toBe('3 of 3') - expect(onToggleSpy.mock.calls.map(([sessionId]) => sessionId).toSorted()).toEqual([ - 'also-in-child', - 'in-child', - 'in-parent' - ]) -}) diff --git a/src/renderer/src/components/NewWorkspaceComposerCard.tsx b/src/renderer/src/components/NewWorkspaceComposerCard.tsx index b3214247197..514a3b90408 100644 --- a/src/renderer/src/components/NewWorkspaceComposerCard.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerCard.tsx @@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next' import { toast } from 'sonner' import { useAppStore } from '@/store' import { cn } from '@/lib/utils' -import { getAgentCatalog } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { getScreenSubmitModifierLabel } from '@/lib/screen-submit-shortcut' import { resolveProjectCloneUrlPrefill } from '@/lib/project-clone-url-prefill' import { useContextualTour } from '@/components/contextual-tours/use-contextual-tour' diff --git a/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx b/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx index 2dbb0447b44..d01c63cd408 100644 --- a/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx +++ b/src/renderer/src/components/NewWorkspaceComposerModal.retention.test.tsx @@ -176,6 +176,8 @@ vi.mock('@/hooks/useComposerState', () => ({ onReuseSelectedBranchChange: noOp, forkPushWarning: null, advancedOpen: false, + setupChoiceRevealRequest: 0, + onSetupChoiceRevealed: noOp, onToggleAdvanced: noOp, parentWorktreeId: null, onParentWorktreeIdChange: noOp, diff --git a/src/renderer/src/components/NotificationCardStack.test.tsx b/src/renderer/src/components/NotificationCardStack.test.tsx deleted file mode 100644 index 6dbbc3298cf..00000000000 --- a/src/renderer/src/components/NotificationCardStack.test.tsx +++ /dev/null @@ -1,67 +0,0 @@ -// @vitest-environment happy-dom - -import { act, useRef } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { NOTIFICATION_CARD_STACK_HEIGHT_VAR } from '@/lib/notification-card-stack-height' -import { useNotificationCardLayoutVarReader } from '@/lib/notification-card-layout-vars' -import { NotificationCardStack } from './NotificationCardStack' - -let resize: (() => void) | null = null -let height = 0 -let root: Root | null = null - -const toasterVar = (name: string): string => - document.querySelector('[data-toaster]')?.style.getPropertyValue(name) ?? '' -const published = (): string => toasterVar(NOTIFICATION_CARD_STACK_HEIGHT_VAR) - -function ToasterStandIn(): React.JSX.Element { - const ref = useRef(null) - useNotificationCardLayoutVarReader(ref) - return
-} - -function Corner(): React.JSX.Element { - return ( - <> - - card - - ) -} - -beforeEach(() => { - height = 0 - vi.stubGlobal( - 'ResizeObserver', - class { - callback: () => void - constructor(callback: () => void) { - this.callback = callback - resize = callback - } - observe(): void {} - disconnect(): void {} - } - ) - vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(() => height) - root = createRoot(document.body.appendChild(document.createElement('div'))) -}) - -afterEach(() => { - act(() => root?.unmount()) - vi.unstubAllGlobals() - vi.restoreAllMocks() -}) - -describe('NotificationCardStack', () => { - it('publishes its height plus the gap so toasts sit above the cards, and clears it when empty', () => { - height = 120 - act(() => root?.render()) - expect(published()).toBe('calc(120px + 0.5rem)') - - height = 0 - act(() => resize?.()) - expect(published()).toBe('') - }) -}) diff --git a/src/renderer/src/components/UpdateCard.error-card.test.tsx b/src/renderer/src/components/UpdateCard.error-card.test.tsx index 3449613c48d..839bb14ed30 100644 --- a/src/renderer/src/components/UpdateCard.error-card.test.tsx +++ b/src/renderer/src/components/UpdateCard.error-card.test.tsx @@ -131,14 +131,6 @@ function showPackageRecovery(recovery = PACKAGE_RECOVERY): void { } describe('UpdateCard Linux package-install recovery', () => { - it('uses the recovery version when cached update state is stale', () => { - renderWithInitialStatus({ state: 'available', version: '1.4.199', changelog: null }) - showPackageRecovery() - - fireEvent.click(screen.getByRole('button', { name: 'Download Manually' })) - expect(openUrl).toHaveBeenCalledWith('https://github.com/stablyai/orca/releases/tag/v1.4.200') - }) - it('resets command discovery when a newer package cycle replaces the recovery', async () => { getInstructions.mockResolvedValueOnce({ ok: false, diff --git a/src/renderer/src/components/activity/activity-event-state.ts b/src/renderer/src/components/activity/activity-event-state.ts index 63768a14a61..0c6242dba7c 100644 --- a/src/renderer/src/components/activity/activity-event-state.ts +++ b/src/renderer/src/components/activity/activity-event-state.ts @@ -1,5 +1,8 @@ -import { isExplicitAgentStatusFresh } from '@/lib/pane-agent-evidence' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status/contracts/agent-status-freshness' +import { + isAgentStatusFresh, + AGENT_STATUS_STALE_AFTER_MS +} from '../../../../shared/agent-status/contracts/agent-status-freshness' + import type { AgentStatusEntry, AgentStatusState, @@ -20,7 +23,7 @@ export function freshActivityLiveAgentState( ): ActivityLiveAgentState | null { if ( !isActivityHookLiveAgentState(entry.state) || - !isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS) + !isAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS) ) { return null } diff --git a/src/renderer/src/components/activity/activity-thread-actions.ts b/src/renderer/src/components/activity/activity-thread-actions.ts index fff1580bf85..6c7995f5994 100644 --- a/src/renderer/src/components/activity/activity-thread-actions.ts +++ b/src/renderer/src/components/activity/activity-thread-actions.ts @@ -1,8 +1,8 @@ -import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane' +import { activateTabAndFocusPane } from '@/lib/workspace/tabs/activate-tab-and-focus-pane' import { revealFloatingWorkspacePanel } from '@/lib/floating-workspace-panel-reveal' import { activateStructuredAgentSessionTab } from '@/lib/agent-session/structured-agent-session-tab-activation' import { activateAndRevealWorkspace } from '@/lib/workspace/activation/worktree-activation' -import { jumpToWorktreeFromSidebar } from '@/lib/worktree-jump-navigation' +import { jumpToWorktreeFromSidebar } from '@/lib/workspace/activation/worktree-jump-navigation' import { useAppStore } from '@/store' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { diff --git a/src/renderer/src/components/activity/activity-thread-context-menu.tsx b/src/renderer/src/components/activity/activity-thread-context-menu.tsx index 67ed72093fd..a91d6436a18 100644 --- a/src/renderer/src/components/activity/activity-thread-context-menu.tsx +++ b/src/renderer/src/components/activity/activity-thread-context-menu.tsx @@ -12,7 +12,7 @@ import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { CLOSE_ALL_CONTEXT_MENUS_EVENT } from '@/lib/close-all-context-menus' import { formatClipboardFilePath } from '@/lib/clipboard-file-path' -import { getWorktreeRowLocalPathOpenOwner } from '@/lib/worktree-row-open-in-owner' +import { getWorktreeRowLocalPathOpenOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner' import { useAppStore } from '@/store' import { clearActivityThread, diff --git a/src/renderer/src/components/activity/activity-thread-detail-pane.tsx b/src/renderer/src/components/activity/activity-thread-detail-pane.tsx index 8b4b8b28c67..db2fab50f99 100644 --- a/src/renderer/src/components/activity/activity-thread-detail-pane.tsx +++ b/src/renderer/src/components/activity/activity-thread-detail-pane.tsx @@ -1,6 +1,6 @@ import React from 'react' import { MessageSquareText, TerminalSquare } from 'lucide-react' -import { AgentTypeIcon } from '@/lib/agent-type-icon' +import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' import { EventRepoBadge, ThreadAgentStateIndicator } from './activity-thread-controls' diff --git a/src/renderer/src/components/activity/activity-thread-grouping.status-order.test.ts b/src/renderer/src/components/activity/activity-thread-grouping.status-order.test.ts deleted file mode 100644 index 65c88c243f4..00000000000 --- a/src/renderer/src/components/activity/activity-thread-grouping.status-order.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { activityThreadMatchesSearchQuery } from './activity-thread-grouping' - -import type { AgentPaneThread } from './activity-thread-types' -import { makeWorktree, makeTab } from './ActivityPrototypePage-test-fixtures' - -{ - function makeThread(paneKey: string, paneTitle: string): AgentPaneThread { - return { - paneKey, - tab: makeTab(), - worktree: makeWorktree(), - repo: null, - currentAgentState: null, - currentAgentEntry: null, - latestEvent: null, - latestTimestamp: 1_000, - agentType: 'claude', - unread: false, - paneTitle, - responsePreview: 'x'.repeat(2_000), - events: [] - } - } - - describe('activity thread search', () => { - it('searches rebuilt thread data when the pane key stays the same', () => { - const first = makeThread('tab-1:leaf-1', 'First title') - const rebuilt = makeThread('tab-1:leaf-1', 'Second title') - expect(activityThreadMatchesSearchQuery({ thread: first, searchQuery: 'first' })).toBe(true) - expect(activityThreadMatchesSearchQuery({ thread: rebuilt, searchQuery: 'second' })).toBe( - true - ) - expect(activityThreadMatchesSearchQuery({ thread: rebuilt, searchQuery: 'first' })).toBe( - false - ) - }) - }) -} diff --git a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx index 4c3fd034440..f62405cbfa1 100644 --- a/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx +++ b/src/renderer/src/components/activity/activity-thread-hover-card-summary.tsx @@ -3,14 +3,14 @@ import { Cloud, Copy, FolderGit2, GitBranch, Laptop, LocateFixed, Server } from import { toast } from 'sonner' import { useAppStore } from '@/store' import { RepoBadgeMark } from '@/components/repo/RepoBadgeLabel' -import { AgentTypeIcon } from '@/lib/agent-type-icon' +import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { getWorktreeGitIdentityDisplay } from '../../../../shared/worktree/git-identity-display' -import { jumpToWorktreeFromSidebar } from '@/lib/worktree-jump-navigation' +import { jumpToWorktreeFromSidebar } from '@/lib/workspace/activation/worktree-jump-navigation' import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import { formatClipboardFilePath } from '@/lib/clipboard-file-path' -import { getWorktreeRowLocalPathOpenOwner } from '@/lib/worktree-row-open-in-owner' +import { getWorktreeRowLocalPathOpenOwner } from '@/lib/workspace/ownership/worktree-row-open-in-owner' import { cn } from '@/lib/utils' import { getExecutionHostLabel, diff --git a/src/renderer/src/components/activity/activity-thread-list-pane-collapsible.test.tsx b/src/renderer/src/components/activity/activity-thread-list-pane-collapsible.test.tsx deleted file mode 100644 index 0c57accc254..00000000000 --- a/src/renderer/src/components/activity/activity-thread-list-pane-collapsible.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { ActivityThreadListPane } from './activity-thread-list-pane' -import type { ActivityThreadGroup, AgentPaneThread } from './activity-thread-types' -import { makeTab, makeWorktree } from './ActivityPrototypePage-test-fixtures' - -globalThis.IS_REACT_ACT_ENVIRONMENT = true - -const mockThread: AgentPaneThread = { - paneKey: 'tab-1:agent-1', - tab: makeTab(), - worktree: makeWorktree(), - repo: null, - currentAgentState: null, - currentAgentEntry: null, - latestEvent: null, - latestTimestamp: 1000, - agentType: 'claude', - unread: false, - paneTitle: 'Test agent', - responsePreview: 'Done testing', - events: [] -} - -const mockGroup: ActivityThreadGroup = { - key: 'done', - label: 'Done', - state: 'done', - threads: [mockThread] -} - -describe('ActivityThreadListPane collapsible sections', () => { - let container: HTMLDivElement - let root: Root - - beforeEach(() => { - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) - }) - - afterEach(() => { - act(() => root.unmount()) - container.remove() - document.body.replaceChildren() - }) - - it('toggles thread visibility when header is clicked in uncontrolled mode', () => { - const inputRef = { current: null } - act(() => { - root.render( - - true} - showFilterControls={false} - showOptionsMenu={false} - /> - - ) - }) - - expect(container.textContent).toContain('Test agent') - - const header = container.querySelector('[role="button"]') as HTMLElement - act(() => { - header.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(container.textContent).not.toContain('Test agent') - expect(header.getAttribute('aria-expanded')).toBe('false') - - act(() => { - header.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) - - expect(container.textContent).toContain('Test agent') - expect(header.getAttribute('aria-expanded')).toBe('true') - }) -}) diff --git a/src/renderer/src/components/activity/activity-thread-presentation.ts b/src/renderer/src/components/activity/activity-thread-presentation.ts index aa37ffe17ee..92913fa6841 100644 --- a/src/renderer/src/components/activity/activity-thread-presentation.ts +++ b/src/renderer/src/components/activity/activity-thread-presentation.ts @@ -1,7 +1,7 @@ import type { AgentDotState } from '@/components/AgentStateDot' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { getAgentRowPrimaryText } from '../../../../shared/agent-status/presentation/agent-row-primary-text' -import { showsAgentToolPreview } from '@/lib/agent-row-tool-preview' +import { showsAgentToolPreview } from '@/lib/agent-status/presentation/agent-row-tool-preview' import { agentMainAgentVerdict, agentVerdictDisplayMark diff --git a/src/renderer/src/components/activity/activity-thread-row.tsx b/src/renderer/src/components/activity/activity-thread-row.tsx index ce64868966e..ef6e21f58fa 100644 --- a/src/renderer/src/components/activity/activity-thread-row.tsx +++ b/src/renderer/src/components/activity/activity-thread-row.tsx @@ -1,6 +1,6 @@ import React from 'react' import { Bell, ExternalLink, X } from 'lucide-react' -import { AgentTypeIcon } from '@/lib/agent-type-icon' +import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip' diff --git a/src/renderer/src/components/activity/useActivityUnreadCount.ts b/src/renderer/src/components/activity/useActivityUnreadCount.ts index 613e0941836..df3761ab0b0 100644 --- a/src/renderer/src/components/activity/useActivityUnreadCount.ts +++ b/src/renderer/src/components/activity/useActivityUnreadCount.ts @@ -2,7 +2,7 @@ import { useState } from 'react' import { migrationUnsupportedToAgentStatusEntry } from '../../../../shared/migration-unsupported-agent-entry' import { useAppStore } from '@/store' -import { createAgentStatusEpochSelector } from '@/lib/agent-status-epoch-selector' +import { createAgentStatusEpochSelector } from '@/lib/agent-status/evidence/agent-status-epoch-selector' import type { AppState } from '@/store/types' import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' diff --git a/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx b/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx index 0d860a215e8..73eae33015f 100644 --- a/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx +++ b/src/renderer/src/components/agent-session-continuation/AgentSessionContinuationDialog.tsx @@ -29,13 +29,13 @@ import { SelectValue } from '@/components/ui/select' import { useTranslate } from '@/i18n/use-translate' -import { getAgentCatalog, getAgentLabel } from '@/lib/agent-catalog' +import { getAgentCatalog, getAgentLabel } from '@/lib/agent-catalog/agent-catalog' import { buildAgentSessionContinuationPrompt, hasFullAgentSessionContext, type AgentSessionContinuationContextMode, type AgentSessionContinuationRequest -} from '@/lib/agent-session-continuation' +} from '@/lib/agent-session/context/agent-session-continuation' import { launchAgentSessionContinuation } from '@/lib/agent-session/launch/continuation/launch-agent-session-continuation' import { useAppStore } from '@/store' import { isTuiAgentEnabled } from '../../../../shared/agent-launch/catalog/tui-agent-selection' diff --git a/src/renderer/src/components/agent/AgentCombobox.tsx b/src/renderer/src/components/agent/AgentCombobox.tsx index 64d98889abe..a91dbaf4751 100644 --- a/src/renderer/src/components/agent/AgentCombobox.tsx +++ b/src/renderer/src/components/agent/AgentCombobox.tsx @@ -4,12 +4,13 @@ import { Button } from '@/components/ui/button' import { Command, CommandEmpty, CommandInput, CommandList } from '@/components/ui/command' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { AgentIcon, type AgentCatalogEntry } from '@/lib/agent-catalog' +import type { AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { agentPickerBlankTerminalMatches, getAgentPickerCommandValue, searchAgentPickerEntries -} from '@/lib/agent-picker-search' +} from '@/lib/agent-catalog/agent-picker-search' import { cn } from '@/lib/utils' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import * as state from './agent-combobox-command-state' diff --git a/src/renderer/src/components/agent/AgentLaunchPicker.tsx b/src/renderer/src/components/agent/AgentLaunchPicker.tsx index a27d05e6cce..4c28231b0b6 100644 --- a/src/renderer/src/components/agent/AgentLaunchPicker.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPicker.tsx @@ -21,7 +21,8 @@ import { DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' -import { AgentIcon, getAgentLabel } from '@/lib/agent-catalog' +import { getAgentLabel } from '@/lib/agent-catalog/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { useTranslate } from '@/i18n/use-translate' import { rowLabel } from '../tab-bar/tab-agent-row-presentation' import type { NewTabAgentMenuModel } from '../tab-bar/use-new-tab-agent-menu-rows' diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.language.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.language.test.tsx deleted file mode 100644 index bfb526c2ecb..00000000000 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.language.test.tsx +++ /dev/null @@ -1,62 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { createRoot } from 'react-dom/client' -import { expect, it, vi } from 'vitest' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuTrigger -} from '@/components/ui/dropdown-menu' -import { TooltipProvider } from '@/components/ui/tooltip' -import { i18n } from '@/i18n/i18n' -import es from '@/i18n/locales/es.json' -import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' -import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' - -vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) - -it('refreshes translated row labels on a language change with unchanged props', async () => { - const language = i18n.language - const host = document.createElement('div') - document.body.append(host) - const root = createRoot(host) - const entry: AgentPickerEntry = { - agent: 'codex', - label: 'Codex', - rows: [{ agent: 'codex', kind: 'chat-unavailable', reason: 'ssh' }], - surfaces: ['terminal'], - defaultSurface: 'terminal', - terminal: {}, - structured: {}, - catalog: { origin: 'probe', fetchedAt: 1, models: [] } - } - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) - try { - i18n.addResourceBundle('es', 'translation', es) - await i18n.changeLanguage('en') - act(() => - root.render( - - - New tab - - - - - - ) - ) - const row = document.querySelector('[role="menuitem"]')! - expect(row.textContent).toContain('No chat over SSH') - await act(async () => { - await i18n.changeLanguage('es') - }) - expect(row.textContent).toContain(es.auto.components.tab.bar.QuickLaunchButton.chatNotOverSsh) - expect(row.textContent).not.toContain('No chat over SSH') - } finally { - act(() => root.unmount()) - host.remove() - await i18n.changeLanguage(language) - vi.unstubAllGlobals() - } -}) diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx new file mode 100644 index 00000000000..42aac33f20c --- /dev/null +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.select.test.tsx @@ -0,0 +1,99 @@ +// @vitest-environment happy-dom +import { useState } from 'react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' +import { useAgentPickerDraftScope } from './agent-launch-picker-drafts' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { TooltipProvider } from '@/components/ui/tooltip' +import type { + AgentPickerDraft, + AgentPickerEntry +} from '../../../../shared/agent-launch/picker/agent-launch-picker' +vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) +afterEach(cleanup) + +const efforts = [ + { value: 'low', label: 'Low' }, + { value: 'high', label: 'High' } +] +const entry: AgentPickerEntry = { + agent: 'codex', + label: 'Codex', + defaultSurface: 'terminal', + surfaces: ['chat', 'terminal'], + terminal: {}, + structured: {}, + catalog: { + origin: 'probe', + fetchedAt: 1, + models: [ + { id: 'astra', label: 'Astra', isDefault: true, efforts }, + { id: 'luna', label: 'Luna', isDefault: false, efforts } + ] + }, + rows: [{ kind: 'cli', agent: 'codex', chat: true }] +} + +// A form that re-derives each entry's draft from what it saved and resets its draft scope, as Automations do. +function Form({ query, onPick }: { query: string; onPick: (draft?: AgentPickerDraft) => void }) { + const [saved, setSaved] = useState({}) + const draftScope = useAgentPickerDraftScope(saved.model) + return ( + + + Agent + + ({ agent: 'codex', surface: 'terminal', choices: { ...saved } })} + runLaunch={(_row, draft) => { + onPick(draft) + if (draft) { + setSaved(draft.choices) + } + }} + /> + + + + ) +} + +it.each([ + ['an agent row', ''], + ['a search-result row', 'astra low'] +])( + 'applies each model and effort picked in %s setup to the form and keeps the panel on them', + (_row, query) => { + const onPick = vi.fn() + render(
) + fireEvent.click(screen.getAllByRole('button', { name: 'Configure Codex' })[0]) + fireEvent.click(screen.getByRole('option', { name: 'Luna' })) + expect(onPick).toHaveBeenLastCalledWith( + expect.objectContaining({ choices: expect.objectContaining({ model: 'luna' }) }) + ) + expect(screen.getByRole('option', { name: 'Luna' }).getAttribute('data-current')).toBe('true') + fireEvent.click(screen.getByRole('radio', { name: 'High' })) + expect(onPick).toHaveBeenLastCalledWith( + expect.objectContaining({ + choices: expect.objectContaining({ model: 'luna', options: { effort: 'high' } }) + }) + ) + // Typed Arguments stay staged in the panel across a close, after the form took its picks. + fireEvent.change(screen.getByRole('textbox', { name: 'Arguments' }), { + target: { value: '--search' } + }) + fireEvent.keyDown(screen.getByRole('menu', { name: 'Configure Codex' }), { key: 'Escape' }) + expect(screen.queryByRole('menu', { name: 'Configure Codex' })).toBeNull() + fireEvent.click(screen.getAllByRole('button', { name: 'Configure Codex' })[0]) + expect(screen.getByRole('textbox', { name: 'Arguments' })).toHaveProperty('value', '--search') + } +) diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx index 31b1804db26..90bf546b321 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenu.tsx @@ -7,7 +7,7 @@ import { useAppStore } from '@/store/index' import { parseExecutionHostId } from '../../../../shared/execution-host' import { Input } from '@/components/ui/input' import { Terminal } from 'lucide-react' -import { agentPickerBlankTerminalMatches } from '@/lib/agent-picker-search' +import { agentPickerBlankTerminalMatches } from '@/lib/agent-catalog/agent-picker-search' import { AgentDefaultContextMenu } from './agent-combobox-items' import { AgentPickerMenuRow, type AgentPickerMenuLaunch } from './AgentLaunchPickerMenuRow' import { DropdownMenuItem } from '@/components/ui/dropdown-menu' diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx index 18b9adfe0a1..ce63771d05c 100644 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx +++ b/src/renderer/src/components/agent/AgentLaunchPickerMenuRow.tsx @@ -6,7 +6,7 @@ import { DropdownMenuShortcut, useDropdownMenuClose } from '@/components/ui/dropdown-menu' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' import { AgentDefaultContextMenu } from './agent-combobox-items' import { AgentLaunchSetupButton, type AgentPickerSetupIdentity } from './AgentLaunchSetupButton' @@ -161,6 +161,11 @@ export const AgentPickerMenuRow = memo(function AgentPickerMenuRow({ onSelectAgent?.(entry.agent) } }} + onSelect={ + mode === 'select' + ? (draft) => runLaunch(pickerLaunchRow(entry, draft.surface), draft, entry) + : undefined + } onUse={(draft) => { const chosen = mode === 'select' ? draft.surface : undefined const result = diff --git a/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx b/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx index 0d14332b0b7..a955acefea8 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupButton.tsx @@ -2,6 +2,10 @@ import { useState, type ReactElement } from 'react' import { AgentLaunchSetupSubmenu } from './AgentLaunchSetupSubmenu' import { useTranslate } from '@/i18n/use-translate' import { AgentLaunchSetupPanel } from './AgentLaunchSetupPanel' +import { + acceptAgentPickerArguments, + type AgentPickerEdit +} from '../../../../shared/agent-launch/picker/agent-launch-picker-edits' import type { AgentPickerDraft, AgentPickerEntry, @@ -25,7 +29,7 @@ export type AgentLaunchSetupPanelProps = { disabled?: boolean autoFocus?: boolean terminalBlocked?: boolean - onDraftChange: (draft: AgentPickerDraft) => void + onDraftChange: (draft: AgentPickerDraft, edit: AgentPickerEdit['kind']) => void onUse: (draft: AgentPickerDraft) => boolean | void | Promise } @@ -44,6 +48,7 @@ export function AgentLaunchSetupButton({ open: controlledOpen, onOpenChange, returnFocus, + onSelect, onUse }: { entry: AgentPickerEntry @@ -60,6 +65,8 @@ export function AgentLaunchSetupButton({ open?: boolean onOpenChange?: (open: boolean) => void returnFocus?: () => void + /** Select mode: a pick in the panel applies to the form without closing the menu. */ + onSelect?: (draft: AgentPickerDraft) => void onUse: (draft: AgentPickerDraft) => boolean | void | Promise }) { const t = useTranslate() @@ -96,7 +103,18 @@ export function AgentLaunchSetupButton({ disabled={disabled} autoFocus={autoFocus} terminalBlocked={terminalBlocked} - onDraftChange={setup.change} + onDraftChange={(draft, edit) => { + setup.change(draft) + // Why: a launch form's trigger and Create read its selection, so a pick applies without closing the panel. + // Arguments edits and text cards stay staged until Launch or Use. + const picked = edit === 'choice' || edit === 'permission' || edit === 'speed' + const current = + picked && mode === 'select' && !entry.textGeneration ? setup.getDraft() : undefined + const selected = current && acceptAgentPickerArguments(entry, current) + if (selected && setup.accept(selected, true)) { + onSelect?.(selected) + } + }} onUse={(draft) => { if (mode !== 'select' && terminalBlocked && draft.surface === 'terminal') { return false diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index f1674e82ec5..3e4850dfffa 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -65,7 +65,7 @@ export function AgentLaunchSetupPanel({ const editDraft = (edit: AgentPickerEdit) => { const current = getDraft() if (current) { - onDraftChange(applyAgentPickerEdit(entry, current, edit)) + onDraftChange(applyAgentPickerEdit(entry, current, edit), edit.kind) } } const [modelQuery, setModelQuery] = useState('') diff --git a/src/renderer/src/components/agent/agent-combobox-surface-items.tsx b/src/renderer/src/components/agent/agent-combobox-surface-items.tsx index afb2c99c53c..0749ff09194 100644 --- a/src/renderer/src/components/agent/agent-combobox-surface-items.tsx +++ b/src/renderer/src/components/agent/agent-combobox-surface-items.tsx @@ -1,8 +1,9 @@ import { terminalPendingLabel, terminalPendingReason } from '../tab-bar/new-tab-agent-menu-model' import React, { useState } from 'react' import { CommandItem, CommandSeparator } from '@/components/ui/command' -import { AgentIcon, getAgentCatalog, type AgentCatalogEntry } from '@/lib/agent-catalog' -import { searchAgentPickerEntries } from '@/lib/agent-picker-search' +import { getAgentCatalog, type AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' +import { searchAgentPickerEntries } from '@/lib/agent-catalog/agent-picker-search' import type { AgentLaunchSurface } from '@/lib/agent-session/launch/routing/agent-session-launch-plan' import type { NewTabAgentMenuRow } from '../../../../shared/agent-launch/picker/agent-launch-picker-rows' import type { NewTabAgentMenuModel } from '@/components/tab-bar/use-new-tab-agent-menu-rows' @@ -16,7 +17,7 @@ import { cn } from '@/lib/utils' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' -import type { resolveAgentMenuSelection } from '@/lib/agent-menu-selection' +import type { resolveAgentMenuSelection } from '@/lib/agent-session/launch/routing/agent-menu-selection' import { renderAgentComboboxItem } from './agent-combobox-items' import { AgentSurfaceLaunchButton } from './AgentSurfaceLaunchButton' diff --git a/src/renderer/src/components/agent/agent-launch-picker-drafts.ts b/src/renderer/src/components/agent/agent-launch-picker-drafts.ts index 96d828773dd..7754bad5123 100644 --- a/src/renderer/src/components/agent/agent-launch-picker-drafts.ts +++ b/src/renderer/src/components/agent/agent-launch-picker-drafts.ts @@ -5,10 +5,10 @@ import { useMemo, useReducer, useRef, + useState, useSyncExternalStore } from 'react' -import { sameSourceControlSetupSelection } from '../../lib/source-control/ai/source-control-agent-launch-picker' -import { shallow } from 'zustand/shallow' +import { sameAgentPickerSetupSource as sameSource } from './agent-launch-picker-setup-source' import { agentPickerDraft, type AgentPickerDraft, @@ -32,6 +32,8 @@ import { writeLaunchSetupOptions } from '../native-chat/drafts/native-chat-compo export type AgentPickerSetupIdentity = { model: string; effort?: string } const appSession: AgentPickerDraftOwner = {} const sessionDrafts = new WeakMap>() +// Why: a form re-derives its source (and may reset its scope) from each pick; the open panel stays the authority. +const pickedSetups = new WeakSet() export function invalidateAgentPickerDrafts(scope: AgentPickerDraftOwner) { sessionDrafts.set(scope, new Map()) @@ -48,32 +50,6 @@ export function useAgentPickerDraftScope(resetSignal?: unknown) { return scope } -function sameSource(before?: AgentPickerDraft, after?: AgentPickerDraft) { - if (before === after) { - return true - } - if (!before || !after || before.agent !== after.agent) { - return false - } - const a = before.recipeEdits?.selection - const b = after.recipeEdits?.selection - if (a && b) { - return sameSourceControlSetupSelection( - { ...a, current: { ...a.current, surface: b.current.surface } }, - b - ) - } - return ( - !a && - !b && - before.arguments === after.arguments && - before.choices.model === after.choices.model && - before.choices.permissionMode === after.choices.permissionMode && - shallow(before.choices.options, after.choices.options) && - shallow(before.delegated, after.delegated) - ) -} - export function retireAgentPickerDrafts( entries: readonly AgentPickerEntry[], scope = appSession, @@ -149,9 +125,12 @@ export function useAgentPickerSetup({ [mode, open, launchKey] ) useSyncExternalStore(subscribe, () => read()?.draft) + // The last pick the form took while this panel is open, carried into a record its scope reset recreates. + const [picked, setPicked] = useState() const matches = useCallback( - (record: RetainedSetup) => sameSource(record.source, initial), - [initial] + (record: RetainedSetup) => + (open && pickedSetups.has(record)) || sameSource(record.source, initial), + [open, initial] ) const lifetime = useMemo( () => ({ @@ -177,9 +156,12 @@ export function useAgentPickerSetup({ agent: entry.agent, preset: originalPreset, source: initial, - draft: authored ?? seed ?? agentPickerDraft(entry), + draft: authored ?? (open ? picked : undefined) ?? seed ?? agentPickerDraft(entry), active: open } + if (open && picked) { + pickedSetups.add(record) + } if (mode === 'launch') { writeLaunchSetupOptions(launchKey, record.draft, slot, record) } else { @@ -201,6 +183,7 @@ export function useAgentPickerSetup({ initial, seed, open, + picked, mode, launchKey, slot, @@ -215,18 +198,26 @@ export function useAgentPickerSetup({ } }, [lifetime]) useLayoutEffect(() => { - if ((mode === 'launch' || !open) && !read()) { + const current = read() + if (!open && current) { + pickedSetups.delete(current) + } + if ((mode === 'launch' || !open) && !current) { return } const activeRecord = acquire() activeRecord.active = open + if (open && pickedSetups.has(activeRecord)) { + // The form now derives its source from this record's pick, so later edits survive a close. + activeRecord.source = initial + } if (activeRecord !== retained) { publish() } return () => { activeRecord.active = false } - }, [open, read, acquire, retained, mode]) + }, [open, read, acquire, retained, mode, initial]) let record = retained && matches(retained) ? retained : undefined const currentDraft = (draft: AgentPickerDraft) => { const current = @@ -266,6 +257,7 @@ export function useAgentPickerSetup({ getDraft, change, activate: () => { + setPicked(undefined) if ( live.current === lifetime && sessionDrafts.get(draftScope) === collection && @@ -277,7 +269,8 @@ export function useAgentPickerSetup({ publish() } }, - accept: (draft: AgentPickerDraft) => { + /** `pick`: the form applies this while the panel stays open (select mode). */ + accept: (draft: AgentPickerDraft, pick = false) => { if (!getDraft()) { return false } @@ -292,6 +285,10 @@ export function useAgentPickerSetup({ } : draft store(accepted) + if (pick) { + pickedSetups.add(record!) + setPicked(accepted) + } return true } } diff --git a/src/renderer/src/components/agent/agent-launch-picker-setup-source.ts b/src/renderer/src/components/agent/agent-launch-picker-setup-source.ts new file mode 100644 index 00000000000..229d862b09d --- /dev/null +++ b/src/renderer/src/components/agent/agent-launch-picker-setup-source.ts @@ -0,0 +1,30 @@ +import { shallow } from 'zustand/shallow' +import { sameSourceControlSetupSelection } from '../../lib/source-control/ai/source-control-agent-launch-picker' +import type { AgentPickerDraft } from '../../../../shared/agent-launch/picker/agent-launch-picker' + +/** Whether a retained setup still derives from the form's current draft for its agent. */ +export function sameAgentPickerSetupSource(before?: AgentPickerDraft, after?: AgentPickerDraft) { + if (before === after) { + return true + } + if (!before || !after || before.agent !== after.agent) { + return false + } + const a = before.recipeEdits?.selection + const b = after.recipeEdits?.selection + if (a && b) { + return sameSourceControlSetupSelection( + { ...a, current: { ...a.current, surface: b.current.surface } }, + b + ) + } + return ( + !a && + !b && + before.arguments === after.arguments && + before.choices.model === after.choices.model && + before.choices.permissionMode === after.choices.permissionMode && + shallow(before.choices.options, after.choices.options) && + shallow(before.delegated, after.delegated) + ) +} diff --git a/src/renderer/src/lib/agent-catalog.tsx b/src/renderer/src/components/agent/icons/AgentIcon.tsx similarity index 68% rename from src/renderer/src/lib/agent-catalog.tsx rename to src/renderer/src/components/agent/icons/AgentIcon.tsx index 9a18e6f075f..38189616d4d 100644 --- a/src/renderer/src/lib/agent-catalog.tsx +++ b/src/renderer/src/components/agent/icons/AgentIcon.tsx @@ -1,8 +1,7 @@ import type React from 'react' +import { getAgentCatalog, getAgentLabel } from '../../../lib/agent-catalog/agent-catalog' import { ClaudeIcon, DroidIcon, OpenAIIcon } from '@/components/status-bar/icons' -import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' -import type { TerminalAgent } from '../../../shared/agent-status/identity/terminal-agent' -import { formatAgentTypeLabel } from '../../../shared/agent-status/presentation/agent-type-label' +import type { TerminalAgent } from '../../../../../shared/agent-status/identity/terminal-agent' import { AgentLetterIcon, AiderIcon, @@ -12,32 +11,7 @@ import { OpenCodeIcon, PiIcon } from './agent-icon-glyphs' -import { createLocalizedCatalog } from '@/i18n/localized-catalog' import { AGENT_FAVICON_ASSETS } from './agent-favicon-assets' -import { buildAgentCatalogEntries } from './agent-catalog-entries' - -export type AgentCatalogEntry = { - id: TuiAgent - label: string - /** Default CLI binary name used for PATH detection. */ - cmd: string - searchAliases?: readonly string[] - /** Direct or bundled image URL for agents whose project identity is not represented by a favicon service. */ - iconUrl?: string - /** Domain for Google's favicon service — used for agents without an SVG icon. */ - faviconDomain?: string - /** Homepage/install docs URL, sourced from the README agent badge list. */ - homepageUrl: string -} - -export const getAgentCatalog = createLocalizedCatalog(buildAgentCatalogEntries) - -// Why: tests and a few legacy call sites still import a catalog snapshot. -export const AGENT_CATALOG: AgentCatalogEntry[] = getAgentCatalog() - -export function getAgentLabel(agent: TerminalAgent): string { - return getAgentCatalog().find((entry) => entry.id === agent)?.label ?? formatAgentTypeLabel(agent) -} export function AgentIcon({ agent, diff --git a/src/renderer/src/components/agent/icons/agent-favicon-assets.ts b/src/renderer/src/components/agent/icons/agent-favicon-assets.ts new file mode 100644 index 00000000000..87ce603600c --- /dev/null +++ b/src/renderer/src/components/agent/icons/agent-favicon-assets.ts @@ -0,0 +1,70 @@ +import qoderUrl from '../../../../../shared/agent-icons/qoder.png?url' +import type { TuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent' +import grokUrl from '../../../../../shared/agent-icons/grok.png?url' +import mimoCodeUrl from '../../../../../shared/agent-icons/mimo-code.png?url' +import anteUrl from '../../../../../shared/agent-icons/ante.png?url' +import traeUrl from '../../../../../shared/agent-icons/trae.png?url' +import primeAgentUrl from '../../../../../shared/agent-icons/prime-agent.png?url' +import geminiUrl from '../../../../../shared/agent-icons/gemini.png?url' +import antigravityUrl from '../../../../../shared/agent-icons/antigravity.png?url' +import gooseUrl from '../../../../../shared/agent-icons/goose.png?url' +import ampUrl from '../../../../../shared/agent-icons/amp.png?url' +import kiroUrl from '../../../../../shared/agent-icons/kiro.png?url' +import crushUrl from '../../../../../shared/agent-icons/crush.png?url' +import augUrl from '../../../../../shared/agent-icons/aug.png?url' +import autohandUrl from '../../../../../shared/agent-icons/autohand.png?url' +import clineUrl from '../../../../../shared/agent-icons/cline.png?url' +import freebuffUrl from '../../../../../shared/agent-icons/freebuff.png?url' +import codebuffUrl from '../../../../../shared/agent-icons/codebuff.png?url' +import commandCodeUrl from '../../../../../shared/agent-icons/command-code.png?url' +import continueUrl from '../../../../../shared/agent-icons/continue.png?url' +import cursorUrl from '../../../../../shared/agent-icons/cursor.png?url' +import kimiUrl from '../../../../../shared/agent-icons/kimi.png?url' +import mistralVibeUrl from '../../../../../shared/agent-icons/mistral-vibe.png?url' +import qwenCodeUrl from '../../../../../shared/agent-icons/qwen-code.png?url' +import rovoUrl from '../../../../../shared/agent-icons/rovo.png?url' +import hermesUrl from '../../../../../shared/agent-icons/hermes.png?url' +import devinUrl from '../../../../../shared/agent-icons/devin.png?url' +import museUrl from '../../../../../shared/agent-icons/muse.png?url' +import zcodeUrl from '../../../../../shared/agent-icons/zcode.png?url' +import openclawUrl from '../../../../../shared/agent-icons/openclaw.png?url' +import dshUrl from '../../../../../shared/agent-icons/dsh.png?url' +import jcodeUrl from '../../../../../shared/agent-icons/jcode.png?url' +import codebuddyUrl from '../../../../../shared/agent-icons/codebuddy.png?url' + +// Bundle favicons for offline/Google-blocked regions (#8451); shared/agent-icons also supplies mobile-agent-icon-assets.ts. +export const AGENT_FAVICON_ASSETS: Partial> = { + grok: grokUrl, + 'mimo-code': mimoCodeUrl, + ante: anteUrl, + trae: traeUrl, + 'prime-agent': primeAgentUrl, + qoder: qoderUrl, + 'qoder-cn': qoderUrl, + gemini: geminiUrl, + antigravity: antigravityUrl, + goose: gooseUrl, + amp: ampUrl, + kiro: kiroUrl, + crush: crushUrl, + aug: augUrl, + autohand: autohandUrl, + cline: clineUrl, + codebuff: codebuffUrl, + freebuff: freebuffUrl, + 'command-code': commandCodeUrl, + continue: continueUrl, + cursor: cursorUrl, + kimi: kimiUrl, + 'mistral-vibe': mistralVibeUrl, + 'qwen-code': qwenCodeUrl, + rovo: rovoUrl, + hermes: hermesUrl, + devin: devinUrl, + muse: museUrl, + dsh: dshUrl, + zcode: zcodeUrl, + openclaw: openclawUrl, + jcode: jcodeUrl, + codebuddy: codebuddyUrl +} diff --git a/src/renderer/src/lib/agent-icon-glyphs.tsx b/src/renderer/src/components/agent/icons/agent-icon-glyphs.tsx similarity index 99% rename from src/renderer/src/lib/agent-icon-glyphs.tsx rename to src/renderer/src/components/agent/icons/agent-icon-glyphs.tsx index 66c3aa786ed..be70a55196e 100644 --- a/src/renderer/src/lib/agent-icon-glyphs.tsx +++ b/src/renderer/src/components/agent/icons/agent-icon-glyphs.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { cn } from './utils' +import { cn } from '../../../lib/utils' export function PiIcon({ size = 14, diff --git a/src/renderer/src/lib/agent-type-icon.tsx b/src/renderer/src/components/agent/icons/agent-type-icon.tsx similarity index 80% rename from src/renderer/src/lib/agent-type-icon.tsx rename to src/renderer/src/components/agent/icons/agent-type-icon.tsx index 1b98492d56c..b12412deb72 100644 --- a/src/renderer/src/lib/agent-type-icon.tsx +++ b/src/renderer/src/components/agent/icons/agent-type-icon.tsx @@ -1,8 +1,8 @@ import type React from 'react' -import type { AgentType } from '../../../shared/agent-status/contracts/agent-status-types' -import { AgentIcon } from './agent-catalog' +import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types' +import { AgentIcon } from './AgentIcon' import { AgentLetterIcon } from './agent-icon-glyphs' -import { agentTypeToIconAgent } from '../../../shared/agent-status/presentation/agent-type-icon-agent' +import { agentTypeToIconAgent } from '../../../../../shared/agent-status/presentation/agent-type-icon-agent' /** Status-row icon: known agents get their brand icon, any other OSC 7501 program its first letter. */ export function AgentTypeIcon({ diff --git a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx index c3d5bf943cc..b47f494f994 100644 --- a/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx +++ b/src/renderer/src/components/agent/launch-settings/AgentDefaultSurfacePreviews.tsx @@ -16,7 +16,7 @@ import { import { composeActiveTerminalTheme } from '@/components/terminal-pane/appearance/terminal-appearance' import { useSystemPrefersDark } from '@/hooks/theme/use-system-prefers-dark' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { buildFontFamily } from '@/lib/monospace-font-family' import { resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' import { cn } from '@/lib/utils' diff --git a/src/renderer/src/components/automations/AutomationAgentLaunchPicker.tsx b/src/renderer/src/components/automations/AutomationAgentLaunchPicker.tsx index c84bc199de9..beee205e96a 100644 --- a/src/renderer/src/components/automations/AutomationAgentLaunchPicker.tsx +++ b/src/renderer/src/components/automations/AutomationAgentLaunchPicker.tsx @@ -10,7 +10,7 @@ import { resolveHostCapabilities, type ProspectiveWorkspace } from '@/lib/agent-session/launch/routing/agent-launch-route-input' -import type { AgentCatalogEntry } from '@/lib/agent-catalog' +import type { AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' import { parseExecutionHostId } from '../../../../shared/execution-host' import { AUTOMATION_LAUNCH_SETUP_RUNTIME_CAPABILITY } from '../../../../shared/automations/automation-runtime-capabilities' import { automationLegacyArguments } from '../../../../shared/automations/launch/automation-legacy-arguments' diff --git a/src/renderer/src/components/automations/AutomationDetail.tsx b/src/renderer/src/components/automations/AutomationDetail.tsx index 82213b9e4b5..cb8f9f992e3 100644 --- a/src/renderer/src/components/automations/AutomationDetail.tsx +++ b/src/renderer/src/components/automations/AutomationDetail.tsx @@ -3,7 +3,8 @@ import { Pencil, Pause, Play, Trash2 } from 'lucide-react' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { getAgentCatalog, AgentIcon } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import type { Automation } from '../../../../shared/automations/automation-definition' import type { AutomationRun } from '../../../../shared/automations/history/automation-run' import { formatUiAutomationSchedule } from './automation-schedule-label' diff --git a/src/renderer/src/components/automations/AutomationEditorDialog.tsx b/src/renderer/src/components/automations/AutomationEditorDialog.tsx index 3d57e56bce5..9a8b4ac659e 100644 --- a/src/renderer/src/components/automations/AutomationEditorDialog.tsx +++ b/src/renderer/src/components/automations/AutomationEditorDialog.tsx @@ -9,7 +9,7 @@ import { automationLaunchWorkspace } from './automation-launch-surface' import { Dialog, DialogContent } from '@/components/ui/dialog' -import { getAgentCatalog } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { filterEnabledTuiAgents } from '../../../../shared/agent-launch/catalog/tui-agent-selection' import type { AutomationLaunchPreferences, diff --git a/src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx b/src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx index e50ae15e367..4db710ee4f4 100644 --- a/src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx +++ b/src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx @@ -14,7 +14,7 @@ vi.mock('@monaco-editor/react', () => ({ }, loader: { config: vi.fn() } })) -vi.mock('@/lib/monaco-setup', () => ({ monaco: {} })) +vi.mock('@/lib/editor/monaco/monaco-setup', () => ({ monaco: {} })) vi.mock('@/store', () => ({ useAppStore: (selector: (state: Record) => unknown) => selector({ diff --git a/src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx b/src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx index 5535d225d40..15bf790323d 100644 --- a/src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx +++ b/src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx @@ -4,9 +4,9 @@ import type { editor } from 'monaco-editor' import { installMonacoEditorFindShortcut } from '@/components/editor/editor-shortcuts' import { syncContentOnMount, syncContentUpdate } from '@/components/editor/monaco-content-sync' import { isMonacoFindWidgetOpen } from '@/components/editor/monaco-find-widget' -import { monacoTypographyOptions } from '@/lib/editor-typography' +import { monacoTypographyOptions } from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' -import '@/lib/monaco-setup' +import '@/lib/editor/monaco/monaco-setup' import { cn } from '@/lib/utils' import { buildAutomationPromptEditorOptions } from './automation-editor-prompt-options' import { useMonacoTheme } from '@/hooks/use-monaco-theme' diff --git a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx index ced6fef4624..fedae0d26ae 100644 --- a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx +++ b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.test.tsx @@ -1,12 +1,11 @@ // @vitest-environment happy-dom -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { useState } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AGENT_CATALOG } from '@/lib/agent-catalog' +import { AGENT_CATALOG } from '@/lib/agent-catalog/agent-catalog' import { TooltipProvider } from '@/components/ui/tooltip' import { useAppStore } from '@/store' -import { createCompatibleRuntimeStatusResponse } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/hosts/capabilities/local-runtime-capabilities' import { AUTOMATION_RUNTIME_CAPABILITIES } from '../../../../shared/automations/automation-runtime-capabilities' @@ -155,18 +154,6 @@ function renderSidebar( return render() } -function setOldHostCapabilities(capabilities: readonly string[]) { - act(() => { - const status = { - ...createCompatibleRuntimeStatusResponse().result, - capabilities: [...capabilities] - } - useAppStore.setState({ - runtimeStatusByEnvironmentId: new Map([['old', { status, checkedAt: 1 }]]) - }) - }) -} - beforeEach(() => { clearNativeChatComposerDraftsForTests() setLocalRuntimeCapabilitiesForTests(AUTOMATION_RUNTIME_CAPABILITIES) @@ -183,55 +170,6 @@ function openPicker() { } describe('AutomationEditorSettingsSidebar agent picker', () => { - it('keeps agent selection usable on an older host without exposing unsupported setup', () => { - setLocalRuntimeCapabilitiesForTests([]) - const onDraftChange = vi.fn() - setOldHostCapabilities([]) - renderSidebar(onDraftChange, DRAFT, { - kind: 'runtime', - environmentId: 'old', - pairingRevision: 1 - }) - openPicker() - expect(screen.queryByRole('button', { name: /^Configure / })).toBeNull() - fireEvent.click(screen.getByRole('menuitem', { name: 'Claude' })) - expect(onDraftChange.mock.calls[0][0](DRAFT).agentId).toBe('claude') - }) - - it('offers fresh sessions for a full launch setup and preserves its choices', () => { - const changed = vi.fn() - renderSidebar(changed, { - ...DRAFT, - reuseSession: true, - launchPreferences: { model: 'gpt-5.5' } - }) - fireEvent.click(screen.getByRole('button', { name: 'Use fresh sessions' })) - const next = changed.mock.calls[0][0]({ - ...DRAFT, - reuseSession: true, - launchPreferences: { model: 'gpt-5.5' } - }) - expect(next.reuseSession).toBe(false) - expect(next.launchPreferences).toEqual({ model: 'gpt-5.5' }) - }) - - it('keeps agent and legacy editing available before selecting a destination', () => { - const changed = vi.fn() - renderSidebar(changed, { ...DRAFT, agentId: 'claude' }, null) - fireEvent.change(screen.getByLabelText('Extra agent arguments'), { - target: { value: '--add-dir docs' } - }) - openPicker() - expect(screen.queryByRole('button', { name: /^Configure / })).toBeNull() - fireEvent.click(screen.getByRole('menuitem', { name: 'Codex' })) - const next = changed.mock.calls.reduce((draft, [update]) => update(draft), { - ...DRAFT, - agentId: 'claude' - }) - expect(next.agentId).toBe('codex') - expect(next.extraAgentArgs).toBe('--add-dir docs') - }) - it('discards an unaccepted setup when the editor owner closes', () => { const onDraftChange = vi.fn() const form = renderSidebar(onDraftChange) diff --git a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx index 51f95c09d7d..6c89609af50 100644 --- a/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx +++ b/src/renderer/src/components/automations/AutomationEditorSettingsSidebar.tsx @@ -8,7 +8,7 @@ import type { OrcaHooks } from '../../../../shared/orca-yaml-hook-types' import type { ProjectHostSetup } from '../../../../shared/project-types' import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' -import type { AgentCatalogEntry } from '@/lib/agent-catalog' +import type { AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' import { AUTOMATION_EDITOR_SECTION_LABEL_CLASS, Field } from './automation-page-parts' import { AutomationMissedRunGraceField } from './AutomationMissedRunGraceField' import { AutomationPrecheckFields } from './AutomationPrecheckFields' diff --git a/src/renderer/src/components/automations/AutomationListFilterMenu.tsx b/src/renderer/src/components/automations/AutomationListFilterMenu.tsx index e8d472695db..cc11fbcad2f 100644 --- a/src/renderer/src/components/automations/AutomationListFilterMenu.tsx +++ b/src/renderer/src/components/automations/AutomationListFilterMenu.tsx @@ -16,8 +16,9 @@ import { DropdownMenuSubTrigger, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' -import { AgentIcon, getAgentCatalog } from '@/lib/agent-catalog' -import { searchAgentPickerEntries } from '@/lib/agent-picker-search' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' +import { searchAgentPickerEntries } from '@/lib/agent-catalog/agent-picker-search' import { useTranslate } from '@/i18n/use-translate' import { useBoundedHostRows } from '@/components/host-picker/use-bounded-host-rows' import { HostListSearchField } from '@/components/host-picker/HostListSearchField' diff --git a/src/renderer/src/components/automations/AutomationListLocalRow.tsx b/src/renderer/src/components/automations/AutomationListLocalRow.tsx index 0682e16c3cc..8c0bd693100 100644 --- a/src/renderer/src/components/automations/AutomationListLocalRow.tsx +++ b/src/renderer/src/components/automations/AutomationListLocalRow.tsx @@ -19,7 +19,7 @@ import { } from '@/components/ui/dropdown-menu' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { cn } from '@/lib/utils' import type { AutomationRun } from '../../../../shared/automations/history/automation-run' import { getAutomationRunRepoId } from '../../../../shared/automations/history/automation-run-identity' diff --git a/src/renderer/src/components/automations/AutomationTimeField.test.tsx b/src/renderer/src/components/automations/AutomationTimeField.test.tsx index aee7d7f15c7..3a230ca8a87 100644 --- a/src/renderer/src/components/automations/AutomationTimeField.test.tsx +++ b/src/renderer/src/components/automations/AutomationTimeField.test.tsx @@ -5,33 +5,12 @@ import React from 'react' import { cleanup, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AutomationTimeField, resolveDigitCommit, resolveDigitStep } from './AutomationTimeField' +import { AutomationTimeField } from './AutomationTimeField' afterEach(() => { cleanup() }) -describe('AutomationTimeField helpers', () => { - it('resolves digit commits with empty → min and range clamp', () => { - expect(resolveDigitCommit('', 9, 1, 12)).toBe(1) - expect(resolveDigitCommit('', 15, 0, 59)).toBe(0) - expect(resolveDigitCommit('9', 1, 1, 12)).toBe(9) - expect(resolveDigitCommit('00', 9, 1, 12)).toBe(1) - expect(resolveDigitCommit('24', 9, 0, 23)).toBe(23) - expect(resolveDigitCommit('99', 15, 0, 59)).toBe(59) - expect(resolveDigitCommit('abc', 15, 0, 59)).toBe(15) - }) - - it('steps from in-progress text rather than only the committed value', () => { - expect(resolveDigitStep('1', 9, 1, 12, 1)).toBe(2) - // At the min bound, down wraps to max. - expect(resolveDigitStep('1', 9, 1, 12, -1)).toBe(12) - expect(resolveDigitStep('', 9, 1, 12, 1)).toBe(10) - expect(resolveDigitStep('12', 12, 1, 12, 1)).toBe(1) - expect(resolveDigitStep('0', 0, 0, 59, -1)).toBe(59) - }) -}) - function ControlledTimeField({ initialTime = '09:15', mode = 'time', diff --git a/src/renderer/src/components/automations/AutomationsListPanel.test.tsx b/src/renderer/src/components/automations/AutomationsListPanel.test.tsx deleted file mode 100644 index 5d58d267389..00000000000 --- a/src/renderer/src/components/automations/AutomationsListPanel.test.tsx +++ /dev/null @@ -1,153 +0,0 @@ -// @vitest-environment happy-dom - -/** Preserve picker/search identity across loading, empty, no-match and failure states so refresh cannot erase the query/caret. */ - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { AutomationsListPanel } from './AutomationsListPanel' -import { - buildAutomationListViewItems, - EMPTY_AUTOMATION_LIST_FILTER, - type AutomationListSort, - type AutomationListSortField -} from './automation-list-view' -import type { AutomationHostCatalogView } from './use-automation-host-catalog' -import { makeAutomationListRow } from './automations-page-fixtures' -import type { AutomationListRow } from './automation-list-row-identity' -import type { ExternalAutomationListEntry } from './external-automation-list-entries' -import type { AutomationPaneTab } from './automation-page-state' - -let container: HTMLDivElement -let root: Root - -beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() -}) - -const HOST_CATALOG = { - catalog: { entries: [], byStableKey: new Map(), hydration: {} }, - entries: [], - resolution: { - effective: { kind: 'all' }, - entry: null, - status: 'all', - announceFallback: false - }, - rows: { - rows: [], - automations: [], - capturedOwners: new Map(), - groups: [], - answered: true - }, - loadCounts: { failedHostCount: 0, totalHostCount: 1 }, - selectHost: () => undefined, - recover: () => undefined, - refreshHosts: () => undefined, - notifyAuthorityChange: () => undefined -} as unknown as AutomationHostCatalogView - -function renderPanel( - rows: readonly AutomationListRow[], - query: string, - onQueryChange: (next: string) => void = () => undefined, - uncheckedNotice: string | null = null, - options: { - selectedRowKey?: string | null - selectedExternalKey?: string | null - onOpenDetail?: () => void - selectAutomationRow?: (key: string | null) => void - selectExternalKey?: (key: string | null) => void - externalEntries?: readonly ExternalAutomationListEntry[] - setActivePaneTab?: (tab: AutomationPaneTab) => void - listSort?: AutomationListSort | null - onListSortChange?: (field: AutomationListSortField) => void - } = {} -): void { - const externalEntries = options.externalEntries ?? [] - act(() => { - root.render( - - 0 || externalEntries.length > 0} - hasFilteredListItems={rows.length > 0 || externalEntries.length > 0} - listFilter={EMPTY_AUTOMATION_LIST_FILTER} - onListFilterChange={() => undefined} - listSearchQuery={query} - isListSearchQueryTooLarge={false} - onListSearchQueryChange={onQueryChange} - searchCounts={{ - hostRowCount: rows.length + externalEntries.length, - visibleRowCount: rows.length + externalEntries.length, - searchActive: query !== '' - }} - hostCatalog={HOST_CATALOG} - canCreateAutomation={true} - onOpenRuns={() => undefined} - externalManagersUncheckedNotice={uncheckedNotice} - onSelectHost={() => undefined} - onRecoverHost={() => undefined} - sortedListItems={buildAutomationListViewItems({ - rows, - externalEntries - })} - listSort={options.listSort ?? null} - onListSortChange={options.onListSortChange ?? (() => undefined)} - selectedRowKey={options.selectedRowKey ?? null} - selectedExternalKey={options.selectedExternalKey ?? null} - relativeNow={0} - repoMap={new Map()} - worktreeMap={new Map()} - projectHostSetups={[]} - sshConnectionStates={new Map()} - runtimeStatusByEnvironmentId={new Map()} - hostTargetFor={() => null} - isActionEnabled={() => true} - externalActionKey={null} - selectAutomationRow={options.selectAutomationRow ?? (() => undefined)} - selectExternalKey={options.selectExternalKey ?? (() => undefined)} - setActivePaneTab={options.setActivePaneTab ?? (() => undefined)} - runNow={() => undefined} - openEditDialog={() => undefined} - toggleAutomation={() => undefined} - requestDeleteAutomation={() => undefined} - requestExternalAction={() => undefined} - openCreateDialog={() => undefined} - onOpenDetail={options.onOpenDetail ?? (() => undefined)} - onRefresh={() => undefined} - isRefreshing={false} - /> - - ) - }) -} - -function searchField(): HTMLInputElement | null { - return container.querySelector('input[aria-label="Search automations"]') -} - -describe('AutomationsListPanel search field persistence', () => { - it('survives a refresh tick that momentarily empties the list', () => { - const row = makeAutomationListRow() - renderPanel([row], 'night') - const before = searchField() - before?.focus() - - renderPanel([], 'night') - - // Identity, not presence: a remount is what loses the caret and the query. - expect(searchField()).toBe(before) - expect(searchField()?.value).toBe('night') - expect(document.activeElement).toBe(before) - }) -}) diff --git a/src/renderer/src/components/automations/automation-detail-tab-navigation.test.ts b/src/renderer/src/components/automations/automation-detail-tab-navigation.test.ts deleted file mode 100644 index e39f852ed01..00000000000 --- a/src/renderer/src/components/automations/automation-detail-tab-navigation.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -// @vitest-environment happy-dom - -import { describe, expect, it } from 'vitest' -import { - getAutomationDetailNextTab, - shouldHandleAutomationDetailEscapeKey, - shouldHandleAutomationDetailTabArrowKey -} from './automation-detail-tab-navigation' - -describe('shouldHandleAutomationDetailTabArrowKey', () => { - function makeEvent( - overrides: Partial<{ - key: string - altKey: boolean - ctrlKey: boolean - metaKey: boolean - shiftKey: boolean - isComposing: boolean - target: EventTarget | null - }> = {} - ) { - return { - key: 'ArrowRight', - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - nativeEvent: { isComposing: overrides.isComposing ?? false }, - target: overrides.target ?? document.body, - ...overrides - } - } - - it('ignores modified or composing arrow keys', () => { - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ metaKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ ctrlKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ altKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ shiftKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ isComposing: true }))).toBe(false) - }) - - it('ignores keys when focus is inside text input, textarea, or contentEditable', () => { - const input = document.createElement('input') - const textarea = document.createElement('textarea') - const select = document.createElement('select') - const editable = document.createElement('div') - editable.contentEditable = 'true' - - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ target: input }))).toBe(false) - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ target: textarea }))).toBe(false) - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ target: select }))).toBe(false) - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ target: editable }))).toBe(false) - }) - - it.each(['dialog', 'menu', 'listbox'])('ignores keys inside a %s', (role) => { - const dialog = document.createElement('div') - dialog.setAttribute('role', role) - const childButton = document.createElement('button') - dialog.appendChild(childButton) - document.body.appendChild(dialog) - - expect(shouldHandleAutomationDetailTabArrowKey(makeEvent({ target: childButton }))).toBe(false) - - dialog.remove() - }) -}) - -describe('getAutomationDetailNextTab', () => { - it('prevents switching to runs if canAccessRuns is false', () => { - expect( - getAutomationDetailNextTab({ - currentTab: 'overview', - key: 'ArrowRight', - canAccessRuns: false - }) - ).toBeNull() - }) -}) - -describe('shouldHandleAutomationDetailEscapeKey', () => { - function makeEvent( - overrides: Partial<{ - key: string - defaultPrevented: boolean - altKey: boolean - ctrlKey: boolean - metaKey: boolean - shiftKey: boolean - isComposing: boolean - target: EventTarget | null - }> = {} - ) { - return { - key: 'Escape', - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - nativeEvent: { isComposing: overrides.isComposing ?? false }, - target: overrides.target ?? document.body, - ...overrides - } - } - - it('ignores Escape already consumed while returning from a run', () => { - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ defaultPrevented: true }))).toBe(false) - }) - - it('ignores modified or composing Escape keys', () => { - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ metaKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ ctrlKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ altKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ shiftKey: true }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ isComposing: true }))).toBe(false) - }) - - it('ignores Escape when focus is inside text input, textarea, contentEditable, or escapeClearsValue', () => { - const input = document.createElement('input') - const textarea = document.createElement('textarea') - const select = document.createElement('select') - const editable = document.createElement('div') - editable.contentEditable = 'true' - const clearsValue = document.createElement('div') - clearsValue.setAttribute('data-escape-clears-value', 'true') - - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ target: input }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ target: textarea }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ target: select }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ target: editable }))).toBe(false) - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ target: clearsValue }))).toBe(false) - }) - - it.each(['dialog', 'menu', 'listbox'])('ignores Escape inside a %s', (role) => { - const dialog = document.createElement('div') - dialog.setAttribute('role', role) - const childButton = document.createElement('button') - dialog.appendChild(childButton) - document.body.appendChild(dialog) - - expect(shouldHandleAutomationDetailEscapeKey(makeEvent({ target: childButton }))).toBe(false) - - dialog.remove() - }) -}) diff --git a/src/renderer/src/components/automations/automation-draft-model.ts b/src/renderer/src/components/automations/automation-draft-model.ts index 9b2f2fda161..cf776994c35 100644 --- a/src/renderer/src/components/automations/automation-draft-model.ts +++ b/src/renderer/src/components/automations/automation-draft-model.ts @@ -1,6 +1,6 @@ import { buildAutomationRrule } from '../../../../shared/automations/scheduling/automation-schedule-occurrences' import { automationLaunchInputs } from '../../../../shared/automations/launch/automation-launch-choices' -import { getAgentCatalog } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import type { AutomationPrecheck } from '../../../../shared/automations/automation-definition' import type { Worktree } from '../../../../shared/worktree/types' import { diff --git a/src/renderer/src/components/automations/automation-editor-prompt-options.ts b/src/renderer/src/components/automations/automation-editor-prompt-options.ts index ecf32efc959..ce01e95b45b 100644 --- a/src/renderer/src/components/automations/automation-editor-prompt-options.ts +++ b/src/renderer/src/components/automations/automation-editor-prompt-options.ts @@ -1,6 +1,6 @@ import type { editor } from 'monaco-editor' import { monacoFindOptions } from '@/components/editor/monaco-find-options' -import type { MonacoTypographyOptions } from '@/lib/editor-typography' +import type { MonacoTypographyOptions } from '@/lib/editor/appearance/editor-typography' export function buildAutomationPromptEditorOptions(args: { ariaLabel: string diff --git a/src/renderer/src/components/automations/automation-host-status-descriptors.test.ts b/src/renderer/src/components/automations/automation-host-status-descriptors.test.ts deleted file mode 100644 index 509f354ad20..00000000000 --- a/src/renderer/src/components/automations/automation-host-status-descriptors.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AutomationHostCatalogEntry } from './automation-host-catalog-types' - -import { automationHostRecoveryActions } from './automation-host-status-descriptors' - -function entry(overrides: Partial = {}): AutomationHostCatalogEntry { - return { - stableRef: { authority: { kind: 'desktop' }, selector: { kind: 'ssh', targetId: 't1' } }, - owner: null, - stableKey: 'host:desktop:ssh:t1', - label: 'web-01', - authorityLabel: 'This computer', - kind: 'ssh', - catalogState: 'authoritative', - authorityHealth: 'fresh', - executionHealth: 'connected', - querySupport: 'scoped', - ...overrides - } -} - -describe('automation host recovery actions', () => { - it('asks for a server update when the authority itself lacks host scoping', () => { - expect( - automationHostRecoveryActions( - entry({ querySupport: 'legacy-unscoped', scopeGap: 'authority-unscoped' }) - ).authority - ).toBe('update-server') - expect( - automationHostRecoveryActions(entry({ authorityHealth: 'incompatible' })).authority - ).toBe('update-server') - }) - - it('never offers a server update for a host that was removed', () => { - expect( - automationHostRecoveryActions( - entry({ - catalogState: 'removed', - executionHealth: 'unavailable', - querySupport: 'legacy-unscoped', - scopeGap: 'target-removed' - }) - ) - ).toEqual({ authority: null, execution: null }) - }) - - it('offers Reconnect, not a server update, for a target with no verified registration', () => { - expect( - automationHostRecoveryActions( - entry({ - catalogState: 'unhydrated', - executionHealth: 'unknown', - querySupport: 'legacy-unscoped', - scopeGap: 'target-unverified' - }) - ) - ).toEqual({ authority: 'reconnect', execution: null }) - }) - - it('offers no repair for a live target the authority never registered', () => { - expect( - automationHostRecoveryActions( - entry({ querySupport: 'legacy-unscoped', scopeGap: 'target-unregistered' }) - ).authority - ).toBeNull() - }) -}) diff --git a/src/renderer/src/components/automations/automation-list-keyboard-navigation.test.ts b/src/renderer/src/components/automations/automation-list-keyboard-navigation.test.ts deleted file mode 100644 index 4d0de0e150a..00000000000 --- a/src/renderer/src/components/automations/automation-list-keyboard-navigation.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - shouldHandleAutomationListSearchArrowKey, - shouldHandleAutomationListSearchEnterKey -} from './automation-list-keyboard-navigation' - -describe('shouldHandleAutomationListSearchArrowKey', () => { - function event( - overrides: Partial<{ - key: string - altKey: boolean - ctrlKey: boolean - metaKey: boolean - shiftKey: boolean - isComposing: boolean - }> = {} - ) { - return { - key: 'ArrowDown', - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - nativeEvent: { isComposing: overrides.isComposing ?? false }, - ...overrides - } - } - - it('ignores composing, modified, and non-arrow keys', () => { - expect(shouldHandleAutomationListSearchArrowKey(event({ isComposing: true }))).toBe(false) - expect(shouldHandleAutomationListSearchArrowKey(event({ metaKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchArrowKey(event({ ctrlKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchArrowKey(event({ altKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchArrowKey(event({ shiftKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchArrowKey(event({ key: 'Escape' }))).toBe(false) - }) -}) - -describe('shouldHandleAutomationListSearchEnterKey', () => { - function event( - overrides: Partial<{ - key: string - altKey: boolean - ctrlKey: boolean - metaKey: boolean - shiftKey: boolean - isComposing: boolean - }> = {} - ) { - return { - key: 'Enter', - altKey: false, - ctrlKey: false, - metaKey: false, - shiftKey: false, - nativeEvent: { isComposing: overrides.isComposing ?? false }, - ...overrides - } - } - - it('ignores composing, modified, and non-enter keys', () => { - expect(shouldHandleAutomationListSearchEnterKey(event({ isComposing: true }))).toBe(false) - expect(shouldHandleAutomationListSearchEnterKey(event({ metaKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchEnterKey(event({ ctrlKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchEnterKey(event({ altKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchEnterKey(event({ shiftKey: true }))).toBe(false) - expect(shouldHandleAutomationListSearchEnterKey(event({ key: 'ArrowDown' }))).toBe(false) - expect(shouldHandleAutomationListSearchEnterKey(event({ key: 'Escape' }))).toBe(false) - }) -}) diff --git a/src/renderer/src/components/automations/automation-project-groups.test.ts b/src/renderer/src/components/automations/automation-project-groups.test.ts deleted file mode 100644 index 740c6d39485..00000000000 --- a/src/renderer/src/components/automations/automation-project-groups.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { Repo } from '../../../../shared/repo-types' -import { - getAutomationProjectGroupForRepo, - getAutomationProjectGroups, - getAutomationProjectSelectedSource -} from './automation-project-groups' - -function repo(overrides: Partial): Repo { - return { - id: overrides.id ?? 'repo-1', - displayName: overrides.displayName ?? 'repo', - path: overrides.path ?? '/repo', - kind: 'git', - addedAt: overrides.addedAt ?? 1, - badgeColor: overrides.badgeColor ?? '#777777', - connectionId: overrides.connectionId ?? null, - executionHostId: overrides.executionHostId, - upstream: overrides.upstream, - repoIcon: overrides.repoIcon - } as Repo -} - -describe('getAutomationProjectGroups', () => { - it('finds and preserves the selected concrete source', () => { - const groups = getAutomationProjectGroups( - [ - repo({ id: 'local', upstream: { owner: 'stablyai', repo: 'orca' } }), - repo({ - id: 'ssh', - connectionId: 'builder', - upstream: { owner: 'stablyai', repo: 'orca' } - }) - ], - 'ssh' - ) - const group = getAutomationProjectGroupForRepo(groups, 'ssh') - - expect(group).not.toBeNull() - expect(group ? getAutomationProjectSelectedSource(group, 'ssh').id : null).toBe('ssh') - }) -}) diff --git a/src/renderer/src/components/automations/automation-run-open-target.ts b/src/renderer/src/components/automations/automation-run-open-target.ts index fc7801f4754..3ba854dd0a4 100644 --- a/src/renderer/src/components/automations/automation-run-open-target.ts +++ b/src/renderer/src/components/automations/automation-run-open-target.ts @@ -23,13 +23,13 @@ import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import { getFolderWorkspaceWorktree } from '../../../../shared/folder-workspaces/folder-workspace-worktree' -import { resolveExactWorktreeRoute } from '@/lib/worktree-owner-route' +import { resolveExactWorktreeRoute } from '@/lib/workspace/ownership/worktree-owner-route' import { parseWorkspaceKey } from '../../../../shared/workspace-scope' import { getAutomationRunViewState } from './automation-run-view-state' -import { resolveOwner } from '@/lib/resolve-owner' -import type { WorktreeOperationRouteState } from '@/lib/worktree-operation-route' +import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' +import type { WorktreeOperationRouteState } from '@/lib/workspace/ownership/worktree-operation-route' import { resolveQualifiedFolderWorkspaceResult } from '../../../../shared/folder-workspaces/folder-workspace-execution-host' -import { getRuntimeEnvironmentIdForFolderWorkspace } from '@/lib/folder-workspace-runtime-owner' +import { getRuntimeEnvironmentIdForFolderWorkspace } from '@/lib/workspace/ownership/folder-workspace-runtime-owner' export type AutomationRunPaneTarget = { tabId: string diff --git a/src/renderer/src/components/automations/automation-run-workspace-action.ts b/src/renderer/src/components/automations/automation-run-workspace-action.ts index 28a772479de..7606afe8169 100644 --- a/src/renderer/src/components/automations/automation-run-workspace-action.ts +++ b/src/renderer/src/components/automations/automation-run-workspace-action.ts @@ -6,12 +6,12 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { activateAndRevealWorktree, - activateAndRevealFolderWorkspace, - type ActivateAndRevealResult + activateAndRevealFolderWorkspace } from '@/lib/workspace/activation/worktree-activation' -import { activateWslMovedWorkspace } from '@/lib/wsl-moved-chat-activation' +import type { ActivateAndRevealResult } from '@/lib/workspace/activation/worktree-activation-outcome' +import { activateWslMovedWorkspace } from '@/lib/workspace/activation/wsl-moved-chat-activation' import { useAppStore } from '@/store' -import { activateTerminalTabOnOwner } from '@/lib/terminal-tab-owner-activation' +import { activateTerminalTabOnOwner } from '@/lib/workspace/tabs/terminal-tab-owner-activation' import { activateWebRuntimeSessionTab } from '@/runtime/web-session-tabs-sync/actions/web-runtime-session-tab-lifecycle' import { resolveWebSessionVisibleTabId } from '@/runtime/web-session-tabs-sync/navigation/web-session-focus-intent' import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' diff --git a/src/renderer/src/components/automations/automation-setup-decision.test.ts b/src/renderer/src/components/automations/automation-setup-decision.test.ts index ac3e4e18935..e99e6edfb46 100644 --- a/src/renderer/src/components/automations/automation-setup-decision.test.ts +++ b/src/renderer/src/components/automations/automation-setup-decision.test.ts @@ -37,34 +37,6 @@ function setup(overrides: Partial = {}): ProjectHostSetup { } describe('automation setup decision defaults', () => { - it('hides setup choice outside Orca new-run automations with setup', () => { - const baseArgs = { - repoId: 'repo-1', - repos: [repo], - projectHostSetups: [], - yamlHooks: null - } - - expect( - getVisibleAutomationSetupDecision({ - ...baseArgs, - workspaceMode: 'existing' - }) - ).toBeUndefined() - expect( - getVisibleAutomationSetupDecision({ - ...baseArgs, - workspaceMode: 'new_per_run', - repos: [ - { - ...repo, - hookSettings: { mode: 'override', scripts: { setup: '', archive: '' } } - } - ] - }) - ).toBeUndefined() - }) - it('uses only the selected repo host setup and refuses an ambiguous repo table', () => { const remote = { ...repo, connectionId: 'builder' } const localSetup = setup({ @@ -91,26 +63,6 @@ describe('automation setup decision defaults', () => { expect(getVisibleAutomationSetupDecision({ ...args, repos: [repo, remote] })).toBeUndefined() }) - it('uses ready project-host setup hook settings before repo fallback', () => { - expect( - getVisibleAutomationSetupDecision({ - workspaceMode: 'new_per_run', - repoId: 'repo-1', - repos: [repo], - projectHostSetups: [ - setup({ - hookSettings: { - mode: 'override', - setupRunPolicy: 'skip-by-default', - scripts: { setup: 'bun install', archive: '' } - } - }) - ], - yamlHooks: null - }) - ).toBe('skip') - }) - it('shows setup choice for shared orca.yaml setup and default tabs', () => { expect( getVisibleAutomationSetupDecision({ diff --git a/src/renderer/src/components/automations/external-automation-scope-gating.test.ts b/src/renderer/src/components/automations/external-automation-scope-gating.test.ts index 49e2620f825..6060de28186 100644 --- a/src/renderer/src/components/automations/external-automation-scope-gating.test.ts +++ b/src/renderer/src/components/automations/external-automation-scope-gating.test.ts @@ -7,8 +7,7 @@ import type { AutomationHostCatalogEntry } from './automation-host-catalog-types import { externalAutomationProbeOwners, externalAutomationScopeGateFromError, - parseExternalAutomationScopeCode, - resolveExternalAutomationScopeGate + parseExternalAutomationScopeCode } from './external-automation-scope-gating' function entry(overrides: Partial = {}): AutomationHostCatalogEntry { @@ -39,36 +38,6 @@ const runtimeEntry = entry({ }) describe('external automation scope gating', () => { - it('never presents a runtime-owned host as clean', () => { - const gate = resolveExternalAutomationScopeGate(runtimeEntry) - expect(gate.status).toBe('not-listed') - expect(gate.code).toBe(EXTERNAL_AUTOMATION_SCOPE_CODES.authorityNotSupported) - expect(gate.probeOwner).toBeNull() - }) - - it('fails closed when no owner was captured, so nothing is probed', () => { - const gate = resolveExternalAutomationScopeGate(entry({ owner: null })) - expect(gate.status).toBe('not-listed') - expect(gate.probeOwner).toBeNull() - }) - - it('treats the orphan bucket as scope limited rather than empty', () => { - const orphan = entry({ - stableRef: { authority: { kind: 'desktop' }, selector: { kind: 'orphan' } }, - kind: 'orphan', - owner: null, - stableKey: 'host:desktop:orphan' - }) - expect(resolveExternalAutomationScopeGate(orphan).status).toBe('not-listed') - }) - - it('makes no claim for an unresolved host', () => { - const gate = resolveExternalAutomationScopeGate(null) - expect(gate.status).toBe('unknown') - expect(gate.probeOwner).toBeNull() - // Why: 'unknown' is not a limitation, so it must not print the scope note. - }) - it('retains probe owners only for hosts that are actually listed', () => { expect(externalAutomationProbeOwners([entry(), runtimeEntry, entry({ owner: null })])).toEqual([ { authority: { kind: 'desktop' }, selector: { kind: 'self' } } diff --git a/src/renderer/src/components/automations/use-automation-agent-picker-entries.ts b/src/renderer/src/components/automations/use-automation-agent-picker-entries.ts index fd9f85b3892..fb7d2ba5a49 100644 --- a/src/renderer/src/components/automations/use-automation-agent-picker-entries.ts +++ b/src/renderer/src/components/automations/use-automation-agent-picker-entries.ts @@ -1,6 +1,6 @@ import { useCallback, useMemo } from 'react' import { shallow } from 'zustand/shallow' -import type { AgentCatalogEntry } from '@/lib/agent-catalog' +import type { AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' import type { AgentLaunchRouteStore, ProspectiveWorkspace diff --git a/src/renderer/src/components/automations/use-automations-page-store-state.ts b/src/renderer/src/components/automations/use-automations-page-store-state.ts index 798b9dc13f7..4528ee6ea98 100644 --- a/src/renderer/src/components/automations/use-automations-page-store-state.ts +++ b/src/renderer/src/components/automations/use-automations-page-store-state.ts @@ -5,7 +5,7 @@ import { } from '../../../../shared/agent-launch/catalog/tui-agent-selection' import type { Repo } from '../../../../shared/repo-types' import type { Worktree } from '../../../../shared/worktree/types' -import { getAgentCatalog } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { useAppStore } from '@/store' import { useRepoMap } from '@/store/repos/use-repository-catalog' import { useWorktreeMap } from '@/store/slices/worktrees/listing/use-worktree-catalog' diff --git a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx index a977be24d13..d2f5727e213 100644 --- a/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx +++ b/src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx @@ -35,7 +35,8 @@ import { useBrowserPageZoomFeedback } from './host-guest/use-browser-page-zoom-f import { isPageDocumentNavigationStart } from './host-guest/browser-page-webview-navigation-handlers' import { ClientHostedBrowserLoadFailure } from './client-hosted-browser-load-failure' import { useClientHostedPageUrlSubmission } from './navigate/use-client-hosted-page-url-submission' -import { convertBrowserPageToWorkspaceDoc } from '@/lib/file-preview' +import '@/lib/browser/documents/file-preview' +import { convertBrowserPageToWorkspaceDoc } from '@/lib/browser/documents/file-preview-page-conversion' import { isBlankBrowserUrl } from '@/lib/browser/palette/browser-palette-search' import { BrowserNewTabPage } from './new-tab/BrowserNewTabPage' import { useBrowserPageReloadActions } from './navigate/use-browser-page-reload-actions' diff --git a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx b/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx deleted file mode 100644 index 7d802303a96..00000000000 --- a/src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.test.tsx +++ /dev/null @@ -1,42 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' - -const reopenMocks = vi.hoisted(() => ({ reopenBrowserPageOnServer: vi.fn() })) - -vi.mock('./browser-reopen-on-server', () => ({ - reopenBrowserPageOnServer: reopenMocks.reopenBrowserPageOnServer -})) -vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) - -import { ReopenBrowserPageOnServerButton } from './ReopenBrowserPageOnServerButton' - -afterEach(() => { - cleanup() - vi.useRealTimers() - vi.clearAllMocks() -}) - -function renderButton(): HTMLElement { - render( - - ) - return screen.getByRole('button') -} - -describe('ReopenBrowserPageOnServerButton', () => { - it('rejects a second click while the first is still running', () => { - reopenMocks.reopenBrowserPageOnServer.mockImplementation(() => new Promise(() => {})) - const button = renderButton() - - fireEvent.click(button) - fireEvent.click(button) - - expect(reopenMocks.reopenBrowserPageOnServer).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts b/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts index 94844bd25a2..5ae19dbdab9 100644 --- a/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/markup-drawing-model.test.ts @@ -3,10 +3,7 @@ import { canRedo, commitShape, createMarkupDocument, - redoShape, - setShapes, undoShape, - type MarkupShape, type PenShape } from './markup-drawing-model' @@ -15,18 +12,6 @@ function pen(id: string): PenShape { } describe('markup document undo/redo', () => { - it('undoes and redoes in order', () => { - let doc = createMarkupDocument() - doc = commitShape(doc, pen('a')) - doc = commitShape(doc, pen('b')) - doc = undoShape(doc) - expect(doc.shapes.map((s) => s.id)).toEqual(['a']) - expect(canRedo(doc)).toBe(true) - doc = redoShape(doc) - expect(doc.shapes.map((s) => s.id)).toEqual(['a', 'b']) - expect(canRedo(doc)).toBe(false) - }) - it('forks history: committing after undo discards the redo stack', () => { let doc = createMarkupDocument() doc = commitShape(doc, pen('a')) @@ -36,15 +21,4 @@ describe('markup document undo/redo', () => { expect(doc.shapes.map((s) => s.id)).toEqual(['a', 'c']) expect(canRedo(doc)).toBe(false) }) - - it('undoes an edit (not just an add) via whole-list snapshots', () => { - let doc = commitShape(createMarkupDocument(), pen('a')) - doc = setShapes(doc, []) - expect(doc.shapes).toHaveLength(0) - doc = undoShape(doc) - expect(doc.shapes.map((s) => s.id)).toEqual(['a']) - }) }) - -const _exhaustive: MarkupShape['kind'][] = ['pen', 'highlight', 'arrow', 'rect', 'ellipse', 'text'] -void _exhaustive diff --git a/src/renderer/src/components/browser-pane/annotate/use-browser-annotation-images.ts b/src/renderer/src/components/browser-pane/annotate/use-browser-annotation-images.ts index d0826915700..68c8af448c8 100644 --- a/src/renderer/src/components/browser-pane/annotate/use-browser-annotation-images.ts +++ b/src/renderer/src/components/browser-pane/annotate/use-browser-annotation-images.ts @@ -1,7 +1,7 @@ import { useCallback, useState } from 'react' import { toast } from 'sonner' import { useAppStore } from '@/store' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { useMountedRef } from '@/hooks/useMountedRef' import { createNonSecureContextUuid as createBrowserUuid } from '../../../../../shared/non-secure-context-uuid' import { formatClipboardImagePasteError } from '@/components/terminal-pane/input/paste/terminal-pane-paste-execution' diff --git a/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts b/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts index a5c73a46513..579bbae50f0 100644 --- a/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts +++ b/src/renderer/src/components/browser-pane/annotate/useMarkupEditor.test.ts @@ -63,14 +63,6 @@ describe('useMarkupEditor gestures', () => { return result } - it('commits a drawn stroke exactly once under StrictMode', () => { - const result = renderEditor({ wrapper: StrictMode }) - - drawLine(result, 0) - - expect(result.current.shapes).toHaveLength(1) - }) - it('erases the touched mark, hiding it from the export before release, and undo restores it', () => { const result = renderEditor({ wrapper: StrictMode }) drawLine(result, 0) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx index 600c39a0a09..1309fc0be9d 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-pane.tsx @@ -1,12 +1,12 @@ import { useEffect, useLayoutEffect, useRef, useState } from 'react' import { createPortal } from 'react-dom' import { cn } from '@/lib/utils' -import { getConnectionIdFromState } from '@/lib/connection-context' +import '@/lib/workspace/ownership/connection-context' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { useAppStore } from '@/store' import { useShortcutLabel } from '@/hooks/useShortcutLabel' import '../../../../../shared/constants' import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page' -import type { BrowserPage as BrowserPageState } from '../../../../../shared/browser-workspace-types' import { normalizeExternalBrowserUrl } from '../../../../../shared/browser-url' import { getLiveBrowserUrl } from '../describe-page/live-browser-url-registry' import { getBrowserViewportPreset } from '../../../../../shared/browser-viewport-presets' @@ -20,11 +20,7 @@ import { getShareableBrowserArtifactFile } from '../describe-page/browser-artifa import { useGrabMode } from '../annotate/useGrabMode' import { getOpenableExternalUrl, toDisplayUrl } from '../describe-page/browser-page-url-display' import type { BrowserOverlayViewport } from '../describe-page/browser-annotation-geometry' -import type { - BrowserChromeShortcutScope, - BrowserPageUrlSetter, - BrowserTabPageState -} from '../describe-page/browser-page-types' +import type { BrowserPagePaneProps } from '../describe-page/browser-page-types' import { BrowserPageChromeHeader } from './browser-page-chrome-header' import { BrowserPageContextMenu } from './browser-page-context-menu' import { BrowserPageViewportOverlays } from './browser-page-viewport-overlays' @@ -61,21 +57,7 @@ export function BrowserPagePane({ inputLocked, onUpdatePageState, onSetUrl -}: { - browserTab: BrowserPageState - workspaceId: string - worktreeId: string - sessionProfileId: string | null - sessionPartition: string | null - isActive: boolean - chromeShortcutScope: BrowserChromeShortcutScope - isAutomationVisible: boolean - isMobileDriven: boolean - isRemotelyViewed: boolean - inputLocked: boolean - onUpdatePageState: (tabId: string, updates: BrowserTabPageState) => void - onSetUrl: BrowserPageUrlSetter -}): React.JSX.Element { +}: BrowserPagePaneProps): React.JSX.Element { const isPaintable = isBrowserPagePanePaintable({ isActive, isAutomationVisible, diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-toolbar.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-toolbar.tsx index b27f69749c2..e34c92860ec 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-toolbar.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-page-toolbar.tsx @@ -31,7 +31,8 @@ import { advanceAcrossBrowserPageConversion, returnAcrossBrowserPageConversion } from '@/lib/browser/history/browser-page-conversion-history' -import { convertBrowserPageToWorkspaceDoc } from '@/lib/file-preview' +import '@/lib/browser/documents/file-preview' +import { convertBrowserPageToWorkspaceDoc } from '@/lib/browser/documents/file-preview-page-conversion' import type { GrabIntent } from '../../../../../shared/browser/element-grab/browser-grab-types' /** Binds the shared browser chrome to a browsing page: an editable address bar and session tools. */ diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx index f1f0b221a89..b299eb9620b 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/browser-workspace-pane.adoption-chrome.test.tsx @@ -314,258 +314,258 @@ function startEditing(text: string): HTMLInputElement { return input } -describe.each([ - { tree: 'in a plain tree', strict: false }, - { tree: 'under StrictMode', strict: true } -])('BrowserPane adoption keeps live address-bar chrome ($tree)', ({ strict }) => { - let webview: ReturnType - let liveAttachment: { detached: boolean } | null = null +describe.each([{ tree: 'under StrictMode', strict: true }])( + 'BrowserPane adoption keeps live address-bar chrome ($tree)', + ({ strict }) => { + let webview: ReturnType + let liveAttachment: { detached: boolean } | null = null - beforeEach(() => { - strictMode = strict - frameCallbacks = [] - vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { - frameCallbacks.push(callback) - return frameCallbacks.length - }) - vi.stubGlobal('cancelAnimationFrame', () => {}) - webview = createWebview() - liveAttachment = null - mocks.attach.mockReset().mockImplementation((_args: unknown, viewport: HTMLElement) => { - // Model the real visible-attachment claim: a second attach before detach must fail so ordering errors stay observable. - if (liveAttachment?.detached === false) { - throw new Error('browser_client_page_renderer_visible_page_claimed') - } - viewport.appendChild(webview) - const attachment = { - webview, - detached: false, - detach: vi.fn(() => { - attachment.detached = true - webview.remove() - }), - nextMetadataRevision: vi.fn(() => 1) - } - liveAttachment = attachment - return attachment - }) - mocks.ensureRemotePage.mockClear() - mocks.callRuntimeRpc.mockClear() - installClientHostedPaneApi({ - ui: { onFocusBrowserAddressBar: () => () => {}, onShowBrowserHistory: () => () => {} } - }) - useAppStore.setState({ - browserPagesByWorkspace: { [WORKSPACE_ID]: [browserPage()] }, - browserUrlHistory: [ - { - url: 'https://example.internal/docs', - normalizedUrl: 'example.internal/docs', - title: 'Example docs', - lastVisitedAt: Date.now(), - visitCount: 3 + beforeEach(() => { + strictMode = strict + frameCallbacks = [] + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frameCallbacks.push(callback) + return frameCallbacks.length + }) + vi.stubGlobal('cancelAnimationFrame', () => {}) + webview = createWebview() + liveAttachment = null + mocks.attach.mockReset().mockImplementation((_args: unknown, viewport: HTMLElement) => { + // Model the real visible-attachment claim: a second attach before detach must fail so ordering errors stay observable. + if (liveAttachment?.detached === false) { + throw new Error('browser_client_page_renderer_visible_page_claimed') } - ], - browserCertificateFailuresByPageId: {}, - pendingAddressBarFocusByPageId: {}, - pendingAddressBarFocusByTabId: {} - }) - stageHandle() - }) - - afterEach(() => { - cleanup() - clearBrowserAddressBarEditSession(PAGE_ID) - clearBrowserPageDeferredNavigation(PAGE_ID) - vi.unstubAllGlobals() - vi.clearAllMocks() - }) - - it('carries the draft, caret and open suggestions through the staged-to-client swap', () => { - renderWorkspacePane() - expect(screen.getByTestId('streamed-viewport')).not.toBeNull() - - const staged = startEditing('example.int') - act(() => staged.setSelectionRange(3, 7)) - expect(staged.getAttribute('aria-expanded')).toBe('true') - - act(() => adoptOntoClient()) - act(() => flushFrames()) - - // The pane really did swap: the streamed viewport is gone and the guest is attached. - expect(screen.queryByTestId('streamed-viewport')).toBeNull() - expect(mocks.attach).toHaveBeenCalled() - - const adopted = addressBar() - expect(adopted.value).toBe('example.int') - expect(document.activeElement).toBe(adopted) - expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([3, 7]) - expect(adopted.getAttribute('aria-expanded')).toBe('true') - expect(screen.getByRole('option', { name: /Example docs/ })).not.toBeNull() - }) - - // Previewed URLs live in the input; carry the separate typed query too or Escape cannot restore it. - it('carries the typed query behind a previewed suggestion through the swap', () => { - renderWorkspacePane() - const staged = startEditing('example') - act(() => { - fireEvent.keyDown(staged, { key: 'ArrowDown' }) - }) - expect(staged.value).toBe('https://example.internal/docs') - - act(() => adoptOntoClient()) - act(() => flushFrames()) - - const adopted = addressBar() - expect(adopted.value).toBe('https://example.internal/docs') - act(() => { - fireEvent.keyDown(adopted, { key: 'Escape' }) - }) - expect(adopted.value).toBe('example') - }) - - // Apply the saved caret once; retrying it after typing would move it backward or overwrite new text. - it('leaves the caret where the user puts it while the grab is still retrying', () => { - renderWorkspacePane() - const staged = startEditing('example.int') - act(() => staged.setSelectionRange(3, 7)) - - act(() => adoptOntoClient()) - - const adopted = addressBar() - act(() => { - fireEvent.change(adopted, { target: { value: 'example.internal/docs' } }) - }) - act(() => adopted.setSelectionRange(12, 12)) - // The frames the grab would have spent re-taking the bar all land after the user typed. - act(() => flushFrames()) - - expect(adopted.value).toBe('example.internal/docs') - expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([12, 12]) - }) - - // Steal focus after resume to exercise the grab’s caret restore; otherwise select-all retries can escape detection. - - // An open list survives focus naturally; only a dismissed list proves dropdown state crosses the swap. - - // Only same-commit swaps may reclaim focus; later worktree revisits must not resume old edits. - it('does not resume an edit into a pane that mounts in a later task', async () => { - renderWorkspacePane() - startEditing('example.int') - - cleanup() - await act(async () => {}) - renderWorkspacePane() - - const remounted = addressBar() - expect(remounted.value).toBe('') - expect(document.activeElement).not.toBe(remounted) - }) - - // Generation changes reattach in place; edits must survive without remounting. - - // Headless adoption stays streamed and must preserve the same live edit. - - it('holds a URL submitted against the staged page and loads it once the guest attaches', () => { - renderWorkspacePane() - const staged = startEditing('https://example.internal/deferred') - act(() => { - fireEvent.submit(staged.closest('form') ?? staged) + viewport.appendChild(webview) + const attachment = { + webview, + detached: false, + detach: vi.fn(() => { + attachment.detached = true + webview.remove() + }), + nextMetadataRevision: vi.fn(() => 1) + } + liveAttachment = attachment + return attachment + }) + mocks.ensureRemotePage.mockClear() + mocks.callRuntimeRpc.mockClear() + installClientHostedPaneApi({ + ui: { onFocusBrowserAddressBar: () => () => {}, onShowBrowserHistory: () => () => {} } + }) + useAppStore.setState({ + browserPagesByWorkspace: { [WORKSPACE_ID]: [browserPage()] }, + browserUrlHistory: [ + { + url: 'https://example.internal/docs', + normalizedUrl: 'example.internal/docs', + title: 'Example docs', + lastVisitedAt: Date.now(), + visitCount: 3 + } + ], + browserCertificateFailuresByPageId: {}, + pendingAddressBarFocusByPageId: {}, + pendingAddressBarFocusByTabId: {} + }) + stageHandle() }) - // tabShow before host minting returns browser_tab_not_found, which would close the staged tab. - expect(mocks.ensureRemotePage).not.toHaveBeenCalled() - expect(webview.loadURL).not.toHaveBeenCalled() - - act(() => adoptOntoClient()) - act(() => flushFrames()) - - expect(webview.loadURL).toHaveBeenCalledWith('https://example.internal/deferred') - }) - - // Only input identity exposes chrome remounts; save/resume can otherwise hide the repeated dropdown animation. - - // Continuity alone passes if nothing happens; verify generation changes really reattach the guest. - it('re-attaches the guest when a host restart bumps the page generation', () => { - stageClientHostedHandle() - renderWorkspacePane() - act(() => adoptOntoClient()) - act(() => flushFrames()) - - const bar = addressBar() - const stale = mocks.attach.mock.results.at(-1)?.value as { detach: ReturnType } - expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration) - expect(attachedGenerations()).not.toContain(CLIENT_PLACEMENT.pageHostGeneration + 1) - - act(() => adoptOntoClient(CLIENT_PLACEMENT.pageHostGeneration + 1)) - act(() => flushFrames()) - - // The host retires the previous generation’s guest; retaining it would leave an inert tag. - expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration + 1) - // Detach before attach or the visible-page claim strands the pane on the unavailable notice. - expect(stale.detach.mock.invocationCallOrder[0]).toBeLessThan( - mocks.attach.mock.invocationCallOrder.at(-1) as number - ) - expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull() - expect(addressBar()).toBe(bar) - }) - - // Do not consume a one-time tour before placement makes its controls usable. - - // Live host status can override cached client placement and swap to streaming; retain edit-session recovery for this path. - it('carries a live edit when a staged client-hosted page is adopted onto the server', () => { - stageClientHostedHandle() - renderWorkspacePane() - expect(screen.queryByTestId('streamed-viewport')).toBeNull() - - const staged = startEditing('fallback.internal') - act(() => staged.setSelectionRange(4, 4)) - - act(() => adoptOntoServer()) - act(() => flushFrames()) - - // The pane really did fall back to the streamed one. - expect(screen.getByTestId('streamed-viewport')).not.toBeNull() - const adopted = addressBar() - expect(adopted.value).toBe('fallback.internal') - expect(document.activeElement).toBe(adopted) - expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([4, 4]) - }) - - // Restored client-placed pages must await recovery locally; hosts reject server screencasts for them. - it('mounts a restored client-hosted page on the client pane while the host recovers it', () => { - restoreClientHostedHandle() - renderWorkspacePane() - - expect(screen.queryByTestId('streamed-viewport')).toBeNull() - expect(mocks.ensureRemotePage).not.toHaveBeenCalled() - // Recovery retains the ID but replaces its generation; attaching early would strand the pane. - expect(mocks.attach).not.toHaveBeenCalled() - expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull() - - act(() => adoptOntoClient()) - act(() => flushFrames()) - - expect(mocks.attach).toHaveBeenCalled() - }) - - it('replays a URL held against the staged page when a headless host adopts it', async () => { - renderWorkspacePane() - const staged = startEditing('https://example.internal/headless') - act(() => { - fireEvent.submit(staged.closest('form') ?? staged) - }) - expect(mocks.ensureRemotePage).not.toHaveBeenCalled() - - await act(async () => { - adoptOntoServer() + afterEach(() => { + cleanup() + clearBrowserAddressBarEditSession(PAGE_ID) + clearBrowserPageDeferredNavigation(PAGE_ID) + vi.unstubAllGlobals() + vi.clearAllMocks() }) - expect(mocks.ensureRemotePage).toHaveBeenCalledTimes(1) - expect(mocks.callRuntimeRpc).toHaveBeenCalledWith( - expect.objectContaining({ environmentId: ENVIRONMENT_ID }), - 'browser.goto', - expect.objectContaining({ url: 'https://example.internal/headless' }), - expect.anything() - ) - }) -}) + it('carries the draft, caret and open suggestions through the staged-to-client swap', () => { + renderWorkspacePane() + expect(screen.getByTestId('streamed-viewport')).not.toBeNull() + + const staged = startEditing('example.int') + act(() => staged.setSelectionRange(3, 7)) + expect(staged.getAttribute('aria-expanded')).toBe('true') + + act(() => adoptOntoClient()) + act(() => flushFrames()) + + // The pane really did swap: the streamed viewport is gone and the guest is attached. + expect(screen.queryByTestId('streamed-viewport')).toBeNull() + expect(mocks.attach).toHaveBeenCalled() + + const adopted = addressBar() + expect(adopted.value).toBe('example.int') + expect(document.activeElement).toBe(adopted) + expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([3, 7]) + expect(adopted.getAttribute('aria-expanded')).toBe('true') + expect(screen.getByRole('option', { name: /Example docs/ })).not.toBeNull() + }) + + // Previewed URLs live in the input; carry the separate typed query too or Escape cannot restore it. + it('carries the typed query behind a previewed suggestion through the swap', () => { + renderWorkspacePane() + const staged = startEditing('example') + act(() => { + fireEvent.keyDown(staged, { key: 'ArrowDown' }) + }) + expect(staged.value).toBe('https://example.internal/docs') + + act(() => adoptOntoClient()) + act(() => flushFrames()) + + const adopted = addressBar() + expect(adopted.value).toBe('https://example.internal/docs') + act(() => { + fireEvent.keyDown(adopted, { key: 'Escape' }) + }) + expect(adopted.value).toBe('example') + }) + + // Apply the saved caret once; retrying it after typing would move it backward or overwrite new text. + it('leaves the caret where the user puts it while the grab is still retrying', () => { + renderWorkspacePane() + const staged = startEditing('example.int') + act(() => staged.setSelectionRange(3, 7)) + + act(() => adoptOntoClient()) + + const adopted = addressBar() + act(() => { + fireEvent.change(adopted, { target: { value: 'example.internal/docs' } }) + }) + act(() => adopted.setSelectionRange(12, 12)) + // The frames the grab would have spent re-taking the bar all land after the user typed. + act(() => flushFrames()) + + expect(adopted.value).toBe('example.internal/docs') + expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([12, 12]) + }) + + // Steal focus after resume to exercise the grab’s caret restore; otherwise select-all retries can escape detection. + + // An open list survives focus naturally; only a dismissed list proves dropdown state crosses the swap. + + // Only same-commit swaps may reclaim focus; later worktree revisits must not resume old edits. + it('does not resume an edit into a pane that mounts in a later task', async () => { + renderWorkspacePane() + startEditing('example.int') + + cleanup() + await act(async () => {}) + renderWorkspacePane() + + const remounted = addressBar() + expect(remounted.value).toBe('') + expect(document.activeElement).not.toBe(remounted) + }) + + // Generation changes reattach in place; edits must survive without remounting. + + // Headless adoption stays streamed and must preserve the same live edit. + + it('holds a URL submitted against the staged page and loads it once the guest attaches', () => { + renderWorkspacePane() + const staged = startEditing('https://example.internal/deferred') + act(() => { + fireEvent.submit(staged.closest('form') ?? staged) + }) + + // tabShow before host minting returns browser_tab_not_found, which would close the staged tab. + expect(mocks.ensureRemotePage).not.toHaveBeenCalled() + expect(webview.loadURL).not.toHaveBeenCalled() + + act(() => adoptOntoClient()) + act(() => flushFrames()) + + expect(webview.loadURL).toHaveBeenCalledWith('https://example.internal/deferred') + }) + + // Only input identity exposes chrome remounts; save/resume can otherwise hide the repeated dropdown animation. + + // Continuity alone passes if nothing happens; verify generation changes really reattach the guest. + it('re-attaches the guest when a host restart bumps the page generation', () => { + stageClientHostedHandle() + renderWorkspacePane() + act(() => adoptOntoClient()) + act(() => flushFrames()) + + const bar = addressBar() + const stale = mocks.attach.mock.results.at(-1)?.value as { detach: ReturnType } + expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration) + expect(attachedGenerations()).not.toContain(CLIENT_PLACEMENT.pageHostGeneration + 1) + + act(() => adoptOntoClient(CLIENT_PLACEMENT.pageHostGeneration + 1)) + act(() => flushFrames()) + + // The host retires the previous generation’s guest; retaining it would leave an inert tag. + expect(attachedGenerations()).toContain(CLIENT_PLACEMENT.pageHostGeneration + 1) + // Detach before attach or the visible-page claim strands the pane on the unavailable notice. + expect(stale.detach.mock.invocationCallOrder[0]).toBeLessThan( + mocks.attach.mock.invocationCallOrder.at(-1) as number + ) + expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull() + expect(addressBar()).toBe(bar) + }) + + // Do not consume a one-time tour before placement makes its controls usable. + + // Live host status can override cached client placement and swap to streaming; retain edit-session recovery for this path. + it('carries a live edit when a staged client-hosted page is adopted onto the server', () => { + stageClientHostedHandle() + renderWorkspacePane() + expect(screen.queryByTestId('streamed-viewport')).toBeNull() + + const staged = startEditing('fallback.internal') + act(() => staged.setSelectionRange(4, 4)) + + act(() => adoptOntoServer()) + act(() => flushFrames()) + + // The pane really did fall back to the streamed one. + expect(screen.getByTestId('streamed-viewport')).not.toBeNull() + const adopted = addressBar() + expect(adopted.value).toBe('fallback.internal') + expect(document.activeElement).toBe(adopted) + expect([adopted.selectionStart, adopted.selectionEnd]).toEqual([4, 4]) + }) + + // Restored client-placed pages must await recovery locally; hosts reject server screencasts for them. + it('mounts a restored client-hosted page on the client pane while the host recovers it', () => { + restoreClientHostedHandle() + renderWorkspacePane() + + expect(screen.queryByTestId('streamed-viewport')).toBeNull() + expect(mocks.ensureRemotePage).not.toHaveBeenCalled() + // Recovery retains the ID but replaces its generation; attaching early would strand the pane. + expect(mocks.attach).not.toHaveBeenCalled() + expect(screen.queryByText('Client-hosted browser unavailable')).toBeNull() + + act(() => adoptOntoClient()) + act(() => flushFrames()) + + expect(mocks.attach).toHaveBeenCalled() + }) + + it('replays a URL held against the staged page when a headless host adopts it', async () => { + renderWorkspacePane() + const staged = startEditing('https://example.internal/headless') + act(() => { + fireEvent.submit(staged.closest('form') ?? staged) + }) + expect(mocks.ensureRemotePage).not.toHaveBeenCalled() + + await act(async () => { + adoptOntoServer() + }) + + expect(mocks.ensureRemotePage).toHaveBeenCalledTimes(1) + expect(mocks.callRuntimeRpc).toHaveBeenCalledWith( + expect.objectContaining({ environmentId: ENVIRONMENT_ID }), + 'browser.goto', + expect.objectContaining({ url: 'https://example.internal/headless' }), + expect.anything() + ) + }) + } +) diff --git a/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx b/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx index d72076ce9f7..2a8db973059 100644 --- a/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx +++ b/src/renderer/src/components/browser-pane/assemble-chrome/use-browser-chrome-tool-fold.test.tsx @@ -3,11 +3,7 @@ import { act, cleanup, render } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useRef } from 'react' import { BROWSER_CHROME_ADDRESS_SLOT_ATTRIBUTE } from './browser-chrome-address-slot' -import { - BROWSER_CHROME_ADDRESS_MIN_WIDTH_PX, - BROWSER_CHROME_FOLD_ORDER, - useBrowserChromeToolFold -} from './use-browser-chrome-tool-fold' +import { BROWSER_CHROME_FOLD_ORDER, useBrowserChromeToolFold } from './use-browser-chrome-tool-fold' const FIXED_WIDTH = 100 const TOOL_WIDTH = 30 @@ -70,22 +66,7 @@ function resizeTo(width: number): void { act(() => resizeCallbacks.forEach((callback) => callback())) } -function expectedFolded(width: number): number { - const room = width - FIXED_WIDTH - BROWSER_CHROME_ADDRESS_MIN_WIDTH_PX - const fits = Math.max(0, Math.floor(room / TOOL_WIDTH)) - return Math.max(0, BROWSER_CHROME_FOLD_ORDER.length - fits) -} - describe('useBrowserChromeToolFold', () => { - it('measures when a hidden row becomes visible', () => { - let folded = -1 - layout.rowWidth = 0 - render( (folded = count)} />) - - resizeTo(300) - expect(folded).toBe(expectedFolded(300)) - }) - it('discards measurements when the available tools change', () => { let folded = -1 layout.rowWidth = 300 diff --git a/src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx b/src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx deleted file mode 100644 index 0408984c7c7..00000000000 --- a/src/renderer/src/components/browser-pane/browser-client-hosted-download-notices.test.tsx +++ /dev/null @@ -1,103 +0,0 @@ -// @vitest-environment happy-dom -import { act, cleanup, renderHook } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -const toastMocks = vi.hoisted(() => ({ - loading: vi.fn(), - success: vi.fn(), - error: vi.fn() -})) - -vi.mock('sonner', () => ({ toast: toastMocks })) - -const store = vi.hoisted(() => { - const remoteBrowserPageHandlesByPageId: Record = {} - return { state: { remoteBrowserPageHandlesByPageId } } -}) -vi.mock('@/store', () => ({ useAppStore: { getState: () => store.state } })) - -import type { - BrowserDownloadFinishedEvent, - BrowserDownloadProgressEvent, - BrowserDownloadRequestedEvent -} from '../../../../shared/browser/guest-lifecycle/browser-guest-events' -import { paneChannel } from './client-hosted-browser-pane-test-rig' -import { useBrowserClientHostedDownloadNotices } from './browser-client-hosted-download-notices' - -let requested = paneChannel() -let progress = paneChannel() -let finished = paneChannel() - -beforeEach(() => { - requested = paneChannel() - progress = paneChannel() - finished = paneChannel() - store.state.remoteBrowserPageHandlesByPageId = { - 'page-a': { - environmentId: 'environment-a', - remotePageId: 'remote-page-a', - placement: { kind: 'client' } - } - } - Object.defineProperty(window, 'api', { - configurable: true, - value: { - browser: { - onDownloadRequested: requested.subscribe, - onDownloadProgress: progress.subscribe, - onDownloadFinished: finished.subscribe - } - } - }) -}) - -afterEach(() => { - cleanup() - vi.clearAllMocks() -}) - -function renderNotices(): void { - renderHook(useBrowserClientHostedDownloadNotices) -} - -function emitRequested(overrides: Partial = {}): void { - const event = { - browserPageId: 'page-a', - downloadId: 'download-1', - origin: 'https://example.internal', - filename: 'report.pdf', - totalBytes: 1024, - mimeType: 'application/pdf', - savePath: '/tmp/staging/download', - status: 'downloading', - ...overrides - } as BrowserDownloadRequestedEvent - act(() => requested.emit(event)) -} - -function emitFinished(overrides: Partial = {}): void { - const event = { - browserPageId: 'page-a', - downloadId: 'download-1', - status: 'completed', - savePath: null, - error: null, - ...overrides - } as BrowserDownloadFinishedEvent - act(() => finished.emit(event)) -} - -describe('client-hosted browser download notices', () => { - // Downloads outlive their panes; an unsettled loading toast has no close button. - it('settles the toast after the page that started the download is gone', () => { - renderNotices() - emitRequested() - store.state.remoteBrowserPageHandlesByPageId = {} - - emitFinished({ status: 'canceled' }) - - expect(toastMocks.error).toHaveBeenCalledWith('Download canceled.', { - id: 'browser-download:download-1' - }) - }) -}) diff --git a/src/renderer/src/components/browser-pane/browser-client-page-paint-retention.test.ts b/src/renderer/src/components/browser-pane/browser-client-page-paint-retention.test.ts deleted file mode 100644 index a216d32f047..00000000000 --- a/src/renderer/src/components/browser-pane/browser-client-page-paint-retention.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, expect, it, vi } from 'vitest' -import { setRemoteViewersForBrowserPage } from '../../lib/pane-manager/browser-remote-viewer-state' -import { - createRetainedHostFixture, - disposeRetainedHostFixtures -} from './browser-client-page-retained-host-fixture' - -afterEach(() => { - disposeRetainedHostFixtures() - setRemoteViewersForBrowserPage('page-a', false) - document.body.innerHTML = '' -}) - -it('keeps a streamed retained guest invisible and inert across desktop attach and detach', async () => { - const rig = createRetainedHostFixture() - await rig.mount() - setRemoteViewersForBrowserPage('page-a', true) - const host = rig.host() - expect(host.style.left).toBe('0px') - expect(Number.parseInt(host.style.width)).toBeGreaterThanOrEqual(320) - expect(host.style.opacity).toBe('0') - expect(host.inert).toBe(true) - expect(host.style.pointerEvents).toBe('none') - - const observer = new MutationObserver(() => {}) - observer.observe(host, { attributes: true }) - setRemoteViewersForBrowserPage('page-a', true) - expect(observer.takeRecords()).toHaveLength(0) - observer.disconnect() - - const attachment = rig.attach() - expect(host.style.opacity).toBe('') - expect(host.inert).toBe(false) - vi.spyOn(rig.container, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 0, 0)) - setRemoteViewersForBrowserPage('page-a', true) - expect(Number.parseInt(host.style.width)).toBeGreaterThanOrEqual(320) - expect(host.style.opacity).toBe('0') - attachment.detach() - host - .querySelector('webview')! - .dispatchEvent( - Object.assign(new Event('load-commit'), { url: 'about:blank', isMainFrame: true }) - ) - expect(host.style.visibility).toBe('') - expect(host.style.opacity).toBe('0') - expect(host.inert).toBe(true) - expect(host.style.pointerEvents).toBe('none') - - setRemoteViewersForBrowserPage('page-a', false) - expect(host.style.width).toBe('1px') - rig.registry.dispose() - setRemoteViewersForBrowserPage('page-a', true) - expect(host.style.width).toBe('1px') -}) diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts b/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts index df05e189e5c..e8117da4faf 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-annotation-geometry.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest' import type { BrowserGrabPayload } from '../../../../../shared/browser/element-grab/browser-grab-types' import { applyBrowserAnnotationViewportReport, - createBrowserAnnotationPayload, getBrowserOverlayAnchor, getLiveBrowserAnnotationRect } from './browser-annotation-geometry' @@ -80,12 +79,6 @@ describe('browser annotation geometry', () => { } ) }) - - it('strips screenshot bytes from persisted annotation payloads', () => { - const source = payload() - expect(createBrowserAnnotationPayload(source).screenshot).toBeNull() - expect(createBrowserAnnotationPayload(source).target.selector).toBe('button') - }) }) describe('browser annotation card follows the live element', () => { diff --git a/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts b/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts index bfb5421801f..6bed75438f0 100644 --- a/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts +++ b/src/renderer/src/components/browser-pane/describe-page/browser-page-types.ts @@ -131,6 +131,22 @@ export type BrowserPageAnnotationTrayProps = { ) => void } +export type BrowserPagePaneProps = { + browserTab: BrowserPageState + workspaceId: string + worktreeId: string + sessionProfileId: string | null + sessionPartition: string | null + isActive: boolean + chromeShortcutScope: BrowserChromeShortcutScope + isAutomationVisible: boolean + isMobileDriven: boolean + isRemotelyViewed: boolean + inputLocked: boolean + onUpdatePageState: (tabId: string, updates: BrowserTabPageState) => void + onSetUrl: BrowserPageUrlSetter +} + export type ClientHostedBrowserPagePaneProps = { browserTab: BrowserPageState workspaceId: string diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts deleted file mode 100644 index 71e1783f093..00000000000 --- a/src/renderer/src/components/browser-pane/host-guest/browser-focus.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { consumeBrowserFocusRequest, queueBrowserFocusRequest } from './browser-focus' - -describe('browser-focus', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('expires unconsumed requests for pages that never mount', () => { - vi.useFakeTimers() - - queueBrowserFocusRequest({ pageId: 'page-stale', target: 'webview' }) - - vi.advanceTimersByTime(30_000) - - expect(consumeBrowserFocusRequest('page-stale')).toBeNull() - }) -}) diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts deleted file mode 100644 index 0b7830ca9fe..00000000000 --- a/src/renderer/src/components/browser-pane/host-guest/browser-guest-paint-policy.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { browserPageNeedsPaintRetention } from './browser-guest-paint-retention' -import { hydrateBrowserDrivers } from '../../../lib/pane-manager/browser-mobile-driver-state' -import { hydrateBrowserRemoteViewerPages } from '../../../lib/pane-manager/browser-remote-viewer-state' -import { - acquireBrowserAutomationVisibility, - releaseBrowserAutomationVisibility -} from './browser-automation-visibility' - -// The imperative twin, for retention decisions taken outside a render (the eviction budget). -describe('browserPageNeedsPaintRetention', () => { - afterEach(() => { - hydrateBrowserDrivers([]) - hydrateBrowserRemoteViewerPages([]) - }) - - it('answers for each term on its own', () => { - expect(browserPageNeedsPaintRetention('page-a')).toBe(false) - - hydrateBrowserRemoteViewerPages(['page-a']) - expect(browserPageNeedsPaintRetention('page-a')).toBe(true) - hydrateBrowserRemoteViewerPages([]) - - hydrateBrowserDrivers([ - { browserPageId: 'page-a', driver: { kind: 'mobile', clientId: 'phone-1' } } - ]) - expect(browserPageNeedsPaintRetention('page-a')).toBe(true) - hydrateBrowserDrivers([]) - - const token = acquireBrowserAutomationVisibility('page-a') - expect(browserPageNeedsPaintRetention('page-a')).toBe(true) - releaseBrowserAutomationVisibility(token) - expect(browserPageNeedsPaintRetention('page-a')).toBe(false) - }) - - it('stays scoped to the page asked about', () => { - hydrateBrowserRemoteViewerPages(['page-a']) - expect(browserPageNeedsPaintRetention('page-b')).toBe(false) - }) -}) diff --git a/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts b/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts index efff82bd6cf..33989c229ad 100644 --- a/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts +++ b/src/renderer/src/components/browser-pane/host-guest/browser-page-guest-recovery.test.ts @@ -62,36 +62,6 @@ afterEach(() => { }) describe('browser page guest recovery', () => { - it('reloads a lost renderer in place and cancels the failure surface after recovery', () => { - vi.useFakeTimers() - const state = createRecovery() - - state.recovery.recoverRenderer() - - expect(state.reload).toHaveBeenCalledOnce() - expect(state.pending()).toBe(true) - - state.recovery.finish() - vi.advanceTimersByTime(BROWSER_GUEST_RECOVERY_TIMEOUT_MS) - - expect(state.pending()).toBe(false) - expect(state.onRecoveryFailed).not.toHaveBeenCalled() - }) - - it('recreates a guest when in-place reload is unavailable', async () => { - const state = createRecovery({ - reload: () => { - throw new Error('guest destroyed') - } - }) - - state.recovery.recoverRenderer() - await vi.waitFor(() => expect(state.onReplacementReady).toHaveBeenCalledOnce()) - - expect(state.replaceGuest).toHaveBeenCalledOnce() - expect(state.pending()).toBe(true) - }) - it('surfaces guest replacement rejection without marking it ready', async () => { const replacementError = new Error('replacement failed') const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) @@ -139,32 +109,6 @@ describe('browser page guest recovery', () => { expect(state.onReplacementReady).toHaveBeenCalledOnce() }) - it('recreates an active guest missing from the authoritative registry after resume', async () => { - const state = createRecovery({ registered: false }) - - state.recovery.validateAfterResume() - await vi.waitFor(() => expect(state.onReplacementReady).toHaveBeenCalledOnce()) - - expect(state.validateRegistration).toHaveBeenCalledOnce() - expect(state.replaceGuest).toHaveBeenCalledOnce() - }) - - it('waits for an attaching guest instead of replacing it as missing', async () => { - vi.useFakeTimers() - const state = createRecovery() - state.validateRegistration.mockResolvedValueOnce(null).mockResolvedValueOnce(true) - - state.recovery.validateAfterResume() - await vi.advanceTimersByTimeAsync(0) - - expect(state.replaceGuest).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(BROWSER_GUEST_VALIDATION_RETRY_DELAY_MS) - - expect(state.validateRegistration).toHaveBeenCalledTimes(2) - expect(state.onRecoverySucceeded).toHaveBeenCalledOnce() - expect(state.replaceGuest).not.toHaveBeenCalled() - }) - it('surfaces an attaching guest that never becomes identifiable', async () => { vi.useFakeTimers() const state = createRecovery() @@ -251,17 +195,6 @@ describe('browser page guest recovery', () => { expect(state.onRecoveryFailed).not.toHaveBeenCalled() }) - it('surfaces an explicit recovery failure instead of leaving a permanent blank page', () => { - vi.useFakeTimers() - const state = createRecovery() - - state.recovery.recoverRenderer() - vi.advanceTimersByTime(BROWSER_GUEST_RECOVERY_TIMEOUT_MS) - - expect(state.pending()).toBe(false) - expect(state.onRecoveryFailed).toHaveBeenCalledOnce() - }) - it('keeps the original recovery deadline across repeated renderer loss events', () => { vi.useFakeTimers() const state = createRecovery() diff --git a/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.test.ts b/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.test.ts index 4f4617c1d65..968097cc67d 100644 --- a/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.test.ts +++ b/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.test.ts @@ -1,8 +1,8 @@ import { afterEach, expect, it, vi } from 'vitest' -import type * as ConnectionOwnerModule from '@/lib/connection-owner-resolution' +import type * as ConnectionOwnerModule from '@/lib/workspace/ownership/connection-owner-resolution' // A workspace this computer owns. -vi.mock('@/lib/connection-owner-resolution', async (importOriginal) => ({ +vi.mock('@/lib/workspace/ownership/connection-owner-resolution', async (importOriginal) => ({ ...(await importOriginal()), getConnectionIdFromState: () => null, getConnectionIdForFileFromState: () => null diff --git a/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.ts b/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.ts index 99341bb5884..ab370e94327 100644 --- a/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.ts +++ b/src/renderer/src/components/browser-pane/navigate/browser-file-editor-open.ts @@ -1,4 +1,4 @@ -import { getConnectionIdFromState } from '@/lib/connection-owner-resolution' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { getRuntimeTargetForWorktreeOwner } from '@/lib/file-owner-runtime-target' import { getRelativePathInsideRoot } from '@/lib/path' import { statUserOpenedPath } from '@/lib/user-opened-local-path' diff --git a/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts b/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts index 328c48e0f9e..17b2bcd10fa 100644 --- a/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts +++ b/src/renderer/src/components/browser-pane/navigate/navigate-browser-page-url.ts @@ -1,5 +1,5 @@ -import { detectLanguage } from '@/lib/language-detect' -import { getConnectionId } from '@/lib/connection-context' +import { detectLanguage } from '../../../../../shared/editor-language/editor-language-detect' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { isPathInsideWorktree, toWorktreeRelativePath diff --git a/src/renderer/src/components/browser-pane/navigate/workspace-doc-address-submission.ts b/src/renderer/src/components/browser-pane/navigate/workspace-doc-address-submission.ts index 56358dd9f89..19f103e6932 100644 --- a/src/renderer/src/components/browser-pane/navigate/workspace-doc-address-submission.ts +++ b/src/renderer/src/components/browser-pane/navigate/workspace-doc-address-submission.ts @@ -1,5 +1,6 @@ import type { BrowserLoadError } from '../../../../../shared/browser-workspace-types' -import { convertBrowserPageToWorkspaceDoc } from '@/lib/file-preview' +import '@/lib/browser/documents/file-preview' +import { convertBrowserPageToWorkspaceDoc } from '@/lib/browser/documents/file-preview-page-conversion' import { resolveWorkspaceDocAddressTarget } from '@/lib/workspace-doc-address-input' import { useAppStore } from '@/store' diff --git a/src/renderer/src/components/browser-pane/passwords/BrowserPasswordSaveButton.tsx b/src/renderer/src/components/browser-pane/passwords/BrowserPasswordSaveButton.tsx index ee36e12851d..15d7a324a49 100644 --- a/src/renderer/src/components/browser-pane/passwords/BrowserPasswordSaveButton.tsx +++ b/src/renderer/src/components/browser-pane/passwords/BrowserPasswordSaveButton.tsx @@ -115,7 +115,7 @@ function BrowserPasswordSavePopover({
-
+
{isUpdate ? ( ) : ( @@ -123,7 +123,7 @@ function BrowserPasswordSavePopover({ {t('browser.passwords.savePrompt.never', 'Never for this site')} )} -
+
- {card.lastUserMessage || card.lastAgentMessage ? ( -
- {card.lastUserMessage ? ( -
- - {t('dashboardPopout.card.you', 'You')} - {' '} - {card.lastUserMessage} -
- ) : null} - {card.lastAgentMessage ? ( -
- - {formatAgentTypeLabel(card.agentType)} - {' '} - {card.lastAgentMessage} -
- ) : null} -
+ {hasAgentCardLastMessages(card) ? ( + ) : card.task ? (
{card.task} diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx index bffc3de2dd0..ed29e67385e 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx @@ -123,3 +123,24 @@ it.each([false, true])( ) } ) + +it('shows last messages when a card has no live terminal', () => { + const { rerender } = render( + {}} + onReveal={() => {}} + /> + ) + expect(screen.getByText('Roll out rc-18')).toBeInTheDocument() + expect(screen.getByText('Rollout finished')).toBeInTheDocument() + + rerender( + {}} onReveal={() => {}} /> + ) + expect(screen.queryByText('Rollout finished')).not.toBeInTheDocument() +}) diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx index cd9c92f07f6..560c0e3459a 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx @@ -1,6 +1,6 @@ import { useEffect, useId, useRef } from 'react' import { SquareArrowOutUpRight, XIcon } from 'lucide-react' -import { AgentTypeIcon } from '@/lib/agent-type-icon' +import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { agentStateLabel } from '@/components/AgentStateDot' import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog' @@ -11,6 +11,7 @@ import { type DashboardRevealAgentArgs } from '../../../../shared/dashboard-snapshot' import { AgentTerminalPreview } from './AgentTerminalPreview' +import { AgentCardLastMessages, hasAgentCardLastMessages } from './AgentCardLastMessages' import { terminalPreviewUnavailableMessage } from './terminal-preview-unavailable-message' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' @@ -101,8 +102,13 @@ function AgentTerminalFrame({ onRequestClose={() => onOpenChange(false)} /> ) : ( -
- {terminalPreviewUnavailableMessage({ hostKind: card.hostKind }, t)} +
+
+ {terminalPreviewUnavailableMessage({ hostKind: card.hostKind }, t)} +
+ {hasAgentCardLastMessages(card) ? ( + + ) : null}
)}
diff --git a/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts b/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts index af784e17dab..d2bf0a8f9b3 100644 --- a/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts +++ b/src/renderer/src/components/dashboard-popout/dashboard-preview-http-actions.ts @@ -8,8 +8,8 @@ import { isRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' import { useAppStore } from '@/store' -import { resolveOwner } from '@/lib/resolve-owner' -import { resolveWorktreeOperationRoute } from '@/lib/worktree-operation-route' +import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' +import { resolveWorktreeOperationRoute } from '@/lib/workspace/ownership/worktree-operation-route' import { createBrowserLinkHostMatcher } from '@/lib/browser/navigation/browser-link-owner' import { getWorkspaceClientCreationActionPolicy } from '@/lib/client-creation-action-policy' import { diff --git a/src/renderer/src/components/dashboard/AgentDashboardDrawer.focus.test.tsx b/src/renderer/src/components/dashboard/AgentDashboardDrawer.focus.test.tsx index 20749a747a6..5ed42ac97d4 100644 --- a/src/renderer/src/components/dashboard/AgentDashboardDrawer.focus.test.tsx +++ b/src/renderer/src/components/dashboard/AgentDashboardDrawer.focus.test.tsx @@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('@/lib/workspace/activation/worktree-activation', () => ({ activateAndRevealWorkspace: mocks.activateAndRevealWorkspace })) -vi.mock('@/lib/activate-tab-and-focus-pane', () => ({ +vi.mock('@/lib/workspace/tabs/activate-tab-and-focus-pane', () => ({ activateTabAndFocusPane: mocks.activateTabAndFocusPane })) vi.mock('./useLiveDashboardSnapshot', () => ({ diff --git a/src/renderer/src/components/dashboard/AgentDashboardDrawer.test.tsx b/src/renderer/src/components/dashboard/AgentDashboardDrawer.test.tsx index 65c67ca8cc8..1094ff92a0f 100644 --- a/src/renderer/src/components/dashboard/AgentDashboardDrawer.test.tsx +++ b/src/renderer/src/components/dashboard/AgentDashboardDrawer.test.tsx @@ -13,7 +13,7 @@ const mocks = vi.hoisted(() => ({ activateAndRevealWorkspace: vi.fn(() => ({ primaryTabId: null }) as unknown) })) -vi.mock('@/lib/activate-tab-and-focus-pane', () => ({ +vi.mock('@/lib/workspace/tabs/activate-tab-and-focus-pane', () => ({ activateTabAndFocusPane: mocks.activateTabAndFocusPane })) diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx index 1a61fa91825..7d676e65533 100644 --- a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -1,6 +1,9 @@ import React, { useState, useCallback } from 'react' import { cn } from '@/lib/utils' -import { opensClaudeParentConversation, viewClaudeAgentFromRow } from '@/lib/claude-agent-row-view' +import { + opensClaudeParentConversation, + viewClaudeAgentFromRow +} from '@/lib/agent-session/navigation/claude-agent-row-view' import { useClaudeAgentRowView } from './use-claude-agent-row-view' import { AgentStateDot, @@ -8,26 +11,32 @@ import { agentStateProgressLabel, type AgentDotState } from '@/components/AgentStateDot' -import { AgentTypeIcon } from '@/lib/agent-type-icon' +import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { formatAgentTypeLabel } from '../../../../shared/agent-status/presentation/agent-type-label' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { DashboardAgentRowMessage } from './DashboardAgentRowMessage' import { DashboardAgentRowTrailingControls } from './DashboardAgentRowTrailingControls' import { DashboardAgentRowToolStep } from './DashboardAgentRowToolStep' import { programStatusAttentionLine } from '../../../../shared/program-status/presentation' -import { agentRowToolInput, showsAgentToolPreview } from '@/lib/agent-row-tool-preview' +import { + agentRowToolInput, + showsAgentToolPreview +} from '@/lib/agent-status/presentation/agent-row-tool-preview' import { resolveRowProgramStatus } from '@/lib/program-status/agent-row-presentation' -import { agentRowStoppingLabel } from '@/lib/agent-row-stopping-label' +import { agentRowStoppingLabel } from '@/lib/agent-status/presentation/agent-row-stopping-label' import { agentNoUpdateLabel, formatCompactDuration } from '../../../../shared/agent-status/presentation/agent-row-decay-state' -import { agentRowDisplayDotState, agentRowDotState as asDotState } from '@/lib/agent-row-dot-state' +import { + agentRowDisplayDotState, + agentRowDotState as asDotState +} from '@/lib/agent-status/presentation/agent-row-dot-state' import { agentMainAgentVerdict, agentVerdictDisplayMark } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' -import { agentVerdictStatusLine } from '@/lib/agent-verdict-status-line' +import { agentVerdictStatusLine } from '@/lib/agent-status/presentation/agent-verdict-status-line' import type { DashboardAgentRow as DashboardAgentRowData } from './useDashboardData' import { getAgentRowPrimaryText } from '../../../../shared/agent-status/presentation/agent-row-primary-text' import { useAgentRowConversationName } from './use-agent-row-conversation-name' diff --git a/src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts b/src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts index 8c97efe2039..75d2e5688dc 100644 --- a/src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts +++ b/src/renderer/src/components/dashboard/agent-row-lineage-model.test.ts @@ -100,27 +100,6 @@ describe('buildAgentRowLineageTree', () => { }) describe('unreachable lineage cleanup', () => { - it('bounds pane-key reads while flattening disconnected cycles', () => { - let paneKeyReads = 0 - const root = makeRow('root') - const cycles = Array.from({ length: 200 }, (_, index) => { - const row = makeRow(`cycle-${index}`, { parentPaneKey: `cycle-${index ^ 1}` }) - Object.defineProperty(row, 'paneKey', { - get() { - paneKeyReads++ - return `cycle-${index}` - } - }) - return row - }) - const tree = buildAgentRowLineageTree([root, ...cycles]) - const measuredReads = paneKeyReads - expect(tree.rootRows).toEqual([root, ...cycles]) - expect(tree.childrenByParentPaneKey.size).toBe(0) - expect(tree.childPaneKeys.size).toBe(0) - expect(measuredReads).toBeLessThanOrEqual(cycles.length * 20) - }) - it('preserves reachable edges and promotes the first disconnected duplicate in input order', () => { const root = makeRow('root') const child = makeRow('child', { parentPaneKey: 'root' }) diff --git a/src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts b/src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts index ca9b746ceed..966355c4260 100644 --- a/src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts +++ b/src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts @@ -3,7 +3,8 @@ import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-sn import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent' import { toRuntimeExecutionHostId, toSshExecutionHostId } from '../../../../shared/execution-host' import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' -import { getConnectionIdFromState } from '@/lib/connection-context' +import '@/lib/workspace/ownership/connection-context' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { getExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' import { shouldDisableKittyKeyboardForTerminal } from '@/lib/pane-manager/terminal-keyboard-protocol' import { isLocalNativeWindowsConpty } from '@/lib/pane-manager/windows-pty-compatibility' diff --git a/src/renderer/src/components/dashboard/reveal-dashboard-agent.test.ts b/src/renderer/src/components/dashboard/reveal-dashboard-agent.test.ts index 39f96bb8d10..fad79235b6f 100644 --- a/src/renderer/src/components/dashboard/reveal-dashboard-agent.test.ts +++ b/src/renderer/src/components/dashboard/reveal-dashboard-agent.test.ts @@ -29,10 +29,10 @@ vi.mock('@/lib/workspace/activation/worktree-activation', () => ({ vi.mock('@/lib/workspace/ownership/worktree-runtime-owner', () => ({ runtimeEnvironmentIdOrLocalUnlessTwin: () => 'host-A' })) -vi.mock('@/lib/activate-tab-and-focus-pane', () => ({ +vi.mock('@/lib/workspace/tabs/activate-tab-and-focus-pane', () => ({ activateTabAndFocusPane: mocks.activateTabAndFocusPane })) -vi.mock('@/lib/terminal-tab-owner-activation', () => ({ +vi.mock('@/lib/workspace/tabs/terminal-tab-owner-activation', () => ({ activateTerminalTabOnOwner: mocks.activateTerminalTabOnOwner })) vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ diff --git a/src/renderer/src/components/dashboard/useRetainedAgents.ts b/src/renderer/src/components/dashboard/useRetainedAgents.ts index 573e3eb03a3..fa75f806fa6 100644 --- a/src/renderer/src/components/dashboard/useRetainedAgents.ts +++ b/src/renderer/src/components/dashboard/useRetainedAgents.ts @@ -2,7 +2,10 @@ import { agentEntrySessionStartedAt } from '../../../../shared/agent-session/lif import { useEffect, useRef } from 'react' import { useShallow } from 'zustand/react/shallow' import { useAppStore } from '@/store' -import { isExplicitAgentStatusFresh } from '@/lib/pane-agent-evidence' +import { + isAgentStatusFresh, + AGENT_STATUS_STALE_AFTER_MS +} from '../../../../shared/agent-status/contracts/agent-status-freshness' import type { DashboardAgentRow } from './useDashboardData' import type { RetainedAgentEntry } from '@/store/slices/agent-status/agent-status-contract' import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' @@ -11,7 +14,7 @@ import type { TerminalTab } from '../../../../shared/workspace-layout/terminal-t import type { Worktree } from '../../../../shared/worktree/types' import { folderWorkspaceKey } from '../../../../shared/workspace-scope' import { resolveAgentPaneAuthorityKey } from '@/store/slices/agent-status/agent-pane-authority' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status/contracts/agent-status-freshness' + import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' import { parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { agentTurnEndedOnPurpose } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' @@ -19,7 +22,7 @@ import { agentTurnEndedOnPurpose } from '../../../../shared/agent-status/lifecyc import { createWorktreeTabBucketProjection, type WorktreeTabBucketProjection -} from '@/lib/worktree-tab-bucket-projection' +} from '@/lib/workspace/tabs/worktree-tab-bucket-projection' import { selectFolderWorkspaces, selectWorktreesByRepo @@ -116,7 +119,7 @@ export function buildRetainedAgentsSyncSnapshot(args: RetainedAgentsSyncSnapshot if (!owner) { continue } - const isFresh = isExplicitAgentStatusFresh(entry, args.now, AGENT_STATUS_STALE_AFTER_MS) + const isFresh = isAgentStatusFresh(entry, args.now, AGENT_STATUS_STALE_AFTER_MS) const shouldDecay = !isFresh && (entry.state === 'working' || entry.state === 'blocked' || entry.state === 'waiting') diff --git a/src/renderer/src/components/dictation/DictationController.tsx b/src/renderer/src/components/dictation/DictationController.tsx index 0e5cbcc60ef..9c4957044bc 100644 --- a/src/renderer/src/components/dictation/DictationController.tsx +++ b/src/renderer/src/components/dictation/DictationController.tsx @@ -3,6 +3,7 @@ import { useAppStore } from '@/store' import { useAudioCapture } from '@/hooks/use-audio-capture' import { DictationIndicator } from './DictationIndicator' import { captureInsertionTarget } from './dictation-insertion-target' +import { captureDictationContext } from './dictation-context' import { dictationPillAnchorFor, type DictationPillAnchor } from './dictation-pill-anchor' import { canRetryDictation, @@ -30,6 +31,7 @@ import { useHoldDictationGesture } from './use-hold-dictation-gesture' import { publishDictationMeter } from './dictation-meter-store' import { useDictationSilenceStop } from './use-dictation-silence-stop' import { useDictationSpeechEvents } from './use-dictation-speech-events' +import { NO_DICTATION_LIVE_TEXT } from '@/store/slices/dictation/dictation' import { canStartDictation, initialDictationSession, @@ -42,7 +44,7 @@ import { export function DictationController() { const dictationState = useAppStore((s) => s.dictationState) const setDictationState = useAppStore((s) => s.setDictationState) - const setPartialTranscript = useAppStore((s) => s.setPartialTranscript) + const setLiveText = useAppStore((s) => s.setLiveText) const recordFeatureInteraction = useAppStore((s) => s.recordFeatureInteraction) const settings = useAppStore((s) => s.settings) const keybindings = useAppStore((s) => s.keybindings) @@ -82,11 +84,11 @@ export function DictationController() { if (next.sessionId === null) { deliverRef.current = null } + if (next.sessionId !== previous.sessionId) { + setLiveText(NO_DICTATION_LIVE_TEXT) + } if (next.phase !== previous.phase) { setDictationState(next.phase) - if (next.phase !== 'listening' && next.phase !== 'stopping') { - setPartialTranscript('') - } if (next.phase === 'idle') { setPillAnchor(null) keptRef.current = null @@ -100,7 +102,7 @@ export function DictationController() { } return next }, - [setDictationState, setPartialTranscript, clearQueuedSend] + [setDictationState, setLiveText, clearQueuedSend] ) const drainStoppedSession = useCallback((sessionId: string) => { @@ -206,7 +208,8 @@ export function DictationController() { const insertionTarget = captureInsertionTarget() const deliver = createDictationTranscriptDelivery() deliverRef.current = (text) => deliver(text, insertionTarget) - const kept = createDictationKeptRecording(insertionTarget, deliver) + const context = captureDictationContext() + const kept = createDictationKeptRecording(insertionTarget, deliver, context) keptRef.current = kept setRecordingKey((key) => key + 1) setCaptureLive(false) @@ -269,7 +272,7 @@ export function DictationController() { } setCaptureLive(true) - await window.api.speech.startDictation(modelId, undefined, sessionId) + await window.api.speech.startDictation(modelId, context, sessionId) if (!isCurrent()) { await releaseStart(true) return @@ -379,9 +382,8 @@ export function DictationController() { useDictationSpeechEvents({ currentSessionId: () => sessionRef.current.sessionId, - onPartial: setPartialTranscript, + onLiveText: setLiveText, onFinal: (text) => { - setPartialTranscript('') dispatch({ type: 'final-text' }) deliverRef.current?.(text) }, diff --git a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx index c09e2132eb5..ca8b05f0971 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.fixture.tsx @@ -51,8 +51,49 @@ export const liveText = defineFixture({ width: 520, store: { dictationState: 'listening', - partialTranscript: - 'It should go back to the page you came from. Check where returnTo gets dropped' + liveText: { + committed: 'It should go back to the page you came from.', + tentative: 'Check where returnTo gets dropped', + speechPending: false + } + }, + setup: () => publishDictationMeter({ level: 0.6, isSpeaking: true, isClipping: false }), + render: () => +}) + +export const committedText = defineFixture({ + width: 520, + store: { + dictationState: 'listening', + liveText: { + committed: 'It should go back to the page you came from. Check where returnTo gets dropped.', + tentative: '', + speechPending: false + } + }, + setup: () => publishDictationMeter({ level: 0.2, isSpeaking: false, isClipping: false }), + render: () => +}) + +export const pendingSpeech = defineFixture({ + width: 520, + store: { + dictationState: 'listening', + liveText: { + committed: 'It should go back to the page you came from.', + tentative: '', + speechPending: true + } + }, + setup: () => publishDictationMeter({ level: 0.6, isSpeaking: true, isClipping: false }), + render: () => +}) + +export const pendingFirstWords = defineFixture({ + width: 520, + store: { + dictationState: 'listening', + liveText: { committed: '', tentative: '', speechPending: true } }, setup: () => publishDictationMeter({ level: 0.6, isSpeaking: true, isClipping: false }), render: () => diff --git a/src/renderer/src/components/dictation/DictationIndicator.tsx b/src/renderer/src/components/dictation/DictationIndicator.tsx index e28f3d62f16..83e1eaada07 100644 --- a/src/renderer/src/components/dictation/DictationIndicator.tsx +++ b/src/renderer/src/components/dictation/DictationIndicator.tsx @@ -10,6 +10,7 @@ import { cn } from '@/lib/utils' import { useAppStore } from '@/store' import { ArrowUp, Check, CornerDownLeft, Loader2 } from 'lucide-react' import { isDictationPillShown } from '../../../../shared/dictation-session-machine' +import { dictationSeparators } from '../../../../shared/dictation-transcript-spacing' import { CLOUD_DICTATION_MAX_SECONDS } from '../../../../shared/rpc-contract/speech-params' import type { SpeechModelManifest } from '../../../../shared/speech-types' import { dispatchDictationControl } from './dictation-control-events' @@ -81,7 +82,7 @@ function useIsCloudModel(): boolean { } void catalogRequest.then((catalog) => { if (current) { - setCloud(catalog.some((model) => model.id === modelId && model.provider === 'openai')) + setCloud(catalog.some((model) => model.id === modelId && model.provider !== 'local')) } }) return () => { @@ -125,6 +126,21 @@ function DictationPillMeter({ recording, status }: { recording: boolean; status: ) } +// Words heard but not committed yet: they land at the next pause. +function DictationPendingDots() { + return ( + + {[0, 150, 300].map((delayMs) => ( + + ))} + + ) +} + // Presses on the pill keep focus where the words are going. const keepFocus = (event: React.MouseEvent): void => event.preventDefault() const keepFocusProps = { [KEEPS_FOCUS_ATTRIBUTE]: '', onMouseDown: keepFocus } @@ -132,7 +148,7 @@ const keepFocusProps = { [KEEPS_FOCUS_ATTRIBUTE]: '', onMouseDown: keepFocus } function DictationPill({ captureLive, anchor, failure, queued }: DictationIndicatorProps) { const t = useTranslate() const dictationState = useAppStore((state) => state.dictationState) - const partialTranscript = useAppStore((state) => state.partialTranscript) + const liveText = useAppStore((state) => state.liveText) const isHoldMode = useAppStore((state) => state.settings?.voice?.dictationMode === 'hold') const shortcut = useShortcutKeyDetails('voice.dictation') const box = useDictationPillBox(anchor) @@ -145,7 +161,8 @@ function DictationPill({ captureLive, anchor, failure, queued }: DictationIndica const showSpinner = useDelayedFlag(finishing, FINISH_SPINNER_DELAY_MS) const nearCloudLimit = cloudModel && seconds >= CLOUD_LIMIT_WARNING_SECONDS const failedKind = dictationState === 'error' ? failure : null - const transcript = partialTranscript.trim() + const { committed, speechPending } = liveText + const tentative = liveText.tentative.trim() const queuedStatus = queued === 'chat' ? t( @@ -198,12 +215,18 @@ function DictationPill({ captureLive, anchor, failure, queued }: DictationIndica )} {queuedStatus} - ) : transcript ? ( + ) : committed || tentative || speechPending ? ( + // Right-aligned so the newest words stay in view; older ones fade off the left edge. - {transcript} + + {committed} + {dictationSeparators(committed, tentative, '').leading} + {tentative} + {speechPending ? : null} + ) : ( diff --git a/src/renderer/src/components/dictation/SpeechModelUpdateCard.tsx b/src/renderer/src/components/dictation/SpeechModelUpdateCard.tsx new file mode 100644 index 00000000000..c7ae7f642a8 --- /dev/null +++ b/src/renderer/src/components/dictation/SpeechModelUpdateCard.tsx @@ -0,0 +1,285 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { Check, CircleAlert, Download, Mic, X } from 'lucide-react' +import { toast } from 'sonner' +import { useAppStore } from '@/store' +import { useTranslate } from '@/i18n/use-translate' +import { isPairedWebClientWindow } from '@/lib/desktop-window-chrome' +import { Card } from '../ui/card' +import { Button } from '../ui/button' +import { Progress } from '../ui/progress' +import { + findSpeechModelUpdateTarget, + type SpeechModelUpdateTarget +} from './speech-model-update-target' + +const DONE_AUTO_HIDE_MS = 4000 + +function useSpeechModelUpdateTarget(): SpeechModelUpdateTarget | null { + // Why no hydration check: the flag defaults to true until the persisted value arrives. + const seen = useAppStore((s) => s.speechModelUpdateNoticeSeen) + const voice = useAppStore((s) => s.settings?.voice) + const [target, setTarget] = useState(null) + + useEffect(() => { + // Why skip paired web clients: the models live on the host, whose own window shows this. + if (seen || !voice || isPairedWebClientWindow()) { + return + } + let cancelled = false + void Promise.all([window.api.speech.getCatalog(), window.api.speech.getModelStates()]) + .then(([catalog, states]) => { + if (cancelled) { + return + } + const store = useAppStore.getState() + store.setModelStates(states) + setTarget(findSpeechModelUpdateTarget(voice, catalog, states)) + // Why mark on the first check, shown or not: the card is for the first launch after the engine change. + store.markSpeechModelUpdateNoticeSeen() + }) + .catch(() => {}) + return () => { + cancelled = true + } + }, [seen, voice]) + + return target +} + +/** One-time card offering the download the transcribe-cpp engine needs for the selected model. */ +export function SpeechModelUpdateCard(): React.JSX.Element | null { + const target = useSpeechModelUpdateTarget() + const [closed, setClosed] = useState(false) + const close = useCallback(() => setClosed(true), []) + if (!target || closed) { + return null + } + return +} + +function SpeechModelUpdateCardBody({ + target: { model, retired }, + onClose +}: { + target: SpeechModelUpdateTarget + onClose: () => void +}): React.JSX.Element { + const t = useTranslate() + const state = useAppStore((s) => s.modelStates.find((m) => m.id === model.id)) + const refreshModelStates = useAppStore((s) => s.refreshModelStates) + const [failedAtMb, setFailedAtMb] = useState(null) + const [deleting, setDeleting] = useState(false) + const lastMbRef = useRef(0) + + // The Settings row starts the same download, so both follow the shared model states. + useEffect( + () => window.api.speech.onDownloadProgress(() => void refreshModelStates()), + [refreshModelStates] + ) + + const totalMb = Math.round((model.sizeBytes ?? 0) / 1_000_000) + const downloading = state?.status === 'downloading' || state?.status === 'extracting' + const percent = Math.round((state?.progress ?? 0) * 100) + const doneMb = Math.round((state?.progress ?? 0) * totalMb) + const phase = downloading + ? 'downloading' + : state?.status === 'ready' + ? 'done' + : failedAtMb !== null + ? 'failed' + : 'notice' + + useEffect(() => { + if (downloading) { + lastMbRef.current = doneMb + } + }, [downloading, doneMb]) + + useEffect(() => { + if (phase !== 'done' || retired) { + return + } + const timer = window.setTimeout(onClose, DONE_AUTO_HIDE_MS) + return () => window.clearTimeout(timer) + }, [phase, retired, onClose]) + + const startDownload = (): void => { + setFailedAtMb(null) + lastMbRef.current = 0 + void window.api.speech + .downloadModel(model.id) + .catch(() => setFailedAtMb(lastMbRef.current)) + .finally(() => void refreshModelStates()) + } + + const deleteRetired = (): void => { + if (!retired) { + return + } + setDeleting(true) + void window.api.speech + .deleteModel(retired.id) + .then(() => { + void refreshModelStates() + onClose() + }) + .catch(() => { + setDeleting(false) + toast.error( + t('speechModelUpdate.deleteFailed', 'Failed to delete {{model}}.', { + model: retired.label + }) + ) + }) + } + + const names = { model: model.label, old: retired?.label ?? '', size: totalMb } + const later = ( + + ) + let icon = + let title: string + let description: string + let actions: React.ReactNode = null + + if (phase === 'downloading') { + icon = + title = retired + ? t('speechModelUpdate.downloadingTitle', 'Downloading {{model}}', names) + : t('speechModelUpdate.updatingTitle', 'Updating {{model}}', names) + description = t( + 'speechModelUpdate.downloadingDescription', + 'You can keep working. Dictation is back when this finishes.' + ) + actions = ( + + ) + } else if (phase === 'done') { + icon = + title = t('speechModelUpdate.doneTitle', 'Dictation is ready') + description = retired + ? t( + 'speechModelUpdate.doneRetiredDescription', + '{{model}} is set up. The old {{old}} files are still on disk.', + names + ) + : t( + 'speechModelUpdate.doneDescription', + '{{model}} is updated. The old files were removed.', + names + ) + actions = retired ? ( + <> + + + + ) : null + } else if (phase === 'failed') { + icon = + title = retired + ? t('speechModelUpdate.downloadFailedTitle', "Couldn't download {{model}}", names) + : t('speechModelUpdate.updateFailedTitle', "Couldn't update {{model}}", names) + description = failedAtMb + ? t( + 'speechModelUpdate.failedAtDescription', + 'The download stopped at {{mb}} MB. Check your connection and try again.', + { mb: failedAtMb } + ) + : t( + 'speechModelUpdate.failedDescription', + 'The download stopped. Check your connection and try again.' + ) + actions = ( + <> + {later} + + + ) + } else { + title = retired + ? t('speechModelUpdate.replacedTitle', 'Your speech model was replaced') + : t('speechModelUpdate.updateTitle', 'Update your speech model') + description = retired + ? t( + 'speechModelUpdate.replacedDescription', + "{{old}} can't run on the new speech engine. {{model}} replaces it ({{size}} MB).", + names + ) + : t( + 'speechModelUpdate.updateDescription', + 'Dictation now runs on a faster engine. {{model}} needs a one-time download ({{size}} MB) before you can dictate again.', + names + ) + actions = ( + <> + {later} + + + ) + } + + return ( + +
+
+
{icon}
+
+

+ {title} +

+

{description}

+
+ +
+ {phase === 'downloading' && ( +
+ +
+ + {t('speechModelUpdate.progress', '{{done}} of {{total}} MB', { + done: doneMb, + total: totalMb + })} + + {percent}% +
+
+ )} + {actions &&
{actions}
} +
+
+ ) +} diff --git a/src/renderer/src/components/dictation/dictation-context.ts b/src/renderer/src/components/dictation/dictation-context.ts new file mode 100644 index 00000000000..08f9db5290a --- /dev/null +++ b/src/renderer/src/components/dictation/dictation-context.ts @@ -0,0 +1,19 @@ +import { useAppStore } from '@/store' +import { selectRepoByIdForActiveWorkspace } from '@/store/repos/active-workspace-repository' +import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' +import type { DictationContext } from '../../../../shared/speech-types' + +/** The worktree a dictation starts in, with its repo's terms for an engine running in this app. */ +export function captureDictationContext(): DictationContext { + const state = useAppStore.getState() + const worktreeId = state.activeWorktreeId + if (!worktreeId) { + return {} + } + const repo = selectRepoByIdForActiveWorkspace(state, getRepoIdFromWorktreeId(worktreeId)) + return { + worktreeId, + ...(repo?.dictationTerms ? { repoTerms: repo.dictationTerms } : {}), + ...(repo ? { repoName: repo.displayName } : {}) + } +} diff --git a/src/renderer/src/components/dictation/dictation-kept-recording.ts b/src/renderer/src/components/dictation/dictation-kept-recording.ts index 9853bb5b438..7981c21c90f 100644 --- a/src/renderer/src/components/dictation/dictation-kept-recording.ts +++ b/src/renderer/src/components/dictation/dictation-kept-recording.ts @@ -2,9 +2,11 @@ import { CLOUD_DICTATION_MAX_SECONDS, DICTATION_SAMPLE_RATE } from '../../../../shared/rpc-contract/speech-params' +import type { DictationContext } from '../../../../shared/speech-types' import type { DictationInsertionTarget } from './dictation-insertion-target' import type { DictationTranscriptDelivery } from './dictation-transcript-delivery' import { trimLandedOverlap } from './dictation-retry-overlap' +import { appendDictationText } from '../../../../shared/dictation-transcript-spacing' import { showRetryOverlapUnmatchedToast } from './dictation-toasts' // The cloud cap, ten minutes, is about 38 MB of 16 kHz float audio. @@ -17,11 +19,14 @@ export type DictationKeptRecording = { complete: boolean target: DictationInsertionTarget | null deliver: DictationTranscriptDelivery + /** A retry spells with the dictionary of the place it started in. */ + context: DictationContext } export function createDictationKeptRecording( target: DictationInsertionTarget | null, - deliver: DictationTranscriptDelivery + deliver: DictationTranscriptDelivery, + context: DictationContext ): DictationKeptRecording & { keep: (samples: Float32Array) => void /** The host stopped accepting audio at its own cap, so the first ten minutes are all it would hear. */ @@ -35,6 +40,7 @@ export function createDictationKeptRecording( complete: true, target, deliver, + context, keep: (frame: Float32Array): void => { const room = MAX_KEPT_SAMPLES - samples if (room <= 0) { @@ -87,7 +93,10 @@ function* joinIntoBlocks(chunks: Float32Array[]): Generator { // The retry repeats words that landed before the failure; only what follows them is typed. function insertAfterLanded(recording: DictationKeptRecording, retried: string[]): void { - const { text, matched } = trimLandedOverlap(recording.deliver.landedText(), retried.join(' ')) + const { text, matched } = trimLandedOverlap( + recording.deliver.landedText(), + retried.reduce(appendDictationText, '') + ) if (text) { recording.deliver(text, recording.target) } @@ -111,7 +120,7 @@ export async function transcribeKeptRecording(args: { const retried: string[] = [] args.routeFinals((text) => retried.push(text)) try { - await window.api.speech.startDictation(args.modelId, undefined, sessionId) + await window.api.speech.startDictation(args.modelId, args.recording.context, sessionId) for (const block of joinIntoBlocks(args.recording.chunks)) { if (!isCurrent()) { break diff --git a/src/renderer/src/components/dictation/dictation-toasts.ts b/src/renderer/src/components/dictation/dictation-toasts.ts index a196f050220..4d16b528431 100644 --- a/src/renderer/src/components/dictation/dictation-toasts.ts +++ b/src/renderer/src/components/dictation/dictation-toasts.ts @@ -3,6 +3,7 @@ import { useAppStore } from '@/store' import { translate } from '@/i18n/i18n' import { compactIpcErrorMessage } from '@/lib/ipc-error' import { hostDictationErrorMessage } from '../../../../shared/host-dictation-error-messages' +import { SPEECH_MODEL_NEEDS_UPDATE_ERROR } from '../../../../shared/speech-model-retirement' export function openVoiceSettings(): void { useAppStore.getState().openSettingsTarget({ pane: 'voice', repoId: null }) @@ -137,6 +138,14 @@ export function showDictationStartErrorToast(message: string): void { 'Microphone access denied. Grant access in system settings, then restart Orca.' ) ) + } else if (message.includes(SPEECH_MODEL_NEEDS_UPDATE_ERROR)) { + toast( + translate( + 'auto.components.dictation.DictationController.modelNeedsUpdate', + 'Your speech model needs an update to keep working. Update it to the faster version in Settings > Voice.' + ), + { action: openVoiceSettingsAction() } + ) } else if (kind === 'model-not-ready') { toast( translate( diff --git a/src/renderer/src/components/dictation/dictation-transcript-delivery.ts b/src/renderer/src/components/dictation/dictation-transcript-delivery.ts index 9680bded9e1..0b890d3bf31 100644 --- a/src/renderer/src/components/dictation/dictation-transcript-delivery.ts +++ b/src/renderer/src/components/dictation/dictation-transcript-delivery.ts @@ -1,7 +1,7 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import { describeClipboardWriteFailure } from '@/lib/clipboard-write-failure' -import { dictationSeparators } from '../../../../shared/dictation-transcript-spacing' +import { appendDictationText } from '../../../../shared/dictation-transcript-spacing' import { insertText, type DictationInsertionTarget } from './dictation-insertion-target' export type DictationTranscriptDelivery = (( @@ -25,10 +25,10 @@ export function createDictationTranscriptDelivery(): DictationTranscriptDelivery const landed = target ? await insertText(text, target, lastLanded).catch(() => false) : false if (landed) { lastLanded = text - allLanded += `${dictationSeparators(allLanded, text, '').leading}${text}` + allLanded = appendDictationText(allLanded, text) return } - missed += `${dictationSeparators(missed, text, '').leading}${text}` + missed = appendDictationText(missed, text) await copyMissedDictation(missed, target !== null) }) } diff --git a/src/renderer/src/components/dictation/speech-model-update-target.test.ts b/src/renderer/src/components/dictation/speech-model-update-target.test.ts new file mode 100644 index 00000000000..538bf45e94d --- /dev/null +++ b/src/renderer/src/components/dictation/speech-model-update-target.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import type { SpeechModelManifest, SpeechModelState } from '../../../../shared/speech-types' +import { findSpeechModelUpdateTarget } from './speech-model-update-target' + +function model(id: string, extra: Partial = {}): SpeechModelManifest { + return { + id, + label: id, + type: 'transducer', + provider: 'local', + language: 'en', + languages: ['en'], + sampleRate: 16000, + streaming: false, + ...extra + } +} + +const catalog = [ + model('parakeet'), + model('nemotron'), + model('zipformer-ko', { replacedBy: 'nemotron' }), + model('gpt', { provider: 'openai' }) +] + +function target(sttModel: string, states: SpeechModelState[], enabled = true) { + const found = findSpeechModelUpdateTarget({ enabled, sttModel }, catalog, states) + return found && { model: found.model.id, retired: found.retired?.id } +} + +describe('findSpeechModelUpdateTarget', () => { + it('offers the update when only the old files of the selected model are on disk', () => { + const states: SpeechModelState[] = [ + { id: 'parakeet', status: 'not-downloaded', needsUpdate: true } + ] + expect(target('parakeet', states)).toEqual({ model: 'parakeet', retired: undefined }) + expect(target('parakeet', states, false)).toBeNull() + }) + + it('offers the replacement when the retired model it replaced is still downloaded', () => { + const states: SpeechModelState[] = [ + { id: 'nemotron', status: 'not-downloaded' }, + { id: 'zipformer-ko', status: 'ready' } + ] + expect(target('nemotron', states)).toEqual({ model: 'nemotron', retired: 'zipformer-ko' }) + expect( + target('nemotron', [ + { id: 'nemotron', status: 'ready' }, + { id: 'zipformer-ko', status: 'ready' } + ]) + ).toBeNull() + }) + + it('stays hidden for cloud models and for people who never downloaded one', () => { + expect(target('gpt', [{ id: 'zipformer-ko', status: 'ready' }])).toBeNull() + expect(target('nemotron', [{ id: 'nemotron', status: 'not-downloaded' }])).toBeNull() + }) +}) diff --git a/src/renderer/src/components/dictation/speech-model-update-target.ts b/src/renderer/src/components/dictation/speech-model-update-target.ts new file mode 100644 index 00000000000..4b948a07b7d --- /dev/null +++ b/src/renderer/src/components/dictation/speech-model-update-target.ts @@ -0,0 +1,37 @@ +import type { + SpeechModelManifest, + SpeechModelState, + VoiceSettings +} from '../../../../shared/speech-types' + +export type SpeechModelUpdateTarget = { + /** The model to download: the selection itself. */ + model: SpeechModelManifest + /** The retired model the selection replaced on load, still on disk. */ + retired?: SpeechModelManifest +} + +/** Whether the engine change left the selected local model needing a download, and why. */ +export function findSpeechModelUpdateTarget( + voice: Pick, + catalog: readonly SpeechModelManifest[], + states: readonly SpeechModelState[] +): SpeechModelUpdateTarget | null { + const model = catalog.find((m) => m.id === voice.sttModel) + if (!voice.enabled || !model || model.provider !== 'local') { + return null + } + const stateOf = (id: string): SpeechModelState | undefined => states.find((s) => s.id === id) + const selected = stateOf(model.id) + if (selected?.needsUpdate) { + return { model } + } + if (selected?.status === 'ready') { + return null + } + // Settings load already moved the selection off the retired id, so find it by its files. + const retired = catalog.find( + (m) => m.replacedBy === model.id && stateOf(m.id)?.status === 'ready' + ) + return retired ? { model, retired } : null +} diff --git a/src/renderer/src/components/dictation/use-dictation-speech-events.ts b/src/renderer/src/components/dictation/use-dictation-speech-events.ts index 3fc07a10979..c551e1e3d1a 100644 --- a/src/renderer/src/components/dictation/use-dictation-speech-events.ts +++ b/src/renderer/src/components/dictation/use-dictation-speech-events.ts @@ -1,17 +1,42 @@ -import { useEffect, useEffectEvent } from 'react' +import { useEffect, useEffectEvent, useRef } from 'react' +import { DictationTranscript } from '../../../../shared/dictation-transcript' +import type { DictationLiveText } from '@/store/slices/dictation/dictation' type DictationSpeechEventHandlers = { /** Text events are dropped unless they belong to this session. */ currentSessionId: () => string | null - onPartial: (text: string) => void + /** The session's words so far, after every partial or final. */ + onLiveText: (text: DictationLiveText) => void onFinal: (text: string) => void onStopped: (sessionId: string) => void onError: (sessionId: string, error: string) => void } export function useDictationSpeechEvents(handlers: DictationSpeechEventHandlers): void { + const liveRef = useRef<{ + sessionId: string + transcript: DictationTranscript + speechPending: boolean + } | null>(null) const isCurrent = useEffectEvent((sessionId: string) => sessionId === handlers.currentSessionId()) - const onPartial = useEffectEvent(handlers.onPartial) + const onLiveEvent = useEffectEvent( + ( + sessionId: string, + event: { type: 'partial' | 'final'; text: string } | { type: 'pending'; pending: boolean } + ) => { + if (liveRef.current?.sessionId !== sessionId) { + liveRef.current = { sessionId, transcript: new DictationTranscript(), speechPending: false } + } + const live = liveRef.current + if (event.type === 'pending') { + live.speechPending = event.pending + } else { + live.transcript.accept(event) + } + const { committed, tentative } = live.transcript.snapshot() + handlers.onLiveText({ committed, tentative, speechPending: live.speechPending }) + } + ) const onFinal = useEffectEvent(handlers.onFinal) const onStopped = useEffectEvent(handlers.onStopped) const onError = useEffectEvent(handlers.onError) @@ -20,14 +45,20 @@ export function useDictationSpeechEvents(handlers: DictationSpeechEventHandlers) const cleanups = [ window.api.speech.onPartialTranscript((data) => { if (isCurrent(data.sessionId)) { - onPartial(data.text) + onLiveEvent(data.sessionId, { type: 'partial', text: data.text }) } }), window.api.speech.onFinalTranscript((data) => { if (data.text && isCurrent(data.sessionId)) { + onLiveEvent(data.sessionId, { type: 'final', text: data.text }) onFinal(data.text) } }), + window.api.speech.onSpeechPending((data) => { + if (isCurrent(data.sessionId)) { + onLiveEvent(data.sessionId, { type: 'pending', pending: data.pending }) + } + }), window.api.speech.onStopped((data) => onStopped(data.sessionId)), window.api.speech.onError((data) => { if (isCurrent(data.sessionId)) { diff --git a/src/renderer/src/components/diff-comments/use-diff-comment-owner.ts b/src/renderer/src/components/diff-comments/use-diff-comment-owner.ts index 692677e0871..88bcd069bdc 100644 --- a/src/renderer/src/components/diff-comments/use-diff-comment-owner.ts +++ b/src/renderer/src/components/diff-comments/use-diff-comment-owner.ts @@ -10,7 +10,7 @@ import { type DiffCommentOwner, type DiffCommentView } from '@/store/slices/diff-comments/diff-comment-owner' -import type { WorkspaceCopySource } from '@/lib/workspace-copy-owner' +import type { WorkspaceCopySource } from '@/lib/workspace/ownership/workspace-copy-owner' import type { DiffComment } from '../../../../shared/diff-comment-types' /** diff --git a/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts b/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts index 246ef2e3414..e27370983a8 100644 --- a/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts +++ b/src/renderer/src/components/diff-comments/use-visible-worktree-diff-comments.ts @@ -1,12 +1,12 @@ import { useAppStateValue } from '@/store/retained-views/app-state-view' import { useDiffCommentView } from './use-diff-comment-owner' import type { DiffCommentOwner } from '@/store/slices/diff-comments/diff-comment-owner' -import type { WorkspaceCopySource } from '@/lib/workspace-copy-owner' +import type { WorkspaceCopySource } from '@/lib/workspace/ownership/workspace-copy-owner' import { useMemo } from 'react' import { isMarkdownReviewNotesEnabled, withoutMarkdownReviewNotes -} from '@/lib/markdown-review-notes-setting' +} from '@/lib/editor/markdown/review-notes/markdown-review-notes-setting' import type { DiffComment } from '../../../../shared/diff-comment-types' const NO_COMMENTS: DiffComment[] = [] diff --git a/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx b/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx index 9868d8bd97f..492624e8f1d 100644 --- a/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx +++ b/src/renderer/src/components/editor/EditorConflictReviewSurface.tsx @@ -1,6 +1,6 @@ import React from 'react' import { conflictOverviewView } from '@/store/slices/editor/buffers/editor-buffer-conflict-overview' -import { detectLanguage } from '@/lib/language-detect' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' import { joinPath } from '@/lib/path' import { useAppStore } from '@/store' import type { OpenFile } from '@/store/slices/editor/types/open-file' diff --git a/src/renderer/src/components/editor/EditorEditFileSurface.tsx b/src/renderer/src/components/editor/EditorEditFileSurface.tsx index 87aed56dba1..9ab30a934e2 100644 --- a/src/renderer/src/components/editor/EditorEditFileSurface.tsx +++ b/src/renderer/src/components/editor/EditorEditFileSurface.tsx @@ -1,5 +1,5 @@ import { useTranslate } from '@/i18n/use-translate' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import type { MarkdownViewMode, OpenFile } from '@/store/slices/editor/types/open-file' import type { PendingEditorReveal } from '@/store/slices/editor/types/pending-editor-reveal' import type { GitDiffResult } from '../../../../shared/git/diff/git-diff-compare-types' diff --git a/src/renderer/src/components/editor/EditorFileLoadErrorView.test.tsx b/src/renderer/src/components/editor/EditorFileLoadErrorView.test.tsx index 261ea742a19..0cba5651e78 100644 --- a/src/renderer/src/components/editor/EditorFileLoadErrorView.test.tsx +++ b/src/renderer/src/components/editor/EditorFileLoadErrorView.test.tsx @@ -17,7 +17,7 @@ vi.mock('../wsl-host-stopped/use-stopped-wsl-host', () => ({ useStoppedWslHost: (worktreeId: string | undefined) => worktreeId === 'wt-wsl' ? mocks.stopped.current : null })) -vi.mock('@/lib/wsl-host-user-start', () => ({ +vi.mock('@/runtime/hosts/wsl/wsl-host-user-start', () => ({ startWslHostAndReloadProjects: mocks.start })) diff --git a/src/renderer/src/components/editor/EditorPanel.tsx b/src/renderer/src/components/editor/EditorPanel.tsx index 4dcd5a6db66..252570c45c0 100644 --- a/src/renderer/src/components/editor/EditorPanel.tsx +++ b/src/renderer/src/components/editor/EditorPanel.tsx @@ -1,9 +1,9 @@ import React, { useCallback, useMemo, useRef, useState } from 'react' import { useAppStore } from '@/store' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { formatClipboardFilePath } from '@/lib/clipboard-file-path' import { getOpenFileRevealOwner } from '@/lib/reveal-in-file-manager' -import { canShowWorkspaceFileBrowserAction } from '@/lib/file-preview' +import { canShowWorkspaceFileBrowserAction } from '@/lib/browser/documents/file-preview' import { openEditorHtmlPreview } from './open-editor-html-preview' import { getEditorHeaderCopyState } from './editor-header' import { getRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' @@ -30,7 +30,7 @@ import { editorArtifactContentType } from './editor-artifact-upload' import { useEditorPanelSave } from './save/commands/useEditorPanelSave' -import { isMarkdownReviewNotesEnabled } from '@/lib/markdown-review-notes-setting' +import { isMarkdownReviewNotesEnabled } from '@/lib/editor/markdown/review-notes/markdown-review-notes-setting' import { useFileCustomEditors } from '@/store/plugins/file-editors/plugin-custom-editors' import { applyCustomEditorToggle } from './view-mode/custom-editor-toggle' import { editorPanelFileActions } from './editor-panel-file-actions' @@ -89,6 +89,7 @@ function EditorPanelInner({ ) const editorDrafts = useAppStore(editorDraftSelector) const diffDefaultView = useAppStore((s) => s.settings?.diffDefaultView) + const updateSettings = useAppStore((s) => s.updateSettings) const customEditors = useFileCustomEditors(activeFileId, activeFile?.filePath) const markdownReviewNotesEnabled = useAppStore((s) => isMarkdownReviewNotesEnabled(s.settings)) const panelRef = useRef(null) @@ -115,15 +116,7 @@ function EditorPanelInner({ }, [clearCopiedPathToastResetTimer] ) - const [sideBySide, setSideBySide] = useState(diffDefaultView === 'side-by-side') - const [prevDiffView, setPrevDiffView] = useState(diffDefaultView) - - if (diffDefaultView !== prevDiffView) { - setPrevDiffView(diffDefaultView) - if (diffDefaultView !== undefined) { - setSideBySide(diffDefaultView === 'side-by-side') - } - } + const sideBySide = diffDefaultView === 'side-by-side' const requestedChangesMode = !!activeFile && @@ -345,7 +338,9 @@ function EditorPanelInner({ onOpenDiffTargetFile={handleOpenDiffTargetFile} onOpenPreview={handleOpenPreview} onOpenMarkdownPreview={handleOpenMarkdownPreview} - onToggleSideBySide={() => setSideBySide((prev) => !prev)} + onToggleSideBySide={() => + void updateSettings({ diffDefaultView: sideBySide ? 'inline' : 'side-by-side' }) + } onEditorToggleChange={handleEditorToggleChange} onToggleMarkdownTableOfContents={() => setMarkdownTableOfContentsVisible( diff --git a/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx b/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx index 7d023efb7ef..17ea73dd547 100644 --- a/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx +++ b/src/renderer/src/components/editor/MonacoCodeExcerpt.tsx @@ -1,6 +1,9 @@ import React, { useEffect, useMemo, useState } from 'react' -import { monaco } from '@/lib/monaco-setup' -import { EDITOR_TYPOGRAPHY_SURFACE_CLASS, editorTypographyTextStyle } from '@/lib/editor-typography' +import { monaco } from '@/lib/editor/monaco/monaco-setup' +import { + EDITOR_TYPOGRAPHY_SURFACE_CLASS, + editorTypographyTextStyle +} from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' import { cn } from '@/lib/utils' import { useMonacoTheme } from '@/hooks/use-monaco-theme' diff --git a/src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx b/src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx index f599ae45e03..5fe29c1c11c 100644 --- a/src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx +++ b/src/renderer/src/components/editor/MonacoEditor.owner-view-state.test.tsx @@ -31,12 +31,12 @@ vi.mock('@/store', () => { ) } }) -vi.mock('@/lib/monaco-setup', async () => { +vi.mock('@/lib/editor/monaco/monaco-setup', async () => { const { loader } = await import('@monaco-editor/react') // Why: the real setup installs this guard; without it a disposed editor's pending word // highlight rejects with Monaco's "Canceled" and the run reports unhandled errors. const { installMonacoDelayerCancellationGuard } = - await import('@/lib/monaco-delayer-cancellation-guard') + await import('@/lib/editor/monaco/monaco-delayer-cancellation-guard') installMonacoDelayerCancellationGuard() loader.config({ monaco }) return {} diff --git a/src/renderer/src/components/editor/MonacoEditor.tsx b/src/renderer/src/components/editor/MonacoEditor.tsx index 4ee504c6c36..f14c078a460 100644 --- a/src/renderer/src/components/editor/MonacoEditor.tsx +++ b/src/renderer/src/components/editor/MonacoEditor.tsx @@ -3,8 +3,8 @@ import Editor from '@monaco-editor/react' import type { editor, IRange } from 'monaco-editor' import type { MarkdownDocument } from '../../../../shared/file-listing/file-document' import { useAppStore } from '@/store' -import '@/lib/monaco-setup' -import { monacoTypographyOptions } from '@/lib/editor-typography' +import '@/lib/editor/monaco/monaco-setup' +import { monacoTypographyOptions } from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' import { useContextualCopySetup } from './useContextualCopySetup' import { MonacoGutterContextMenu } from './MonacoGutterContextMenu' @@ -13,7 +13,10 @@ import { MAX_TOKENIZATION_LINE_LENGTH } from '@/lib/monaco-languages/monarch-emb import { buildFileEditorWordWrapOptions } from './file-editor-word-wrap-options' import { toEditorModelUri } from './model-lifetime/identity/editor-model-uri' import { getEditorModelOwnerKey } from './model-lifetime/identity/editor-model-owner' -import { NO_RESOURCE_EVIDENCE, type WorkspaceResource } from '@/lib/workspace-copy-owner' +import { + NO_RESOURCE_EVIDENCE, + type WorkspaceResource +} from '@/lib/workspace/ownership/workspace-copy-owner' import { getMonacoAutoHeightForContent, isMonacoAutoHeightCapped } from './monaco-auto-height' import { monacoFindOptions } from './monaco-find-options' import { buildEditorUnicodeHighlightOptions } from './editor-unicode-highlight-options' diff --git a/src/renderer/src/components/editor/MonacoGutterContextMenu.tsx b/src/renderer/src/components/editor/MonacoGutterContextMenu.tsx index bb6c5dcfd44..869a71c7f24 100644 --- a/src/renderer/src/components/editor/MonacoGutterContextMenu.tsx +++ b/src/renderer/src/components/editor/MonacoGutterContextMenu.tsx @@ -9,7 +9,7 @@ import { DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { useAppStore } from '@/store' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { findFirstIndexedWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner-index' import { getRuntimeGitRemoteFileUrl } from '@/runtime/source-control/git/runtime-git-working-tree-client' import { formatPathLineReference } from './line-copy-path' diff --git a/src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx b/src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx index bbcd52b0067..db24ade6b07 100644 --- a/src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx +++ b/src/renderer/src/components/editor/ai-vault-session-log-content.test.tsx @@ -4,7 +4,7 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useAppStore } from '@/store' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { TEST_REPO } from '@/store/repos/repo.test-fixture' import type { OpenFile } from '@/store/slices/editor/types/open-file' diff --git a/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts b/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts index 29d6903c91a..26808c81cca 100644 --- a/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts +++ b/src/renderer/src/components/editor/autosave/editor-autosave-conflict-flow.test.ts @@ -19,7 +19,7 @@ const mocks = vi.hoisted(() => ({ getConnectionIdForFile: vi.fn() })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: mocks.getConnectionIdForFile })) diff --git a/src/renderer/src/components/editor/autosave/editor-autosave-controller.test.ts b/src/renderer/src/components/editor/autosave/editor-autosave-controller.test.ts index f5fc02a72f0..6c5521037d0 100644 --- a/src/renderer/src/components/editor/autosave/editor-autosave-controller.test.ts +++ b/src/renderer/src/components/editor/autosave/editor-autosave-controller.test.ts @@ -29,7 +29,7 @@ const mocks = vi.hoisted(() => ({ getConnectionIdForFile: vi.fn() })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: mocks.getConnectionIdForFile })) diff --git a/src/renderer/src/components/editor/check-details/actions/check-run-details-fix-with-ai.ts b/src/renderer/src/components/editor/check-details/actions/check-run-details-fix-with-ai.ts index 39ae86e6723..0d48367b4ae 100644 --- a/src/renderer/src/components/editor/check-details/actions/check-run-details-fix-with-ai.ts +++ b/src/renderer/src/components/editor/check-details/actions/check-run-details-fix-with-ai.ts @@ -9,10 +9,10 @@ import { resolveCheckRunDetailsFixRepo } from './check-run-details-fix-context' import { openSourceControlAiSettingsTarget } from '@/components/right-sidebar/source-control/panel/source-control-ai-settings-navigation' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { startFixChecksAgent } from '@/lib/fix-checks-agent-launch' import { readSourceControlLaunchRecipeAgentId } from '../../../../../../shared/source-control/ai/source-control-launch-agent-selection' -import { resolveRepoWorktreeLaunchPlatform } from '@/lib/execution-host-facts' +import { resolveRepoWorktreeLaunchPlatform } from '@/runtime/hosts/platform/execution-host-facts' import { useAppStore } from '@/store/index' import { findFirstIndexedWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner-index' import { resolveSourceControlActionRecipe } from '../../../../../../shared/source-control/ai/source-control-ai-operation-policy' diff --git a/src/renderer/src/components/editor/closed-unsaved-files-toast.test.ts b/src/renderer/src/components/editor/closed-unsaved-files-toast.test.ts index d1aa4528c9e..1ea2e5ed7eb 100644 --- a/src/renderer/src/components/editor/closed-unsaved-files-toast.test.ts +++ b/src/renderer/src/components/editor/closed-unsaved-files-toast.test.ts @@ -38,10 +38,14 @@ vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state } })) vi.mock('sonner', () => ({ toast: { warning: mocks.warning, error: mocks.error, dismiss: mocks.dismiss } })) -vi.mock('@/lib/create-untitled-markdown', () => ({ createUntitledMarkdownFile: mocks.create })) -vi.mock('@/lib/editor-file-operation-owner', () => ({ +vi.mock('@/lib/editor/file-operations/create-untitled-markdown', () => ({ + createUntitledMarkdownFile: mocks.create +})) +vi.mock('@/lib/editor/file-operations/editor-file-operation-owner', () => ({ + getEditorFileOperationContext: mocks.context +})) +vi.mock('@/lib/editor/file-operations/editor-file-operation-provenance', () => ({ captureEditorFileOperationProvenance: mocks.capture, - getEditorFileOperationContext: mocks.context, assertEditorFileOperationCurrent: mocks.assertCurrent })) import { reopenClosedUnsavedFiles, showClosedUnsavedFilesToast } from './closed-unsaved-files-toast' diff --git a/src/renderer/src/components/editor/closed-unsaved-files-toast.ts b/src/renderer/src/components/editor/closed-unsaved-files-toast.ts index 523983b4945..a56138b5119 100644 --- a/src/renderer/src/components/editor/closed-unsaved-files-toast.ts +++ b/src/renderer/src/components/editor/closed-unsaved-files-toast.ts @@ -1,12 +1,12 @@ import { toast } from 'sonner' import { useAppStore } from '@/store' import type { ClosedUnsavedFile } from '@/store/slices/worktrees/teardown/removed-workspace-unsaved-files' +import { getEditorFileOperationContext } from '@/lib/editor/file-operations/editor-file-operation-owner' import { assertEditorFileOperationCurrent, - captureEditorFileOperationProvenance, - getEditorFileOperationContext -} from '@/lib/editor-file-operation-owner' -import { createUntitledMarkdownFile } from '@/lib/create-untitled-markdown' + captureEditorFileOperationProvenance +} from '@/lib/editor/file-operations/editor-file-operation-provenance' +import { createUntitledMarkdownFile } from '@/lib/editor/file-operations/create-untitled-markdown' import { translate } from '@/i18n/i18n' function closedUnsavedFilesToastTitle(count: number, workspace: string): string { diff --git a/src/renderer/src/components/editor/combined-diff/CombinedDiffViewer.tsx b/src/renderer/src/components/editor/combined-diff/CombinedDiffViewer.tsx index 4c4a27dee2c..74ae2a9ad7e 100644 --- a/src/renderer/src/components/editor/combined-diff/CombinedDiffViewer.tsx +++ b/src/renderer/src/components/editor/combined-diff/CombinedDiffViewer.tsx @@ -2,10 +2,10 @@ import { editorViewPlacement } from '@/store/slices/editor/tabs/editor-view-plac import React, { useCallback, useRef, useState } from 'react' import { useAppStore } from '@/store' import { createProgrammaticScrollMarks } from '@/hooks/programmatic-scroll-marks' -import { useWorkspaceFileBrowserActionPredicate } from '@/lib/file-preview' +import { useWorkspaceFileBrowserActionPredicate } from '@/lib/browser/documents/file-preview' import { useVisibleWorktreeDiffComments } from '../../diff-comments/use-visible-worktree-diff-comments' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import '@/lib/monaco-setup' +import '@/lib/editor/monaco/monaco-setup' import type { DiffSection } from '../diff/sections/diff-section-types' import { EMPTY_GIT_BRANCH_ENTRIES, @@ -111,7 +111,6 @@ export default function CombinedDiffViewer({ setGeneration, setSectionHeights, setSections, - setSideBySide: preferences.setSideBySide, succession: buildCombinedDiffViewTabSuccession(file.id, viewStateScopeId), viewStateKey }) @@ -242,7 +241,6 @@ export default function CombinedDiffViewer({ scrollContainerRef, sectionHeights, sections, - sideBySide: preferences.sideBySide, viewStateKey }) useCombinedDiffScrollPersistence({ diff --git a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-metadata-retention.test.tsx b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-metadata-retention.test.tsx index d38ed6157d2..4ba6eb94852 100644 --- a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-metadata-retention.test.tsx +++ b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-metadata-retention.test.tsx @@ -51,7 +51,6 @@ function useReview(props: Review) { const [sections, setSections] = useState([]) const [sectionHeights, setSectionHeights] = useState>({}) const [generation, setGeneration] = useState(0) - const [sideBySide, setSideBySide] = useState(false) const registry = useCombinedDiffSectionLoadRegistry(sections) const entrySet = useCombinedDiffEntrySet({ file: props.file, @@ -67,7 +66,6 @@ function useReview(props: Review) { setGeneration, setSectionHeights, setSections, - setSideBySide, viewStateKey: props.viewStateKey }) const loader = useCombinedDiffSectionLoader({ @@ -109,7 +107,6 @@ function useReview(props: Review) { scrollContainerRef, sectionHeights, sections, - sideBySide, viewStateKey: props.viewStateKey }) return { diff --git a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-section-connection.ts b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-section-connection.ts index bbbdd3fcd7c..9d67215d6ec 100644 --- a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-section-connection.ts +++ b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-section-connection.ts @@ -1,7 +1,7 @@ -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { joinPath } from '@/lib/path' import { useAppStore } from '@/store' -import { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' +import { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' import type { OpenFile } from '@/store/slices/editor/types/open-file' export function acquireCombinedDiffSectionOperation(file: OpenFile, sectionPath: string) { diff --git a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx index 09e2a57a626..06de4ab6c35 100644 --- a/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx +++ b/src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx @@ -80,7 +80,6 @@ function useViewer(props: Viewer) { const [sections, setSections] = useState([]) const [sectionHeights, setSectionHeights] = useState>({}) const [generation, setGeneration] = useState(0) - const [, setSideBySide] = useState(false) const registry = useCombinedDiffSectionLoadRegistry(sections) const restore = useCombinedDiffViewRestore({ entrySet: props.entrySet, @@ -90,7 +89,6 @@ function useViewer(props: Viewer) { setGeneration, setSectionHeights, setSections, - setSideBySide, viewStateKey: props.viewStateKey }) const loader = useCombinedDiffSectionLoader({ diff --git a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache-body-budget.test.ts b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache-body-budget.test.ts index 575eb7ace9e..8e0071fa5dd 100644 --- a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache-body-budget.test.ts +++ b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache-body-budget.test.ts @@ -40,8 +40,7 @@ function view(sections: DiffSection[]): CachedCombinedDiffViewState { gitStatusSignature: 'status', sections, sectionHeights: { 0: 320 }, - loadedIndices: sections.map((_, index) => index), - sideBySide: true + loadedIndices: sections.map((_, index) => index) } } diff --git a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache.ts b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache.ts index 516b7f114a4..a3fb978f42f 100644 --- a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache.ts +++ b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-cache.ts @@ -7,7 +7,6 @@ export type CachedCombinedDiffViewState = { sections: DiffSection[] sectionHeights: Record loadedIndices: number[] - sideBySide: boolean } type CombinedDiffViewMemory = { diff --git a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-draft-retention.test.ts b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-draft-retention.test.ts index 0db464bae90..b860cc1b187 100644 --- a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-draft-retention.test.ts +++ b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-draft-retention.test.ts @@ -32,8 +32,7 @@ function rememberView(index: number, section: Partial = {}) { gitStatusSignature: '', sections, sectionHeights: {}, - loadedIndices: [0], - sideBySide: false + loadedIndices: [0] } }) return lease diff --git a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-memory.ts b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-memory.ts index 2571b01e774..8f8db141656 100644 --- a/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-memory.ts +++ b/src/renderer/src/components/editor/combined-diff/remember-view/combined-diff-view-memory.ts @@ -7,9 +7,8 @@ import { forgetCombinedDiffViewsShowingPath } from './combined-diff-view-cache' // Module state retains toolbar choices across viewer unmounts within this session. export const combinedDiffViewPreferences: { collapsed: boolean | null - sideBySide: boolean | null fileTreeCollapsed: boolean | null -} = { collapsed: null, sideBySide: null, fileTreeCollapsed: null } +} = { collapsed: null, fileTreeCollapsed: null } function handleCombinedDiffExternalFileChange(event: Event): void { const detail = (event as CustomEvent).detail diff --git a/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-persist.ts b/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-persist.ts index 7379ceb75d1..cdbdf7831da 100644 --- a/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-persist.ts +++ b/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-persist.ts @@ -16,7 +16,6 @@ export function useCombinedDiffViewPersist({ sectionHeights, sections, loadedIndicesRef, - sideBySide, viewStateKey }: { combinedGitStatusSignature: string @@ -27,7 +26,6 @@ export function useCombinedDiffViewPersist({ sectionHeights: Record sections: DiffSection[] loadedIndicesRef: React.RefObject> - sideBySide: boolean viewStateKey: string }): void { useEffect(() => { @@ -46,8 +44,7 @@ export function useCombinedDiffViewPersist({ sectionHeights, loadedIndices: Array.from(loadedIndicesRef.current).filter( (index) => !sections[index]?.loading - ), - sideBySide + ) } }) }, [ @@ -59,7 +56,6 @@ export function useCombinedDiffViewPersist({ scrollContainerRef, sectionHeights, sections, - sideBySide, viewStateKey ]) } diff --git a/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-restore.ts b/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-restore.ts index a2d8592580d..7a7ee57b7b8 100644 --- a/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-restore.ts +++ b/src/renderer/src/components/editor/combined-diff/remember-view/use-combined-diff-view-restore.ts @@ -43,7 +43,6 @@ export function useCombinedDiffViewRestore({ setGeneration, setSectionHeights, setSections, - setSideBySide, succession, viewStateKey }: { @@ -54,7 +53,6 @@ export function useCombinedDiffViewRestore({ setGeneration: React.Dispatch> setSectionHeights: React.Dispatch>> setSections: React.Dispatch> - setSideBySide: React.Dispatch> /** Set for tab-scoped keys so a reopened tab restores the view its closed predecessor left. */ succession?: CombinedDiffViewSuccession viewStateKey: string @@ -211,7 +209,6 @@ export function useCombinedDiffViewRestore({ sectionsRef.current = restoredSections setSections(restoredSections) setSectionHeights(cached.sectionHeights) - setSideBySide(combinedDiffViewPreferences.sideBySide ?? cached.sideBySide) loadedIndicesRef.current = new Set( cached.loadedIndices.filter((index) => { const section = restoredSections[index] @@ -288,7 +285,6 @@ export function useCombinedDiffViewRestore({ setGeneration, setSectionHeights, setSections, - setSideBySide, shouldAutoReloadFromGitStatus, treeMode, ownerKey, diff --git a/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-review-host.test-fixture.ts b/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-review-host.test-fixture.ts index b32984df104..64f541289bb 100644 --- a/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-review-host.test-fixture.ts +++ b/src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-review-host.test-fixture.ts @@ -52,7 +52,7 @@ vi.mock('@/store/index', () => ({ }) })) vi.mock('@/hooks/use-document-dark-theme', () => ({ useDocumentDarkTheme: () => false })) -vi.mock('@/lib/monaco-setup', async () => ({ +vi.mock('@/lib/editor/monaco/monaco-setup', async () => ({ monaco: await import('monaco-editor/esm/vs/editor/editor.api.js') })) vi.mock('../../../diff-comments/useDiffCommentDecorator', () => ({ diff --git a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-notes-actions.ts b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-notes-actions.ts index 76263d456b7..32715254740 100644 --- a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-notes-actions.ts +++ b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-notes-actions.ts @@ -1,7 +1,7 @@ import type { AppState } from '@/store/types' import type { DiffCommentOwner } from '@/store/slices/diff-comments/diff-comment-owner' import { useOwnedDiffComments } from '@/components/diff-comments/use-diff-comment-owner' -import { withoutMarkdownReviewNotes } from '@/lib/markdown-review-notes-setting' +import { withoutMarkdownReviewNotes } from '@/lib/editor/markdown/review-notes/markdown-review-notes-setting' import React, { useCallback, useEffect, useRef, useState } from 'react' import { toast } from 'sonner' import { formatDiffComments } from '@/lib/diff-comments-format' diff --git a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.ts b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.ts index af6f1152b8f..e2b751179b2 100644 --- a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.ts +++ b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.ts @@ -3,9 +3,9 @@ import { useCallback } from 'react' import { useCombinedDiffSectionSave } from './use-combined-diff-section-save' import type React from 'react' import { useAppStore } from '@/store' -import { detectLanguage } from '@/lib/language-detect' +import { detectLanguage } from '../../../../../../shared/editor-language/editor-language-detect' import { joinPath } from '@/lib/path' -import { openFilePreviewToSide } from '@/lib/file-preview' +import { openFilePreviewToSide } from '@/lib/browser/documents/file-preview' import type { AppState } from '@/store/types' import type { OpenFile } from '@/store/slices/editor/types/open-file' import type { GitBranchChangeEntry } from '../../../../../../shared/git/diff/git-diff-compare-types' diff --git a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-view-preferences.ts b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-view-preferences.ts index b3694397718..ddcafa64296 100644 --- a/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-view-preferences.ts +++ b/src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-view-preferences.ts @@ -1,15 +1,20 @@ import { useCallback, useState } from 'react' import type React from 'react' +import type { GlobalSettings } from '../../../../../../shared/global-settings-types' import type { DiffSection } from '../../diff/sections/diff-section-types' import { combinedDiffViewPreferences } from '../remember-view/combined-diff-view-memory' import { getInitialCombinedDiffSectionLoadIndices } from '../load-sections/combined-diff-initial-section-load' import type { CombinedDiffSectionLoadRegistry } from '../load-sections/combined-diff-section-load-registry' +type DiffViewSettings = Pick< + GlobalSettings, + 'diffDefaultView' | 'diffShowWhitespace' | 'diffWordWrap' +> + export type CombinedDiffViewPreferences = { fileTreeCollapsed: boolean setAllSectionsCollapsed: (collapsed: boolean) => void setFileTreeCollapsed: (collapsed: boolean) => void - setSideBySide: React.Dispatch> sideBySide: boolean toggleDiffShowWhitespace: () => void toggleDiffWordWrap: () => void @@ -26,32 +31,21 @@ export function useCombinedDiffViewPreferences({ updateSettings }: { combinedDiffFileTreeVisibleByDefault: boolean | undefined - diffDefaultView: string | undefined + diffDefaultView: DiffViewSettings['diffDefaultView'] | undefined diffShowWhitespace: boolean | undefined diffWordWrap: boolean | undefined registry: CombinedDiffSectionLoadRegistry setSections: React.Dispatch> - updateSettings: (patch: { diffShowWhitespace?: boolean; diffWordWrap?: boolean }) => unknown + updateSettings: (patch: Partial) => unknown }): CombinedDiffViewPreferences { const { loadSchedulerRef, loadedIndicesRef, sectionsRef } = registry - const [sideBySide, setSideBySide] = useState( - () => combinedDiffViewPreferences.sideBySide ?? diffDefaultView === 'side-by-side' - ) + const sideBySide = diffDefaultView === 'side-by-side' const [fileTreeCollapsed, setFileTreeCollapsedState] = useState( () => // While settings load, open the opt-in tree only for an explicit saved preference. combinedDiffViewPreferences.fileTreeCollapsed ?? combinedDiffFileTreeVisibleByDefault !== true ) - // Use settings until the first session toolbar choice, then retain that choice over global defaults. - const [prevDiffDefaultView, setPrevDiffDefaultView] = useState(diffDefaultView) - if (prevDiffDefaultView !== diffDefaultView) { - setPrevDiffDefaultView(diffDefaultView) - if (diffDefaultView !== undefined && combinedDiffViewPreferences.sideBySide === null) { - setSideBySide(diffDefaultView === 'side-by-side') - } - } - const [prevFileTreeVisibleByDefault, setPrevFileTreeVisibleByDefault] = useState( combinedDiffFileTreeVisibleByDefault ) @@ -88,11 +82,8 @@ export function useCombinedDiffViewPreferences({ ) const toggleSideBySide = useCallback(() => { - // Write module preferences outside React updaters, which may replay. - const next = !sideBySide - combinedDiffViewPreferences.sideBySide = next - setSideBySide(next) - }, [sideBySide]) + void updateSettings({ diffDefaultView: sideBySide ? 'inline' : 'side-by-side' }) + }, [sideBySide, updateSettings]) const toggleDiffWordWrap = useCallback(() => { void updateSettings({ diffWordWrap: diffWordWrap !== true }) @@ -106,7 +97,6 @@ export function useCombinedDiffViewPreferences({ fileTreeCollapsed, setAllSectionsCollapsed, setFileTreeCollapsed, - setSideBySide, sideBySide, toggleDiffShowWhitespace, toggleDiffWordWrap, diff --git a/src/renderer/src/components/editor/csv/csv-link-routing.ts b/src/renderer/src/components/editor/csv/csv-link-routing.ts index 297f97aa74a..f205d261e4c 100644 --- a/src/renderer/src/components/editor/csv/csv-link-routing.ts +++ b/src/renderer/src/components/editor/csv/csv-link-routing.ts @@ -1,4 +1,4 @@ -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { openHttpLink, type HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' import { resolveMarkdownPreviewHttpOpenOptions } from '../markdown/link-routing/markdown-preview-links' diff --git a/src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.ts b/src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.ts index e7ca20385f2..c2e53f3f5f3 100644 --- a/src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.ts +++ b/src/renderer/src/components/editor/diff/large-files/useDiffViewerLargeDiffLifecycle.ts @@ -1,7 +1,7 @@ import { useEffect, useMemo, useRef, useState } from 'react' import type { RefObject } from 'react' import type { editor } from 'monaco-editor' -import { monaco } from '@/lib/monaco-setup' +import { monaco } from '@/lib/editor/monaco/monaco-setup' import { disposeUnattachedDiffViewerMonacoModels, disposeUnattachedMonacoModelPaths, diff --git a/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx b/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx index c493955fc4e..e02d1627e37 100644 --- a/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx +++ b/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.tsx @@ -1,11 +1,11 @@ -import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace-copy-owner' +import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace/ownership/workspace-copy-owner' import { useDiffCommentView } from '../../../diff-comments/use-diff-comment-owner' import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { DiffEditor, type DiffOnMount } from '@monaco-editor/react' import type { editor } from 'monaco-editor' import { useAppStore } from '@/store/index' import { diffViewStateCache, setWithLRU } from '@/lib/scroll-cache' -import { monacoTypographyOptions } from '@/lib/editor-typography' +import { monacoTypographyOptions } from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' import { useContextualCopySetup } from '../../useContextualCopySetup' import { useDiffCommentDecorator } from '../../../diff-comments/useDiffCommentDecorator' diff --git a/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.word-wrap-lifecycle.test.tsx b/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.word-wrap-lifecycle.test.tsx index 958825d6c1e..a09d10641ae 100644 --- a/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.word-wrap-lifecycle.test.tsx +++ b/src/renderer/src/components/editor/diff/monaco-view/DiffViewer.word-wrap-lifecycle.test.tsx @@ -79,7 +79,7 @@ vi.mock('@/store/slices/diff-comments/diff-comment-owner', () => ({ selectDiffCommentView: () => ({ owner: null, comments: undefined }), diffCommentOwnerKey: () => '' })) -vi.mock('@/lib/monaco-setup', () => ({ +vi.mock('@/lib/editor/monaco/monaco-setup', () => ({ monaco: { Uri: { parse: (path: string) => path }, editor: { getModel: () => null } } })) vi.mock('../../useContextualCopySetup', () => ({ diff --git a/src/renderer/src/components/editor/diff/monaco-view/diff-viewer-props.ts b/src/renderer/src/components/editor/diff/monaco-view/diff-viewer-props.ts index f27914f9b45..80b606f0617 100644 --- a/src/renderer/src/components/editor/diff/monaco-view/diff-viewer-props.ts +++ b/src/renderer/src/components/editor/diff/monaco-view/diff-viewer-props.ts @@ -1,4 +1,4 @@ -import type { WorkspaceResource } from '@/lib/workspace-copy-owner' +import type { WorkspaceResource } from '@/lib/workspace/ownership/workspace-copy-owner' import type { LargeDiffRenderLimit } from '../../../../../../shared/large-diff-render-limit' export type DiffViewerProps = { diff --git a/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx b/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx index 9c1f7af768a..cb755f699c9 100644 --- a/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx +++ b/src/renderer/src/components/editor/diff/sections/DiffSectionBody.tsx @@ -28,7 +28,10 @@ import { } from '@/lib/monaco-languages/plugin-syntax-editor-options' import { useMonacoTheme } from '@/hooks/use-monaco-theme' import { wholeFileDiffTintClass } from '../monaco-view/whole-file-diff-tint' -import { monacoTypographyOptions, type EditorTypography } from '@/lib/editor-typography' +import { + monacoTypographyOptions, + type EditorTypography +} from '@/lib/editor/appearance/editor-typography' const ImageDiffViewer = lazy(() => import('../large-files/ImageDiffViewer')) diff --git a/src/renderer/src/components/editor/diff/sections/DiffSectionItem.tsx b/src/renderer/src/components/editor/diff/sections/DiffSectionItem.tsx index 7bd87e72b5c..4c980ab1d6d 100644 --- a/src/renderer/src/components/editor/diff/sections/DiffSectionItem.tsx +++ b/src/renderer/src/components/editor/diff/sections/DiffSectionItem.tsx @@ -1,4 +1,4 @@ -import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace-copy-owner' +import { NO_RESOURCE_EVIDENCE } from '@/lib/workspace/ownership/workspace-copy-owner' import { useDiffCommentView } from '../../../diff-comments/use-diff-comment-owner' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { DiffOnMount } from '@monaco-editor/react' diff --git a/src/renderer/src/components/editor/diff/sections/diff-section-item-props.ts b/src/renderer/src/components/editor/diff/sections/diff-section-item-props.ts index 10a35b52707..1e3399bc38b 100644 --- a/src/renderer/src/components/editor/diff/sections/diff-section-item-props.ts +++ b/src/renderer/src/components/editor/diff/sections/diff-section-item-props.ts @@ -1,5 +1,5 @@ import type { GitHubImageIntake } from '@/components/github/use-github-image-uploads' -import type { WorkspaceResource } from '@/lib/workspace-copy-owner' +import type { WorkspaceResource } from '@/lib/workspace/ownership/workspace-copy-owner' import type { Dispatch, MutableRefObject, ReactNode, SetStateAction } from 'react' import type { editor as monacoEditor } from 'monaco-editor' import type { DecoratedDiffComment } from '../../../diff-comments/decorated-diff-comment' diff --git a/src/renderer/src/components/editor/diff/sections/diff-section-preview.ts b/src/renderer/src/components/editor/diff/sections/diff-section-preview.ts index 86d8d13192b..c3a1fa695c7 100644 --- a/src/renderer/src/components/editor/diff/sections/diff-section-preview.ts +++ b/src/renderer/src/components/editor/diff/sections/diff-section-preview.ts @@ -1,5 +1,5 @@ import { detectLanguage } from '../../../../../../shared/editor-language/editor-language-detect' -import { canPreviewLanguage } from '@/lib/file-preview' +import { canPreviewLanguage } from '@/lib/browser/documents/file-preview' // Preview reads the working file on disk; exclude deleted files and historical snapshots that may differ from it. export function canOpenDiffSectionPreviewToSide(params: { diff --git a/src/renderer/src/components/editor/diff/sections/diff-section-types.ts b/src/renderer/src/components/editor/diff/sections/diff-section-types.ts index f1839c3fa80..ccdd55f2b5f 100644 --- a/src/renderer/src/components/editor/diff/sections/diff-section-types.ts +++ b/src/renderer/src/components/editor/diff/sections/diff-section-types.ts @@ -1,7 +1,7 @@ import type { GitDiffResult } from '../../../../../../shared/git/diff/git-diff-compare-types' import type { GitStatusEntry } from '../../../../../../shared/git/status/git-status-types' import type { LargeDiffRenderLimit } from '../../../../../../shared/large-diff-render-limit' -import type { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' +import type { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' export type DiffSection = { key: string diff --git a/src/renderer/src/components/editor/diff/sections/use-diff-section-model-lifecycle.ts b/src/renderer/src/components/editor/diff/sections/use-diff-section-model-lifecycle.ts index 7b0bb9f9c3a..35735dda361 100644 --- a/src/renderer/src/components/editor/diff/sections/use-diff-section-model-lifecycle.ts +++ b/src/renderer/src/components/editor/diff/sections/use-diff-section-model-lifecycle.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect, useRef } from 'react' -import { monaco } from '@/lib/monaco-setup' +import { monaco } from '@/lib/editor/monaco/monaco-setup' import { disposeUnattachedMonacoModelPaths } from '../monaco-view/diff-monaco-model-disposal' // Dispose virtualized rows’ models on unmount/collapse so remounts cannot leak detached models. diff --git a/src/renderer/src/components/editor/editor-dropped-file-open.ts b/src/renderer/src/components/editor/editor-dropped-file-open.ts index 89ff59c69d6..3710cedf3ec 100644 --- a/src/renderer/src/components/editor/editor-dropped-file-open.ts +++ b/src/renderer/src/components/editor/editor-dropped-file-open.ts @@ -1,12 +1,12 @@ import type { EditorFileDropDestination } from './editor-file-drop-destination' import { toast } from 'sonner' -import { detectLanguage } from '@/lib/language-detect' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' import { isPathInsideWorktree, toWorktreeRelativePath } from '../../../../shared/terminal/links/terminal-links' import { useAppStore } from '@/store' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { basename, joinPath } from '@/lib/path' import type { WorktreeRuntimeOwnerState } from '@/lib/workspace/ownership/worktree-runtime-owner-state' import { importExternalPathsToRuntime } from '@/runtime/files/imports/runtime-file-import-client' diff --git a/src/renderer/src/components/editor/editor-header-file-rename.test.ts b/src/renderer/src/components/editor/editor-header-file-rename.test.ts index e7e0b6f5dd0..141c8b15a5b 100644 --- a/src/renderer/src/components/editor/editor-header-file-rename.test.ts +++ b/src/renderer/src/components/editor/editor-header-file-rename.test.ts @@ -28,7 +28,9 @@ vi.mock('./autosave/editor-autosave', async (original) => ({ requestEditorSaveQuiesce: renameIO.quiesce, requestEditorFileSave: renameIO.save })) -vi.mock('@/lib/execute-open-editor-path-move', () => ({ executeOpenEditorPathMove: renameIO.move })) +vi.mock('@/lib/editor/file-operations/execute-open-editor-path-move', () => ({ + executeOpenEditorPathMove: renameIO.move +})) vi.mock('@/store/workspaces/selection/use-selected-worktree', () => ({ useWorktreeById: () => ({ path: '/repo', repoId: 'repo-1' }) diff --git a/src/renderer/src/components/editor/editor-panel-file-actions.ts b/src/renderer/src/components/editor/editor-panel-file-actions.ts index 4245c452be6..6f81ff78092 100644 --- a/src/renderer/src/components/editor/editor-panel-file-actions.ts +++ b/src/renderer/src/components/editor/editor-panel-file-actions.ts @@ -1,6 +1,6 @@ import { useAppStore } from '@/store' import { editorViewPlacement } from '@/store/slices/editor/tabs/editor-view-placement' -import { detectLanguage } from '@/lib/language-detect' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' import type { OpenFile } from '@/store/slices/editor/types/open-file' import type { getEditorPanelRenderModel } from './editor-panel-render-model' diff --git a/src/renderer/src/components/editor/editor-panel-host-content-recovery.spec.ts b/src/renderer/src/components/editor/editor-panel-host-content-recovery.spec.ts index 20267797e77..be700c40671 100644 --- a/src/renderer/src/components/editor/editor-panel-host-content-recovery.spec.ts +++ b/src/renderer/src/components/editor/editor-panel-host-content-recovery.spec.ts @@ -4,7 +4,7 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' import { createTestStore } from '@/store/testing/app-store-test-fixture' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' +import { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' import { createCompatibleRuntimeStatusResponse } from '@/runtime/rpc/testing/runtime-compatibility-test-fixture' import { editorSaveWriterView } from './save/queue/editor-save-writer-view' import { ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT } from './autosave/editor-autosave' diff --git a/src/renderer/src/components/editor/editor-panel-render-model.ts b/src/renderer/src/components/editor/editor-panel-render-model.ts index 218944c98b6..c424da1f119 100644 --- a/src/renderer/src/components/editor/editor-panel-render-model.ts +++ b/src/renderer/src/components/editor/editor-panel-render-model.ts @@ -1,5 +1,5 @@ -import { detectLanguage } from '@/lib/language-detect' -import { canPreviewLanguage } from '@/lib/file-preview' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' +import { canPreviewLanguage } from '@/lib/browser/documents/file-preview' import type { useAppStore } from '@/store' import type { MarkdownViewMode, OpenFile } from '@/store/slices/editor/types/open-file' import type { MarkdownDefaultViewMode } from '../../../../shared/markdown-default-view-mode' diff --git a/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx b/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx index d0a7c7b8f02..2b8271ce223 100644 --- a/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx +++ b/src/renderer/src/components/editor/external-changes/ExternalFileChangeBanner.tsx @@ -2,7 +2,7 @@ import React, { useState } from 'react' import { TriangleAlert } from 'lucide-react' import { toast } from 'sonner' import { Button } from '@/components/ui/button' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { editorTabFileAccess } from '@/lib/local-file-access' import { readRuntimeFileContent } from '@/runtime/files/reads/runtime-file-read-client' import { getRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' diff --git a/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx b/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx index f9984c91369..3e7babeb41a 100644 --- a/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx +++ b/src/renderer/src/components/editor/external-changes/ExternalFileChangeCompareDialog.tsx @@ -10,7 +10,7 @@ import { DialogTitle } from '@/components/ui/dialog' import { lazyWithRetry as lazy } from '@/lib/lazy-with-retry' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { editorTabFileAccess } from '@/lib/local-file-access' import { detectLanguage } from '../../../../../shared/editor-language/editor-language-detect' import { readRuntimeFileContent } from '@/runtime/files/reads/runtime-file-read-client' diff --git a/src/renderer/src/components/editor/external-changes/editor-external-change-tab-reset.ts b/src/renderer/src/components/editor/external-changes/editor-external-change-tab-reset.ts index fd98c909ac8..c76e4909b53 100644 --- a/src/renderer/src/components/editor/external-changes/editor-external-change-tab-reset.ts +++ b/src/renderer/src/components/editor/external-changes/editor-external-change-tab-reset.ts @@ -1,4 +1,4 @@ -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { getOpenFilesForExternalFileChange, type EditorPathMutationTarget diff --git a/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts b/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts index 32c7bbcccc5..88770dbe900 100644 --- a/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts +++ b/src/renderer/src/components/editor/external-changes/editor-external-change-telemetry.ts @@ -1,6 +1,6 @@ // Share path-free conflict enums across marking and banner actions so false-banner rates remain comparable by transport. import { track } from '@/lib/telemetry' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import type { OpenFile } from '@/store/slices/editor/types/open-file' type ConflictSurface = 'edit' | 'unstaged-diff' diff --git a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts index 62b04a4a8b5..44e1125884f 100644 --- a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts +++ b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.recheck.test.ts @@ -11,7 +11,9 @@ vi.mock('@/runtime/files/reads/runtime-file-read-client', () => ({ vi.mock('@/runtime/files/metadata/runtime-path-existence-batch', () => ({ runtimePathsExist: mocks.runtimePathsExist })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) vi.mock('@/lib/file-owner-runtime-target', () => { const owner = { kind: 'environment', environmentId: 'env-1' } return { diff --git a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts index 26a37718b04..ad10b6b085e 100644 --- a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts +++ b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.test.ts @@ -17,7 +17,7 @@ vi.mock('@/runtime/files/reads/runtime-file-read-client', () => ({ readRuntimeFileContent: mocks.readRuntimeFileContent })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: mocks.getConnectionIdForFile })) diff --git a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts index 773167b2108..4e11728a802 100644 --- a/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts +++ b/src/renderer/src/components/editor/external-changes/editor-restored-tab-conflict-scan.ts @@ -2,7 +2,7 @@ import type { StoreApi } from 'zustand' import type { AppState } from '@/store/types' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { editorTabFileAccess } from '@/lib/local-file-access' import { readRuntimeFileContent } from '@/runtime/files/reads/runtime-file-read-client' import { diff --git a/src/renderer/src/components/editor/external-changes/useEditorPanelExternalContentEvents.ts b/src/renderer/src/components/editor/external-changes/useEditorPanelExternalContentEvents.ts index c45bac703db..02870177a15 100644 --- a/src/renderer/src/components/editor/external-changes/useEditorPanelExternalContentEvents.ts +++ b/src/renderer/src/components/editor/external-changes/useEditorPanelExternalContentEvents.ts @@ -1,6 +1,6 @@ import { useEffect, useRef, type Dispatch, type MutableRefObject, type SetStateAction } from 'react' import { useAppStore } from '@/store/index' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { ORCA_EDITOR_EXTERNAL_FILE_CHANGE_EVENT, diff --git a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx index f4b13750029..ba96587e12e 100644 --- a/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx +++ b/src/renderer/src/components/editor/git-graph/git-graph-rendering.test.tsx @@ -4,7 +4,7 @@ import { useAppStore } from '@/store' import { gitGraphHistoryForTab, disposeGitGraphHistory } from './git-graph-tab-controllers' import { attachClosedEditorTabCleanup } from '../model-lifetime/retention/closed-editor-tab-controller' import { gitGraphScope } from '@/lib/git-graph-tab' -import { captureWorktreeOperationGenerationSnapshot } from '@/lib/worktree-operation-generation' +import { captureWorktreeOperationGenerationSnapshot } from '@/lib/workspace/ownership/worktree-operation-generation' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { act } from 'react' import { createRoot } from 'react-dom/client' diff --git a/src/renderer/src/components/editor/markdown-export-extract.ts b/src/renderer/src/components/editor/markdown-export-extract.ts index 969d577847e..470a6cfb28e 100644 --- a/src/renderer/src/components/editor/markdown-export-extract.ts +++ b/src/renderer/src/components/editor/markdown-export-extract.ts @@ -1,5 +1,5 @@ import { useAppStore } from '@/store' -import { detectLanguage } from '@/lib/language-detect' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' import { buildMarkdownExportHtml } from './markdown-export-html' export type MarkdownExportPayload = { diff --git a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts index 5f62566da08..9d02603dbe1 100644 --- a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts +++ b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-link-actions.ts @@ -1,6 +1,6 @@ import { afterPendingEntityTabs } from '@/runtime/workspace-layout/intents/layout-owner-pending-tabs' import { toast } from 'sonner' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { detectLanguage } from '../../../../../../shared/editor-language/editor-language-detect' import { isLocalPathOpenBlocked, showLocalPathOpenBlockedToast } from '@/lib/local-path-open-guard' import { getLinkSourceLocalOpenOwner } from '@/lib/link-source-local-open-owner' diff --git a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-source-routing.ts b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-source-routing.ts index 4d1743fa1e5..c64a01d60b5 100644 --- a/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-source-routing.ts +++ b/src/renderer/src/components/editor/markdown-preview/links/markdown-preview-source-routing.ts @@ -1,4 +1,4 @@ -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' import { dirname } from '@/lib/path' import { findFirstIndexedWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner-index' diff --git a/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts b/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts index 42ec4540d41..f7e3685d82d 100644 --- a/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts +++ b/src/renderer/src/components/editor/markdown-preview/render-tree/markdown-preview-types.ts @@ -1,5 +1,5 @@ import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' -import type { EditorFileOperationProvenance } from '@/lib/editor-file-operation-provenance' +import type { EditorFileOperationProvenance } from '@/lib/editor/file-operations/editor-file-operation-provenance' export type MarkdownPreviewProps = { content: string diff --git a/src/renderer/src/components/editor/markdown-preview/review/MarkdownPreviewAnnotationComposer.tsx b/src/renderer/src/components/editor/markdown-preview/review/MarkdownPreviewAnnotationComposer.tsx index c232e8a39a7..18b945c93a9 100644 --- a/src/renderer/src/components/editor/markdown-preview/review/MarkdownPreviewAnnotationComposer.tsx +++ b/src/renderer/src/components/editor/markdown-preview/review/MarkdownPreviewAnnotationComposer.tsx @@ -5,7 +5,10 @@ import { CornerDownLeft } from 'lucide-react' import { Button } from '@/components/ui/button' import { useMountedRef } from '@/hooks/useMountedRef' import { useTranslate } from '@/i18n/use-translate' -import { formatMarkdownReviewNotes, type MarkdownReviewNote } from '@/lib/markdown-review-notes' +import { + formatMarkdownReviewNotes, + type MarkdownReviewNote +} from '@/lib/editor/markdown/review-notes/markdown-review-notes' import { installOpenDraftAddReviewNoteGuard } from '../../editor-shortcuts' import { NotesSendMenu } from '../../review-note-delivery/NotesSendMenu' diff --git a/src/renderer/src/components/editor/markdown-preview/review/markdown-preview-block-model.ts b/src/renderer/src/components/editor/markdown-preview/review/markdown-preview-block-model.ts index 83752f739d3..092e30f8ce3 100644 --- a/src/renderer/src/components/editor/markdown-preview/review/markdown-preview-block-model.ts +++ b/src/renderer/src/components/editor/markdown-preview/review/markdown-preview-block-model.ts @@ -1,5 +1,5 @@ import React from 'react' -import { formatMarkdownReviewCardQuote } from '@/lib/markdown-review-notes' +import { formatMarkdownReviewCardQuote } from '@/lib/editor/markdown/review-notes/markdown-review-notes' import type { MarkdownPreviewBlockRange, MarkdownPreviewPositionNode diff --git a/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-annotation-renderers.tsx b/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-annotation-renderers.tsx index 22984eaa20d..e8891b98e6f 100644 --- a/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-annotation-renderers.tsx +++ b/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-annotation-renderers.tsx @@ -7,7 +7,7 @@ import { formatMarkdownReviewCardQuote, getMarkdownReviewCardQuote, type MarkdownReviewNote -} from '@/lib/markdown-review-notes' +} from '@/lib/editor/markdown/review-notes/markdown-review-notes' import { DiffCommentCard } from '../../../diff-comments/DiffCommentCard' import { MarkdownPreviewAnnotationComposer, diff --git a/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-review-actions.ts b/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-review-actions.ts index 2bc2d74acee..adadc181228 100644 --- a/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-review-actions.ts +++ b/src/renderer/src/components/editor/markdown-preview/review/use-markdown-preview-review-actions.ts @@ -1,6 +1,6 @@ import { useCallback } from 'react' -import { copyMarkdownReviewNotesForAgent } from '@/lib/markdown-review-note-copy' -import type { MarkdownReviewNote } from '@/lib/markdown-review-notes' +import { copyMarkdownReviewNotesForAgent } from '@/lib/editor/markdown/review-notes/markdown-review-note-copy' +import type { MarkdownReviewNote } from '@/lib/editor/markdown/review-notes/markdown-review-notes' import type { DiffComment } from '../../../../../../shared/diff-comment-types' import type { MarkdownPreviewBlockRange } from '../render-tree/markdown-preview-types' import { requestMarkdownPreviewEditorRevealFrame } from '../links/markdown-preview-editor-reveal' diff --git a/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.link-routing.interaction.test.tsx b/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.link-routing.interaction.test.tsx index 0d4c84683ee..6dbe378bcac 100644 --- a/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.link-routing.interaction.test.tsx +++ b/src/renderer/src/components/editor/markdown-preview/surface/MarkdownPreview.link-routing.interaction.test.tsx @@ -82,10 +82,10 @@ vi.mock('../../../../runtime/rpc/targets/use-worktree-runtime-target', () => ({ vi.mock('@/runtime/files/metadata/runtime-file-metadata-client', () => ({ statRuntimePath: statRuntimePathMock })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: (worktreeId: string) => targetConnectionOwners.get(worktreeId) })) -vi.mock('@/lib/connection-owner-resolution', () => ({ +vi.mock('@/lib/workspace/ownership/connection-owner-resolution', () => ({ createConnectionIdForFileSelector: () => () => connectionOwner.value })) vi.mock('@/i18n/i18n', () => ({ diff --git a/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts b/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts index 0dfabf4cd0a..cac19ed04a7 100644 --- a/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts +++ b/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-foundation.ts @@ -5,7 +5,7 @@ import { formatMarkdownReviewNotes, sortMarkdownReviewNotes, type MarkdownReviewNote -} from '@/lib/markdown-review-notes' +} from '@/lib/editor/markdown/review-notes/markdown-review-notes' import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { createMarkdownDocumentIndex } from '../../markdown/documents/markdown-doc-links' import { exceedsMarkdownRichModeSizeLimit } from '../../markdown/render-mode/markdown-rich-size-limit' diff --git a/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-source-foundation.ts b/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-source-foundation.ts index 7eefb31d9e4..7da3e2aa8b2 100644 --- a/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-source-foundation.ts +++ b/src/renderer/src/components/editor/markdown-preview/surface/use-markdown-preview-source-foundation.ts @@ -1,7 +1,7 @@ import { useDiffCommentView } from '../../../diff-comments/use-diff-comment-owner' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { createConnectionIdForFileSelector } from '@/lib/connection-owner-resolution' -import { computeEditorFontSize } from '@/lib/editor-font-zoom' +import { createConnectionIdForFileSelector } from '@/lib/workspace/ownership/connection-owner-resolution' +import { computeEditorFontSize } from '@/lib/editor/appearance/editor-font-zoom' import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' import { isMarkdownComment } from '@/lib/diff-comment-compat' import { useFileOwnerRuntimeTarget } from '@/runtime/rpc/targets/use-worktree-runtime-target' diff --git a/src/renderer/src/components/editor/markdown-source-tools/monaco/use-monaco-markdown-annotations.ts b/src/renderer/src/components/editor/markdown-source-tools/monaco/use-monaco-markdown-annotations.ts index a2be1f49da8..1aaf08c391b 100644 --- a/src/renderer/src/components/editor/markdown-source-tools/monaco/use-monaco-markdown-annotations.ts +++ b/src/renderer/src/components/editor/markdown-source-tools/monaco/use-monaco-markdown-annotations.ts @@ -14,12 +14,15 @@ import { } from 'react' import type { editor } from 'monaco-editor' import type { DiffComment } from '../../../../../../shared/diff-comment-types' -import type { WorkspaceResource } from '@/lib/workspace-copy-owner' +import type { WorkspaceResource } from '@/lib/workspace/ownership/workspace-copy-owner' import { toast } from 'sonner' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store/index' import { isMarkdownComment } from '@/lib/diff-comment-compat' -import { formatMarkdownReviewNotes, type MarkdownReviewNote } from '@/lib/markdown-review-notes' +import { + formatMarkdownReviewNotes, + type MarkdownReviewNote +} from '@/lib/editor/markdown/review-notes/markdown-review-notes' import { useDiffCommentDecorator } from '../../../diff-comments/useDiffCommentDecorator' import { getDiffCommentPopoverLeft, diff --git a/src/renderer/src/components/editor/markdown/documents/MarkdownTemplatePicker.tsx b/src/renderer/src/components/editor/markdown/documents/MarkdownTemplatePicker.tsx index 045de69af1f..311a8722cd3 100644 --- a/src/renderer/src/components/editor/markdown/documents/MarkdownTemplatePicker.tsx +++ b/src/renderer/src/components/editor/markdown/documents/MarkdownTemplatePicker.tsx @@ -11,8 +11,8 @@ import { import type { MarkdownTemplatePickerRequest, MarkdownTemplateSelection -} from '@/lib/markdown-template-picker-request' -import { subscribeMarkdownTemplatePicker } from '@/lib/markdown-template-picker-request' +} from '@/lib/editor/markdown/documents/markdown-template-picker-request' +import { subscribeMarkdownTemplatePicker } from '@/lib/editor/markdown/documents/markdown-template-picker-request' import { useTranslate } from '@/i18n/use-translate' export function MarkdownTemplatePicker(): JSX.Element { diff --git a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.navigation.test.ts b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.navigation.test.ts index 8709d9db8cf..e49ef399bd6 100644 --- a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.navigation.test.ts +++ b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.navigation.test.ts @@ -3,7 +3,7 @@ import { act, createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { MarkdownViewMode, OpenFile } from '@/store/slices/editor/types/open-file' -import type * as ConnectionOwnerResolution from '@/lib/connection-owner-resolution' +import type * as ConnectionOwnerResolution from '@/lib/workspace/ownership/connection-owner-resolution' import { useMarkdownDocuments } from './useMarkdownDocuments' import { useAppStore } from '@/store/index' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' @@ -26,8 +26,10 @@ const state = { openFile: vi.fn(), openMarkdownPreview: vi.fn() } -vi.mock('@/lib/connection-context', () => ({ getConnectionIdFromState: () => runtimeConnectionId })) -vi.mock('@/lib/connection-owner-resolution', async (importOriginal) => { +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdFromState: () => runtimeConnectionId +})) +vi.mock('@/lib/workspace/ownership/connection-owner-resolution', async (importOriginal) => { const actual = await importOriginal() return { ...actual, getConnectionIdFromState: () => runtimeConnectionId } }) diff --git a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts index 366f918a926..04a0f9151ac 100644 --- a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts +++ b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.ts @@ -3,10 +3,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import { useAppStore } from '@/store/index' import { translate } from '@/i18n/i18n' -import '@/lib/connection-context' -import { getConnectionIdFromState } from '@/lib/connection-owner-resolution' +import '@/lib/workspace/ownership/connection-context' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { statRuntimePath } from '@/runtime/files/metadata/runtime-file-metadata-client' -import { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' +import { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' import { getRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' import type { MarkdownViewMode, OpenFile } from '@/store/slices/editor/types/open-file' import { diff --git a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts index f3eab1176d8..49184312c61 100644 --- a/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts +++ b/src/renderer/src/components/editor/markdown/documents/useMarkdownDocuments.watch.test.ts @@ -6,7 +6,7 @@ import type { FsChangeEvent } from '../../../../../../shared/file-watch/filesyst import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { ORCA_WORKTREE_FILE_CHANGE_EVENT } from '@/hooks/worktree-file-change-event' -import type * as ConnectionOwnerResolution from '@/lib/connection-owner-resolution' +import type * as ConnectionOwnerResolution from '@/lib/workspace/ownership/connection-owner-resolution' import { useMarkdownDocuments } from './useMarkdownDocuments' const runtime = vi.hoisted(() => ({ list: vi.fn(), stat: vi.fn() })) @@ -21,8 +21,10 @@ vi.mock('@/store/index', () => ({ getState: () => state }) })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdFromState: () => null })) -vi.mock('@/lib/connection-owner-resolution', async (importOriginal) => { +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdFromState: () => null +})) +vi.mock('@/lib/workspace/ownership/connection-owner-resolution', async (importOriginal) => { const actual = await importOriginal() return { ...actual, getConnectionIdFromState: () => null } }) diff --git a/src/renderer/src/components/editor/migrate-restored-editor-file-owner.ts b/src/renderer/src/components/editor/migrate-restored-editor-file-owner.ts index 7a63f0c44c1..d984b9a0487 100644 --- a/src/renderer/src/components/editor/migrate-restored-editor-file-owner.ts +++ b/src/renderer/src/components/editor/migrate-restored-editor-file-owner.ts @@ -4,11 +4,12 @@ import { findWorkspaceFileRoute, type RuntimeWorkspaceFileRoute } from '@/lib/runtime-workspace-file-route' +import '@/lib/editor/file-operations/editor-file-operation-owner' import { assertEditorFileOperationCurrent, - captureEditorFileOperationProvenance, - type EditorFileOperationProvenance -} from '@/lib/editor-file-operation-owner' + captureEditorFileOperationProvenance +} from '@/lib/editor/file-operations/editor-file-operation-provenance' +import type { EditorFileOperationProvenance } from '@/lib/editor/file-operations/editor-file-operation-provenance' import { requestEditorSaveQuiesce } from './autosave/editor-autosave' import type { RestoredEditorOwnerResult } from '@/store/slices/editor/types/restored-editor-owner' import { contentRekeyOutcome } from '@/runtime/workspace-layout/intents/layout-owner-content-rekeys' diff --git a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.test.ts b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.test.ts index 7f9faf24dd3..56c7866a8e8 100644 --- a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import type { StoreApi } from 'zustand' import type { AppState } from '@/store/types' -import { createEditorModelRegistry } from '@/lib/editor-model-registry' +import { createEditorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' import { applyEditorBufferText } from './editor-buffer-adapter' diff --git a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.ts b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.ts index f84af1f56e5..37f538d8910 100644 --- a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.ts +++ b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-adapter.ts @@ -1,6 +1,9 @@ import type { AppState } from '@/store/types' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { editorModelRegistry, type EditorModelRegistryBridge } from '@/lib/editor-model-registry' +import { + editorModelRegistry, + type EditorModelRegistryBridge +} from '@/lib/editor/monaco/editor-model-registry' import { editorBufferSiblingViewIds } from '@/store/slices/editor/buffers/editor-buffer-views' import { editorModelSiblingTabs, diff --git a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts index d1cab149838..045d15caae5 100644 --- a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-buffer-sharing.test.ts @@ -20,7 +20,9 @@ import { registerPendingEditorFlush } from '../../save/flush/editor-pending-flus const storeRef = vi.hoisted((): { current: StoreApi | null } => ({ current: null })) vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { error: vi.fn() }) })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) vi.mock('@/store/index', () => { const getState = () => storeRef.current!.getState() return { diff --git a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts index 43d6c1e6508..bea35aa3783 100644 --- a/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/buffer-text/editor-shared-record-clean-view.test.ts @@ -6,7 +6,7 @@ import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import type { editor } from 'monaco-editor' import type { StoreApi } from 'zustand' import type { AppState } from '@/store/types' -import { editorModelRegistry } from '@/lib/editor-model-registry' +import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' import { editorTabModelUri } from '../../save/queue/editor-save-disk-precondition' diff --git a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-host-isolation.test.ts b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-host-isolation.test.ts index 2c8f9432179..1626f2d5ffc 100644 --- a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-host-isolation.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-host-isolation.test.ts @@ -4,7 +4,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import '@/store/slices/editor/create-editor-slice' import { buildOwnedEditorFileId } from '@/store/slices/editor/file-ids/editor-file-ids' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import type { WorktreeOperationRoute } from '@/lib/worktree-operation-route' +import type { WorktreeOperationRoute } from '@/lib/workspace/ownership/worktree-operation-route' import { attachModelLifetimeView, createModelLifetimeFixture, diff --git a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-owner.ts b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-owner.ts index 469b3f157bf..d38bc403f1e 100644 --- a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-owner.ts +++ b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-owner.ts @@ -1,7 +1,7 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' -import type { WorktreeOperationRouteState } from '@/lib/worktree-operation-route' -import '@/lib/editor-file-operation-owner' -import { resolveEditorOwnerRoute } from '@/lib/editor-file-operation-provenance' +import type { WorktreeOperationRouteState } from '@/lib/workspace/ownership/worktree-operation-route' +import '@/lib/editor/file-operations/editor-file-operation-owner' +import { resolveEditorOwnerRoute } from '@/lib/editor/file-operations/editor-file-operation-provenance' import { isDetachedEditorBufferId, type EditorBufferViewIndex diff --git a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-rekey-carry.ts b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-rekey-carry.ts index 49a68ee5d64..93464a9baf8 100644 --- a/src/renderer/src/components/editor/model-lifetime/identity/editor-model-rekey-carry.ts +++ b/src/renderer/src/components/editor/model-lifetime/identity/editor-model-rekey-carry.ts @@ -1,6 +1,6 @@ import { useLayoutEffect, useRef } from 'react' import { useAppStore } from '@/store/index' -import { editorModelRegistry } from '@/lib/editor-model-registry' +import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' type ModelRegistry = NonNullable> diff --git a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-shell.test.tsx b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-shell.test.tsx index c079e42fe05..e47810f2fb8 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-shell.test.tsx +++ b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-model-shell.test.tsx @@ -7,7 +7,7 @@ import { afterEach, expect, it, vi } from 'vitest' import type { AppState } from '@/store/types' import type { TerminalController } from '../../../use-terminal-controller' import { TerminalLegacyEditorSurface } from '../../../TerminalLegacyEditorSurface' -import { editorModelRegistry } from '@/lib/editor-model-registry' +import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { useClosedEditorTabCleanup } from './useClosedEditorTabCleanup' import { createModelLifetimeFixture, diff --git a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-controller.ts b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-controller.ts index 42d29da24d9..02123b8d0d3 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-controller.ts +++ b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-tab-controller.ts @@ -2,7 +2,7 @@ import { disposeGitGraphHistory } from '../../git-graph/git-graph-tab-controller import type { StoreApi } from 'zustand' import type { editor } from 'monaco-editor' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { editorModelRegistry } from '@/lib/editor-model-registry' +import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { disposeClosedEditorModels, disposeClosedCheckDetailsReadingCache, diff --git a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts index 4e316bcbe21..22c96ca76ab 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts +++ b/src/renderer/src/components/editor/model-lifetime/retention/closed-editor-view-state-retention.test.ts @@ -3,7 +3,7 @@ import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import { createStore } from 'zustand/vanilla' import { afterEach, expect, it } from 'vitest' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { createEditorModelRegistry } from '@/lib/editor-model-registry' +import { createEditorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { attachClosedEditorTabCleanup } from '@/components/editor/model-lifetime/retention/closed-editor-tab-controller' import { toEditorModelUri } from '@/components/editor/model-lifetime/identity/editor-model-uri' import { scrollTopCache, editorSelectionCache, pdfViewPositionCache } from '@/lib/scroll-cache' diff --git a/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts b/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts index 99d78a916eb..c1564d6759e 100644 --- a/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts +++ b/src/renderer/src/components/editor/model-lifetime/retention/editor-model-lifetime-fixture.ts @@ -1,6 +1,6 @@ import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import { vi } from 'vitest' -import { createEditorModelRegistry } from '@/lib/editor-model-registry' +import { createEditorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { createEditorTabsStore } from '@/store/slices/editor/editor-slice-test-harness' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { TEST_REPO } from '@/store/repos/repo.test-fixture' diff --git a/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx b/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx index f4f59a83000..461c7a317ac 100644 --- a/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx +++ b/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.external-sync.test.tsx @@ -38,7 +38,7 @@ vi.mock('@/store/index', () => { vi.mock('@/hooks/use-document-dark-theme', () => ({ useDocumentDarkTheme: () => true })) vi.mock('../../MonacoCodeExcerpt', () => ({ useMonacoColorizedLines: () => [] })) vi.mock('../../editor-shortcuts', () => ({ installMonacoEditorFindShortcut: () => () => {} })) -vi.mock('@/lib/monaco-setup', async () => { +vi.mock('@/lib/editor/monaco/monaco-setup', async () => { const actual = await import('monaco-editor/esm/vs/editor/editor.api.js') for (const id of ['python', 'javascript', 'markdown']) { actual.languages.register({ id }) diff --git a/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx b/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx index 507544c5dc6..f9aef8b6d7e 100644 --- a/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx +++ b/src/renderer/src/components/editor/notebook/cells/IpynbCellEditor.tsx @@ -1,12 +1,12 @@ import { useLayoutEffect, useMemo, useRef, useState } from 'react' import type { Components } from 'react-markdown' import type { editor } from 'monaco-editor' -import { monaco } from '@/lib/monaco-setup' +import { monaco } from '@/lib/editor/monaco/monaco-setup' import { EDITOR_TYPOGRAPHY_SURFACE_CLASS, editorTypographyTextStyle, monacoTypographyOptions -} from '@/lib/editor-typography' +} from '@/lib/editor/appearance/editor-typography' import { useEditorTypography } from '@/hooks/use-editor-typography' import { cn } from '@/lib/utils' import { installMonacoEditorFindShortcut } from '../../editor-shortcuts' diff --git a/src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx b/src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx index 7b68fe96de1..8d5dea34034 100644 --- a/src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx +++ b/src/renderer/src/components/editor/notebook/document/IpynbRendering.test.tsx @@ -10,7 +10,7 @@ vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) vi.mock('@/hooks/use-document-dark-theme', () => ({ useDocumentDarkTheme: () => true })) -vi.mock('@/lib/monaco-setup', () => ({ monaco: {} })) +vi.mock('@/lib/editor/monaco/monaco-setup', () => ({ monaco: {} })) vi.mock('../../MonacoCodeExcerpt', () => ({ useMonacoColorizedLines: () => [] })) diff --git a/src/renderer/src/components/editor/notebook/document/IpynbViewer.tsx b/src/renderer/src/components/editor/notebook/document/IpynbViewer.tsx index c2ff47106fc..5f538ade877 100644 --- a/src/renderer/src/components/editor/notebook/document/IpynbViewer.tsx +++ b/src/renderer/src/components/editor/notebook/document/IpynbViewer.tsx @@ -1,7 +1,7 @@ import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event' import { useCallback, useMemo, useState } from 'react' import { AlertCircle, Save } from 'lucide-react' -import { computeEditorFontSize } from '@/lib/editor-font-zoom' +import { computeEditorFontSize } from '@/lib/editor/appearance/editor-font-zoom' import { useAppStore } from '@/store/index' import { Button } from '@/components/ui/button' import { diff --git a/src/renderer/src/components/editor/notebook/kernel/ipynb-execution-host.ts b/src/renderer/src/components/editor/notebook/kernel/ipynb-execution-host.ts index 12cd4c06258..afe6e7699f2 100644 --- a/src/renderer/src/components/editor/notebook/kernel/ipynb-execution-host.ts +++ b/src/renderer/src/components/editor/notebook/kernel/ipynb-execution-host.ts @@ -1,6 +1,6 @@ import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host' -import { resolveOwner } from '@/lib/resolve-owner' -import type { WorktreeOperationRouteState } from '@/lib/worktree-operation-route' +import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' +import type { WorktreeOperationRouteState } from '@/lib/workspace/ownership/worktree-operation-route' /** Where a notebook's kernel would run: kernels exist only on this computer. */ export type NotebookExecutionHost = 'local' | 'remote' | 'unresolved' diff --git a/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.test.tsx b/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.test.tsx index 3fba1ebf4cc..5c49f2123df 100644 --- a/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.test.tsx +++ b/src/renderer/src/components/editor/notebook/kernel/useIpynbCellExecution.test.tsx @@ -6,7 +6,7 @@ import type { KernelFrameEvent } from '../../../../../../shared/notebook-kernel- import type { WorktreeOperationOwnerRecord, WorktreeOperationRouteState -} from '@/lib/worktree-operation-route' +} from '@/lib/workspace/ownership/worktree-operation-route' const { storeState, notebookApi, toastError, frameListener } = vi.hoisted(() => { const frameListener = { current: (_event: KernelFrameEvent): void => {} } diff --git a/src/renderer/src/components/editor/open-editor-html-preview.ts b/src/renderer/src/components/editor/open-editor-html-preview.ts index 961faee6361..320351d3638 100644 --- a/src/renderer/src/components/editor/open-editor-html-preview.ts +++ b/src/renderer/src/components/editor/open-editor-html-preview.ts @@ -4,8 +4,8 @@ import { editorViewPlacement, editorViewTab } from '@/store/slices/editor/tabs/editor-view-placement' -import { openFileInBrowserTab } from '@/lib/file-preview' -import { resolveFileBrowserLinkExecutionHostId } from '@/lib/file-preview-link-open' +import { openFileInBrowserTab } from '@/lib/browser/documents/file-preview' +import { resolveFileBrowserLinkExecutionHostId } from '@/lib/browser/documents/file-preview-link-open' import { captureBrowserLinkReveal } from '@/lib/browser/navigation/browser-link-reveal' import { createBrowserLinkHostMatcher } from '@/lib/browser/navigation/browser-link-owner' import { beginLinkOpenRequest, subscribeLinkOpenRequests } from '@/lib/link-open-request' diff --git a/src/renderer/src/components/editor/restored-editor-same-workspace-reown.test.tsx b/src/renderer/src/components/editor/restored-editor-same-workspace-reown.test.tsx index c6a137e699f..e1fdca5a809 100644 --- a/src/renderer/src/components/editor/restored-editor-same-workspace-reown.test.tsx +++ b/src/renderer/src/components/editor/restored-editor-same-workspace-reown.test.tsx @@ -7,11 +7,8 @@ import type * as RuntimeFileReadClient from '@/runtime/files/reads/runtime-file- import { useAppStore } from '@/store' import type { AppState } from '@/store/types' import { makeWorktree } from '../../store/slices/worktrees/worktree.test-fixture' -import type { FileContent } from './editor-panel-content-types' -import { - useEditorPanelFileContentLoader, - type EditorPanelFileContentLoader -} from './useEditorPanelFileContentLoader' +import type { FileContent, EditorPanelFileContentLoader } from './editor-panel-content-types' +import { useEditorPanelFileContentLoader } from './useEditorPanelFileContentLoader' import { layoutApplyTestTransport } from '@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture' import { drawTabsFromMain, diff --git a/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.test.tsx b/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.test.tsx index ac92b0f7eaa..f79281c1ffe 100644 --- a/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.test.tsx +++ b/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.test.tsx @@ -6,11 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as RuntimeFileReadClient from '@/runtime/files/reads/runtime-file-read-client' import { useAppStore } from '@/store' import { makeWorktree } from '../../store/slices/worktrees/worktree.test-fixture' -import type { FileContent } from './editor-panel-content-types' -import { - useEditorPanelFileContentLoader, - type EditorPanelFileContentLoader -} from './useEditorPanelFileContentLoader' +import type { FileContent, EditorPanelFileContentLoader } from './editor-panel-content-types' +import { useEditorPanelFileContentLoader } from './useEditorPanelFileContentLoader' const mocks = vi.hoisted(() => ({ readRuntimeFileContent: vi.fn() })) vi.mock('@/runtime/files/reads/runtime-file-read-client', async (importOriginal) => ({ diff --git a/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.ts b/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.ts index bee2a4f29ac..ba869f52977 100644 --- a/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.ts +++ b/src/renderer/src/components/editor/restored-editor-workspace-runtime-owner.ts @@ -1,7 +1,7 @@ import type { OpenFile } from '@/store/slices/editor/types/open-file' import type { AppState } from '@/store/types' -import { hasOpenFileExecutionHostEvidence } from '@/lib/unified-tab-host-ownership' -import { runtimeEnvironmentIdUnlessTwin } from '@/lib/resolve-owner' +import { hasOpenFileExecutionHostEvidence } from '@/lib/workspace/ownership/unified-tab-host-ownership' +import { runtimeEnvironmentIdUnlessTwin } from '@/lib/workspace/ownership/resolve-owner' import { findRuntimeWorkspaceFileRoute, type RuntimeWorkspaceFileRoute diff --git a/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx b/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx index 027468d1b0a..6612ba225c7 100644 --- a/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx +++ b/src/renderer/src/components/editor/review-note-delivery/ReviewNotesSendMenuContent.tsx @@ -22,24 +22,24 @@ import { } from '@/runtime/native-chat/naming/structured-chat-name-observation' import { QuickLaunchAgentMenuItems } from '@/components/tab-bar/QuickLaunchButton' import { AgentStateDot, agentStateLabel } from '@/components/AgentStateDot' -import { AgentTypeIcon } from '@/lib/agent-type-icon' +import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator } from '@/components/ui/dropdown-menu' import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' -import '@/lib/active-agent-note-send' +import '@/lib/agent-session/messaging/terminal/active-agent-note-send' import { activeAgentNotesSendFailureMessage, type ActiveAgentNotesSendResult -} from '@/lib/active-agent-note-send-result' -import { sendMessageToAgent } from '@/lib/agent-message-send' +} from '@/lib/agent-session/messaging/terminal/active-agent-note-send-result' +import { sendMessageToAgent } from '@/lib/agent-session/messaging/agent-message-send' import { deriveNotesSendAgentTargets, type NotesSendAgentTarget -} from '@/lib/notes-send-agent-targets' -import { agentKindForAgentType } from '@/lib/agent-status' +} from '@/lib/agent-session/messaging/notes-send-agent-targets' +import { agentKindForAgentType } from '@/lib/agent-status/aggregation/worktree-agent-status' import { formatAgentTypeLabel } from '../../../../../shared/agent-status/presentation/agent-type-label' import { track } from '@/lib/telemetry' import { useNow } from '@/hooks/use-now' @@ -49,10 +49,10 @@ import { useWorktreeAgentRows } from '@/components/sidebar/workspace-card/activi import { useAgentRowConversationName } from '@/components/dashboard/use-agent-row-conversation-name' import { getAgentRowPrimaryText } from '../../../../../shared/agent-status/presentation/agent-row-primary-text' import type { LaunchSource } from '../../../../../shared/telemetry-property-schemas' -import { agentRowDisplayDotState } from '@/lib/agent-row-dot-state' +import { agentRowDisplayDotState } from '@/lib/agent-status/presentation/agent-row-dot-state' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' -import { agentSendDisabledReasonLabel } from '@/lib/agent-send-disabled-reason-label' +import { agentSendDisabledReasonLabel } from '@/lib/agent-session/messaging/agent-send-disabled-reason-label' import { addQuoteToAgent } from '@/components/native-chat/selection-quotes/native-chat-workspace-selection' import React, { useCallback, useMemo } from 'react' import { orderSendTargetsByWorktreeAgentRows } from './review-notes-send-target-order' diff --git a/src/renderer/src/components/editor/review-note-delivery/review-notes-send-target-order.ts b/src/renderer/src/components/editor/review-note-delivery/review-notes-send-target-order.ts index d7a498d62a1..274d678fc80 100644 --- a/src/renderer/src/components/editor/review-note-delivery/review-notes-send-target-order.ts +++ b/src/renderer/src/components/editor/review-note-delivery/review-notes-send-target-order.ts @@ -1,5 +1,5 @@ import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' -import type { NotesSendAgentTarget } from '@/lib/notes-send-agent-targets' +import type { NotesSendAgentTarget } from '@/lib/agent-session/messaging/notes-send-agent-targets' export type OrderedSendTarget = { target: NotesSendAgentTarget diff --git a/src/renderer/src/components/editor/rich-markdown/citations/useRichMarkdownSuperscriptLinkSetup.ts b/src/renderer/src/components/editor/rich-markdown/citations/useRichMarkdownSuperscriptLinkSetup.ts index 4f64648fe79..0d9490dd4a0 100644 --- a/src/renderer/src/components/editor/rich-markdown/citations/useRichMarkdownSuperscriptLinkSetup.ts +++ b/src/renderer/src/components/editor/rich-markdown/citations/useRichMarkdownSuperscriptLinkSetup.ts @@ -2,7 +2,7 @@ import { useLayoutEffect, useMemo, useState } from 'react' import { useAppStore } from '@/store/index' import { getIndexedWorktreeById } from '@/store/slices/worktrees/listing/worktree-catalog-index' import { parseWorkspaceKey } from '../../../../../../shared/workspace-scope' -import { createConnectionIdForFileSelector } from '@/lib/connection-owner-resolution' +import { createConnectionIdForFileSelector } from '@/lib/workspace/ownership/connection-owner-resolution' import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport' import { createRichMarkdownHtmlSuperscriptLinkContext } from './rich-markdown-html-superscript-link-context' diff --git a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.selection.test.ts b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.selection.test.ts index c1847880b6c..4d7a79d4d66 100644 --- a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.selection.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.selection.test.ts @@ -19,7 +19,9 @@ const boundaryMocks = vi.hoisted(() => ({ }) })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: boundaryMocks.getConnectionId })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionId: boundaryMocks.getConnectionId +})) const editors: Editor[] = [] const largeText = 'X'.repeat(70 * 1024) diff --git a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.test.ts b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.test.ts index dbe0f800900..56e0d6d944c 100644 --- a/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/clipboard/rich-markdown-large-text-paste.test.ts @@ -21,7 +21,9 @@ const boundaryMocks = vi.hoisted(() => ({ }) })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: boundaryMocks.getConnectionId })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionId: boundaryMocks.getConnectionId +})) const editors: Editor[] = [] diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-paste.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-paste.test.ts index 53daa1d64cc..166308130c0 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-paste.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-paste.test.ts @@ -11,7 +11,9 @@ import { handleRichMarkdownImagePaste } from './rich-markdown-paste-image' vi.mock('@/runtime/files/imports/runtime-file-import-client', () => ({ importExternalPathsToRuntime: vi.fn() })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: vi.fn(() => null) })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionId: vi.fn(() => null) +})) vi.mock('@/store/index', () => ({ useAppStore: { getState: vi.fn(() => ({ diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-table.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-table.test.ts index ca1362ba320..f55c7dc3259 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-table.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-async-image-table.test.ts @@ -10,7 +10,9 @@ import { handleRichMarkdownImagePaste } from './rich-markdown-paste-image' vi.mock('@/runtime/files/imports/runtime-file-import-client', () => ({ importExternalPathsToRuntime: vi.fn() })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: vi.fn(() => null) })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionId: vi.fn(() => null) +})) vi.mock('@/store/index', () => ({ useAppStore: { getState: vi.fn(() => ({ diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-blob-image-paste.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-blob-image-paste.test.ts index aaa9aca060f..2d800ba69db 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-blob-image-paste.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-blob-image-paste.test.ts @@ -19,7 +19,7 @@ vi.mock('@/store/index', () => ({ getState: vi.fn() } })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: () => null, getConnectionIdForFile: () => null })) diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.test.ts index 507416d0139..cc06e5724f0 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.test.ts @@ -9,7 +9,7 @@ import { prewarmMarkdownPreviewLocalImages } from '../../markdown-preview/links/ import { loadLocalImageSrc } from '../../document-images/useLocalImageSrc' import { resetLocalImageCacheState as resetLocalImageSrcStateForTests } from '../../document-images/local-image-src-cache' -vi.mock('@/lib/connection-context', () => ({ getConnectionId: () => null })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: () => null })) describe('image reads for a document whose owner is unresolved', () => { afterEach(() => { diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.ts index 31bc35f3e3c..dab8a0b154c 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-context.ts @@ -1,5 +1,5 @@ import type { Editor } from '@tiptap/core' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import type { RuntimeFileOperationArgs } from '@/runtime/files/runtime-file-client-types' diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts index 83470f2588e..e977e28d0d7 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert-code-block.test.ts @@ -13,7 +13,7 @@ vi.mock('@/runtime/files/imports/runtime-file-import-client', () => ({ }) })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: vi.fn(() => null) })) diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts index 472b19a429b..faaea3b6d6f 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-image-insert.ts @@ -1,13 +1,13 @@ import type { Editor } from '@tiptap/react' import { toast } from 'sonner' import { dirname, basename } from '@/lib/path' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { useAppStore } from '@/store/index' import { importExternalPathsToRuntime } from '@/runtime/files/imports/runtime-file-import-client' import { acquireEditorFileOperation, getEditorFileOperationContext -} from '@/lib/editor-file-operation-owner' +} from '@/lib/editor/file-operations/editor-file-operation-owner' import { editorTabDocumentFolderAccess } from '@/lib/local-file-access' import { requireRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' import { captureDirectSshMutationExpectation } from '@/lib/ssh-mutation-expectation' diff --git a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-paste-image.ts b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-paste-image.ts index c783de0eea1..e028d53f095 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-paste-image.ts +++ b/src/renderer/src/components/editor/rich-markdown/images/rich-markdown-paste-image.ts @@ -1,6 +1,6 @@ import type { Editor } from '@tiptap/react' import { toast } from 'sonner' -import { getConnectionId } from '@/lib/connection-context' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' import { useAppStore } from '@/store/index' import { requireRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' import { extractIpcErrorMessage } from './rich-markdown-ipc-error-message' diff --git a/src/renderer/src/components/editor/rich-markdown/images/useLocalImagePick.test.tsx b/src/renderer/src/components/editor/rich-markdown/images/useLocalImagePick.test.tsx index ab6ff1e68a7..3daa0eff498 100644 --- a/src/renderer/src/components/editor/rich-markdown/images/useLocalImagePick.test.tsx +++ b/src/renderer/src/components/editor/rich-markdown/images/useLocalImagePick.test.tsx @@ -12,7 +12,9 @@ import { useLocalImagePick } from './useLocalImagePick' vi.mock('@/runtime/files/imports/runtime-file-import-client', () => ({ importExternalPathsToRuntime: vi.fn() })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: vi.fn(() => null) })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionId: vi.fn(() => null) +})) vi.mock('@/store/index', () => ({ useAppStore: { getState: vi.fn(() => ({ diff --git a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditorSurface.tsx b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditorSurface.tsx index 67cb45d8d25..8ff7e4f5494 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditorSurface.tsx +++ b/src/renderer/src/components/editor/rich-markdown/instance/RichMarkdownEditorSurface.tsx @@ -20,7 +20,7 @@ import type { } from '../commands/rich-markdown-slash-command-primitives' import type { MarkdownTocItem } from '../../markdown/navigation/markdown-table-of-contents' import type { NotesSendMenuScope } from '../../review-note-delivery/NotesSendMenu' -import type { MarkdownReviewNote } from '@/lib/markdown-review-notes' +import type { MarkdownReviewNote } from '@/lib/editor/markdown/review-notes/markdown-review-notes' import type { RichMarkdownAnnotationTarget } from '../review/rich-markdown-review-annotations' import type { RichMarkdownReviewNotePosition } from '../review/rich-markdown-review-note-layout' import type { DiffComment } from '../../../../../../shared/diff-comment-types' diff --git a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts index f953ad38baa..0375c397f69 100644 --- a/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts +++ b/src/renderer/src/components/editor/rich-markdown/instance/rich-markdown-editor-props.ts @@ -1,6 +1,6 @@ import type React from 'react' import type { MarkdownDocument } from '../../../../../../shared/file-listing/file-document' -import type { EditorFileOperationProvenance } from '@/lib/editor-file-operation-provenance' +import type { EditorFileOperationProvenance } from '@/lib/editor/file-operations/editor-file-operation-provenance' export type RichMarkdownEditorProps = { fileId: string diff --git a/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewNoteLayer.tsx b/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewNoteLayer.tsx index 51b0befbc10..f78a0fe83d2 100644 --- a/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewNoteLayer.tsx +++ b/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewNoteLayer.tsx @@ -10,7 +10,7 @@ import { formatMarkdownReviewNotes, getMarkdownReviewCardQuote, type MarkdownReviewNote -} from '@/lib/markdown-review-notes' +} from '@/lib/editor/markdown/review-notes/markdown-review-notes' import type { RichMarkdownReviewNotePosition } from './rich-markdown-review-note-layout' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewRailActions.tsx b/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewRailActions.tsx index 012a98d676e..be3089f9ca1 100644 --- a/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewRailActions.tsx +++ b/src/renderer/src/components/editor/rich-markdown/review/RichMarkdownReviewRailActions.tsx @@ -1,7 +1,7 @@ import type { DiffCommentOwner } from '@/store/slices/diff-comments/diff-comment-owner' import { Check, Copy, MessageSquare } from 'lucide-react' import { NotesSendMenu, type NotesSendMenuScope } from '../../review-note-delivery/NotesSendMenu' -import type { MarkdownReviewNote } from '@/lib/markdown-review-notes' +import type { MarkdownReviewNote } from '@/lib/editor/markdown/review-notes/markdown-review-notes' import { useTranslate } from '@/i18n/use-translate' type RichMarkdownReviewRailActionsProps = { diff --git a/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewController.ts b/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewController.ts index 4b9d6939bdb..27bb28000ca 100644 --- a/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewController.ts +++ b/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewController.ts @@ -19,7 +19,7 @@ import { useRichMarkdownReviewData } from './useRichMarkdownReviewData' import { useRichMarkdownReviewCopyFeedback } from './useRichMarkdownReviewCopyFeedback' import { useRichMarkdownReviewRailController } from './useRichMarkdownReviewRailController' import type { DiffComment } from '../../../../../../shared/diff-comment-types' -import type { WorkspaceResource } from '@/lib/workspace-copy-owner' +import type { WorkspaceResource } from '@/lib/workspace/ownership/workspace-copy-owner' type UseRichMarkdownReviewControllerOptions = { addDiffComment: AppState['addDiffComment'] diff --git a/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewCopyFeedback.ts b/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewCopyFeedback.ts index 1916954e6f3..0201186570e 100644 --- a/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewCopyFeedback.ts +++ b/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewCopyFeedback.ts @@ -1,7 +1,7 @@ import { useCallback, useRef, useState } from 'react' import type { MutableRefObject } from 'react' -import { copyMarkdownReviewNotesForAgent } from '@/lib/markdown-review-note-copy' -import type { MarkdownReviewNote } from '@/lib/markdown-review-notes' +import { copyMarkdownReviewNotesForAgent } from '@/lib/editor/markdown/review-notes/markdown-review-note-copy' +import type { MarkdownReviewNote } from '@/lib/editor/markdown/review-notes/markdown-review-notes' type UseRichMarkdownReviewCopyFeedbackOptions = { markdownReviewContent: string diff --git a/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewData.ts b/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewData.ts index 8df381e56ed..5c1f52edfd5 100644 --- a/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewData.ts +++ b/src/renderer/src/components/editor/rich-markdown/review/useRichMarkdownReviewData.ts @@ -6,7 +6,7 @@ import { formatMarkdownReviewNotes, sortMarkdownReviewNotes, type MarkdownReviewNote -} from '@/lib/markdown-review-notes' +} from '@/lib/editor/markdown/review-notes/markdown-review-notes' import type { NotesSendMenuScope } from '../../review-note-delivery/NotesSendMenu' import type { DiffComment } from '../../../../../../shared/diff-comment-types' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts b/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts index 48dfd267e84..fb5c15432e3 100644 --- a/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts +++ b/src/renderer/src/components/editor/save/commands/editor-file-save-utf8-conversion.test.ts @@ -12,7 +12,9 @@ import { __clearNonUtf8AutosavePausesForTests } from '../../autosave/editor-non- import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' vi.mock('sonner', () => ({ toast: { warning: vi.fn(), error: vi.fn() } })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) // "café" saved as Latin-1, decoded as UTF-8. const LATIN1 = Buffer.from([0x63, 0x61, 0x66, 0xe9]).toString('utf8') diff --git a/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts b/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts index fb85e094e96..97eefdea5a2 100644 --- a/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts +++ b/src/renderer/src/components/editor/save/commands/editor-untitled-save-lifecycle.test.ts @@ -24,7 +24,7 @@ function requireStore(): StoreApi { } vi.mock('@/store/index', () => ({ useAppStore: { getState: () => requireStore().getState() } })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: vi.fn() })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: vi.fn() })) const FILE_ID = '/repo/untitled.md' diff --git a/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts b/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts index 025edd65118..b74dd8fd23d 100644 --- a/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts +++ b/src/renderer/src/components/editor/save/flush/discard-editor-file-changes.save-race.test.ts @@ -22,7 +22,9 @@ const storeRef = vi.hoisted((): { current: ReturnType current: null })) vi.mock('@/store/index', () => ({ useAppStore: { getState: () => storeRef.current?.getState() } })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) // Hold the remote capability/status round trip before bytes are sent. const hostCheck = vi.hoisted((): { wait: Promise | null } => ({ wait: null })) vi.mock('@/runtime/files/mutations/runtime-file-mutation-client', async (importOriginal) => { diff --git a/src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.ts b/src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.ts index 2b6901c1752..d39f9f10b5a 100644 --- a/src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.ts +++ b/src/renderer/src/components/editor/save/flush/removal-unsaved-editor-files.ts @@ -9,7 +9,7 @@ import { worktreePurgeClosedFileIds } from '@/store/slices/worktrees/teardown/wo import { canAutoSaveOpenFile } from '../../autosave/editor-autosave' import { flushClosingEditorBuffers } from './editor-pending-flush' import { editorTabModelUri, isCodeViewTab } from '../queue/editor-save-disk-precondition' -import { editorModelRegistry } from '@/lib/editor-model-registry' +import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' /** Prompt once per writable dirty record only when every view of it is closing. */ export function lastViewUnsavedFiles(state: AppState, closedIds: ReadonlySet): OpenFile[] { diff --git a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts index d31a018accd..8a863405f85 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.races.test.ts @@ -20,7 +20,9 @@ const storeRef = vi.hoisted((): { current: ReturnType })) vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { error: mocks.toastError }) })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) vi.mock('@/store/index', () => ({ useAppStore: { getState: () => storeRef.current?.getState() } })) vi.mock('@/lib/file-owner-runtime-target', () => ({ getRuntimeTargetForFileOwner: () => ({ kind: 'local' }) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts index 4b91bd1f4f6..a5108677b4e 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-disk-precondition.test.ts @@ -18,7 +18,7 @@ const storeRef = vi.hoisted((): { current: ReturnType current: null })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: mocks.getConnectionIdForFile })) vi.mock('@/store/index', () => ({ useAppStore: { getState: () => storeRef.current?.getState() } })) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts deleted file mode 100644 index 4d3fd153072..00000000000 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view-records.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { - closedViewTab, - createClosedViewHarness, - type ClosedViewHarness -} from './editor-save-closed-view.test-fixture' - -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) - -// A view opened before a reconnect: its captured connection generation no longer matches. - -describe('editor save queue: closed saving view, record changes', () => { - let h: ClosedViewHarness - - beforeEach(() => { - h = createClosedViewHarness() - }) - - afterEach(() => h.dispose()) - - // Wrap the save promise so this async function does not await the held write. - const startHeldSave = async (): Promise<{ saved: Promise }> => { - h.holdNextWrite() - const saved = h.queue.queueSave(h.view('A'), 'edit') - await vi.advanceTimersByTimeAsync(0) - return { saved } - } - - it('marks the record clean when only a read-only view is left', async () => { - h.store.setState({ openFiles: [] }) - h.store.setState({ - openFiles: [closedViewTab('A', 'wt-1'), { ...closedViewTab('log', 'wt-2'), readOnly: true }] - }) - h.type('A', 'edit') - expect(h.view('log').isDirty).toBe(true) - const { saved } = await startHeldSave() - h.closeView('A') - h.release() - await expect(saved).resolves.toBe('written') - - expect(h.view('log').isDirty).toBe(false) - expect(h.store.getState().editorDrafts.log).toBeUndefined() - }) -}) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts index 118b3f38780..69eb7cc2d3f 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue-closed-view.test.ts @@ -8,32 +8,19 @@ import { type ClosedViewHarness } from './editor-save-closed-view.test-fixture' -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) describe('editor save queue: the saving view closes mid-write', () => { let h: ClosedViewHarness beforeEach(() => { h = createClosedViewHarness() - expect(h.recordOf('A')).toBe(h.recordOf('B')) }) afterEach(() => h.dispose()) - it('a refused write banners the view left', async () => { - h.type('A', 'edit') - h.holdNextWrite(true) - const saved = h.queue.queueSave(h.view('A'), 'edit') - await vi.advanceTimersByTimeAsync(0) - h.closeView('A') - h.release() - await expect(saved).resolves.toBe('blocked-stale') - - expect(h.view('B').externalMutation).toBe('changed') - expect(h.view('B').isDirty).toBe(true) - expect(h.store.getState().editorDrafts.B).toBe('edit') - }) - it('writes through the view left when the writer closes while another record holds the file', async () => { // Divergent dirty drafts keep C off the A+B record, but both write the same file. h.store.setState({ openFiles: [] }) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue-records.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue-records.test.ts deleted file mode 100644 index 6c742c398a5..00000000000 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue-records.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { createEditorSaveQueue } from './editor-save-queue' -import type { EditorSaveQueue } from './editor-save-queue-contract' -import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' -import { - createEditorStore, - createFakeEditorDisk, - stubEditorWindowWithDisk, - withLoadedBaselines, - type FakeEditorDisk -} from '../../autosave/editor-autosave-controller-test-fixture' - -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) - -const PATH = '/repo/a.ts' -const DELAY_MS = 1000 - -function tab(id: string, patch: Partial = {}): OpenFile { - return { - id, - filePath: PATH, - relativePath: 'a.ts', - worktreeId: 'wt-1', - language: 'typescript', - isDirty: false, - mode: 'edit', - ...patch - } -} - -describe('editor save queue: one autosave timer per record across its views', () => { - let disk: FakeEditorDisk - let store: ReturnType - let queue: EditorSaveQueue - - // Use the real middleware to join same-file views by identity. - const share = (views: OpenFile[]): void => { - store.setState({ openFiles: views }) - const recordIds = new Set(views.map((open) => store.getState().editorBufferIdOf[open.id])) - expect(recordIds.size).toBe(1) - } - const type = (viewId: string, text: string): void => { - store.getState().setEditorDraft(viewId, text) - store.getState().markFileDirty(viewId, true) - queue.syncAutoSave() - } - const view = (id: string): OpenFile => { - const found = store.getState().openFiles.find((openFile) => openFile.id === id) - if (!found) { - throw new Error(`no view ${id}`) - } - return found - } - const writtenContents = (): string[] => disk.fs.writeFile.mock.calls.map(([args]) => args.content) - - beforeEach(() => { - vi.useFakeTimers() - disk = stubEditorWindowWithDisk(createFakeEditorDisk({ [PATH]: '' })) - store = createEditorStore() - store.setState({ - worktreesByRepo: { - 'repo-1': [ - makeWorktree({ id: 'wt-1', repoId: 'repo-1', path: '/repo', hostId: 'local' }), - makeWorktree({ id: 'wt-2', repoId: 'repo-1', path: '/repo', hostId: 'local' }) - ] - } - }) - share([tab('w1'), tab('w2', { worktreeId: 'wt-2' })]) - withLoadedBaselines(store, disk) - queue = createEditorSaveQueue(store) - }) - - afterEach(() => { - queue.dispose() - __clearSelfWriteRegistryForTests() - vi.useRealTimers() - vi.unstubAllGlobals() - }) - - it('keeps the timer when the view that scheduled it closes', async () => { - type('w1', 'abc') - await vi.advanceTimersByTimeAsync(DELAY_MS / 2) - share([view('w2')]) - queue.syncAutoSave() - await vi.advanceTimersByTimeAsync(DELAY_MS) - - expect(writtenContents()).toEqual(['abc']) - expect(view('w2').isDirty).toBe(false) - }) - - it.each(['w1', 'w2'])( - 'schedules nothing for a conflicted record, whichever view (%s) typed', - async (typist) => { - store.getState().setExternalMutation('w2', 'changed') - expect(view('w1').externalMutation).toBe('changed') - type(typist, 'abc') - await vi.advanceTimersByTimeAsync(DELAY_MS * 2) - - expect(writtenContents()).toEqual([]) - expect(view('w1').isDirty).toBe(true) - expect(view('w2').isDirty).toBe(true) - } - ) -}) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts index b21e8574f79..c04644be550 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue-shared-records.test.ts @@ -15,7 +15,9 @@ import { type FakeEditorDisk } from '../../autosave/editor-autosave-controller-test-fixture' -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) const PATH = '/repo/a.ts' const WORKTREES = { diff --git a/src/renderer/src/components/editor/save/queue/editor-save-queue.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-queue.test.ts index ee1df4afcdb..a9323988cfc 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-queue.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-queue.test.ts @@ -11,7 +11,9 @@ import { type FakeEditorDisk } from '../../autosave/editor-autosave-controller-test-fixture' -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) const PATH = '/repo/a.ts' diff --git a/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts index e2ade6884f9..73818a94955 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-shared-model-dirty.test.ts @@ -17,7 +17,9 @@ const storeRef = vi.hoisted((): { current: ReturnType vi.mock('@/store/index', () => ({ useAppStore: { getState: () => storeRef.current?.getState() } })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) vi.mock('@/lib/file-owner-runtime-target', () => ({ getRuntimeTargetForFileOwner: () => ({ kind: 'local' }), requireRuntimeTargetForFileOwner: () => ({ kind: 'local' }) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts b/src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts deleted file mode 100644 index 58b32cf7296..00000000000 --- a/src/renderer/src/components/editor/save/queue/editor-save-shared-model.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -// Keep text, disk baseline and conflict state synchronized across workspaces sharing one Monaco model. -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor-self-write-registry' -import { createEditorStore } from '../../autosave/editor-autosave-controller-test-fixture' -import { reloadTabContentFromDisk } from '../../external-changes/ExternalFileChangeBanner' -import { getDiskBaselineSignature } from '../../../../../../shared/file-write/disk-baseline-signature' - -import { GUARDED_PATH } from './editor-save-guarded-disk-fixture' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { toast } from 'sonner' - -const mocks = vi.hoisted(() => ({ readRuntimeFileContent: vi.fn() })) -const storeRef = vi.hoisted((): { current: ReturnType | null } => ({ - current: null -})) - -vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { error: vi.fn() }) })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) -vi.mock('@/store/index', () => ({ useAppStore: { getState: () => storeRef.current?.getState() } })) -vi.mock('@/lib/file-owner-runtime-target', () => ({ - getRuntimeTargetForFileOwner: () => ({ kind: 'local' }) -})) -vi.mock('@/runtime/files/reads/runtime-file-read-client', async (importOriginal) => ({ - ...(await importOriginal()), - readRuntimeFileContent: mocks.readRuntimeFileContent -})) - -function openSharedTabs(disk: string) { - const store = createEditorStore() - storeRef.current = store - store.setState({ - worktreesByRepo: { - 'repo-1': [ - makeWorktree({ id: 'wt-1', repoId: 'repo-1', path: '/repo', hostId: 'local' }), - makeWorktree({ id: 'wt-2', repoId: 'repo-1', path: '/repo', hostId: 'local' }) - ] - } - }) - for (const worktreeId of ['wt-1', 'wt-2']) { - store.getState().openFile({ - filePath: GUARDED_PATH, - relativePath: 'file.ts', - worktreeId, - language: 'typescript', - mode: 'edit' - }) - } - const [a, b] = store.getState().openFiles - for (const tab of [a, b]) { - store.getState().setLastKnownDiskSignature(tab.id, getDiskBaselineSignature(disk)) - } - const edit = (id: string, text: string): void => { - store.getState().setEditorDraft(id, text) - store.getState().markFileDirty(id, true) - } - const tab = (id: string) => store.getState().openFiles.find((file) => file.id === id) - return { store, a, b, edit, tab } -} - -type ClickAction = { onClick: () => void } - -function isClickAction(value: unknown): value is ClickAction { - return ( - typeof value === 'object' && - value !== null && - 'onClick' in value && - typeof value.onClick === 'function' - ) -} - -describe('two tabs sharing one model', () => { - beforeEach(() => { - vi.useFakeTimers() - }) - - afterEach(() => { - vi.useRealTimers() - vi.unstubAllGlobals() - __clearSelfWriteRegistryForTests() - }) - - it('Reload discards both drafts and reloads both tabs', () => { - const { store, a, b, edit, tab } = openSharedTabs('A') - edit(a.id, 'mine') - edit(b.id, 'mine') - for (const id of [a.id, b.id]) { - store.getState().setExternalMutation(id, 'changed') - } - const reloadContent = vi.fn() - - reloadTabContentFromDisk(store.getState().openFiles[0], reloadContent) - - expect(reloadContent.mock.calls.map(([file]) => file.id).sort()).toEqual([a.id, b.id].sort()) - for (const id of [a.id, b.id]) { - expect(store.getState().editorDrafts[id]).toBeUndefined() - expect(tab(id)?.externalMutation).toBeUndefined() - } - }) - - it("Reload from a clean tab offers Undo of the sibling's discarded edits", () => { - const { store, a, b, edit } = openSharedTabs('A') - edit(b.id, 'mine') - for (const id of [a.id, b.id]) { - store.getState().setExternalMutation(id, 'changed') - } - const toastMock = vi.mocked(toast) - toastMock.mockClear() - reloadTabContentFromDisk(store.getState().openFiles[0], vi.fn()) - expect(store.getState().editorDrafts[b.id]).toBeUndefined() - - const undo: unknown = toastMock.mock.calls[0]?.[1]?.action - expect(isClickAction(undo)).toBe(true) - if (isClickAction(undo)) { - undo.onClick() - } - - expect(store.getState().editorDrafts[b.id]).toBe('mine') - }) -}) diff --git a/src/renderer/src/components/editor/save/queue/editor-save-slots.ts b/src/renderer/src/components/editor/save/queue/editor-save-slots.ts index 71dbc2f19ae..7b796312202 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-slots.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-slots.ts @@ -1,4 +1,4 @@ -import type { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' +import type { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' import type { LocalFileAccess } from '../../../../../../shared/file-access/local-file-access' import type { EditorSaveResult, EditorSaveTrigger } from './editor-save-disk-precondition' diff --git a/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts b/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts index 12b4c7f1f59..cbc680c8225 100644 --- a/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts +++ b/src/renderer/src/components/editor/save/queue/editor-save-writer-view.ts @@ -1,8 +1,8 @@ import { editorSaveResourceKey } from '@/store/slices/editor/buffers/editor-buffer-identity' import type { AppState } from '@/store/types' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' -import { captureEditorFileOperationForOwner } from '@/lib/editor-file-child-owner' +import { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' +import { captureEditorFileOperationForOwner } from '@/lib/editor/file-operations/editor-file-child-owner' import { editorTabFileAccess } from '@/lib/local-file-access' import type { AppStoreApi } from './editor-save-queue-contract' import type { EditorSaveAcquisition, EditorSaveRequest } from './editor-save-slots' diff --git a/src/renderer/src/components/editor/save/transforms/editor-final-newline-save.test.ts b/src/renderer/src/components/editor/save/transforms/editor-final-newline-save.test.ts index 6381b05cac0..20954ea6abb 100644 --- a/src/renderer/src/components/editor/save/transforms/editor-final-newline-save.test.ts +++ b/src/renderer/src/components/editor/save/transforms/editor-final-newline-save.test.ts @@ -4,7 +4,7 @@ import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js' import type { StoreApi } from 'zustand' import type { AppState } from '@/store/types' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' -import { editorModelRegistry } from '@/lib/editor-model-registry' +import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { usePluginPanelsStore } from '@/store/plugins/catalog/plugin-contribution-catalog' import { requestEditorFileSave } from '../../autosave/editor-autosave' @@ -17,7 +17,9 @@ import { __clearSelfWriteRegistryForTests } from '../../external-changes/editor- const storeRef = vi.hoisted((): { current: StoreApi | null } => ({ current: null })) -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => null })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => null +})) vi.mock('@/store/index', () => ({ useAppStore: { getState: () => storeRef.current?.getState() } })) vi.mock('@/lib/file-owner-runtime-target', () => ({ getRuntimeTargetForFileOwner: () => ({ kind: 'local' }) diff --git a/src/renderer/src/components/editor/save/transforms/editor-final-newline.ts b/src/renderer/src/components/editor/save/transforms/editor-final-newline.ts index a42a9dd4602..f8225d6e5fe 100644 --- a/src/renderer/src/components/editor/save/transforms/editor-final-newline.ts +++ b/src/renderer/src/components/editor/save/transforms/editor-final-newline.ts @@ -1,6 +1,6 @@ import type { AppState } from '@/store/types' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { editorModelRegistry } from '@/lib/editor-model-registry' +import { editorModelRegistry } from '@/lib/editor/monaco/editor-model-registry' import { editorTabModelUri } from '../queue/editor-save-disk-precondition' import { hasPendingEditorBufferChange } from '../flush/editor-pending-flush' import { normalizeToModelEol } from '../../monaco-content-sync' diff --git a/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts b/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts index 954ba01b01b..34d8f382841 100644 --- a/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts +++ b/src/renderer/src/components/editor/save/transforms/editor-format-on-save.test.ts @@ -17,7 +17,9 @@ import { usePluginPanelsStore } from '@/store/plugins/catalog/plugin-contributio import { bumpEditorDiscardEpoch, EditorSaveDiscardedError } from '../flush/editor-discard-epoch' import { editorBufferIdOfView } from '@/store/slices/editor/buffers/editor-buffer-views' -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: vi.fn() })) diff --git a/src/renderer/src/components/editor/save/transforms/editor-save-plugin-hook.test.ts b/src/renderer/src/components/editor/save/transforms/editor-save-plugin-hook.test.ts index c6859f52467..55143a51a1a 100644 --- a/src/renderer/src/components/editor/save/transforms/editor-save-plugin-hook.test.ts +++ b/src/renderer/src/components/editor/save/transforms/editor-save-plugin-hook.test.ts @@ -16,7 +16,9 @@ import { import { EditorSaveDeniedByPluginError } from './editor-save-plugin-hook' import { registerPendingEditorFlush } from '../flush/editor-pending-flush' -vi.mock('@/lib/connection-context', () => ({ getConnectionIdForFile: () => undefined })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionIdForFile: () => undefined +})) vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) const PATH = '/repo/src/a.ts' diff --git a/src/renderer/src/components/editor/setup-contextual-copy.ts b/src/renderer/src/components/editor/setup-contextual-copy.ts index 4adae5c4ad0..4b10cf8e6bf 100644 --- a/src/renderer/src/components/editor/setup-contextual-copy.ts +++ b/src/renderer/src/components/editor/setup-contextual-copy.ts @@ -1,6 +1,6 @@ import type { editor } from 'monaco-editor' import { formatShortcutLabel } from '@/hooks/useShortcutLabel' -import { monaco } from '@/lib/monaco-setup' +import { monaco } from '@/lib/editor/monaco/monaco-setup' import { useAppStore } from '@/store' import { editorShortcutMatches } from './editor-shortcuts' import { diff --git a/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts b/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts index 001f3ad3053..e9ea12f0a7b 100644 --- a/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts +++ b/src/renderer/src/components/editor/use-custom-editor-outside-merge.ts @@ -1,6 +1,6 @@ import { useEffect, useLayoutEffect, useRef } from 'react' import { create } from 'zustand' -import { getConnectionIdForFile } from '@/lib/connection-context' +import { getConnectionIdForFile } from '@/lib/workspace/ownership/connection-context' import { editorTabFileAccess } from '@/lib/local-file-access' import { getRuntimeTargetForFileOwner } from '@/lib/file-owner-runtime-target' import { readRuntimeFileContent } from '@/runtime/files/reads/runtime-file-read-client' diff --git a/src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx b/src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx index 8dae32d8eb4..5f66a377961 100644 --- a/src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx +++ b/src/renderer/src/components/editor/use-monaco-editor-mount.cursor-owner.test.tsx @@ -7,7 +7,8 @@ import type { OnMount } from '@monaco-editor/react' import type { StoreApi } from 'zustand' import type { AppState } from '@/store/types' import { createEditorTabsStore } from '@/store/slices/editor/editor-slice-test-harness' -import { captureEditorFileOperationProvenance } from '@/lib/editor-file-operation-owner' +import '@/lib/editor/file-operations/editor-file-operation-owner' +import { captureEditorFileOperationProvenance } from '@/lib/editor/file-operations/editor-file-operation-provenance' import type { MonacoEditorMountParams } from './monaco-editor-mount-params' import { useMonacoEditorMount } from './use-monaco-editor-mount' import { MonacoGutterContextMenu } from './MonacoGutterContextMenu' diff --git a/src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.ts b/src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.ts index f33c7617fcf..d146d060ff4 100644 --- a/src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.ts +++ b/src/renderer/src/components/editor/useEditorPanelActiveTabContentLoad.ts @@ -6,10 +6,13 @@ import { import type { OpenFile } from '@/store/slices/editor/types/open-file' import { joinPath } from '@/lib/path' import { useAppStore } from '@/store' -import type { DiffContent, FileContent } from './editor-panel-content-types' +import type { + DiffContent, + FileContent, + EditorPanelFileContentLoader +} from './editor-panel-content-types' import { isReloadableSingleFileDiffTab } from './editor-panel-diff-reload' import type { EditorPanelDiffContentLoader } from './useEditorPanelDiffContentLoader' -import type { EditorPanelFileContentLoader } from './useEditorPanelFileContentLoader' import { useQuickOpenHistoryVisit } from './use-quick-open-history-visit' // Showing a tab is a user act: its first load may start a stopped WSL distro. Re-runs from diff --git a/src/renderer/src/components/editor/useEditorPanelContentReloadTriggers.ts b/src/renderer/src/components/editor/useEditorPanelContentReloadTriggers.ts index 5c1f9887daf..e21a356bb38 100644 --- a/src/renderer/src/components/editor/useEditorPanelContentReloadTriggers.ts +++ b/src/renderer/src/components/editor/useEditorPanelContentReloadTriggers.ts @@ -1,13 +1,12 @@ import { useEffect, useMemo, type MutableRefObject } from 'react' import type { OpenFile } from '@/store/slices/editor/types/open-file' import type { useAppStore } from '@/store' -import type { DiffContent } from './editor-panel-content-types' +import type { DiffContent, EditorPanelFileContentLoader } from './editor-panel-content-types' import { isReloadableSingleFileDiffTab, shouldReloadDiffOnGitStatusChange } from './editor-panel-diff-reload' import type { EditorPanelDiffContentLoader } from './useEditorPanelDiffContentLoader' -import type { EditorPanelFileContentLoader } from './useEditorPanelFileContentLoader' type GitStatusByWorktree = ReturnType['gitStatusByWorktree'] diff --git a/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx index 49f0bb4d24a..394a1411f99 100644 --- a/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelContentState.test.tsx @@ -41,7 +41,7 @@ vi.mock('@/runtime/source-control/git/runtime-git-client-context', () => ({ getRuntimeGitScope: vi.fn(() => null) })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: mocks.getConnectionId, getConnectionIdForFile: mocks.getConnectionIdForFile, isWorktreeConnectionResolved: mocks.isWorktreeConnectionResolved diff --git a/src/renderer/src/components/editor/useEditorPanelDiffContentLoader.ts b/src/renderer/src/components/editor/useEditorPanelDiffContentLoader.ts index 52ac77a3a5d..a6c216f8173 100644 --- a/src/renderer/src/components/editor/useEditorPanelDiffContentLoader.ts +++ b/src/renderer/src/components/editor/useEditorPanelDiffContentLoader.ts @@ -1,5 +1,5 @@ import { useCallback, type Dispatch, type MutableRefObject, type SetStateAction } from 'react' -import { getEditorFileReadContext } from '@/lib/editor-file-operation-owner' +import { getEditorFileReadContext } from '@/lib/editor/file-operations/editor-file-operation-owner' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { useAppStore } from '@/store' import { diff --git a/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts b/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts index 79dc1786905..5d342546add 100644 --- a/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts +++ b/src/renderer/src/components/editor/useEditorPanelFileContentLoader.ts @@ -2,7 +2,10 @@ import { useCallback } from 'react' import { translate } from '@/i18n/i18n' import { readEditorPanelFileContent } from './editor-panel-file-reads' import type { OpenFile } from '@/store/slices/editor/types/open-file' -import { getConnectionIdForFile, isWorktreeConnectionResolved } from '@/lib/connection-context' +import { + getConnectionIdForFile, + isWorktreeConnectionResolved +} from '@/lib/workspace/ownership/connection-context' import { useAppStore } from '@/store' import { getRuntimeFileReadScope } from '@/runtime/files/runtime-file-routing' import { readEditorCsvFileContent } from './csv/csv-file-content' @@ -19,7 +22,6 @@ import { type EditorPanelFileContentLoader, type UseEditorPanelFileContentLoaderParams } from './editor-panel-content-types' -import type { EditorPanelContentLoadOptions } from './external-changes/useEditorPanelExternalContentEvents' import { migrateRestoredEditorFileOwner, restoredOwnerMigrationErrorMessage @@ -33,11 +35,10 @@ import { applyEditorFileLoadFailure, getEditorFileLoadFailureContent } from './external-changes/editor-deleted-file-reload' -export type { EditorPanelFileContentLoader } from './editor-panel-content-types' import { acquireEditorFileOperation, isSameEditorFileOperationIdentity -} from '@/lib/editor-file-operation-owner' +} from '@/lib/editor/file-operations/editor-file-operation-owner' export function useEditorPanelFileContentLoader({ fileLoadRetryAttemptsRef, @@ -47,14 +48,8 @@ export function useEditorPanelFileContentLoader({ outstandingFileReadsRef, setFileContents }: UseEditorPanelFileContentLoaderParams): EditorPanelFileContentLoader { - return useCallback( - async ( - filePath: string, - id: string, - worktreeId?: string, - relativePath?: string, - options?: EditorPanelContentLoadOptions - ): Promise => { + return useCallback( + async (filePath, id, worktreeId, relativePath, options) => { const generation = ++fileReadGenerationCounterRef.current fileReadGenerationRef.current[id] = generation outstandingFileReadsRef.current[id] = generation diff --git a/src/renderer/src/components/editor/useEditorPanelFloatingTabContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelFloatingTabContentState.test.tsx index 9eda67b2bc4..ac264d281dd 100644 --- a/src/renderer/src/components/editor/useEditorPanelFloatingTabContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelFloatingTabContentState.test.tsx @@ -37,7 +37,7 @@ vi.mock('@/runtime/source-control/git/runtime-git-client-context', () => ({ getRuntimeGitScope: vi.fn(() => null) })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: vi.fn(() => null), getConnectionIdForFile: vi.fn(() => null), isWorktreeConnectionResolved: vi.fn(() => true) diff --git a/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx index 129bcdd32f2..237b24d9ba5 100644 --- a/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelHostUnresolvedContentState.test.tsx @@ -35,7 +35,7 @@ vi.mock('@/runtime/source-control/git/runtime-git-client-context', () => ({ getRuntimeGitScope: vi.fn(() => null) })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: vi.fn(), getConnectionIdForFile: vi.fn(), isWorktreeConnectionResolved: vi.fn(() => true) diff --git a/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx b/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx index 0054859050a..39e22be2676 100644 --- a/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx +++ b/src/renderer/src/components/editor/useEditorPanelVisibilityContentState.test.tsx @@ -32,7 +32,7 @@ vi.mock('@/runtime/source-control/git/runtime-git-client-context', () => ({ getRuntimeGitScope: vi.fn(() => null) })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionId: vi.fn(), getConnectionIdForFile: vi.fn(), isWorktreeConnectionResolved: vi.fn(() => true) diff --git a/src/renderer/src/components/editor/useUntitledFileRename.ts b/src/renderer/src/components/editor/useUntitledFileRename.ts index 8b7134319f9..1c5897647ab 100644 --- a/src/renderer/src/components/editor/useUntitledFileRename.ts +++ b/src/renderer/src/components/editor/useUntitledFileRename.ts @@ -5,8 +5,8 @@ import { useAppStore } from '@/store' import type { OpenFile } from '@/store/slices/editor/types/open-file' import { createRuntimePath } from '@/runtime/files/mutations/runtime-file-mutation-client' import { runtimePathExists } from '@/runtime/files/metadata/runtime-file-metadata-client' -import { executeOpenEditorPathMove } from '@/lib/execute-open-editor-path-move' -import { acquireEditorFileOperation } from '@/lib/editor-file-operation-owner' +import { executeOpenEditorPathMove } from '@/lib/editor/file-operations/execute-open-editor-path-move' +import { acquireEditorFileOperation } from '@/lib/editor/file-operations/editor-file-operation-owner' import { requestEditorFileSave, requestEditorSaveQuiesce } from './autosave/editor-autosave' import { getUntitledFileRoot } from './untitled-file-rename-path' diff --git a/src/renderer/src/components/emulator-pane/MobileEmulatorAgentSetupGuideSteps.tsx b/src/renderer/src/components/emulator-pane/MobileEmulatorAgentSetupGuideSteps.tsx index 9e061859f0b..23ce5fbfadd 100644 --- a/src/renderer/src/components/emulator-pane/MobileEmulatorAgentSetupGuideSteps.tsx +++ b/src/renderer/src/components/emulator-pane/MobileEmulatorAgentSetupGuideSteps.tsx @@ -1,5 +1,5 @@ import { useAppStore } from '@/store' -import { ORCA_CLI_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { ORCA_CLI_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { AgentSkillSetupPanel } from '../skills/setup/AgentSkillSetupPanel' import type { useMobileEmulatorAgentSetupState } from './use-mobile-emulator-agent-setup-state' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/emulator-pane/emulator-device-picker-groups.ts b/src/renderer/src/components/emulator-pane/emulator-device-picker-groups.ts index 6de74367bca..ea4fdd6cdf3 100644 --- a/src/renderer/src/components/emulator-pane/emulator-device-picker-groups.ts +++ b/src/renderer/src/components/emulator-pane/emulator-device-picker-groups.ts @@ -1,4 +1,4 @@ -import { simulatorRuntimeLabel } from '@/lib/simulator-runtime-label' +import { simulatorRuntimeLabel } from '@/lib/simulator/launch/simulator-runtime-label' import type { SimulatorDeviceRow } from './emulator-pane-types' export function groupEmulatorDevices(devices: SimulatorDeviceRow[], selected: string | null) { diff --git a/src/renderer/src/components/emulator-pane/emulator-pane-error-copy.ts b/src/renderer/src/components/emulator-pane/emulator-pane-error-copy.ts index 284598efd16..840dbe53901 100644 --- a/src/renderer/src/components/emulator-pane/emulator-pane-error-copy.ts +++ b/src/renderer/src/components/emulator-pane/emulator-pane-error-copy.ts @@ -1,5 +1,5 @@ import { translate } from '@/i18n/i18n' -import { emulatorErrorText } from '@/lib/emulator-error-copy' +import { emulatorErrorText } from '@/lib/simulator/launch/emulator-error-copy' export function emulatorListDevicesErrorText(error: unknown): string { return emulatorErrorText( diff --git a/src/renderer/src/components/emulator-pane/emulator-pane-session-view.ts b/src/renderer/src/components/emulator-pane/emulator-pane-session-view.ts index 9f2a01d721c..33d58471e1c 100644 --- a/src/renderer/src/components/emulator-pane/emulator-pane-session-view.ts +++ b/src/renderer/src/components/emulator-pane/emulator-pane-session-view.ts @@ -1,4 +1,4 @@ -import { SIMULATOR_DEFAULT_TAB_LABEL } from '@/lib/simulator-tab-label' +import { SIMULATOR_DEFAULT_TAB_LABEL } from '@/lib/simulator/tabs/simulator-tab-label' import { simulatorPreviewStreamUrl, type EmulatorPaneSession, diff --git a/src/renderer/src/components/emulator-pane/emulator-pane-types.ts b/src/renderer/src/components/emulator-pane/emulator-pane-types.ts index 0e60de62b02..c7de9e2480a 100644 --- a/src/renderer/src/components/emulator-pane/emulator-pane-types.ts +++ b/src/renderer/src/components/emulator-pane/emulator-pane-types.ts @@ -1,4 +1,4 @@ -import { SIMULATOR_DEFAULT_TAB_LABEL } from '@/lib/simulator-tab-label' +import { SIMULATOR_DEFAULT_TAB_LABEL } from '@/lib/simulator/tabs/simulator-tab-label' export type SimulatorDeviceRow = { name: string @@ -28,6 +28,12 @@ export type EmulatorPaneSession = { info?: EmulatorStreamInfo } +export type UseEmulatorPaneSessionArgs = { + worktreeId: string + tabId?: string + autoAttachOnMount: boolean +} + export function deviceLabel( device: SimulatorDeviceRow | EmulatorStreamInfo | string | undefined ): string { diff --git a/src/renderer/src/components/emulator-pane/use-emulator-input-check.ts b/src/renderer/src/components/emulator-pane/use-emulator-input-check.ts index 7ba69bceabe..4944fc02e6b 100644 --- a/src/renderer/src/components/emulator-pane/use-emulator-input-check.ts +++ b/src/renderer/src/components/emulator-pane/use-emulator-input-check.ts @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' -import { emulatorErrorText } from '@/lib/emulator-error-copy' +import { emulatorErrorText } from '@/lib/simulator/launch/emulator-error-copy' import { hasRuntimeRpcErrorCode } from '../../../../shared/runtime-rpc-error-code' import { EMULATOR_FAILURE_COPY } from '../../../../shared/emulator-failure-copy' diff --git a/src/renderer/src/components/emulator-pane/use-emulator-pane-lifecycle.ts b/src/renderer/src/components/emulator-pane/use-emulator-pane-lifecycle.ts index 6070cc5f378..35e0b1c5d07 100644 --- a/src/renderer/src/components/emulator-pane/use-emulator-pane-lifecycle.ts +++ b/src/renderer/src/components/emulator-pane/use-emulator-pane-lifecycle.ts @@ -2,7 +2,7 @@ import { useEffect } from 'react' import { cancelPendingSimulatorPaneShutdown, scheduleSimulatorPaneManagedShutdown -} from '@/lib/simulator-pane-shutdown-scheduler' +} from '@/lib/simulator/tabs/simulator-pane-shutdown-scheduler' import type { SimulatorDeviceRow } from './emulator-pane-types' type UseEmulatorPaneLifecycleArgs = { diff --git a/src/renderer/src/components/emulator-pane/use-emulator-pane-manual-launch-events.ts b/src/renderer/src/components/emulator-pane/use-emulator-pane-manual-launch-events.ts index 938d8beb51d..1059cc5c6ba 100644 --- a/src/renderer/src/components/emulator-pane/use-emulator-pane-manual-launch-events.ts +++ b/src/renderer/src/components/emulator-pane/use-emulator-pane-manual-launch-events.ts @@ -4,8 +4,8 @@ import type { EmulatorPaneSession } from './emulator-pane-types' import { EMULATOR_MANUAL_LAUNCH_FAILED_EVENT, EMULATOR_MANUAL_LAUNCH_STARTED_EVENT -} from '@/lib/simulator-launch-coordination' -import { SIMULATOR_DEFAULT_TAB_LABEL } from '@/lib/simulator-tab-label' +} from '@/lib/simulator/launch/simulator-launch-coordination' +import { SIMULATOR_DEFAULT_TAB_LABEL } from '@/lib/simulator/tabs/simulator-tab-label' type UseEmulatorPaneManualLaunchEventsArgs = { worktreeId: string diff --git a/src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx b/src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx index 1e86fb6c484..2c4368a3fa7 100644 --- a/src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx +++ b/src/renderer/src/components/emulator-pane/use-emulator-pane-session.test.tsx @@ -1,4 +1,4 @@ -import * as emulatorPreferences from '@/lib/emulator-opening-preferences-capability' +import * as emulatorPreferences from '@/lib/simulator/launch/emulator-opening-preferences-capability' import { setLocalRuntimeCapabilitiesForTests } from '@/runtime/hosts/capabilities/local-runtime-capabilities' // @vitest-environment happy-dom @@ -9,8 +9,8 @@ import { useAppStore } from '@/store' import { consumePrelaunchedSimulatorSession, rememberPrelaunchedSimulatorSession -} from '@/lib/simulator-launch-coordination' -import { cancelPendingSimulatorPaneShutdown } from '@/lib/simulator-pane-shutdown-scheduler' +} from '@/lib/simulator/launch/simulator-launch-coordination' +import { cancelPendingSimulatorPaneShutdown } from '@/lib/simulator/tabs/simulator-pane-shutdown-scheduler' import { useEmulatorPaneSession } from './use-emulator-pane-session' import type { SimulatorDeviceRow } from './emulator-pane-types' diff --git a/src/renderer/src/components/emulator-pane/use-emulator-pane-session.ts b/src/renderer/src/components/emulator-pane/use-emulator-pane-session.ts index ba1a11f75ad..ce7cd214c72 100644 --- a/src/renderer/src/components/emulator-pane/use-emulator-pane-session.ts +++ b/src/renderer/src/components/emulator-pane/use-emulator-pane-session.ts @@ -3,14 +3,15 @@ import { getEmulatorOpeningMode, type EmulatorSelectionRequired } from '../../../../shared/emulator-opening-preferences' -import { supportsEmulatorOpeningPreferences } from '@/lib/emulator-opening-preferences-capability' +import { supportsEmulatorOpeningPreferences } from '@/lib/simulator/launch/emulator-opening-preferences-capability' import { useCallback, useEffect, useRef, useState } from 'react' import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call' import { useAppStore } from '@/store' import { deviceLabel, simulatorPreviewStreamUrl, - type EmulatorPaneSession + type EmulatorPaneSession, + type UseEmulatorPaneSessionArgs } from './emulator-pane-types' import { markSimulatorDeviceShutdown } from './emulator-device-state' import { useEmulatorPaneControls } from './use-emulator-pane-controls' @@ -18,8 +19,8 @@ import { useEmulatorPaneSessionEvents } from './use-emulator-pane-session-events import { consumePrelaunchedSimulatorSession, isManualSimulatorLaunchPending -} from '@/lib/simulator-launch-coordination' -import { shutdownManagedSimulatorIfNoPane } from '@/lib/simulator-pane-shutdown-scheduler' +} from '@/lib/simulator/launch/simulator-launch-coordination' +import { shutdownManagedSimulatorIfNoPane } from '@/lib/simulator/tabs/simulator-pane-shutdown-scheduler' import { buildPrelaunchedEmulatorSessionState } from './emulator-prelaunched-session' import { useEmulatorPaneManualLaunchEvents } from './use-emulator-pane-manual-launch-events' import { buildEmulatorPaneSessionView } from './emulator-pane-session-view' @@ -27,15 +28,12 @@ import { attachWithAvdFallback } from './emulator-attach-target' import { useEmulatorPaneLifecycle } from './use-emulator-pane-lifecycle' import { useEmulatorPaneShutdown } from './use-emulator-pane-shutdown' import { emulatorStartErrorText, noEmulatorDevicesError } from './emulator-pane-error-copy' -import { SIMULATOR_DEFAULT_TAB_LABEL, formatSimulatorTabLabel } from '@/lib/simulator-tab-label' +import { + SIMULATOR_DEFAULT_TAB_LABEL, + formatSimulatorTabLabel +} from '@/lib/simulator/tabs/simulator-tab-label' import { useTranslate } from '@/i18n/use-translate' -type UseEmulatorPaneSessionArgs = { - worktreeId: string - tabId?: string - autoAttachOnMount: boolean -} - export function useEmulatorPaneSession({ worktreeId, tabId, diff --git a/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts b/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts index 8182008b6c7..35d7b3e1e7c 100644 --- a/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts +++ b/src/renderer/src/components/emulator-pane/use-mobile-emulator-agent-setup-state.ts @@ -1,7 +1,7 @@ import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' import { useCallback, useEffect, useState } from 'react' import { toast } from 'sonner' -import { ORCA_CLI_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { ORCA_CLI_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill diff --git a/src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.tsx b/src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.tsx index 8843b4abca0..504ce6f3b20 100644 --- a/src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.tsx +++ b/src/renderer/src/components/feature-tips/ChatUiHereFeatureTipVisual.tsx @@ -5,7 +5,7 @@ import { usePrefersReducedMotion } from '@/components/feature-wall/feature-wall- import { nativeChatPermissionModeLabel } from '@/components/native-chat/session/options/controls/native-chat-permission-mode-labels' import { nativeChatToolRowVerb } from '@/components/native-chat/tools/lines/native-chat-tool-line-label' import { useIntlLocale, useTranslate } from '@/i18n/use-translate' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { cn } from '@/lib/utils' import { CHAT_DEMO_FILE, diff --git a/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx b/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx index 973778d798a..29e6bc84d87 100644 --- a/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx +++ b/src/renderer/src/components/feature-tips/CliSkillSetupPanel.tsx @@ -1,6 +1,9 @@ import { CliSkillSetupTerminal } from './CliSkillSetupTerminal' import { AgentSkillSetupPanel } from '@/components/skills/setup/AgentSkillSetupPanel' -import { ORCA_CLI_SKILL_NAME, ORCHESTRATION_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { + ORCA_CLI_SKILL_NAME, + ORCHESTRATION_SKILL_NAME +} from '@/lib/skills/installation/agent-feature-skill-names' import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, diff --git a/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx b/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx index a8ed33a815b..66dba756e26 100644 --- a/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx +++ b/src/renderer/src/components/feature-tips/CliSkillSetupTerminal.tsx @@ -8,7 +8,7 @@ import { buildSkillCommandForRuntime, buildSkillSetupTerminalCommand } from '@/lib/skill-runtime-command' -import { ORCA_CLI_ORCHESTRATION_SKILL_INSTALL_COMMAND } from '@/lib/agent-feature-install-commands' +import { ORCA_CLI_ORCHESTRATION_SKILL_INSTALL_COMMAND } from '@/lib/skills/installation/agent-feature-install-commands' import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/feature-tips/feature-tip-session-panel-demo.tsx b/src/renderer/src/components/feature-tips/feature-tip-session-panel-demo.tsx index 31241c22cd8..a555cebaa37 100644 --- a/src/renderer/src/components/feature-tips/feature-tip-session-panel-demo.tsx +++ b/src/renderer/src/components/feature-tips/feature-tip-session-panel-demo.tsx @@ -16,7 +16,7 @@ import { DEFAULT_AI_VAULT_GROUP, DEFAULT_AI_VAULT_HIDE_EMPTY_SESSIONS } from '@/components/right-sidebar/ai-vault/scope/ai-vault-view-defaults' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { useTranslate } from '@/i18n/use-translate' import type { SessionSearchDemoRow } from './session-search-feature-tip-demo' diff --git a/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx b/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx index 37296243aeb..d9c96a59896 100644 --- a/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx +++ b/src/renderer/src/components/feature-wall/AgentCapabilitiesSetupAction.tsx @@ -5,7 +5,7 @@ import { import { bundledSkillSetupActionLabel } from '../skills/setup/bundled-skill-setup-copy' import { useOnboardingSkillRuntime } from '@/hooks/use-onboarding-skill-runtime' import { FeatureSetupInlineTerminal } from '../onboarding/FeatureSetupInlineTerminal' -import { buildAgentFeatureSkillInstallCommand } from '@/lib/agent-feature-install-commands' +import { buildAgentFeatureSkillInstallCommand } from '@/lib/skills/installation/agent-feature-install-commands' import { buildSkillCommandForRuntime } from '../../lib/skill-runtime-command' import type { OnboardingFeatureSetupRuntimeContext } from '../onboarding/onboarding-feature-setup-runtime' import { useCallback, useEffect, useRef, useState } from 'react' diff --git a/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx b/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx index 79117be2416..50ba20b0691 100644 --- a/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx +++ b/src/renderer/src/components/feature-wall/BrowserUseSkillSetupCard.tsx @@ -1,5 +1,5 @@ import type { JSX } from 'react' -import { ORCA_CLI_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { ORCA_CLI_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { BROWSER_USE_ENABLED_STORAGE_KEY } from '@/lib/browser/browser-use-setup-state' import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills' import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' diff --git a/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx b/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx index 2e5dacb6e21..c75a4e6cde8 100644 --- a/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx +++ b/src/renderer/src/components/feature-wall/FeatureWallBrowserAction.tsx @@ -1,9 +1,9 @@ import { useBundledSkillInstallAction } from '@/hooks/use-bundled-skill-install-action' import { bundledSkillSetupActionLabel } from '../skills/setup/bundled-skill-setup-copy' -import { ORCA_CLI_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { ORCA_CLI_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { useOnboardingSkillRuntime } from '@/hooks/use-onboarding-skill-runtime' import { FeatureSetupInlineTerminal } from '../onboarding/FeatureSetupInlineTerminal' -import { buildAgentFeatureSkillInstallCommand } from '@/lib/agent-feature-install-commands' +import { buildAgentFeatureSkillInstallCommand } from '@/lib/skills/installation/agent-feature-install-commands' import { buildSkillCommandForRuntime } from '../../lib/skill-runtime-command' import type { OnboardingFeatureSetupRuntimeContext } from '../onboarding/onboarding-feature-setup-runtime' import { useCallback, useState } from 'react' diff --git a/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx b/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx index 587853da0a9..b4414b55fd4 100644 --- a/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx +++ b/src/renderer/src/components/feature-wall/OrchestrationSetupCard.tsx @@ -1,5 +1,5 @@ import type { JSX } from 'react' -import { ORCHESTRATION_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { ORCHESTRATION_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import type { InstalledAgentSkillState } from '@/hooks/useInstalledAgentSkills' import { useActiveProjectSkillRuntime } from '@/hooks/useActiveProjectSkillRuntime' import { AgentSkillSetupPanel } from '../skills/setup/AgentSkillSetupPanel' diff --git a/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts b/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts index 192f3010d2e..102ccf8ac71 100644 --- a/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts +++ b/src/renderer/src/components/feature-wall/agent-capability-setup-status.ts @@ -7,7 +7,7 @@ import { COMPUTER_USE_SKILL_NAME, ORCA_CLI_SKILL_NAME, ORCHESTRATION_SKILL_NAME -} from '@/lib/agent-feature-skill-names' +} from '@/lib/skills/installation/agent-feature-skill-names' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill diff --git a/src/renderer/src/components/feature-wall/agents-orchestration/StatusesPage.tsx b/src/renderer/src/components/feature-wall/agents-orchestration/StatusesPage.tsx index d5a4de1475b..2fa39d369e2 100644 --- a/src/renderer/src/components/feature-wall/agents-orchestration/StatusesPage.tsx +++ b/src/renderer/src/components/feature-wall/agents-orchestration/StatusesPage.tsx @@ -2,7 +2,8 @@ import { useEffect, useRef, useState } from 'react' import type { JSX, ReactNode } from 'react' import { Wrench } from 'lucide-react' import { AgentStateDot } from '@/components/AgentStateDot' -import { getAgentCatalog, AgentIcon, type AgentCatalogEntry } from '@/lib/agent-catalog' +import { getAgentCatalog, type AgentCatalogEntry } from '@/lib/agent-catalog/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { ClaudeIcon, OpenAIIcon } from '../../status-bar/icons' import { installWindowVisibilityInterval } from '@/lib/window-visibility-interval' import { cn } from '@/lib/utils' diff --git a/src/renderer/src/components/feature-wall/ai-commit-pr-settings-helpers.ts b/src/renderer/src/components/feature-wall/ai-commit-pr-settings-helpers.ts index 7a5f4046b7c..53e37a5f95d 100644 --- a/src/renderer/src/components/feature-wall/ai-commit-pr-settings-helpers.ts +++ b/src/renderer/src/components/feature-wall/ai-commit-pr-settings-helpers.ts @@ -8,7 +8,7 @@ import { type CommitMessageAgentChoice, type CommitMessageModelCapability } from '../../../../shared/source-control/ai/generation/commit-message-agent-spec' -import { getAgentCatalog } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' export const EMPTY_COMMIT_MESSAGE_AI_SETTINGS: CommitMessageAiSettings = { enabled: false, diff --git a/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts b/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts index 4545f81db62..1185bf0b6cf 100644 --- a/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts +++ b/src/renderer/src/components/feature-wall/use-feature-wall-tour-skills.ts @@ -1,4 +1,7 @@ -import { ORCA_CLI_SKILL_NAME, ORCHESTRATION_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { + ORCA_CLI_SKILL_NAME, + ORCHESTRATION_SKILL_NAME +} from '@/lib/skills/installation/agent-feature-skill-names' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill diff --git a/src/renderer/src/components/feature-wall/useAiCommitPrSettings.ts b/src/renderer/src/components/feature-wall/useAiCommitPrSettings.ts index 1ab62151757..719167987c6 100644 --- a/src/renderer/src/components/feature-wall/useAiCommitPrSettings.ts +++ b/src/renderer/src/components/feature-wall/useAiCommitPrSettings.ts @@ -11,7 +11,7 @@ import { LOCAL_COMMIT_MESSAGE_HOST_KEY } from '../../../../shared/source-control import { getDefaultSourceControlAiSettings } from '../../../../shared/source-control/ai/settings/source-control-ai-settings' import { getTextGenerationModels } from '../../../../shared/source-control/ai/settings/source-control-ai-model-selection' import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config' -import { getAgentCatalog } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' import { useAppStore } from '@/store/index' import type { AgentPickerDraft, diff --git a/src/renderer/src/components/file-actions/OpenInContextSubmenu.tsx b/src/renderer/src/components/file-actions/OpenInContextSubmenu.tsx index cec96cedec0..f9cf4e81ea4 100644 --- a/src/renderer/src/components/file-actions/OpenInContextSubmenu.tsx +++ b/src/renderer/src/components/file-actions/OpenInContextSubmenu.tsx @@ -11,7 +11,7 @@ import { } from '@/components/ui/context-menu' import { getRouteForLocalPathOpenOwner } from '@/lib/local-path-open-guard' import { OpenInApplicationIcon } from '@/lib/open-in-app-catalog' -import { getWorkspaceEditorSshHost } from '@/lib/workspace-editor-ssh-target' +import { getWorkspaceEditorSshHost } from '@/components/file-actions/workspace-editor-ssh-target' import { NO_OPEN_IN_APPLICATIONS } from '@/lib/open-in-application-selection' import type { ExecutionHostId } from '../../../../shared/execution-host' import type { OpenInApplication } from '../../../../shared/ui-chrome-types' diff --git a/src/renderer/src/lib/workspace-editor-ssh-target.ts b/src/renderer/src/components/file-actions/workspace-editor-ssh-target.ts similarity index 79% rename from src/renderer/src/lib/workspace-editor-ssh-target.ts rename to src/renderer/src/components/file-actions/workspace-editor-ssh-target.ts index ae77686c362..6b3136e2284 100644 --- a/src/renderer/src/lib/workspace-editor-ssh-target.ts +++ b/src/renderer/src/components/file-actions/workspace-editor-ssh-target.ts @@ -1,10 +1,10 @@ -import { isRuntimeOwnedSshTargetId } from '../../../shared/execution-host' +import { isRuntimeOwnedSshTargetId } from '../../../../shared/execution-host' import { getRuntimeSshAccess, type PublicKnownRuntimeEnvironment -} from '../../../shared/remote-runtime/host-catalog/runtime-environments' -import { resolveOwner, type WorkspaceOwnerRef } from './resolve-owner' -import type { WorktreeOperationRouteState } from './worktree-operation-route' +} from '../../../../shared/remote-runtime/host-catalog/runtime-environments' +import { resolveOwner, type WorkspaceOwnerRef } from '../../lib/workspace/ownership/resolve-owner' +import type { WorktreeOperationRouteState } from '../../lib/workspace/ownership/worktree-operation-route' type EditorSshTargetState = Omit & { runtimeEnvironments?: readonly Pick< diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx index 0140259f836..39bc18b48cf 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalOrchestrationDialog.tsx @@ -9,7 +9,7 @@ import { import { AgentSkillSetupPanel } from '@/components/skills/setup/AgentSkillSetupPanel' import { IntegrationStatusPill } from '@/components/integration-status-pill' import { SkillFreshnessStatusPill } from '@/components/skills/SkillFreshnessStatusPill' -import { ORCHESTRATION_SKILL_NAME } from '@/lib/agent-feature-skill-names' +import { ORCHESTRATION_SKILL_NAME } from '@/lib/skills/installation/agent-feature-skill-names' import { GLOBAL_AGENT_SKILL_SOURCE_KINDS, useInstalledAgentSkill diff --git a/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx b/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx index d31dda2e7ae..32d7b8bb2f7 100644 --- a/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx +++ b/src/renderer/src/components/floating-terminal/FloatingTerminalWindowControls.tsx @@ -2,7 +2,8 @@ import { useCallback, useMemo } from 'react' import { Maximize2, Minimize2, Minus } from 'lucide-react' import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { getAgentCatalog, AgentIcon } from '@/lib/agent-catalog' +import { getAgentCatalog } from '@/lib/agent-catalog/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' import { launchAgentInNewTab } from '@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab' import { newAgentLaunchRequestId } from '@/lib/agent-session/launch/routing/agent-launch-request-id' diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts index 2970d44d5d7..faa1c0de455 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-create-actions.ts @@ -1,8 +1,8 @@ import { useCallback } from 'react' import { toast } from 'sonner' import { resolveGroupTabFromVisibleId } from '@/components/tab-group/tab-group-visible-id' -import { getConnectionId } from '@/lib/connection-context' -import { createUntitledMarkdownFileWithTemplateSelection } from '@/lib/create-untitled-markdown' +import { getConnectionId } from '@/lib/workspace/ownership/connection-context' +import { createUntitledMarkdownFileWithTemplateSelection } from '@/lib/editor/file-operations/create-untitled-markdown' import { ensureClientCreationActionAllowed } from '@/lib/client-creation-action-error' import { openDocumentInFloatingWorkspace } from '@/lib/open-document-in-floating-workspace' import { extractIpcErrorMessage } from '@/lib/ipc-error' diff --git a/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts b/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts index fdfadb6fbc8..dd730267828 100644 --- a/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts +++ b/src/renderer/src/components/floating-terminal/use-floating-terminal-orchestration-visibility.ts @@ -1,5 +1,5 @@ import { useCallback, useEffect } from 'react' -import { isOrcaCliAvailableOnPath } from '@/lib/agent-skill-cli-prerequisite' +import { isOrcaCliAvailableOnPath } from '@/lib/skills/installation/agent-skill-cli-prerequisite' import { ORCHESTRATION_SETUP_STATE_EVENT, hasOrchestrationSetupMarker, diff --git a/src/renderer/src/components/github-project/ProjectCellIssueType.tsx b/src/renderer/src/components/github-project/ProjectCellIssueType.tsx index 6911e619c7a..ad0735c268e 100644 --- a/src/renderer/src/components/github-project/ProjectCellIssueType.tsx +++ b/src/renderer/src/components/github-project/ProjectCellIssueType.tsx @@ -4,7 +4,7 @@ import { useShallow } from 'zustand/react/shallow' import { CircleDot } from 'lucide-react' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { useRepoSlugIndex } from '@/lib/repo-slug-index' -import { runtimeTargetForRepoOwner } from '@/lib/repo-runtime-owner' +import { runtimeTargetForRepoOwner } from '@/lib/workspace/ownership/repo-runtime-owner' import { gitHubSlugApiForTarget } from '@/runtime/repository-github/github-slug-owner-api' import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' diff --git a/src/renderer/src/components/github/CommentCodeContext.tsx b/src/renderer/src/components/github/CommentCodeContext.tsx index 61a29502f2b..d667ffafbed 100644 --- a/src/renderer/src/components/github/CommentCodeContext.tsx +++ b/src/renderer/src/components/github/CommentCodeContext.tsx @@ -4,7 +4,7 @@ import { ArrowDown, ArrowUp, Braces, LoaderCircle, UndoDot } from 'lucide-react' import { Button } from '@/components/ui/button' import { ButtonGroup } from '@/components/ui/button-group' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' -import { detectLanguage } from '@/lib/language-detect' +import { detectLanguage } from '../../../../shared/editor-language/editor-language-detect' import { cn } from '@/lib/utils' import { useTranslate } from '@/i18n/use-translate' import { diff --git a/src/renderer/src/components/github/github-work-item-mutation-target.ts b/src/renderer/src/components/github/github-work-item-mutation-target.ts index 8c4cb46f50e..dd908bd4d5b 100644 --- a/src/renderer/src/components/github/github-work-item-mutation-target.ts +++ b/src/renderer/src/components/github/github-work-item-mutation-target.ts @@ -1,6 +1,6 @@ import { useAppStore } from '@/store' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' -import { isTwinRepo, runtimeTargetForRepoOwner } from '@/lib/repo-runtime-owner' +import { isTwinRepo, runtimeTargetForRepoOwner } from '@/lib/workspace/ownership/repo-runtime-owner' import { projectViewCacheKeyTarget } from '@/store/github/cache/cache-identity' import type { GitHubWorkItemProjectOrigin } from './github-work-item-identity' diff --git a/src/renderer/src/components/jira-user-picker.tsx b/src/renderer/src/components/jira-user-picker.tsx index 995a640598e..49b74c6050f 100644 --- a/src/renderer/src/components/jira-user-picker.tsx +++ b/src/renderer/src/components/jira-user-picker.tsx @@ -4,7 +4,7 @@ import { LoaderCircle } from 'lucide-react' import { Input } from '@/components/ui/input' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { jiraSearchUsers } from '@/runtime/jira/runtime-jira-user-fields-client' -import type { RowLessSource as RuntimeJiraSettings } from '@/lib/default-creation-host' +import type { RowLessSource as RuntimeJiraSettings } from '@/runtime/hosts/selection/default-creation-host' import { useTranslate } from '@/i18n/use-translate' import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision' import type { JiraUser } from '../../../shared/jira/jira-types' diff --git a/src/renderer/src/components/linear-api-key-dialog.tsx b/src/renderer/src/components/linear-api-key-dialog.tsx index 6e00a7947bc..ef8c99daa83 100644 --- a/src/renderer/src/components/linear-api-key-dialog.tsx +++ b/src/renderer/src/components/linear-api-key-dialog.tsx @@ -6,7 +6,7 @@ import { buildLinearPersonalApiKeySettingsUrl, buildLinearWorkspaceApiSettingsUrl } from '../../../shared/linear/links' -import { defaultScopeHost } from '@/lib/default-creation-host' +import { defaultScopeHost } from '@/runtime/hosts/selection/default-creation-host' import { useAppStore } from '@/store' import { useMountedRef } from '@/hooks/useMountedRef' import { Button } from '@/components/ui/button' diff --git a/src/renderer/src/components/linear-issue-attribute-filter-dropdowns.tsx b/src/renderer/src/components/linear-issue-attribute-filter-dropdowns.tsx index 78d7c09ffbd..743e341a18e 100644 --- a/src/renderer/src/components/linear-issue-attribute-filter-dropdowns.tsx +++ b/src/renderer/src/components/linear-issue-attribute-filter-dropdowns.tsx @@ -4,7 +4,7 @@ import { Button } from '@/components/ui/button' import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTeamsLabels, useTeamsMembers, useTeamsStates } from '@/hooks/useIssueMetadata' -import type { RowLessSource as RuntimeLinearSettings } from '@/lib/default-creation-host' +import type { RowLessSource as RuntimeLinearSettings } from '@/runtime/hosts/selection/default-creation-host' import { useTranslate } from '@/i18n/use-translate' import { LINEAR_ISSUE_ATTRIBUTE_FILTER_MAX_LABEL_IDS, diff --git a/src/renderer/src/components/linear-issue-project-selector.tsx b/src/renderer/src/components/linear-issue-project-selector.tsx index 79d4d397260..e84cad7264c 100644 --- a/src/renderer/src/components/linear-issue-project-selector.tsx +++ b/src/renderer/src/components/linear-issue-project-selector.tsx @@ -16,7 +16,7 @@ import { useAppStore } from '@/store' import type { LinearIssue } from '../../../shared/linear/issue-types' import type { LinearProjectSummary } from '../../../shared/linear/project-types' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' -import { defaultScopeSource } from '@/lib/default-creation-host' +import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' export function LinearIssueProjectSelector({ issue, diff --git a/src/renderer/src/components/linear-issue-sub-issues.tsx b/src/renderer/src/components/linear-issue-sub-issues.tsx index b49c80b32c3..66b421c8d86 100644 --- a/src/renderer/src/components/linear-issue-sub-issues.tsx +++ b/src/renderer/src/components/linear-issue-sub-issues.tsx @@ -14,7 +14,7 @@ import { linearCreateSubIssue } from '@/runtime/linear/runtime-linear-issue-clie import { useAppStore } from '@/store' import type { LinearIssue, LinearIssueChildSummary } from '../../../shared/linear/issue-types' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' -import { defaultScopeSource } from '@/lib/default-creation-host' +import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' function mergeLinearSubIssues( serverSubIssues: LinearIssueChildSummary[] | undefined, diff --git a/src/renderer/src/components/linear-issue-workspace-detail-state.ts b/src/renderer/src/components/linear-issue-workspace-detail-state.ts index f8a1dd67433..da7cf56d45e 100644 --- a/src/renderer/src/components/linear-issue-workspace-detail-state.ts +++ b/src/renderer/src/components/linear-issue-workspace-detail-state.ts @@ -9,7 +9,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { createNonSecureContextUuid as createBrowserUuid } from '../../../shared/non-secure-context-uuid' import { useMountedRef } from '@/hooks/useMountedRef' import { linearIssueComments } from '@/runtime/linear/runtime-linear-issue-client' -import type { RowLessSource as RuntimeLinearSettings } from '@/lib/default-creation-host' +import type { RowLessSource as RuntimeLinearSettings } from '@/runtime/hosts/selection/default-creation-host' import { initLinearIssueEditState, type LinearEditState, diff --git a/src/renderer/src/components/linear-item-drawer-comment-footer.tsx b/src/renderer/src/components/linear-item-drawer-comment-footer.tsx index d94ceda127f..17c2bb85662 100644 --- a/src/renderer/src/components/linear-item-drawer-comment-footer.tsx +++ b/src/renderer/src/components/linear-item-drawer-comment-footer.tsx @@ -17,7 +17,7 @@ import { translate } from '@/i18n/i18n' import { useTranslate } from '@/i18n/use-translate' import type { TaskSourceContext } from '../../../shared/work-items/task-source-context' import type { LinearLocalComment } from '@/components/linear-item-drawer-types' -import { defaultScopeSource } from '@/lib/default-creation-host' +import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' export function LinearIssueCommentFooter({ issueId, diff --git a/src/renderer/src/components/linear-item-drawer-edit-controller.tsx b/src/renderer/src/components/linear-item-drawer-edit-controller.tsx index 4e3dd0cdd64..2b748d5d479 100644 --- a/src/renderer/src/components/linear-item-drawer-edit-controller.tsx +++ b/src/renderer/src/components/linear-item-drawer-edit-controller.tsx @@ -15,7 +15,7 @@ import { linearUpdateIssue } from '@/runtime/linear/runtime-linear-issue-client' import { translate } from '@/i18n/i18n' import { formatLinearEstimateInput } from '@/components/linear-item-drawer-edit-controls' import type { LinearIssueEditSectionProps } from '@/components/linear-item-drawer-types' -import { defaultScopeSource } from '@/lib/default-creation-host' +import { defaultScopeSource } from '@/runtime/hosts/selection/default-creation-host' export function useLinearIssueEditController({ issue, diff --git a/src/renderer/src/components/managed-runtime/ManagedRuntimeRemoveDialog.tsx b/src/renderer/src/components/managed-runtime/ManagedRuntimeRemoveDialog.tsx index 4ca2458fe2a..d4e10e189e8 100644 --- a/src/renderer/src/components/managed-runtime/ManagedRuntimeRemoveDialog.tsx +++ b/src/renderer/src/components/managed-runtime/ManagedRuntimeRemoveDialog.tsx @@ -1,6 +1,6 @@ import { useAppStateValue } from '@/store/retained-views/app-state-view' import { useTranslate } from '@/i18n/use-translate' -import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' +import { selectExecutionHostDisplayLabel } from '@/runtime/hosts/display/execution-host-display-label' import { toRuntimeExecutionHostId } from '../../../../shared/execution-host' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import { Button } from '../ui/button' diff --git a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx index b8714c4e801..c4fc8c4b958 100644 --- a/src/renderer/src/components/native-chat/NativeChatMessageList.tsx +++ b/src/renderer/src/components/native-chat/NativeChatMessageList.tsx @@ -4,13 +4,14 @@ import { NATIVE_CHAT_TRANSCRIPT_COLUMN_CLASS } from './appearance/native-chat-appearance-style' import { NativeChatJumpToLatest } from './viewport/scroll/NativeChatJumpToLatest' +import { NativeChatNewRowsAnnouncement } from './viewport/new-rows/NativeChatNewRowsMarker' +import { useNativeChatNewRowsMarker } from './viewport/new-rows/native-chat-new-rows-marker' import { withoutPullRequestEventRows } from '../../../../shared/native-chat/native-chat-pull-request-event' import { useNativeChatRowTypography } from './viewport/virtualization/use-native-chat-row-typography' import { useCallback, useMemo, useRef, useState } from 'react' import { useTranslate } from '@/i18n/use-translate' import { useAppStore } from '@/store' import { - nativeChatScrollsToLatestOnSend, nativeChatShowsCiResultLines, nativeChatShowsTurnDiffSummary } from '../../../../shared/native-chat/native-chat-appearance-settings' @@ -124,10 +125,10 @@ export function NativeChatMessageList({ runtimeContext?: RuntimeFileOperationArgs | null }): React.JSX.Element { const t = useTranslate() + const questionTranscript = useMemo(() => desktopStructuredTranscript.stream(), []) const receipts = useMemo( - () => - journalItems ? desktopStructuredTranscript.transcript(journalItems).receipts : new Map(), - [journalItems] + () => (journalItems ? questionTranscript(journalItems).receipts : new Map()), + [journalItems, questionTranscript] ) const scrollRef = useRef(null) const contentRef = useRef(null) @@ -243,12 +244,18 @@ export function NativeChatMessageList({ [allSlots, journalItems, stopping, journalSubmissions, latestTurn, hostWork] ) const navigationRequest = useNativeChatNavigationRequest(slots, messages, subagentSections) + const newRows = useNativeChatNewRowsMarker( + slots, + waitingSlots, + isVisible && session.readCurrent === true + ) const transcriptWindow = useNativeChatTranscriptWindow({ scrollRef, slots, isVisible, // Rail jumps, diff reveals and subagent reveals share one mutually exclusive pin. revealIndex: navigationRequest.revealIndex, + newRowsMarkerIndex: newRows.index, typography }) const transcriptScroll = useNativeChatTranscriptScroll({ @@ -326,25 +333,15 @@ export function NativeChatMessageList({ onLeaveEnd: readerLeavesEnd, onScrollGesture: transcriptScroll.forwardedGesture }) - // Off keeps a reader who scrolled up in place; one at the end still follows the reply. - const revealSent = useCallback( - (readerWasAtEnd = readerAtEnd()) => { - if (!nativeChatScrollsToLatestOnSend(useAppStore.getState().settings) && !readerWasAtEnd) { - return - } - beginNavigation() - scrollToBottom('send') - }, - [beginNavigation, readerAtEnd, scrollToBottom] - ) - useNativeChatMessageListHandle( - ref, - revealSent, - readerInput.revealFindMatch, - allSlots, + useNativeChatMessageListHandle(ref, { readerAtEnd, - navigation.revealSubagent - ) + beginNavigation, + scrollToBottom, + onSent: newRows.dismiss, + revealFindMatch: readerInput.revealFindMatch, + slots: allSlots, + revealSubagent: navigation.revealSubagent + }) const rowContext = useNativeChatTranscriptRowContext({ agent: session.agent, @@ -397,6 +394,7 @@ export function NativeChatMessageList({ loadedMessageIds={loadedMessageIds} context={rowContext} window={transcriptWindow} + newRowsMarker={newRows.marker} forwardGesture={readerInput.forwardedGesture} /> {liveLine ? ( @@ -417,6 +415,7 @@ export function NativeChatMessageList({ pendingId={navigation.pendingRailId} /> + diff --git a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts index 5513a7df51c..87f861438a3 100644 --- a/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts +++ b/src/renderer/src/components/native-chat/appearance/native-chat-appearance-style.ts @@ -7,7 +7,7 @@ import { resolveConfiguredTerminalColors } from '../../../../../shared/terminal- import { MATCH_TERMINAL_APP_THEME } from '../../../../../shared/plugin-theme-settings' import { buildFontFamily } from '@/lib/monospace-font-family' import { buildAppFontFamily } from '@/lib/app-font-family' -import { resolveEditorFontStack } from '@/lib/editor-typography' +import { resolveEditorFontStack } from '@/lib/editor/appearance/editor-typography' import { getSystemPrefersDark } from '@/lib/terminal-theme' import { isTerminalBackgroundLight } from '../../../../../shared/terminal-themes/terminal-title-contrast' import { useSystemPrefersDark } from '../../../hooks/theme/use-system-prefers-dark' diff --git a/src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx b/src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx index ace229b0897..6be4e226b0c 100644 --- a/src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx @@ -17,7 +17,7 @@ vi.mock('@/i18n/i18n', () => ({ fallback.replace(/\{\{(\w+)\}\}/g, (_match, name: string) => options?.[name] ?? '') })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: mocks.getConnectionIdForFile })) diff --git a/src/renderer/src/components/native-chat/attachments/chips/native-chat-image-references.test.tsx b/src/renderer/src/components/native-chat/attachments/chips/native-chat-image-references.test.tsx index 34c3b2bc7ac..f9db36dcad0 100644 --- a/src/renderer/src/components/native-chat/attachments/chips/native-chat-image-references.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/chips/native-chat-image-references.test.tsx @@ -199,17 +199,6 @@ describe('composer image chips', () => { expect(promptValue(composer.textbox())).toBe(`look ${chip('missing')}`) }) - it('leaves a file path that reads like a marker as typed when a message comes back', () => { - const scope = structuredAgentSessionDraftScopeKey('s1') - const file = formatNativeChatFileReference('/repo/[Image #1].md') - handBackStructuredAgentSessionMessage( - 's1', - 'm1', - message(`see ${file} and [Image #1]`, ['/up/a.png']) - ) - expect(readNativeChatComposerDraft(scope).text).toBe(`see ${file} and ${chip('returned-m1-1')}`) - }) - it('keeps a stored draft’s file reference when a message comes back', async () => { const scope = structuredAgentSessionDraftScopeKey('s1') const composer = renderComposer(scope) @@ -224,22 +213,6 @@ describe('composer image chips', () => { await waitFor(() => expect(back.chips()).toEqual(['Image #1'])) }) - it('adds a returned message once even after typing, by its image ids', () => { - const scope = structuredAgentSessionDraftScopeKey('s1') - const returned = message('see [Image #1]', ['/up/a.png']) - handBackStructuredAgentSessionMessage('s1', 'm1', returned) - updateNativeChatComposerDraft( - scope, - { text: `${readNativeChatComposerDraft(scope).text} and more` }, - 'immediate' - ) - handBackStructuredAgentSessionMessage('s1', 'm1', returned) - expect(readNativeChatComposerDraft(scope)).toMatchObject({ - text: `see ${chip('returned-m1-1')} and more`, - images: [{ id: 'returned-m1-1' }] - }) - }) - it('settles a late upload into its own conversation, bound by the same id, while another is shown', async () => { updateNativeChatComposerDraft('chat-b', { text: 'B draft' }, 'immediate') const composer = renderComposer('chat-a') diff --git a/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.test.tsx b/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.test.tsx index c297c00bcf0..313dcf03174 100644 --- a/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.test.tsx @@ -57,30 +57,6 @@ vi.mock( }) ) -function publishUnrelatedStatuses(): void { - for (let tick = 1; tick <= 24; tick += 1) { - useAppStore.setState((state) => ({ - runtimeStatusByEnvironmentId: new Map(state.runtimeStatusByEnvironmentId).set('other-host', { - status: null, - checkedAt: tick - }) - })) - useAppStore.setState((state) => ({ - agentStatusByPaneKey: { - ...state.agentStatusByPaneKey, - 'other-tab:other-pane': { - paneKey: 'other-tab:other-pane', - state: 'working', - prompt: 'background work', - updatedAt: tick, - stateStartedAt: 1, - stateHistory: [] - } - } - })) - } -} - describe('useNativeChatComposerAttachments', () => { afterEach(() => { useAppStore.setState(initialStoreState, true) @@ -100,17 +76,15 @@ describe('useNativeChatComposerAttachments', () => { storage.drafts.set(scope, { text: '', images: [image], owner: storedOwner, savedAt: 1 }) draftStorage.setNativeChatComposerDraftStorageForTests(storage) publishOwner(scope, storedOwner) - const resolveOwner = vi.fn((key: string) => + draftStoreOwner1.setNativeChatComposerDraftOwnerResolver((key) => resolveNativeChatDraftOwner(useAppStore.getState(), key) ) - draftStoreOwner1.setNativeChatComposerDraftOwnerResolver(resolveOwner) const old = Promise.withResolvers() const next = Promise.withResolvers() const pathExists = vi.fn().mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise) const originalApi = window.api Object.assign(window, { api: { fs: { pathExists } } }) let probe: Awaited> | undefined - const originalState = useAppStore.getState() try { await draftStoreOwner2.hydrateNativeChatComposerDrafts() probe = await renderProbe(scope, true) @@ -130,15 +104,8 @@ describe('useNativeChatComposerAttachments', () => { { id: image.id, path: '', unavailableName: 'shot.png' } ]) expect(draftStoreOwner3.readNativeChatComposerDraft(scope).owner).toEqual(storedOwner) - resolveOwner.mockClear() - act(publishUnrelatedStatuses) - expect(resolveOwner).not.toHaveBeenCalled() } finally { act(() => probe?.root.unmount()) - useAppStore.setState({ - runtimeStatusByEnvironmentId: originalState.runtimeStatusByEnvironmentId, - agentStatusByPaneKey: originalState.agentStatusByPaneKey - }) Object.assign(window, { api: originalApi }) } }) diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx index 4f618061b30..323d9b7bcf3 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx @@ -162,13 +162,4 @@ describe('element-owned native chat drops', () => { expect(prepare).toHaveBeenCalledOnce() expect(electron.send).not.toHaveBeenCalled() }) - it('attaches hybrid Files and HTML without inserting HTML into the real editor', async () => { - const attach = vi.fn() - const view = render() - const editor = view.container.querySelector('.ProseMirror')! - await drop(editor, ['Files', 'text/html']) - expect(attach).toHaveBeenCalledExactlyOnceWith(['/drop/a.png']) - expect(editor.textContent).toBe('Original') - expect(editor.querySelector('b')).toBeNull() - }) }) diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx index 22fe9c6dbf9..26eb4bafff8 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx @@ -254,34 +254,6 @@ describe('OS attachment destination through input-method composition', () => { } ) - it.each([true, false])( - 'uses current image support when queued with acceptsImages=%s', - async (acceptsImages) => { - const path = '/local/image.png' - await render('workspace-1', acceptsImages) - await act(async () => latest().attachExternalPaths([path])) - expect(mocks.stat).toHaveBeenCalledOnce() - expect(nativeChatPendingAttachmentSnapshot('drop-test')).toHaveLength(1) - expect(latest().imageAttachments.every(({ pending }) => pending)).toBe(true) - expect(container.querySelector('[data-draft]')?.textContent).toBe('') - - const currentAcceptsImages = !acceptsImages - await render('workspace-1', currentAcceptsImages) - composing = false - act(() => latest().flushPendingAttachments()) - act(() => latest().flushPendingAttachments()) - - expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) - expect(latest().imageAttachments.map(({ path }) => path)).toEqual( - currentAcceptsImages ? [path] : [] - ) - expect(nativeChatImagesHoldSend(latest().imageAttachments)).toBe(false) - expect(container.querySelector('[data-draft]')?.textContent).toBe( - currentAcceptsImages ? '' : `@${path} ` - ) - } - ) - it('reserves before stat and settles the captured scope across removal, failure and remount', async () => { let finish = (): void => {} mocks.stat @@ -323,9 +295,6 @@ describe('OS attachment destination through input-method composition', () => { throw new Error('Missing reserved chip') } act(() => latest().removeImageAttachment(removed.id)) - const other = document.createElement('input') - document.body.append(other) - other.focus() act(() => root.unmount()) expect(nativeChatPendingAttachmentSnapshot('drop-test')).toEqual([]) expect(readNativeChatDraftCache('drop-test')).toBe('@/notes.txt') @@ -333,9 +302,6 @@ describe('OS attachment destination through input-method composition', () => { await render('workspace-1') expect(latest().imageAttachments).toMatchObject([{ path: '/a.png' }]) expect(latest().imageAttachments).toHaveLength(1) - await new Promise((resolve) => requestAnimationFrame(resolve)) - expect(document.activeElement).toBe(other) - other.remove() }) it('releases refused and disabled work, including stat spanning disable and re-enable', async () => { diff --git a/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx index 8328dcb1f8a..78b1fdc9376 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx @@ -2,8 +2,8 @@ import type * as AttachmentOwnerModule from '../uploads/native-chat-attachment-owner' import { useState } from 'react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render } from '@testing-library/react' import { WORKSPACE_FILE_PATH_MIME } from '@/lib/workspace-file-drag' import { @@ -18,9 +18,6 @@ vi.mock('../uploads/native-chat-attachment-owner', async (original) => ({ resolveNativeChatAttachmentOwnerForWorktree: () => ({ kind: 'local' }) })) -const OVERLAY = '[data-native-chat-drop-overlay="true"]' -const IGNORE_DRAG = (): void => {} - class DropDataTransfer { dropEffect = 'none' effectAllowed = 'all' @@ -42,43 +39,6 @@ function workspaceDrag(): DropDataTransfer { return transfer } -function osDrag(): DropDataTransfer { - const transfer = new DropDataTransfer() - transfer.setData('Files', '') - return transfer -} - -function ClaimingComposer({ - disabled = false, - onDragOverCapture = IGNORE_DRAG, - onDropCapture = IGNORE_DRAG -}: { - disabled?: boolean - onDragOverCapture?: (event: React.DragEvent) => void - onDropCapture?: (event: React.DragEvent) => void -}) { - useNativeChatPaneFileDropClaim({ - destinationKey: 'pane:1', - captureExternalDrop: () => async () => {}, - disabled, - onDragOverCapture, - onDropCapture - }) - return
-} - -function renderPane(composer: React.ReactNode) { - const result = render( -
- -
transcript
- {composer} -
-
- ) - return { ...result, transcript: screen.getByTestId('transcript') } -} - function fireDrag( target: HTMLElement, type: 'dragenter' | 'dragover' | 'dragleave' | 'drop', @@ -95,23 +55,6 @@ function fireDrag( afterEach(cleanup) -describe('NativeChatPaneFileDropSurface', () => { - it('observes a native drop that ends before the hover render commits', () => { - const consumeDrop = (event: Event): void => event.stopPropagation() - document.addEventListener('drop', consumeDrop, true) - try { - const { transcript, container } = renderPane() - act(() => { - fireDrag(transcript, 'dragover', osDrag()) - fireDrag(transcript, 'drop', osDrag()) - }) - expect(container.querySelector(OVERLAY)).toBeNull() - } finally { - document.removeEventListener('drop', consumeDrop, true) - } - }) -}) - it('direct drops override last focus; background keeps stable focus through disable and remount, with questions independent', () => { function Composer({ scope, disabled = false }: { scope: string; disabled?: boolean }) { const [value, setValue] = useState('') diff --git a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx index 53fa10fd7cc..68555b64dfb 100644 --- a/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx +++ b/src/renderer/src/components/native-chat/attachments/intake/use-native-chat-external-attachments.test.tsx @@ -43,8 +43,6 @@ vi.mock('../uploads/native-chat-session-attachment-upload', async (importOrigina import { useNativeChatExternalAttachments } from './use-native-chat-external-attachments' import type { NativeChatPendingAttachmentChips } from './native-chat-session-attachment-drop' -import type { AgentSessionAttachmentPathUploadResult } from '../../../../../../shared/agent-session/agent-session-attachments' -import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' import type { NativeChatStructuredAttachmentSession } from '../uploads/native-chat-attachment-owner' type HookApi = ReturnType @@ -98,9 +96,6 @@ function Probe({ return null } -// One past NATIVE_FILE_DROP_MAX_PATHS. -const pathsOverDropLimit = Array.from({ length: 257 }, (_, index) => `/external/${index}.png`) - let root: Root | null = null async function renderProbe(args: { @@ -170,39 +165,6 @@ afterEach(() => { }) describe('useNativeChatExternalAttachments', () => { - it('rejects a whole batch over the drop path limit, like a drop does', async () => { - mocks.resolveNativeChatAttachmentOwner.mockReturnValue({ kind: 'local' }) - const attachResolvedPaths = vi.fn() - const setNotice = vi.fn() - const probe = await renderProbe({ attachResolvedPaths, setNotice }) - await act(async () => { - probe.latest().attachExternalPaths(pathsOverDropLimit) - }) - expect(setNotice).toHaveBeenCalledExactlyOnceWith('Attach 256 or fewer files at a time.') - expect(mocks.stat).not.toHaveBeenCalled() - expect(attachResolvedPaths).not.toHaveBeenCalled() - }) - - it('waits for the local file check and skips rejected paths without blocking other files', async () => { - mocks.resolveNativeChatAttachmentOwner.mockReturnValue({ kind: 'local' }) - const fileCheck = deferred() - mocks.stat.mockReturnValueOnce(fileCheck.promise).mockRejectedValueOnce(new Error('denied')) - const attachResolvedPaths = vi.fn() - const probe = await renderProbe({ attachResolvedPaths }) - act(() => - probe.latest().attachExternalPaths(['/external/a.png', '/external/b.png', '/external/c.png']) - ) - expect(attachResolvedPaths).not.toHaveBeenCalled() - expect(mocks.stat).toHaveBeenCalledTimes(1) - await act(async () => fileCheck.resolve()) - expect(attachResolvedPaths).toHaveBeenCalledExactlyOnceWith( - ['/external/a.png', '/external/c.png'], - undefined, - { destinationIsCurrent: expect.any(Function), operation: expect.any(Object) } - ) - expect(mocks.stat).toHaveBeenCalledTimes(3) - }) - // Recheck after the final path too; otherwise a one-file drop can attach after its host owner changes. it('reports a one-file drop whose owner changes during its file check', async () => { const fileCheck = deferred() @@ -267,103 +229,4 @@ describe('useNativeChatExternalAttachments', () => { expect(takeBrowserAttachmentFile(token!)).toBeNull() }) - - describe('a structured chat on a paired server', () => { - const session = { sessionId: 'session-1', runtimeEnvironmentId: 'env-1' } - const target = { - environmentId: 'env-1', - sessionId: 'session-1', - expectedEnvironmentPairingRevision: 7, - expectedEnvironmentRuntimeId: 'runtime-a' - } - - function trackingChips(): NativeChatPendingAttachmentChips & { - begun: string[] - removed: Set - } { - const begun: string[] = [] - const removed = new Set() - return { - begun, - removed, - begin: vi.fn((_preview?: string, name?: string) => { - begun.push(name ?? '') - return `chip-${begun.length}` - }), - resolve: vi.fn(() => true), - drop: vi.fn((id: string) => !removed.has(id)), - attachReferences: vi.fn(() => true) - } - } - - function uploaded( - pairs: [sourcePath: string, path: string][], - failed: string[] = [] - ): AgentSessionAttachmentPathUploadResult { - return { - uploaded: pairs.map(([sourcePath, path]) => ({ sourcePath, path })), - skipped: [], - failed: failed.map((sourcePath) => ({ - sourcePath, - reason: `'${sourcePath.split('/').at(-1)}' is 60 MB, over the 50 MB chat attachment limit` - })) - } - } - - beforeEach(() => { - replaceRuntimeEnvironmentRevisions([{ id: 'env-1', createdAt: 1, pairingRevision: 7 }]) - mocks.prepareNativeChatSessionAttachmentUpload.mockReset().mockResolvedValue({ - ok: true, - target - }) - mocks.uploadNativeChatSessionAttachmentPaths.mockReset() - }) - - it('discards uploaded files if the captured drop destination changed during upload', async () => { - const upload = deferred() - mocks.uploadNativeChatSessionAttachmentPaths.mockReturnValueOnce(upload.promise) - const chips = trackingChips() - const probe = await renderProbe({ - structuredWorktreeId: 'worktree-1', - structuredSession: session, - attachResolvedPaths: vi.fn(), - pendingChips: chips - }) - let current = true - const deliver = probe.latest().captureExternalDrop(() => current) - act(() => void deliver(['/Users/me/notes.md'])) - current = false - await act(async () => - upload.resolve( - uploaded([['/Users/me/notes.md', '/srv/agent-session-attachments/u1/notes.md']]) - ) - ) - expect(chips.drop).toHaveBeenCalledExactlyOnceWith('chip-1') - expect(chips.attachReferences).not.toHaveBeenCalled() - }) - - it('settles an upload into its captured chips while a prompt card unmounts the composer', async () => { - const upload = deferred() - mocks.uploadNativeChatSessionAttachmentPaths.mockReturnValueOnce(upload.promise) - const chips = trackingChips() - const probe = await renderProbe({ - structuredWorktreeId: 'worktree-1', - structuredSession: session, - attachResolvedPaths: vi.fn(), - pendingChips: chips - }) - act(() => void probe.latest().captureExternalDrop(() => true)(['/Users/me/notes.md'])) - act(() => root?.unmount()) - root = null - await act(async () => - upload.resolve( - uploaded([['/Users/me/notes.md', '/srv/agent-session-attachments/u1/notes.md']]) - ) - ) - expect(chips.attachReferences).toHaveBeenCalledExactlyOnceWith( - [{ id: 'chip-1', path: '/srv/agent-session-attachments/u1/notes.md' }], - undefined - ) - }) - }) }) diff --git a/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts b/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts index 8fac4e5ef99..bd841d66836 100644 --- a/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts +++ b/src/renderer/src/components/native-chat/attachments/uploads/native-chat-attachment-owner.ts @@ -3,8 +3,8 @@ import { chatWorkspaceByTabId as findTerminalTabWorktreeId } from '../../../../l import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' import { getKnownExecutionHostIdForWorktree } from '../../../../lib/workspace/ownership/worktree-runtime-owner' -import { runtimeEnvironmentIdForWorkspaceOwner } from '../../../../lib/resolve-owner' -import { getConnectionIdFromState } from '../../../../lib/connection-owner-resolution' +import { runtimeEnvironmentIdForWorkspaceOwner } from '../../../../lib/workspace/ownership/resolve-owner' +import { getConnectionIdFromState } from '../../../../lib/workspace/ownership/connection-owner-resolution' import { type ExecutionHostId, toRuntimeExecutionHostId, diff --git a/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts b/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts index f381832be04..c0c904f9ad1 100644 --- a/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts +++ b/src/renderer/src/components/native-chat/composer/controls/native-chat-composer-workspace.ts @@ -1,6 +1,6 @@ import type { AppState } from '@/store/types' import { workspaceTabs } from '@/lib/structured-chat-tab-index' -import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' +import { selectExecutionHostDisplayLabel } from '@/runtime/hosts/display/execution-host-display-label' import { findIndexedRepoOwnerForHost } from '@/lib/workspace/ownership/repo-owner-index' import { getWslDistroFromPath } from '@/lib/local-preflight-context' import { selectWslHostDistro } from '@/components/wsl-host-mark/WslHostMark' diff --git a/src/renderer/src/components/native-chat/composer/editor/NativeChatFileReferencePill.tsx b/src/renderer/src/components/native-chat/composer/editor/NativeChatFileReferencePill.tsx index c6e880390b2..870d72f681f 100644 --- a/src/renderer/src/components/native-chat/composer/editor/NativeChatFileReferencePill.tsx +++ b/src/renderer/src/components/native-chat/composer/editor/NativeChatFileReferencePill.tsx @@ -9,7 +9,7 @@ import { NodeViewWrapper, type NodeViewProps } from '@tiptap/react' import { FileX, Hourglass } from 'lucide-react' import { useTranslate } from '@/i18n/use-translate' import { basename } from '@/lib/path' -import { getFileTypeIcon } from '@/lib/file-type-icons' +import { getFileTypeIcon } from '@/lib/file-icons/file-type-icons' import { NativeChatPromptPill } from './NativeChatPromptPill' import { isNativeChatPastedTextPath } from '../../../../../../shared/native-chat/native-chat-image-label' import { diff --git a/src/renderer/src/components/native-chat/composer/editor/inline-rich-draft-consumers.test.tsx b/src/renderer/src/components/native-chat/composer/editor/inline-rich-draft-consumers.test.tsx index fa1ef624ae0..696d62e5a97 100644 --- a/src/renderer/src/components/native-chat/composer/editor/inline-rich-draft-consumers.test.tsx +++ b/src/renderer/src/components/native-chat/composer/editor/inline-rich-draft-consumers.test.tsx @@ -23,10 +23,6 @@ import { setNativeChatComposerDraftStorageForTests, type StoredNativeChatComposerDraft } from '../../drafts/native-chat-composer-draft-storage' -import { - replayNativeChatComposerDraftJournal, - snapshotNativeChatComposerDraftJournal -} from '../../drafts/native-chat-composer-draft-journal' import { resolveNativeChatPastedText } from '../../paste/native-chat-composer-pasted-text-references' import { nativeChatPastedTextToken } from '../../paste/native-chat-pasted-text-reference' import { @@ -163,60 +159,6 @@ it('keeps a rich return through an actual composing editor transaction and next expect(nextSend().skills).toEqual([{ name: 'review', path: '/returned/SKILL.md' }]) }) -it('replays a full rich addition into existing content, renders it and sends resolved files/images/skills', () => { - const edit = returned() - const paste = 'd851d135-98ac-44d1-b122-caf190002345' - const draft = readNativeChatComposerDraft(edit.scopeKey) - updateNativeChatComposerDraft( - edit.scopeKey, - { - text: `${draft.text}\n${nativeChatPastedTextToken(paste)}`, - document: { - ...draft.document, - content: [ - ...(draft.document?.content ?? []), - { - type: 'paragraph', - content: [ - { - type: 'nativeChatFileReference', - attrs: { token: nativeChatPastedTextToken(paste), path: '' } - } - ] - } - ] - }, - pastedTextFiles: { [paste]: '/remote/paste.txt' }, - images: [{ id: 'new', path: '/new.png' }] - }, - 'immediate' - ) - handBackNativeChatQueuedEdit(edit) - discardNativeChatQueuedEdit(edit) - // Simulate another renderer run reading the actual addition journal before storage confirmation. - const raw = localStorage.getItem('orca:nativeChatComposerDraftJournal:v1')! - localStorage.setItem( - 'orca:nativeChatComposerDraftJournal:v1', - raw.replaceAll(/"run":"[^"]+"/g, '"run":"previous-run"') - ) - const loaded = new Map([ - [scope, { text: 'existing', images: [], savedAt: 0 }] - ]) - replayNativeChatComposerDraftJournal(loaded, snapshotNativeChatComposerDraftJournal()) - updateNativeChatComposerDraft(scope, loaded.get(scope)!, 'immediate') - render() - expect(promptSkillRefs(promptEditor(screen.getByRole('textbox')).getJSON())).toEqual([ - { name: 'review', path: '/returned/SKILL.md' } - ]) - expect(nextSend()).toMatchObject({ - blocks: [ - { type: 'text', text: expect.stringContaining('@/remote/paste.txt') }, - { type: 'image-ref', path: '/new.png' } - ], - skills: [{ name: 'review', path: '/returned/SKILL.md' }] - }) -}) - // Joined replacement boundary: real edit owner, picker, mounted rich editor and wire serializer. const leaseRpc = vi.hoisted(() => vi.fn( @@ -563,7 +505,7 @@ it.each(['mounted', 'success', 'unmounted', 'ime', 'cancel'] as const)( act(() => bottom.view.dispatch(bottom.state.tr.insertText('가', bottom.state.doc.content.size - 1)) ) - expect(nextSend().blocks).toEqual([{ type: 'text', text: 'first\n\necho가echo' }]) + expect(nextSend().blocks).toEqual([{ type: 'text', text: 'first\n\necho가 echo' }]) } else { expect(nextSend().blocks).toEqual([ { diff --git a/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-composition.test.tsx b/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-composition.test.tsx index ca88b74749a..8b4e1ccc070 100644 --- a/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-composition.test.tsx +++ b/src/renderer/src/components/native-chat/composer/editor/native-chat-composer-composition.test.tsx @@ -108,7 +108,7 @@ function textarea(): HTMLTextAreaElement { } describe('native chat composer composition ownership', () => { - it('preserves the focused browser preedit through 120 stale streaming rerenders', () => { + it('preserves the focused preedit through a stale streaming rerender', () => { const textareaRef = createRef() const onImeSettled = vi.fn() const props = fieldProps({ textareaRef, onImeSettled }) @@ -118,12 +118,10 @@ describe('native chat composer composition ownership', () => { fireEvent.compositionStart(input) changePrompt(input, '가') - for (let index = 0; index < 120; index += 1) { - view.rerender() - expect(textarea()).toBe(input) - expect(document.activeElement).toBe(input) - expect(promptValue(input)).toBe('가') - } + view.rerender() + expect(textarea()).toBe(input) + expect(document.activeElement).toBe(input) + expect(promptValue(input)).toBe('가') fireEvent.compositionEnd(input, { data: '가' }) expect(onImeSettled).toHaveBeenCalledOnce() diff --git a/src/renderer/src/components/native-chat/composer/focus/native-chat-composer-reveal-focus.test.tsx b/src/renderer/src/components/native-chat/composer/focus/native-chat-composer-reveal-focus.test.tsx index 6269ae1b768..a214010f143 100644 --- a/src/renderer/src/components/native-chat/composer/focus/native-chat-composer-reveal-focus.test.tsx +++ b/src/renderer/src/components/native-chat/composer/focus/native-chat-composer-reveal-focus.test.tsx @@ -289,16 +289,6 @@ describe('useNativeChatComposerRevealFocus', () => { other.remove() }) - it('holds the latch across unrelated rerenders', () => { - render({ isVisible: true, isFocusedGroup: true, nonce: 1 }) - drainFrames() - expect(focusCalls).toBe(1) - render({ isVisible: true, isFocusedGroup: true, nonce: 2 }) - render({ isVisible: true, isFocusedGroup: true, nonce: 3 }) - drainFrames() - expect(focusCalls).toBe(1) - }) - it.each(['menu', 'dialog'] as const)( 'preserves a newer %s when the composer becomes ready', (role) => { diff --git a/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts b/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts index cc3c5158781..c7a41b93e94 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts +++ b/src/renderer/src/components/native-chat/composer/pickers/native-chat-skill-discovery-context.ts @@ -3,7 +3,7 @@ import type { SkillDiscoveryTarget } from '../../../../../../shared/skills' import { parseExecutionHostId } from '../../../../../../shared/execution-host' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import { getExecutionHostIdForWorktree } from '@/lib/workspace/ownership/worktree-runtime-owner' -import { runtimeEnvironmentIdForWorkspaceOwner } from '@/lib/resolve-owner' +import { runtimeEnvironmentIdForWorkspaceOwner } from '@/lib/workspace/ownership/resolve-owner' import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' import { resolveWorkspaceDirectory } from '@/lib/workspace-directory' import { diff --git a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.test.tsx b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.test.tsx deleted file mode 100644 index 1d8d09eaa9d..00000000000 --- a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-mention-files.test.tsx +++ /dev/null @@ -1,84 +0,0 @@ -// @vitest-environment happy-dom -import { renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import * as fileList from '../../../quick-open-file-list' -import * as fileHistory from '@/lib/quick-open-file-history' -import { flushEffects, seedRemoteWorktree } from '../../../quick-open-file-list-test-harness' -import { listRuntimeFilesMock } from '../../../__mocks__/quick-open-runtime-file-client' -import { useNativeChatMentionFiles } from './use-native-chat-mention-files' - -vi.mock('@/runtime/files/search/runtime-file-search-client', async () => { - const mocks = await import('../../../__mocks__/quick-open-runtime-file-client') - return { - listRuntimeFiles: mocks.listRuntimeFilesMock, - cancelRuntimeFileList: mocks.cancelRuntimeFileListMock, - searchRuntimeFilePaths: mocks.searchRuntimeFilePathsMock - } -}) - -describe('useNativeChatMentionFiles', () => { - afterEach(() => vi.restoreAllMocks()) - - it('lists nothing and asks the host for nothing while no token is open', async () => { - seedRemoteWorktree() - const { result, unmount } = renderHook(() => - useNativeChatMentionFiles({ - query: null, - terminalTabId: 'tab-1', - structuredWorktreeId: 'wt-remote' - }) - ) - await flushEffects() - expect(result.current.files).toEqual([]) - expect(listRuntimeFilesMock).not.toHaveBeenCalled() - unmount() - }) - - it('returns the first 20 history-first matches through edits and listing/history replacement', () => { - seedRemoteWorktree() - const needles = Array.from({ length: 25 }, (_, index) => `src/needle-${index}.ts`) - const added = 'src/needle-added.ts' - const list = vi.spyOn(fileList, 'useRuntimeFileListForWorktree').mockReturnValue({ - files: [...needles, 'src/new.ts'], - loading: false, - loadError: null - }) - const history = vi - .spyOn(fileHistory, 'useQuickOpenHistory') - .mockReturnValue(['src/new.ts', added, needles[24], needles[23], 'missing.ts']) - const initialProps: { query: string | null } = { query: null } - const { result, rerender, unmount } = renderHook( - ({ query }: { query: string | null }) => - useNativeChatMentionFiles({ - query, - terminalTabId: 'tab-1', - structuredWorktreeId: 'wt-remote' - }), - { initialProps } - ) - expect(result.current.files).toEqual([]) - rerender({ query: 'n' }) - const broad = ['src/new.ts', needles[24], needles[23], ...needles.slice(0, 17)] - expect(result.current.files).toEqual(broad) - rerender({ query: 'needle' }) - expect(result.current.files).toEqual([needles[24], needles[23], ...needles.slice(0, 18)]) - rerender({ query: 'n' }) - expect(result.current.files).toEqual(broad) - - rerender({ query: 'needle' }) - list.mockReturnValue({ - files: [...needles.slice(0, 24), added], - loading: false, - loadError: null - }) - rerender({ query: 'needle' }) - expect(result.current.files).toEqual([added, needles[23], ...needles.slice(0, 18)]) - history.mockReturnValue([needles[3], 'missing.ts']) - rerender({ query: 'needle' }) - expect(result.current.files).toEqual([ - needles[3], - ...needles.slice(0, 20).filter((path) => path !== needles[3]) - ]) - unmount() - }) -}) diff --git a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.test.tsx b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.test.tsx index eceb210dd65..960f83ef07a 100644 --- a/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.test.tsx +++ b/src/renderer/src/components/native-chat/composer/pickers/use-native-chat-picker-state.test.tsx @@ -1,5 +1,5 @@ // @vitest-environment happy-dom -import { act, renderHook } from '@testing-library/react' +import { renderHook } from '@testing-library/react' import { describe, expect, it, vi } from 'vitest' import { useNativeChatPickerState } from './use-native-chat-picker-state' @@ -54,38 +54,3 @@ describe('useNativeChatPickerState', () => { expect(pickerMode(draft, true)).toBe('none') }) }) - -it('owns demand for the actual slash-menu lifetime, including dismissal and unmount', () => { - const onPickerDemand = vi.fn() - const { result, rerender, unmount } = renderHook( - (draft: string) => - useNativeChatPickerState({ - agent: 'claude', - terminalTabId: 'tab-1', - draftScopeKey: 'pane-1', - draft, - caret: draft.length, - agentCommands: [{ name: 'clear' }], - recalledFromHistory: false, - disabled: false, - isComposing: () => false, - textareaRef: { current: null }, - setDraft: vi.fn(), - setCaret: vi.fn(), - setActiveSuggestion: vi.fn(), - onPickerDemand - }), - { initialProps: '' } - ) - expect(onPickerDemand).toHaveBeenLastCalledWith(false) - rerender('/cl') - expect(onPickerDemand).toHaveBeenLastCalledWith(true) - const autocomplete = result.current.autocomplete - if (autocomplete.mode !== 'slash') { - throw new Error('Expected the slash menu') - } - act(() => result.current.dismiss(autocomplete.triggerKey)) - expect(onPickerDemand).toHaveBeenLastCalledWith(false) - unmount() - expect(onPickerDemand).toHaveBeenLastCalledWith(false) -}) diff --git a/src/renderer/src/components/native-chat/composer/submit/use-native-chat-composer-submit.test.tsx b/src/renderer/src/components/native-chat/composer/submit/use-native-chat-composer-submit.test.tsx index 04a051d8fd6..6e7630e71bf 100644 --- a/src/renderer/src/components/native-chat/composer/submit/use-native-chat-composer-submit.test.tsx +++ b/src/renderer/src/components/native-chat/composer/submit/use-native-chat-composer-submit.test.tsx @@ -92,24 +92,6 @@ function harness(options: { } describe('composer goal mode', () => { - it('sets the draft as the goal instead of sending it, then leaves goal mode', async () => { - const setObjective = vi.fn(async () => true) - const { hook, calls, onSubmitted, type } = harness({ - draft: '/go', - threadGoal: { setObjective } - }) - act(() => hook.result.current.goalMode.interceptPick(vi.fn())(GOAL_ITEM)) - type(' Ship the parser ', 0) - - await act(async () => hook.result.current.send()) - - expect(setObjective).toHaveBeenCalledWith('Ship the parser') - expect(onSubmitted).toHaveBeenCalledOnce() - expect(calls.sendStructured).not.toHaveBeenCalled() - expect(readNativeChatDraftCache(SCOPE)).toBe('') - expect(hook.result.current.goalMode.active).toBe(false) - }) - it('keeps a draft edited while the goal was in flight, and stays in goal mode', async () => { let settle: (accepted: boolean) => void = () => undefined const setObjective = vi.fn(() => new Promise((resolve) => (settle = resolve))) diff --git a/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-send.ts b/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-send.ts index 3eed84ab13a..da38e3036ca 100644 --- a/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-send.ts +++ b/src/renderer/src/components/native-chat/composer/submit/use-native-chat-structured-composer-send.ts @@ -4,7 +4,7 @@ import { captureNativeChatStagedInput } from '../../drafts/native-chat-draft-attachment-staging' import { mayHoldAgentReferences } from '../../../../../../shared/orchestration/mailbox/orchestration-agent-reference' -import { getAgentLabel } from '@/lib/agent-catalog' +import { getAgentLabel } from '@/lib/agent-catalog/agent-catalog' import { formatAgentTypeLabel } from '../../../../../../shared/agent-status/presentation/agent-type-label' import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' import { MAX_SKILL_REFS } from '../../../../../../shared/rpc-contract/structured-agent-session-message-params' diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts index 138ab05320c..2c69315490c 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-projection.ts @@ -4,27 +4,31 @@ import { type NativeChatSubagentRow, type NativeChatTranscriptProjection } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' -import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import { + hostStatesTurnScopes, + type NativeChatTurnJournal +} from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' import { compareNativeChatDisplayMessages as compareMessages, + nativeChatDisplaySortRank, orderNativeChatDisplayMessages as orderMessages } from '../../../../../../shared/native-chat/transcript/native-chat-message-order' - -function sameMessage(left: NativeChatMessage, right: NativeChatMessage): boolean { - // Most rows retain input identity; only folded assistant runs need field comparison. - if (left === right) { - return true - } - const keys = Object.keys(left) as (keyof NativeChatMessage)[] - return ( - keys.length === Object.keys(right).length && - keys.every( - (key) => Object.hasOwn(right, key) && (key === 'blocks' || left[key] === right[key]) - ) && - left.blocks.length === right.blocks.length && - left.blocks.every((block, index) => block === right.blocks[index]) - ) -} +import { buildNativeChatFoldUnits } from '../../../../../../shared/native-chat/transcript/native-chat-fold-units' +import { + nativeChatToolFoldKind, + type NativeChatToolFoldKind +} from '../../../../../../shared/native-chat/tools/native-chat-tool-fold' +import { foldSubagentItems } from '../../../../../../shared/native-chat/transcript/native-chat-subagent-items' +import { stripNoiseMessages } from '../../../../../../shared/native-chat/native-chat-noise' +import { agentJournalItemSubagentId } from '../../../../../../shared/agent-session/journal/agent-session-journal-producer' +import { reuseUnits } from './native-chat-message-list-reuse' +import { subagentTurnKeys } from './native-chat-message-list-turns' +import { + settleUnit, + unitStarts, + type NativeChatListScope, + type NativeChatListState +} from './native-chat-message-list-units' function sameRows( left: readonly T[] | undefined, @@ -41,195 +45,137 @@ function sameRows( const sameSubagentRow = (a: NativeChatSubagentRow, b: NativeChatSubagentRow): boolean => a.message === b.message && a.turnKey === b.turnKey -function plainAssistant(message: NativeChatMessage): boolean { - return ( - message.role === 'assistant' && - message.agentId === undefined && - message.blocks.every((block) => block.type === 'text' && !block.providerFrame) +function projectFully( + messages: readonly NativeChatMessage[], + journal: NativeChatTurnJournal | null | undefined, + previous: NativeChatListState | null +): NativeChatListState { + const ids = new Set(messages.map((message) => message.id)) + if (ids.size !== messages.length) { + // Units are keyed by source id; duplicate ids take the plain fold and leave nothing to reuse. + return { + input: messages, + ids, + journal, + projection: retainIdentity( + projectNativeChatTranscript(messages, compareMessages, journal, orderMessages), + previous?.projection + ), + scopes: [], + place: new Map(), + kinds: new Map(), + turnKeys: null, + ordered: false + } + } + const held = new Map( + previous?.scopes.flatMap((scope) => scope.units.map((unit) => [unit.sources[0]!.id, unit])) ) + const kinds = new Map() + const place = new Map() + const scopes: NativeChatListScope[] = [] + const agentRows = new Map() + let ordered = false + const order = (rows: readonly NativeChatMessage[]) => { + const sorted = orderMessages(rows) + ordered = sorted.every( + (row, index) => + row === rows[index] && row.journalPosition && nativeChatDisplaySortRank(row) === 0 + ) + return sorted + } + const projectScope = (rows: readonly NativeChatMessage[]): NativeChatMessage[] => { + const grouped = foldSubagentItems(rows) + for (const source of grouped) { + kinds.set(source, previous?.kinds.get(source) ?? nativeChatToolFoldKind(source)) + } + const ids = new Set(grouped.map((row) => row.id)) + const units = buildNativeChatFoldUnits(grouped, kinds, held, stripNoiseMessages, ids).map( + (unit) => settleUnit(unit, held.get(unit.sources[0]!.id)) + ) + const agentId = rows[0] ? agentJournalItemSubagentId(rows[0]) : null + const offset = agentId === null ? 0 : (agentRows.get(agentId) ?? 0) + const scope = scopes.length + for (const [index, unit] of units.entries()) { + for (const source of unit.sources) { + place.set(source, { scope, unit: index }) + } + } + const starts = unitStarts(units) + const projected = units.flatMap((unit) => unit.rows) + if (agentId !== null) { + agentRows.set(agentId, offset + projected.length) + } + scopes.push({ agentId, offset, ids, units, starts }) + return projected + } + const projected = projectNativeChatTranscript( + messages, + compareMessages, + journal, + order, + projectScope + ) + for (const scope of scopes) { + const first = + scope.agentId !== null && scope.units.some((unit) => unit.rows.length > 0) + ? projected.subagentRows.get(scope.agentId)?.[scope.offset] + : undefined + if (first) { + scope.turn = { key: first.turnKey } + } + } + return { + input: messages, + ids, + journal, + projection: retainIdentity(projected, previous?.projection), + scopes, + place, + kinds, + turnKeys: + journal && hostStatesTurnScopes(journal.items) + ? projected.subagentRows.size > 0 + ? subagentTurnKeys(projected.subagentRows, journal.items) + : new Map() + : null, + ordered + } } -function sameTextPlacement(before: NativeChatMessage, next: NativeChatMessage): boolean { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Runtime keys are used only for equality, including any extra message fields. - const keys = Object.keys(before) as (keyof NativeChatMessage)[] - return ( - keys.length === Object.keys(next).length && - keys.every((key) => { - if (!Object.hasOwn(next, key)) { - return false - } - if (key === 'blocks') { - return true - } - if (key === 'journalPosition') { - return ( - before.journalPosition?.sequence === next.journalPosition?.sequence && - before.journalPosition?.index === next.journalPosition?.index - ) - } - // Journal creation position, rather than a revised provider clock, orders these rows. - return key === 'timestamp' && before.journalPosition && next.journalPosition - ? true - : before[key] === next[key] - }) - ) -} - -function reuseConversation( - messages: NativeChatMessage[], - before: NativeChatMessage[] | null, - previous: NativeChatTranscriptProjection, - byId: ReadonlyMap, - indexes: ReadonlyMap, - rawIds: ReadonlySet -): { - conversation: NativeChatMessage[] - changes: { index: number; message: NativeChatMessage; source: NativeChatMessage | null }[] -} | null { - if (!before || messages.length < before.length || previous.subagentRows.size > 0) { - return null +function retainIdentity( + projected: NativeChatTranscriptProjection, + previous: NativeChatTranscriptProjection | undefined +): NativeChatTranscriptProjection { + if (!previous) { + return projected } - const changes: { index: number; message: NativeChatMessage; source: NativeChatMessage | null }[] = - [] - for (let index = 0; index < before.length; index += 1) { - const prior = before[index]! - const message = messages[index]! - if (prior === message) { - continue - } - const projectedIndex = indexes.get(prior) - // Folded rows can own later tools: only a directly drawn prose row is independent. - if ( - projectedIndex === undefined || - !plainAssistant(prior) || - !plainAssistant(message) || - !sameTextPlacement(prior, message) - ) { - return null - } - changes.push({ index: projectedIndex, message, source: prior }) + const subagentRows = new Map() + for (const [agentId, rows] of projected.subagentRows) { + const prior = previous.subagentRows.get(agentId) + subagentRows.set(agentId, prior && sameRows(prior, rows, sameSubagentRow) ? prior : rows) } - const appended = messages.slice(before.length) - if (appended.length > 0) { - let last: NativeChatMessage | undefined - for (const message of before) { - if (!message.journalPosition || message.pendingSend || message.queued) { - return null - } - if (!last || compareMessages(last, message) < 0) { - last = message - } - } - const addedIds = new Set() - for (const message of appended) { - if ( - !plainAssistant(message) || - !message.journalPosition || - message.pendingSend || - message.queued || - rawIds.has(message.id) || - byId.has(message.id) || - addedIds.has(message.id) || - (last && compareMessages(last, message) > 0) - ) { - return null - } - addedIds.add(message.id) - last = message - } + const sameConversation = sameRows(previous.conversation, projected.conversation, Object.is) + const sameSubagents = + subagentRows.size === previous.subagentRows.size && + Array.from(subagentRows).every(([agentId, rows]) => previous.subagentRows.get(agentId) === rows) + if (sameConversation && sameSubagents) { + return previous } - if (changes.length === 0 && appended.length === 0) { - return { conversation: previous.conversation, changes } + return { + conversation: sameConversation ? previous.conversation : projected.conversation, + subagentRows: sameSubagents ? previous.subagentRows : subagentRows } - const conversation = previous.conversation.slice() - for (const { index, message } of changes) { - conversation[index] = message - } - for (const message of appended) { - changes.push({ index: conversation.length, message, source: null }) - conversation.push(message) - } - return { conversation, changes } } export function createNativeChatMessageListProjection(): ( messages: NativeChatMessage[], journal?: NativeChatTurnJournal | null ) => NativeChatTranscriptProjection { - let previous: NativeChatTranscriptProjection = { conversation: [], subagentRows: new Map() } - let byId = new Map() - let input: NativeChatMessage[] | null = null - let indexes: Map | null = null - let rawIds: Set | null = null + let state: NativeChatListState | null = null return (messages, journal) => { - const reused = - indexes && rawIds ? reuseConversation(messages, input, previous, byId, indexes, rawIds) : null - const appendedStart = input?.length ?? 0 - input = messages - if (reused) { - if (reused.conversation !== previous.conversation) { - // Reuse the index for content-only revisions; append changes only its new suffix. - for (const { index, message, source } of reused.changes) { - byId.set(message.id, message) - if (source) { - indexes!.delete(source) - } - indexes!.set(message, index) - } - for (let index = appendedStart; index < messages.length; index += 1) { - rawIds!.add(messages[index]!.id) - } - previous = { ...previous, conversation: reused.conversation } - } - return previous - } - const projected = projectNativeChatTranscript(messages, compareMessages, journal, orderMessages) - // Folding clones historical tool runs even when every contributing block is unchanged. - const settle = (message: NativeChatMessage): NativeChatMessage => { - const prior = byId.get(message.id) - return prior && sameMessage(prior, message) ? prior : message - } - const conversation = projected.conversation.map(settle) - const subagentRows = new Map() - for (const [agentId, rows] of projected.subagentRows) { - const settled = rows.map((row) => ({ ...row, message: settle(row.message) })) - const prior = previous.subagentRows.get(agentId) - subagentRows.set( - agentId, - prior && sameRows(prior, settled, sameSubagentRow) ? prior : settled - ) - } - const sameConversation = sameRows(previous.conversation, conversation, Object.is) - const sameSubagents = - subagentRows.size === previous.subagentRows.size && - Array.from(subagentRows).every( - ([agentId, rows]) => previous.subagentRows.get(agentId) === rows - ) - const independent = subagentRows.size === 0 - rawIds = independent ? new Set(messages.map((message) => message.id)) : null - // Settlement can restore raw identity after a fold; only canonical output proves provenance. - indexes = - rawIds?.size === messages.length - ? new Map(projected.conversation.map((message, index) => [message, index])) - : null - if (indexes?.size !== projected.conversation.length) { - indexes = null - } - if (sameConversation && sameSubagents) { - return previous - } - previous = { - conversation: sameConversation ? previous.conversation : conversation, - subagentRows: sameSubagents ? previous.subagentRows : subagentRows - } - byId = new Map( - [ - ...conversation, - ...Array.from(subagentRows.values()) - .flat() - .map((row) => row.message) - ].map((message) => [message.id, message]) - ) - return previous + state = + (state && reuseUnits(state, messages, journal)) ?? projectFully(messages, journal, state) + return state.projection } } diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-reuse.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-reuse.ts new file mode 100644 index 00000000000..efe782103a3 --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-reuse.ts @@ -0,0 +1,279 @@ +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import { + sameNativeChatRowPlacement, + type NativeChatSubagentRow +} from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import { + compareNativeChatDisplayMessages as compareMessages, + nativeChatDisplaySortRank +} from '../../../../../../shared/native-chat/transcript/native-chat-message-order' +import { + buildNativeChatFoldUnit, + groupNativeChatFoldUnitMembers, + type NativeChatFoldUnit +} from '../../../../../../shared/native-chat/transcript/native-chat-fold-units' +import { nativeChatToolFoldKind } from '../../../../../../shared/native-chat/tools/native-chat-tool-fold' +import { isOrphanRowId } from '../../../../../../shared/native-chat/tools/native-chat-folded-tool-results' +import { subagentItemBlock } from '../../../../../../shared/native-chat/transcript/native-chat-subagent-items' +import { stripNoiseMessages } from '../../../../../../shared/native-chat/native-chat-noise' +import { agentJournalItemSubagentId } from '../../../../../../shared/agent-session/journal/agent-session-journal-producer' +import { appendedSubagentTurnKey, appendedTurnNeutralItems } from './native-chat-message-list-turns' +import { + settleUnit, + unitStarts, + type NativeChatListScope, + type NativeChatListState +} from './native-chat-message-list-units' + +/** Revised rows re-fold only their unit, and conversation appends only the last unit onward; else null. */ +export function reuseUnits( + state: NativeChatListState, + messages: readonly NativeChatMessage[], + journal: NativeChatTurnJournal | null | undefined +): NativeChatListState | null { + const before = state.input + const subagents = state.projection.subagentRows.size > 0 + // Revisions keep every ordering field, so only appends need input already in display order. + if (messages.length < before.length || (!state.ordered && messages.length !== before.length)) { + return null + } + // Subagent rows keep their turns only while no earlier turn input changed. + let appendedItems = subagents ? appendedTurnNeutralItems(state.journal, journal) : null + // Only explicit turn scopes prove an appended row leaves earlier rows' turns alone. + if (subagents && (!appendedItems || (messages.length > before.length && !state.turnKeys))) { + return null + } + const changed: [NativeChatMessage, NativeChatMessage][] = [] + for (let index = 0; index < before.length; index += 1) { + const prior = before[index]! + const message = messages[index]! + if (prior === message) { + continue + } + if ( + prior.id !== message.id || + !sameNativeChatRowPlacement(prior, message) || + subagentItemBlock(prior) !== null || + subagentItemBlock(message) !== null || + // A conversation user row opens the turns subagent rows are grouped by. + (subagents && message.role === 'user') || + state.kinds.get(prior) !== nativeChatToolFoldKind(message) + ) { + return null + } + changed.push([prior, message]) + } + const appended = messages.slice(before.length) + const appendedIds = new Set() + const appendedTurns = new Map() + let last = before.at(-1) + for (const message of appended) { + if (agentJournalItemSubagentId(message) !== null) { + appendedItems ??= appendedTurnNeutralItems(state.journal, journal) + const turn = + appendedItems && + state.turnKeys && + appendedSubagentTurnKey(message, appendedItems, state.turnKeys) + if (!turn) { + return null + } + appendedTurns.set(message, turn.turnKey) + } + if ( + !message.journalPosition || + nativeChatDisplaySortRank(message) !== 0 || + subagentItemBlock(message) !== null || + // A raw id shaped like a detached result's renames every later orphan. + isOrphanRowId(message.id) || + state.ids.has(message.id) || + appendedIds.has(message.id) || + (last && compareMessages(last, message) >= 0) + ) { + return null + } + appendedIds.add(message.id) + last = message + } + const scopes = state.scopes.slice() + const edit = (index: number): NativeChatListScope => { + if (scopes[index] === state.scopes[index]) { + scopes[index] = { ...scopes[index]!, units: scopes[index]!.units.slice() } + } + return scopes[index]! + } + let conversation = state.projection.conversation + const copiedRows = new Map() + const agentRowsFor = (agentId: string): NativeChatSubagentRow[] => { + let rows = copiedRows.get(agentId) + if (!rows) { + rows = state.projection.subagentRows.get(agentId)?.slice() ?? [] + copiedRows.set(agentId, rows) + } + return rows + } + // Several revisions in one unit re-fold it once. + const revisedUnits = new Map< + string, + { scope: number; unit: number; swaps: Map } + >() + for (const [prior, message] of changed) { + const at = state.place.get(prior) + if (!at) { + return null + } + const key = `${at.scope}:${at.unit}` + const entry = revisedUnits.get(key) ?? { ...at, swaps: new Map() } + entry.swaps.set(prior, message) + revisedUnits.set(key, entry) + } + for (const { scope: scopeIndex, unit: unitIndex, swaps } of revisedUnits.values()) { + const scope = edit(scopeIndex) + const unit = scope.units[unitIndex]! + // A refused reuse projects in full with fresh maps, so recording sources as we go is safe. + for (const [prior, message] of swaps) { + state.kinds.set(message, state.kinds.get(prior)!) + } + const rebuilt = settleUnit( + buildNativeChatFoldUnit( + unit.sources.map((source) => swaps.get(source) ?? source), + scope.ids, + state.kinds, + unit, + stripNoiseMessages + ), + unit + ) + // Detached result ids are allocated across units, so only a full pass may change them. + if ( + unit.orphans.length > 0 || + rebuilt.orphans.length > 0 || + rebuilt.rows.length !== unit.rows.length + ) { + return null + } + scope.units[unitIndex] = rebuilt + for (const [prior, message] of swaps) { + state.kinds.delete(prior) + state.place.delete(prior) + state.place.set(message, { scope: scopeIndex, unit: unitIndex }) + } + if (rebuilt.rows.every((row, index) => row === unit.rows[index])) { + continue + } + const start = scope.offset + scope.starts[unitIndex]! + if (scope.agentId === null) { + conversation = + conversation === state.projection.conversation ? conversation.slice() : conversation + conversation.splice(start, rebuilt.rows.length, ...rebuilt.rows) + } else { + const rows = agentRowsFor(scope.agentId) + for (const [offset, row] of rebuilt.rows.entries()) { + rows[start + offset] = { message: row, turnKey: rows[start + offset]!.turnKey } + } + } + } + // Each scope's appended rows re-fold from its last unit; a subagent row in a new turn opens a new chunk. + const appendTo = (index: number, added: readonly NativeChatMessage[]): boolean => { + const scope = edit(index) + for (const message of added) { + state.kinds.set(message, nativeChatToolFoldKind(message)) + state.ids.add(message.id) + scope.ids.add(message.id) + } + const from = Math.max(0, scope.units.length - 1) + const head = scope.units[from] + const units: NativeChatFoldUnit[] = [] + for (const members of groupNativeChatFoldUnitMembers( + [...(head?.sources ?? []), ...added], + state.kinds + )) { + const held = members[0] === head?.sources[0] ? head : undefined + const unit = settleUnit( + buildNativeChatFoldUnit(members, scope.ids, state.kinds, held, stripNoiseMessages), + held + ) + if (unit.orphans.length > 0 || (held && held.orphans.length > 0)) { + return false + } + unit.sources.forEach((source) => + state.place.set(source, { scope: index, unit: from + units.length }) + ) + units.push(unit) + } + const start = scope.starts[from] ?? 0 + scope.units.splice(from, scope.units.length - from, ...units) + scope.starts = [ + ...scope.starts.slice(0, from), + ...unitStarts(units).map((offset) => start + offset) + ] + const rows = units.flatMap((unit) => unit.rows) + if (scope.agentId === null) { + conversation = [...conversation.slice(0, start), ...rows] + return true + } + const agentRows = agentRowsFor(scope.agentId) + const turnKey = scope.turn?.key + agentRows.splice( + scope.offset + start, + agentRows.length, + ...rows.map((message) => ({ message, turnKey })) + ) + return true + } + const own = appended.filter((message) => !appendedTurns.has(message)) + if (own.length > 0 && !appendTo(0, own)) { + return null + } + // Per subagent, consecutive rows of one turn extend its last chunk or open the next. + const runs: { agentId: string; turnKey: string | undefined; rows: NativeChatMessage[] }[] = [] + const lastRun = new Map() + for (const [message, turnKey] of appendedTurns) { + const agentId = agentJournalItemSubagentId(message)! + const run = lastRun.get(agentId) + if (run && run.turnKey === turnKey) { + run.rows.push(message) + } else { + const next = { agentId, turnKey, rows: [message] } + runs.push(next) + lastRun.set(agentId, next) + } + } + const lastScope = new Map() + if (runs.length > 0) { + scopes.forEach((scope, index) => scope.agentId !== null && lastScope.set(scope.agentId, index)) + } + for (const { agentId, turnKey, rows } of runs) { + const tail = lastScope.get(agentId) ?? -1 + let index = tail + if (tail === -1 || !scopes[tail]!.turn || scopes[tail]!.turn!.key !== turnKey) { + if (tail !== -1 && !scopes[tail]!.turn) { + return null + } + index = scopes.length + lastScope.set(agentId, index) + scopes.push({ + agentId, + offset: agentRowsFor(agentId).length, + ids: new Set(), + units: [], + starts: [], + turn: { key: turnKey } + }) + } + if (!appendTo(index, rows)) { + return null + } + } + const projection = + conversation === state.projection.conversation && copiedRows.size === 0 + ? state.projection + : { + conversation, + subagentRows: + copiedRows.size === 0 + ? state.projection.subagentRows + : new Map([...state.projection.subagentRows, ...copiedRows]) + } + return { ...state, input: messages, journal, projection, scopes } +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-turns.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-turns.ts new file mode 100644 index 00000000000..b3c25bf7684 --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-turns.ts @@ -0,0 +1,99 @@ +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import type { NativeChatSubagentRow } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' +import { compareAgentJournalItems } from '../../../../../../shared/agent-session/journal/agent-session-journal-position' +import { readAgentJournalTurn } from '../../../../../../shared/agent-session/lifecycle/agent-session-turn-record' + +// Subagent rows are grouped by the parent turn they belong to; these checks prove that grouping still holds. + +/** User rows and turn records anchor turns; neither may change for earlier rows to keep their turn. */ +function opensOrRecordsTurn(item: AgentJournalRenderItem): boolean { + return ( + (item.body.kind === 'message' && item.body.role === 'user') || + readAgentJournalTurn(item.body) !== null + ) +} + +function turnItemId(item: AgentJournalRenderItem): string | undefined { + return item.turnScope?.kind === 'turn' ? item.turnScope.turnItemId : undefined +} + +/** The journal items appended since `before`, by id, when every turn input of the earlier items is unchanged; + * null when a turn input changed. Turn keys read user rows, turn records, scopes, submissions and the latest turn. */ +export function appendedTurnNeutralItems( + before: NativeChatTurnJournal | null | undefined, + after: NativeChatTurnJournal | null | undefined +): ReadonlyMap | null { + if (!before || !after) { + return before === after ? new Map() : null + } + if ( + before.submissions !== after.submissions || + before.working !== after.working || + JSON.stringify(before.latestTurn) !== JSON.stringify(after.latestTurn) || + after.items.length < before.items.length + ) { + return null + } + for (const [index, item] of before.items.entries()) { + const next = after.items[index]! + if ( + item !== next && + (item.itemId !== next.itemId || + item.agentId !== next.agentId || + compareAgentJournalItems(item, next) !== 0 || + item.turnScope?.kind !== next.turnScope?.kind || + turnItemId(item) !== turnItemId(next) || + opensOrRecordsTurn(item) || + opensOrRecordsTurn(next)) + ) { + return null + } + } + const appended = new Map() + for (const item of after.items.slice(before.items.length)) { + if (opensOrRecordsTurn(item)) { + return null + } + appended.set(item.itemId, item) + } + return appended +} + +/** Each journal turn's key as drawn on its subagent rows, for a host that states turn scopes. */ +export function subagentTurnKeys( + subagentRows: ReadonlyMap, + items: readonly AgentJournalRenderItem[] +): Map { + const byId = new Map(items.map((item) => [item.itemId, item])) + const keys = new Map() + for (const rows of subagentRows.values()) { + for (const { message, turnKey } of rows) { + const turn = byId.get(message.id) + const id = turn && turnItemId(turn) + if (id !== undefined) { + keys.set(id, turnKey) + } + } + } + return keys +} + +/** An appended subagent row's turn key, read from an earlier row of the same turn; undefined when unknown. */ +export function appendedSubagentTurnKey( + message: NativeChatMessage, + appendedItems: ReadonlyMap, + turnKeys: ReadonlyMap +): { turnKey: string | undefined } | undefined { + const item = appendedItems.get(message.id) + if (!item) { + return undefined + } + const id = turnItemId(item) + if (id === undefined) { + // Unscoped or unknown-scope rows own no turn. + return { turnKey: undefined } + } + return turnKeys.has(id) ? { turnKey: turnKeys.get(id) } : undefined +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-units.ts b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-units.ts new file mode 100644 index 00000000000..2f027dcbb7a --- /dev/null +++ b/src/renderer/src/components/native-chat/conversation/projection/native-chat-message-list-units.ts @@ -0,0 +1,70 @@ +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import type { NativeChatTranscriptProjection } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-projection' +import type { NativeChatTurnJournal } from '../../../../../../shared/native-chat/transcript/native-chat-turn-membership' +import type { NativeChatFoldUnit } from '../../../../../../shared/native-chat/transcript/native-chat-fold-units' +import type { NativeChatToolFoldKind } from '../../../../../../shared/native-chat/tools/native-chat-tool-fold' + +function sameMessage(left: NativeChatMessage, right: NativeChatMessage): boolean { + // Most rows retain input identity; only folded assistant runs need field comparison. + if (left === right) { + return true + } + const keys = Object.keys(left) as (keyof NativeChatMessage)[] + return ( + keys.length === Object.keys(right).length && + keys.every( + (key) => Object.hasOwn(right, key) && (key === 'blocks' || left[key] === right[key]) + ) && + left.blocks.length === right.blocks.length && + left.blocks.every((block, index) => block === right.blocks[index]) + ) +} + +/** Folding clones a run's head even when every contributing block is unchanged. */ +export function settleUnit(unit: NativeChatFoldUnit, before: NativeChatFoldUnit | undefined) { + if (!before || unit === before) { + return unit + } + const prior = new Map(before.rows.map((row) => [row.id, row])) + const rows = unit.rows.map((row) => { + const held = prior.get(row.id) + return held && sameMessage(held, row) ? held : row + }) + return rows.every((row, index) => row === unit.rows[index]) ? unit : { ...unit, rows } +} + +/** The conversation, or one subagent's rows within one parent turn, folded by units. */ +export type NativeChatListScope = { + agentId: string | null + /** Where the scope's rows start in its agent's subagent rows; 0 for the conversation. */ + offset: number + ids: Set + units: NativeChatFoldUnit[] + /** Each unit's first row within the scope's rows. */ + starts: number[] + /** A subagent chunk's parent turn, when its rows show it. */ + turn?: { key: string | undefined } +} + +export type NativeChatListState = { + input: readonly NativeChatMessage[] + ids: Set + journal: NativeChatTurnJournal | null | undefined + projection: NativeChatTranscriptProjection + scopes: NativeChatListScope[] + place: Map + kinds: Map + /** Subagent rows' turn keys by journal turn, when the host states turn scopes. */ + turnKeys: Map | null + /** Input arrived in display order, every row journal-placed and ordinarily ranked, so appends can follow it. */ + ordered: boolean +} + +export function unitStarts(units: readonly NativeChatFoldUnit[]): number[] { + let start = 0 + return units.map((unit) => { + const at = start + start += unit.rows.length + return at + }) +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts b/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts index 7f8df5ab365..8a3f93ddae4 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts +++ b/src/renderer/src/components/native-chat/conversation/projection/structured-agent-session-message-projection.ts @@ -6,6 +6,7 @@ import { type StructuredAgentSessionOptimisticMessage, projectStructuredAgentSessionMessages as projectMessages } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' +import { createStructuredAgentSessionMessageProjection } from '../../../../../../shared/agent-session/view/structured-agent-session-message-stream' import { createStructuredQuestionProjection } from '../../../../../../shared/structured-agent-question-projection' import { projectStructuredAgentStartItem } from '../../../../../../shared/structured-agent-start-projection' @@ -21,3 +22,8 @@ export function projectStructuredAgentSessionMessages( ) { return projectMessages(items, optimistic, submissions, desktopStructuredTranscript.messages) } + +/** One mounted chat's messages across journal commits. */ +export function createDesktopStructuredAgentSessionMessageProjection() { + return createStructuredAgentSessionMessageProjection(desktopStructuredTranscript.messages) +} diff --git a/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts b/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts index 8557e630ce3..f8a95ea3f76 100644 --- a/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts +++ b/src/renderer/src/components/native-chat/conversation/projection/use-structured-agent-session-messages.ts @@ -4,15 +4,16 @@ import type { AgentJournalSubmission } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import type { StructuredAgentSessionOptimisticMessage } from '../../../../../../shared/agent-session/view/structured-agent-session-message-projection' -import { projectStructuredAgentSessionMessages } from './structured-agent-session-message-projection' +import { createDesktopStructuredAgentSessionMessageProjection } from './structured-agent-session-message-projection' export function useStructuredAgentSessionMessages( items: readonly AgentJournalRenderItem[], optimistic: readonly StructuredAgentSessionOptimisticMessage[], submissions: readonly AgentJournalSubmission[] ) { + const project = useMemo(() => createDesktopStructuredAgentSessionMessageProjection(), []) return useMemo( - () => projectStructuredAgentSessionMessages(items, optimistic, submissions), - [items, optimistic, submissions] + () => project(items, optimistic, submissions), + [items, optimistic, submissions, project] ) } diff --git a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx index cd98f6d34ca..05bc7bcf3ae 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx +++ b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx @@ -21,10 +21,6 @@ vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender: unusedChatLeaves.openSender })) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) import { agentSessionFailureFact } from '../../../../../../shared/agent-session/failures/agent-session-failure' import { agentSessionFailureWords } from '../../../../../../shared/agent-session/failures/agent-session-failure-words' import { agentJournalSubmissionKey } from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' diff --git a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx index 2641e7d8e1d..ca097e112b9 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx +++ b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx @@ -21,10 +21,6 @@ vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender: unusedChatLeaves.openSender })) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) import type { AgentJournalItemBody, AgentJournalRenderItem diff --git a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx index 7169f3d8efa..c376839d8d6 100644 --- a/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx +++ b/src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx @@ -22,10 +22,6 @@ vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender: unusedChatLeaves.openSender })) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) import { agentJournalItemKey, diff --git a/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx b/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx index 8dcfed41138..0e9617fbe84 100644 --- a/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx +++ b/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx @@ -21,10 +21,6 @@ vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender: unusedChatLeaves.openSender })) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' import { NativeChatMessageList } from '../../NativeChatMessageList' import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport' @@ -34,16 +30,6 @@ import type { } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import type { AgentJournalTurnScope } from '../../../../../../shared/agent-session/journal/agent-session-journal-turn-scope' -const reasoningRow: AgentJournalItemBody = { - kind: 'message', - role: 'reasoning', - blocks: [{ type: 'text', text: '' }] -} - -function journalItem(sequence: number, body: AgentJournalItemBody): AgentJournalRenderItem { - return { itemId: `item-${sequence}`, revision: 1, sequence, observedAt: sequence, body } -} - let restoreViewport = (): void => {} beforeAll(() => { restoreViewport = installNativeChatMessageListTestViewport() @@ -73,67 +59,6 @@ const session: NativeChatLiveSession = { // Live turns show a prompt clock and tail activity; settled turns retain the clock bar. describe('NativeChatMessageList turn indicator', () => { - // The trailing run stays live between calls until the turn ends; its motion stays separate from the tail spinner. - it('keeps the trailing run live while the turn tail spins, then settles both', () => { - const workingSession: NativeChatLiveSession = { - ...session, - status: 'working', - messages: [ - { - id: 'assistant-settled-tool', - role: 'assistant', - blocks: [ - { - type: 'tool-call', - name: 'shell', - input: { command: 'pnpm test' }, - state: 'completed' - }, - { type: 'tool-result', output: 'passed' } - ], - timestamp: 1, - source: 'transcript' - } - ] - } - const { container, rerender } = render( - - ) - - const liveRun = screen.getByText('Running 1 command').closest('button') - expect(liveRun).toHaveTextContent('pnpm test') - expect(liveRun?.querySelector('.animate-pulse')).toBeInTheDocument() - expect(liveRun?.querySelector('.animate-spin')).toBeNull() - expect(liveRun?.querySelector('.lucide-check')).toBeNull() - const activity = screen.getByText('Preparing the answer') - expect(activity).not.toHaveClass('animate-pulse', 'animate-spin') - expect(activity.closest('[data-native-chat-turn-activity]')?.querySelector('svg')).toHaveClass( - 'animate-spin' - ) - - rerender( - - ) - - expect(container.querySelector('[data-native-chat-turn-activity]')).toBeNull() - expect(container.querySelector('.animate-pulse')).toBeNull() - expect(container.querySelector('.animate-spin')).toBeNull() - expect(liveRun).toBeInTheDocument() - expect(liveRun).toHaveTextContent('pnpm test') - expect(liveRun).not.toHaveTextContent('Running') - expect(liveRun?.querySelector('.lucide-check')).toBeInTheDocument() - }) - it('replaces a bridge ask row and settles it from the FIFO tool result', () => { const user = { id: 'bridge-user', @@ -195,35 +120,6 @@ describe('NativeChatMessageList turn indicator', () => { expect(screen.queryByText(/AskUserQuestion/)).toBeNull() }) - it('does not reuse completed-turn reasoning while the next dispatch is pending', () => { - render( - - ) - - expect(screen.queryByText('Thinking')).toBeNull() - expect(screen.getByText('Working…')).toBeInTheDocument() - }) - it.each([ ["a host that states each row's turn", true], ['a host that states none', false] diff --git a/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-status.test.tsx b/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-status.test.tsx deleted file mode 100644 index 098485bba1f..00000000000 --- a/src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-status.test.tsx +++ /dev/null @@ -1,262 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, screen } from '@testing-library/react' -import { render } from '../../messages/actions/native-chat-tooltip-test-harness' -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' - -// Why: these fixtures have neither inline visual owners nor sender navigation. -const unusedChatLeaves = vi.hoisted(() => ({ - inlineVisual: vi.fn(() => { - throw new Error('Unexpected inline visual in transcript fixture') - }), - openSender: vi.fn(() => { - throw new Error('Unexpected sender navigation in transcript fixture') - }) -})) -vi.mock('../../media/visuals/NativeChatInlineVisual', () => ({ - NativeChatInlineVisual: unusedChatLeaves.inlineVisual -})) -vi.mock('@/lib/open-agent-message-sender', () => ({ - openAgentMessageSender: unusedChatLeaves.openSender -})) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) -import { NativeChatOrcaStopContext } from '../../messages/notices/native-chat-orca-stop-context' -import { agentSessionFailureWords } from '../../../../../../shared/agent-session/failures/agent-session-failure-words' -import type { - AgentJournalItemBody, - AgentJournalRenderItem -} from '../../../../../../shared/agent-session/journal/agent-session-journal-types' - -import { selectStructuredAgentSettledTurns } from '../../../../../../shared/agent-session/view/structured-agent-session-turn-timing' - -import { NativeChatMessageList } from '../../NativeChatMessageList' -import { installNativeChatMessageListTestViewport } from '../../viewport/virtualization/native-chat-message-list-test-viewport' -import { projectStructuredAgentSessionMessages } from '../projection/structured-agent-session-message-projection' -import { - agentJournalItemKey, - agentJournalSubmissionKey -} from '../../../../../../shared/agent-session/journal/agent-session-journal-item-key' -import { latestNativeChatOrcaStopCut } from '../../../../../../shared/native-chat/native-chat-orca-stop-cut' -import { latestNativeChatUsageLimitCut } from '../../../../../../shared/native-chat/native-chat-usage-limit-cut' -import { latestStructuredAgentSessionRequest } from '../../../../../../shared/agent-session/requests/structured-agent-session-latest-request' - -let restoreViewport = (): void => {} -beforeAll(() => { - restoreViewport = installNativeChatMessageListTestViewport() -}) -afterAll(() => restoreViewport()) -afterEach(cleanup) - -const continueUsageLimit = vi.fn() -const usageLimitView = { - hostLabel: null, - remoteHost: false, - continueAvailable: false, - offeredTurnItemId: null, - continueNow: vi.fn(), - usageLimitTurnItemId: 'item-2', - continueUsageLimit -} -// A host that could continue, with no turn the selectors offered. -const commandView = { - ...usageLimitView, - continueAvailable: true, - offeredTurnItemId: null, - usageLimitTurnItemId: null -} - -{ - function retry(sequence: number, attempt: number): AgentJournalRenderItem { - return { - itemId: `retry-${sequence}`, - revision: 1, - sequence, - observedAt: sequence, - body: { - kind: 'status', - tone: 'warning', - ...agentSessionFailureWords( - { - kind: 'providerRetrying', - detail: { text: `Reconnecting... ${attempt}/5`, audience: 'person' }, - retry: { cause: 'stream disconnected before completion' } - }, - { surface: 'row', agentName: 'Codex' } - ) - } - } - } - - function transcript(items: AgentJournalRenderItem[]) { - return ( - - ) - } - - describe('a Codex retrying a dropped stream', () => { - it('draws one warning for the run, with what failed on its second line', () => { - render(transcript([retry(1, 1), retry(2, 2), retry(3, 3)])) - - const rows = screen.getAllByText(/Codex is retrying/) - expect(rows).toHaveLength(1) - expect(rows[0]?.textContent).toBe( - 'Codex is retrying: Reconnecting... 3/5.\nstream disconnected before completion' - ) - }) - }) -} - -{ - const compactEntry = agentJournalSubmissionKey('cmd-1') - const commandTurn = agentJournalItemKey({ - provider: 'orca', - clientMessageId: 'command-turn:cmd-1' - }) - const row = ( - itemId: string, - sequence: number, - body: AgentJournalItemBody, - turnItemId?: string - ): AgentJournalRenderItem => ({ - itemId, - revision: 1, - sequence, - observedAt: sequence, - body, - turnScope: turnItemId ? { kind: 'turn', turnItemId } : { kind: 'thread' } - }) - const settled = ( - itemId: string, - userItemId: string, - outcome: 'success' | 'failure', - at: number - ) => - row(itemId, at, { - kind: 'turn', - turnId: itemId, - userItemId, - state: 'completed', - outcome, - startedAt: at * 1000, - completedAt: at * 1000 + 4000 - }) - const failures: [string, AgentJournalItemBody, RegExp][] = [ - [ - 'usage-limit warning', - { - kind: 'status', - tone: 'warning', - ...agentSessionFailureWords( - { - kind: 'usageLimitReached', - usageLimit: { window: 'session', resetsAt: 1_700_000_000_000 }, - detail: { text: "You've hit your limit", audience: 'person' } - }, - { surface: 'row', agentName: 'Claude' } - ) - }, - /hit its session limit/ - ], - [ - 'compaction failure', - { - kind: 'status', - tone: 'error', - ...agentSessionFailureWords( - { kind: 'compactionFailed', detail: { text: 'nothing to compact', audience: 'person' } }, - { surface: 'row', agentName: 'Grok' } - ) - }, - /Compaction failed: nothing to compact/ - ], - [ - 'fact-less provider error', - { kind: 'status', tone: 'error', text: 'API Error: 529 upstream overloaded' }, - /API Error: 529 upstream overloaded/ - ] - ] - - describe('a failed /compact command turn', () => { - it.each(failures)( - 'shows its %s with no recovery controls, leaving the request before it as it was', - (_name, failure, words) => { - const items = [ - row('u1', 1, { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: 'Fix it' }] - }), - settled('t1', 'u1', 'success', 2), - row( - 't1-answer', - 3, - { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Fixed.' }] }, - 't1' - ), - row(compactEntry, 10, { - kind: 'message', - role: 'user', - blocks: [{ type: 'text', text: '/compact' }], - command: { name: 'compact' } - }), - settled(commandTurn, compactEntry, 'failure', 11), - row('command-failure', 12, failure, commandTurn) - ] - // The live list's Continue targets come from these selectors; neither offers the command. - expect(latestNativeChatOrcaStopCut(items, [])).toBeNull() - expect(latestNativeChatUsageLimitCut(items, [])).toBeNull() - render( - - - - ) - expect(screen.getByText('/compact')).toBeVisible() - expect(screen.getAllByText(words)).toHaveLength(1) - expect(screen.getByText(words)).toBeVisible() - expect(screen.queryByRole('button', { name: /Continue/ })).toBeNull() - expect(screen.queryByRole('separator', { name: 'Context compacted' })).toBeNull() - expect(screen.getByText('Fixed.')).toBeVisible() - // Status readers keep the last real request's verdict through the failed command. - expect(latestStructuredAgentSessionRequest(items, [])).toMatchObject({ - id: 't1', - outcome: 'success' - }) - } - ) - }) -} diff --git a/src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx b/src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx index 3b7d2c5e720..5c09b84140c 100644 --- a/src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx +++ b/src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx @@ -137,32 +137,4 @@ describe('NativeChatResolvedView turn status', () => { expect(screen.queryByRole('button', { name: 'Toggle turn details' })).toBeNull() expect(screen.getByText('pnpm build')).toBeInTheDocument() }) - - it('folds finished turns from history behind their transcript duration', () => { - const at = Date.parse('2026-09-28T10:00:00.000Z') - retained.session = transcript('ready', false, [ - { ...userTurn, timestamp: at }, - { - id: 'answer-1', - role: 'assistant', - blocks: [{ type: 'text', text: 'Renamed.' }], - timestamp: at + 45_000, - source: 'transcript' - }, - { - id: 'user-2', - role: 'user', - blocks: [{ type: 'text', text: 'Now add tests' }], - timestamp: at + 100_000, - source: 'transcript' - } - ]) - setStatus({ state: 'done' }, 60_000) - - renderPane() - - expect(screen.getByText('Worked for 45s')).toBeInTheDocument() - // The latest turn has no recorded end, and this pane never watched it. - expect(screen.getAllByText(/Work(ing|ed) for/)).toHaveLength(1) - }) }) diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.test.ts b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.test.ts index 2ffd2768117..6967674feca 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.test.ts +++ b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-indexeddb.test.ts @@ -67,7 +67,6 @@ function fakeDatabase(): { return { factory: factory as unknown as IDBFactory, transactions, puts } } -const DRAFT = { text: 'unsent', images: [], savedAt: 1 } const settledYet = async (promise: Promise): Promise => { let settled = false void promise.then(() => (settled = true)) @@ -76,16 +75,6 @@ const settledYet = async (promise: Promise): Promise => { } describe('the IndexedDB draft storage', () => { - it('settles a write only when its transaction completes', async () => { - const { factory, transactions, puts } = fakeDatabase() - const write = createIndexedDbNativeChatComposerDraftStorage(factory).write('scope', DRAFT) - - expect(await settledYet(write)).toBe(false) - expect(puts).toEqual([DRAFT]) - transactions[0]!.oncomplete?.() - await expect(write).resolves.toBeUndefined() - }) - describe('through the draft store', () => { const loaded: { clearNativeChatComposerDraftsForTests: () => void }[] = [] afterEach(() => { diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-lifecycle.test.tsx b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-lifecycle.test.tsx index bb2c672a8b4..5eb597e0024 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-lifecycle.test.tsx +++ b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-lifecycle.test.tsx @@ -309,37 +309,6 @@ describe('native-chat composer draft lifecycle', () => { expect(other.api?.draft).toBe(' and more') }) - it('leaves nothing saved when a send clears a draft whose typing was still deferred', async () => { - vi.useFakeTimers() - const hooks = await loadHooks() - const seen: { api?: ComposerApi } = {} - await mount( - createElement( - composer(hooks, (next) => { - seen.api = next - }), - { scopeKey: 'tab-1:pane' } - ) - ) - await act(async () => { - seen.api?.attachments.attachResolvedPaths(['/repo/a.png']) - }) - await act(async () => { - seen.api?.setDraft('hello') - }) - await act(async () => { - seen.api?.setDraft('') - seen.api?.attachments.clearImageAttachments() - }) - expect(storedDraft('tab-1:pane')).toBeNull() - - await act(async () => { - vi.advanceTimersByTime(1_000) - }) - window.dispatchEvent(new Event('pagehide')) - expect(storedDraft('tab-1:pane')).toBeNull() - }) - it('does not bring back a sent image when a paste from a replaced composer is dropped late', async () => { const hooks = await loadHooks() const first: { api?: ComposerApi } = {} @@ -491,30 +460,6 @@ describe('native-chat composer draft lifecycle', () => { ]) }) - it('leaves a restored image a paired server stored to that server to check', async () => { - // Not on this machine's disk, so a local check could only call it gone. - const pathExists = vi.fn(async () => false) - vi.stubGlobal('api', { fs: { pathExists } }) - const stored = { id: 'a', path: '/srv/orca/agent-session-attachments/0f6c/shot.png' } - storage.drafts.set('agent-session:s1', { text: 'see this', images: [stored], savedAt: 1 }) - const hooks = await loadHooks() - const seen: { api?: ComposerApi } = {} - try { - await mount( - createElement( - composer(hooks, (next) => (seen.api = next)), - { scopeKey: 'agent-session:s1' } - ) - ) - await act(async () => {}) - } finally { - vi.unstubAllGlobals() - } - - expect(pathExists).not.toHaveBeenCalled() - expect(seen.api?.attachments.imageAttachments).toEqual([stored]) - }) - it('shows a restored paste from Orca’s paste folder once main confirms it is kept, and marks the rest', async () => { const folder = '/Users/me/Library/Application Support/orca/native-chat-pastes' let answer: () => void = () => {} @@ -566,38 +511,6 @@ describe('native-chat composer draft lifecycle', () => { ]) }) - it('takes another window’s send of the same draft, unless an edit here is still unsaved', async () => { - storage.drafts.set('tab-1:pane', { text: 'sent in the other tab', images: [], savedAt: 1 }) - const hooks = await loadHooks() - const seen: { api?: ComposerApi } = {} - await mount( - createElement( - composer(hooks, (next) => (seen.api = next)), - { scopeKey: 'tab-1:pane' } - ) - ) - expect(seen.api?.draft).toBe('sent in the other tab') - - // The other tab sends: it removes the draft, and this window hears of it. - await loadHooks() - const otherDrafts = await import('./native-chat-draft-views') - otherDrafts.writeNativeChatDraftCache('tab-1:pane', '') - await act(async () => { - await vi.waitFor(() => expect(seen.api?.draft).toBe('')) - }) - await act(async () => seen.api?.setDraft((previous) => `${previous}next`)) - window.dispatchEvent(new Event('pagehide')) - expect(storedDraft('tab-1:pane')).toMatchObject({ text: 'next' }) - - // An edit here not yet saved wins over the other window's write. - await act(async () => seen.api?.setDraft('mine, unsaved')) - otherDrafts.appendNativeChatDraftCache('tab-1:pane', 'theirs') - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 20)) - }) - expect(seen.api?.draft).toBe('mine, unsaved') - }) - it('ignores foreign present/corrupt setup payloads, but keeps guarded absent-record removal through the real channel', async () => { const hooks = await loadHooks() const store = await import('./native-chat-composer-draft-store') @@ -673,36 +586,6 @@ describe('native-chat composer draft lifecycle', () => { } }) - it('shows a composer its draft was refused, keeps it, and clears the mark once a retry lands', async () => { - const hooks = await loadHooks() - const { useNativeChatComposerDraftUnsaved } = await import('./use-native-chat-draft-unsaved') - const store = await import('./native-chat-composer-draft-persistence') - const seen: { api?: ComposerApi; unsaved?: boolean } = {} - const Draft = composer(hooks, (next) => (seen.api = next)) - function Marked({ scopeKey }: { scopeKey: string }): React.JSX.Element { - seen.unsaved = useNativeChatComposerDraftUnsaved(scopeKey) - return createElement(Draft, { scopeKey }) - } - await mount(createElement(Marked, { scopeKey: 'tab-1:pane' })) - - storage.refuseWrites = true - await act(async () => { - seen.api?.setDraft('typed on a full disk') - store.flushNativeChatComposerDrafts() - await store.nativeChatComposerDraftWritesSettled() - }) - expect(seen.unsaved).toBe(true) - expect(seen.api?.draft).toBe('typed on a full disk') - - storage.refuseWrites = false - await act(async () => { - window.dispatchEvent(new Event('pagehide')) - await store.nativeChatComposerDraftWritesSettled() - }) - expect(seen.unsaved).toBe(false) - expect(storedDraft('tab-1:pane')).toMatchObject({ text: 'typed on a full disk' }) - }) - it('does not bring back an untouched launch link after a reload, when no seed is left to replace it', async () => { const link = 'https://github.com/o/r/issues/12' const seed: NativeChatLaunchDraft = { diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-store.test.ts b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-store.test.ts index 301a90cb3f8..1e58939190a 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-store.test.ts +++ b/src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-store.test.ts @@ -64,11 +64,6 @@ const IMAGES = [ { id: 'a-2', path: '/remote/repo/diagram.png', connectionId: 'ssh-1' } ] -const SKILL_DOCUMENT = { - type: 'doc', - content: [{ type: 'paragraph', content: [{ type: 'text', text: 'with /skill' }] }] -} - let modules: DraftModules const originalPreloadApi = window.api @@ -93,23 +88,6 @@ afterEach(() => { }) describe('native-chat composer draft store', () => { - it('gives back the text, its editor document and the images after a reload', async () => { - vi.useFakeTimers() - modules.attachments.appendNativeChatAttachmentCache('tab-1:pane', IMAGES) - modules.drafts.writeNativeChatDraftDocument('tab-1:pane', 'with /skill', SKILL_DOCUMENT) - modules.drafts.writeNativeChatDraftCache('tab-1:pane', 'with /skill') - expect(storedDraft('tab-1:pane')?.text).toBe('') - vi.advanceTimersByTime(250) - vi.useRealTimers() - - const reloaded = await reload() - expect(reloaded.drafts.readNativeChatDraftCache('tab-1:pane')).toBe('with /skill') - expect(reloaded.drafts.readNativeChatDraftDocument('tab-1:pane', 'with /skill')).toEqual( - SKILL_DOCUMENT - ) - expect(reloaded.attachments.readNativeChatAttachmentCache('tab-1:pane')).toEqual(IMAGES) - }) - it('replays a change storage had not confirmed when the window went away', async () => { const uncommitted = createMemoryNativeChatComposerDraftStorage() uncommitted.write = () => new Promise(() => {}) @@ -191,25 +169,6 @@ describe('native-chat composer draft store', () => { ) }) - it('keeps text given back through a crash before storage commits it, once', async () => { - storage.drafts.set('agent-session:s1', { text: 'typed earlier', images: [], savedAt: 1 }) - const crashing = { ...storage, write: () => new Promise(() => {}) } - const crashed = await reload({ using: crashing }) - // Stop gives a message back; its outbox entry is deleted right after, then Orca crashes. - expect(crashed.drafts.appendNativeChatDraftCache('agent-session:s1', 'returned by Stop')).toBe( - true - ) - crashed.reset.clearNativeChatComposerDraftsForTests() - - const next = await reload() - expect(next.drafts.readNativeChatDraftCache('agent-session:s1')).toBe( - 'typed earlier\n\nreturned by Stop' - ) - await next.persistence.nativeChatComposerDraftWritesSettled() - expect(storedDraft('agent-session:s1')?.text).toBe('typed earlier\n\nreturned by Stop') - expect(localStorage.getItem('orca:nativeChatComposerDraftJournal:v1')).toBeNull() - }) - it('does not give text back twice when storage committed it but the window died first', async () => { storage.drafts.set('agent-session:s1', { text: 'typed earlier', images: [], savedAt: 1 }) const landsUnconfirmed = { @@ -292,42 +251,6 @@ describe('native-chat composer draft store', () => { ]) }) - it('puts a re-attached image in the place of the one to attach again, under its id', async () => { - storage.drafts.set('tab-1:pane', { - text: 'see', - images: [{ id: 'm', path: '', unavailableName: 'shot.png' }, IMAGES[0]], - savedAt: 1 - }) - const reloaded = await reload() - - reloaded.attachments.appendNativeChatAttachmentCache( - 'tab-1:pane', - [{ id: 'again', path: '/Users/me/Desktop/shot.png' }], - { fromUser: true } - ) - expect(reloaded.attachments.readNativeChatAttachmentCache('tab-1:pane')).toEqual([ - { id: 'm', path: '/Users/me/Desktop/shot.png' }, - IMAGES[0] - ]) - }) - - it('adds an image Stop gives back next to a placeholder with its name, never in its place', async () => { - storage.drafts.set('tab-1:pane', { - text: 'compare with this', - images: [{ id: 'm', path: '', unavailableName: 'image.png' }], - savedAt: 1 - }) - const reloaded = await reload() - - reloaded.attachments.appendNativeChatAttachmentCache('tab-1:pane', [ - { id: 'withdrawn-cm-1-1', path: '/Users/me/Downloads/image.png' } - ]) - expect(reloaded.attachments.readNativeChatAttachmentCache('tab-1:pane')).toEqual([ - { id: 'm', path: '', unavailableName: 'image.png' }, - { id: 'withdrawn-cm-1-1', path: '/Users/me/Downloads/image.png' } - ]) - }) - it('removes the saved draft as soon as it is sent, even with a typed change still deferred', async () => { vi.useFakeTimers() modules.attachments.appendNativeChatAttachmentCache('tab-1:pane', IMAGES) @@ -397,16 +320,6 @@ describe('native-chat composer draft store', () => { ) }) - it('drops a stored record that is not a draft', async () => { - storage.drafts.set('broken', JSON.parse('{"text":5}')) - storage.drafts.set('tab-1:pane', { text: 'fine', images: [], savedAt: 1 }) - - const reloaded = await reload() - await reloaded.persistence.nativeChatComposerDraftWritesSettled() - expect(storage.drafts.has('broken')).toBe(false) - expect(reloaded.drafts.readNativeChatDraftCache('tab-1:pane')).toBe('fine') - }) - it('keeps what was typed before a slow load lands, and fills in the rest when it does', async () => { storage.drafts.set('tab-1:pane', { text: 'saved earlier', images: [], savedAt: 1 }) storage.drafts.set('tab-2:pane', { text: 'other chat', images: [], savedAt: 1 }) @@ -461,8 +374,6 @@ describe('native-chat composer draft store', () => { 'saved earlier\n\nreturned by Stop' ) expect(reloaded.attachments.readNativeChatAttachmentCache('agent-session:s1')).toEqual(IMAGES) - const memory = await import('./native-chat-composer-draft-memory') - expect(memory.restoredImageChecks.get('agent-session:s1')).toHaveLength(1) expect(storedDraft('agent-session:s1')).toMatchObject({ text: 'saved earlier\n\nreturned by Stop', images: IMAGES @@ -529,11 +440,9 @@ describe('native-chat composer draft store', () => { it('starts the load on its first write when startup never did', async () => { storage.drafts.set('agent-session:other', { text: 'saved elsewhere', images: [], savedAt: 1 }) - const counted = { ...storage, loadAll: vi.fn(() => storage.loadAll()) } - const reloaded = await reload({ using: counted, hydrate: false }) + const reloaded = await reload({ hydrate: false }) reloaded.drafts.writeNativeChatDraftCache('tab-1:pane', 'typed') - expect(counted.loadAll).toHaveBeenCalledTimes(1) await vi.waitFor(() => expect(reloaded.drafts.readNativeChatDraftCache('agent-session:other')).toBe( 'saved elsewhere' diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-composer-prompt-recall.test.tsx b/src/renderer/src/components/native-chat/drafts/native-chat-composer-prompt-recall.test.tsx index 181af6bfdfe..3ca81e627dc 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-composer-prompt-recall.test.tsx +++ b/src/renderer/src/components/native-chat/drafts/native-chat-composer-prompt-recall.test.tsx @@ -1,7 +1,4 @@ -import { - changePrompt, - promptValue -} from '../composer/editor/native-chat-prompt-editor.test-support' +import { promptValue } from '../composer/editor/native-chat-prompt-editor.test-support' // @vitest-environment happy-dom import { cleanup, fireEvent, render, screen } from '@testing-library/react' @@ -142,11 +139,4 @@ describe('composer prompt recall', () => { expect(press(input, 'ArrowUp')).toBe('/model') expect(press(input, 'ArrowUp')).toBe('one') }) - - it('leaves the arrows alone once a recalled prompt is edited', () => { - const input = renderComposer(['one', 'two']) - press(input, 'ArrowUp') - changePrompt(input, 'two, edited') - expect(press(input, 'ArrowUp')).toBe('two, edited') - }) }) diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts b/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts index ec169cb73a4..8cff22c0b3d 100644 --- a/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts +++ b/src/renderer/src/components/native-chat/drafts/native-chat-draft-owner.ts @@ -8,7 +8,7 @@ import { chatWorkspaceByTabId, structuredChatWorkspacesBySessionId } from '../../../lib/structured-chat-tab-index' -import { resolveWorktreeOperationRoute } from '../../../lib/worktree-operation-route' +import { resolveWorktreeOperationRoute } from '../../../lib/workspace/ownership/worktree-operation-route' function workspaceOfDraftScope( state: Pick, diff --git a/src/renderer/src/components/native-chat/drafts/native-chat-draft-retention.test.ts b/src/renderer/src/components/native-chat/drafts/native-chat-draft-retention.test.ts deleted file mode 100644 index 1ee21faf2e1..00000000000 --- a/src/renderer/src/components/native-chat/drafts/native-chat-draft-retention.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, expect, it, vi } from 'vitest' -import { clearNativeChatComposerDraftsForTests } from './native-chat-draft-reset' -import { - readNativeChatComposerDraft, - subscribeToNativeChatComposerDraft -} from './native-chat-composer-draft-store' -import { hydrateNativeChatComposerDrafts } from './native-chat-composer-draft-load' -import { nativeChatComposerDraftWritesSettled } from './native-chat-composer-draft-persistence' -import { - createMemoryNativeChatComposerDraftStorage, - setNativeChatComposerDraftStorageForTests, - type StoredNativeChatComposerDraft -} from './native-chat-composer-draft-storage' -import { records } from './native-chat-composer-draft-memory' -import { deleteWorkspaceChatDrafts } from '@/store/slices/worktrees/teardown/removed-worktree-chat-drafts' - -afterEach(() => { - vi.restoreAllMocks() - clearNativeChatComposerDraftsForTests() -}) -it('hydrates and explicitly deletes retained closed drafts with linear saved-record work at N and 10N', async () => { - for (const count of [100, 1000]) { - clearNativeChatComposerDraftsForTests() - localStorage.clear() - const storage = createMemoryNativeChatComposerDraftStorage() - for (let i = 0; i < count; i++) { - storage.drafts.set(`agent-session:closed-${i}`, { - text: `retained context ${i}\n${'text '.repeat(40)}`, - images: [], - owner: { - workspaceId: 'folder-workspace:kept', - executionHostId: i % 2 ? 'ssh:other' : 'local' - }, - savedAt: i + 1 - }) - } - let visits = 0 - class SavedRecords extends Map { - override *[Symbol.iterator](): Generator< - [string, StoredNativeChatComposerDraft], - undefined, - unknown - > { - for (const entry of super[Symbol.iterator]()) { - visits++ - yield entry - } - return undefined - } - } - const load = vi.fn(async () => new SavedRecords(storage.drafts)) - const write = vi.fn(storage.write) - const remove = vi.fn(storage.remove) - setNativeChatComposerDraftStorageForTests({ ...storage, loadAll: load, write, remove }) - await hydrateNativeChatComposerDrafts() - expect(load).toHaveBeenCalledOnce() - expect(visits).toBe(count) - expect(records.size).toBe(count) - const gets = vi.spyOn(records, 'get') - const affected = vi.fn(), - otherHost = vi.fn() - const off = subscribeToNativeChatComposerDraft('agent-session:closed-0', affected) - const offOther = subscribeToNativeChatComposerDraft('agent-session:closed-1', otherHost) - deleteWorkspaceChatDrafts({ - owners: [{ workspaceId: 'folder-workspace:kept', executionHostId: 'local' }], - conversations: [], - terminalTabIds: [] - }) - // Owner selection reads each saved record once; persistence may read the selected keys again. - expect(gets.mock.calls.length).toBeLessThanOrEqual(count * 2) - await nativeChatComposerDraftWritesSettled() - expect(records.size).toBe(count / 2) - expect(storage.drafts.size).toBe(count / 2) - expect(remove.mock.calls.flatMap(([keys]) => keys)).toHaveLength(count / 2) - expect(write).not.toHaveBeenCalled() - expect(affected).toHaveBeenCalledOnce() - expect(otherHost).not.toHaveBeenCalled() - expect(readNativeChatComposerDraft('agent-session:closed-1').text).toBe( - `retained context 1\n${'text '.repeat(40)}` - ) - off() - offOther() - gets.mockRestore() - } -}) diff --git a/src/renderer/src/components/native-chat/drafts/use-native-chat-launch-draft-adoption.test.tsx b/src/renderer/src/components/native-chat/drafts/use-native-chat-launch-draft-adoption.test.tsx index 5e5b75a909d..5d45218606a 100644 --- a/src/renderer/src/components/native-chat/drafts/use-native-chat-launch-draft-adoption.test.tsx +++ b/src/renderer/src/components/native-chat/drafts/use-native-chat-launch-draft-adoption.test.tsx @@ -110,12 +110,4 @@ describe('useNativeChatLaunchDraftSignal', () => { rerender({ messages: [turn], transcriptLoading: false }) expect(result.current.launchDraftResolved).toBe(true) }) - - it('does not resolve from an in-flight transcript that still shows recent turns', () => { - // In-flight reads may still show the previous generation’s tail. - const { result } = renderSignal([userTurn('u1', SEEDED_AT)], true) - - expect(result.current.launchDraftResolved).toBe(false) - expect(result.current.launchDraft).not.toBeNull() - }) }) diff --git a/src/renderer/src/components/native-chat/drafts/use-native-chat-terminal-draft-pickup.test.ts b/src/renderer/src/components/native-chat/drafts/use-native-chat-terminal-draft-pickup.test.ts deleted file mode 100644 index f0d8385c0ab..00000000000 --- a/src/renderer/src/components/native-chat/drafts/use-native-chat-terminal-draft-pickup.test.ts +++ /dev/null @@ -1,99 +0,0 @@ -// @vitest-environment happy-dom - -import { renderHook } from '@testing-library/react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatLaunchDraft } from '@/components/native-chat/drafts/native-chat-launch-prompt' -import { useNativeChatTerminalDraftPickup } from './use-native-chat-terminal-draft-pickup' - -const mocks = vi.hoisted(() => { - const launchDrafts: Record = {} - return { - seedNativeChatLaunchDraft: vi.fn(), - resolveNativeChatLaunchDraft: vi.fn(), - launchDrafts - } -}) - -vi.mock('../../../store/index', () => ({ - useAppStore: { - getState: () => ({ - nativeChatLaunchDraftByTabId: mocks.launchDrafts, - seedNativeChatLaunchDraft: mocks.seedNativeChatLaunchDraft, - resolveNativeChatLaunchDraft: mocks.resolveNativeChatLaunchDraft - }) - } -})) - -function seed(overrides: Partial = {}): NativeChatLaunchDraft { - return { - tabId: 'tab-1', - agent: 'claude', - text: 'look at the flaky retry test', - createdAt: 1_000, - fromTerminal: true, - ...overrides - } -} - -describe('useNativeChatTerminalDraftPickup', () => { - beforeEach(() => { - vi.clearAllMocks() - mocks.launchDrafts = {} - }) - - type Props = { - launchDraft: NativeChatLaunchDraft | null - resolved: boolean - transcriptReady: boolean - } - - function render(initialProps: Props) { - const readTerminalDraft = vi.fn(() => 'typed in the terminal') - const hook = renderHook( - (props: Props) => - useNativeChatTerminalDraftPickup({ - terminalTabId: 'tab-1', - agent: 'claude', - launchSeed: { - launchDraft: props.launchDraft, - launchDraftResolved: props.resolved, - transcriptReady: props.transcriptReady, - ownsTabWideLaunchDraft: true, - readTerminalDraft - } - }), - { initialProps } - ) - return { hook, readTerminalDraft } - } - - const orcaDraft = seed({ fromTerminal: undefined }) - - it('reads the line once the transcript shows a draft Orca typed was already sent', () => { - const { hook, readTerminalDraft } = render({ - launchDraft: orcaDraft, - resolved: false, - transcriptReady: false - }) - expect(readTerminalDraft).not.toHaveBeenCalled() - - hook.rerender({ launchDraft: orcaDraft, resolved: true, transcriptReady: true }) - expect(readTerminalDraft).toHaveBeenCalledTimes(1) - expect(mocks.seedNativeChatLaunchDraft).toHaveBeenCalledWith( - expect.objectContaining({ text: 'typed in the terminal', fromTerminal: true }) - ) - }) - - it('never reads after a chat send takes the Orca draft before the transcript is ready', () => { - const { hook, readTerminalDraft } = render({ - launchDraft: orcaDraft, - resolved: false, - transcriptReady: false - }) - // The send drops the seed at once, while its clear may not have reached the terminal yet. - hook.rerender({ launchDraft: null, resolved: false, transcriptReady: false }) - hook.rerender({ launchDraft: null, resolved: false, transcriptReady: true }) - - expect(readTerminalDraft).not.toHaveBeenCalled() - }) -}) diff --git a/src/renderer/src/components/native-chat/host-access/NativeChatInstallTile.tsx b/src/renderer/src/components/native-chat/host-access/NativeChatInstallTile.tsx index cf9e2268acf..582e358c220 100644 --- a/src/renderer/src/components/native-chat/host-access/NativeChatInstallTile.tsx +++ b/src/renderer/src/components/native-chat/host-access/NativeChatInstallTile.tsx @@ -1,5 +1,5 @@ import { TriangleAlert } from 'lucide-react' -import { AgentIcon } from '@/lib/agent-catalog' +import { AgentIcon } from '@/components/agent/icons/AgentIcon' import { agentTypeToIconAgent } from '../../../../../shared/agent-status/presentation/agent-type-icon-agent' import { cn } from '@/lib/utils' import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types' diff --git a/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts b/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts index 004cfff5501..23d0c26dedd 100644 --- a/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts +++ b/src/renderer/src/components/native-chat/host-access/native-chat-sign-in.ts @@ -7,7 +7,7 @@ import { agentSessionRemoteSignInCommand } from '../../../../../shared/agent-ses import { persistAgentLaunchTabOrder } from '@/lib/agent-session/launch/pane/launch-agent-tab-order' import { createWebRuntimeSessionTerminalOnHost } from '@/runtime/hosted-terminals/creation/web-runtime-terminal-creation' import { notifyWebRuntimeTerminalCreateFailure } from '@/runtime/hosted-terminals/creation/web-runtime-terminal-create-failure-notice' -import { startStoppedWslHostForUserAct } from '@/lib/wsl-host-user-start' +import { startStoppedWslHostForUserAct } from '@/runtime/hosts/wsl/wsl-host-user-start' import { toast } from 'sonner' import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' diff --git a/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage-notice.ts b/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage-notice.ts index 2f173083409..c3781e768b3 100644 --- a/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage-notice.ts +++ b/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage-notice.ts @@ -2,7 +2,7 @@ import { useState } from 'react' import { connectRuntimeHostAndReloadProjects } from '@/components/status-bar/runtime-environment-explicit-connect' import { useMountedRef } from '@/hooks/useMountedRef' import { useTranslate } from '@/i18n/use-translate' -import { startWslHostAndReloadProjects } from '@/lib/wsl-host-user-start' +import { startWslHostAndReloadProjects } from '@/runtime/hosts/wsl/wsl-host-user-start' import type { NativeChatComposerNotice } from '../composer/controls/native-chat-composer-notice' import type { NativeChatHostOutage } from './use-native-chat-host-outage' diff --git a/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.ts b/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.ts index ab4c404825a..ac8066b9a92 100644 --- a/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.ts +++ b/src/renderer/src/components/native-chat/host-access/use-native-chat-host-outage.ts @@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from 'react' import { useAppStore } from '@/store' import { toRuntimeExecutionHostId } from '../../../../../shared/execution-host' import { runtimeHostContactFromSnapshot } from '../../../../../shared/remote-runtime/host-status/runtime-host-contact' -import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' +import { selectExecutionHostDisplayLabel } from '@/runtime/hosts/display/execution-host-display-label' import { runtimeHostConnectionStateForEntry } from '@/runtime/hosts/connections/runtime-host-connection-state' import type { RuntimeHostConnectionState } from '../../../../../shared/remote-runtime/host-status/runtime-host-connection-state' import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target' diff --git a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts b/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts index fe785068cb5..5618d990670 100644 --- a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts +++ b/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts @@ -12,7 +12,7 @@ const connection = vi.hoisted(() => ({ currentOwnerResolved: true })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ isWorktreeConnectionResolved: () => connection.resolved })) diff --git a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.ts b/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.ts index a48c02e2ebc..a9f95c2ca9f 100644 --- a/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.ts +++ b/src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.ts @@ -1,5 +1,5 @@ import { createContext } from 'react' -import { isWorktreeConnectionResolved } from '@/lib/connection-context' +import { isWorktreeConnectionResolved } from '@/lib/workspace/ownership/connection-context' import { createTerminalPathExistenceBatch } from '@/components/terminal-pane/links/files/terminal-path-existence-batch' import { mayCheckFileLinkTargetUnprompted, diff --git a/src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts b/src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts index 5eff251d407..bc3890b6acc 100644 --- a/src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts +++ b/src/renderer/src/components/native-chat/links/actions/native-chat-host-file-open.test.ts @@ -15,7 +15,9 @@ vi.mock('@/lib/workspace/activation/worktree-activation', () => ({ activateAndRevealWorkspace: vi.fn(), activateAndRevealWorktree: vi.fn() })) -vi.mock('@/lib/connection-context', () => ({ getConnectionId: vi.fn(() => null) })) +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ + getConnectionId: vi.fn(() => null) +})) installTerminalLinkTestEnvironment(doubles) diff --git a/src/renderer/src/components/native-chat/links/actions/native-chat-http-link-source-owner.ts b/src/renderer/src/components/native-chat/links/actions/native-chat-http-link-source-owner.ts index 43783963424..70cf0f8a6b4 100644 --- a/src/renderer/src/components/native-chat/links/actions/native-chat-http-link-source-owner.ts +++ b/src/renderer/src/components/native-chat/links/actions/native-chat-http-link-source-owner.ts @@ -1,4 +1,4 @@ -import { getConnectionIdFromState } from '@/lib/connection-owner-resolution' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing' import { canOpenWorkspaceBrowserTabOnRuntime, diff --git a/src/renderer/src/components/native-chat/links/actions/use-native-chat-file-link-existence.tsx b/src/renderer/src/components/native-chat/links/actions/use-native-chat-file-link-existence.tsx index f7f6b641fed..8006e01180a 100644 --- a/src/renderer/src/components/native-chat/links/actions/use-native-chat-file-link-existence.tsx +++ b/src/renderer/src/components/native-chat/links/actions/use-native-chat-file-link-existence.tsx @@ -1,6 +1,6 @@ import { useContext, useEffect, useMemo, useRef, useSyncExternalStore, type ReactNode } from 'react' import { useAppStore } from '@/store' -import { getConnectionIdFromState } from '@/lib/connection-owner-resolution' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { getRuntimeEnvironmentRevision, onRuntimeEnvironmentRevisionsChanged diff --git a/src/renderer/src/components/native-chat/markdown/native-chat-markdown.css b/src/renderer/src/components/native-chat/markdown/native-chat-markdown.css index 6a7047a7f04..fed9e2282a1 100644 --- a/src/renderer/src/components/native-chat/markdown/native-chat-markdown.css +++ b/src/renderer/src/components/native-chat/markdown/native-chat-markdown.css @@ -30,6 +30,8 @@ overflow-wrap: anywhere; color: var(--chat-link); text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); + /* Clears descenders; on file-link code chips it deliberately lands on the bottom border. */ + text-underline-offset: 0.25em; } /* File links wrap inline code, so formatted labels follow the link color. */ diff --git a/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx b/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx index 443db26c2f5..c7ef11c5862 100644 --- a/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx +++ b/src/renderer/src/components/native-chat/media/images/NativeChatTranscriptChrome.test.tsx @@ -25,7 +25,7 @@ const mocks = vi.hoisted(() => ({ vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: mocks.callRuntimeRpc })) -vi.mock('@/lib/connection-context', () => ({ +vi.mock('@/lib/workspace/ownership/connection-context', () => ({ getConnectionIdForFile: mocks.getConnectionIdForFile })) diff --git a/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts b/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts index 32282e59bbe..a7a017009ee 100644 --- a/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts +++ b/src/renderer/src/components/native-chat/media/images/native-chat-image-runtime-context.ts @@ -6,7 +6,7 @@ import type { RuntimeClientTarget } from '../../../../../../shared/runtime-clien import { resolveWorktreeOperationRouteResult, type WorktreeOperationRouteResolution -} from '@/lib/worktree-operation-route' +} from '@/lib/workspace/ownership/worktree-operation-route' import { createNativeChatTabOwnerSelector, findNativeChatTabOwnerWorktreeId @@ -18,7 +18,7 @@ import { } from '../../../../../../shared/execution-host' import { isFloatingWorkspaceId } from '../../../../../../shared/floating-workspace-worktree' import { resolveNativeChatTabDirectory } from '../../pane/routing/native-chat-tab-directory' -import { resolveOwner } from '@/lib/resolve-owner' +import { resolveOwner } from '@/lib/workspace/ownership/resolve-owner' import { useMemo } from 'react' import { shallow } from 'zustand/shallow' import { firstRegisteredStructuredChatTab } from '@/lib/structured-chat-tab-index' diff --git a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx index 1e733282a7d..31b9ab781f7 100644 --- a/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx +++ b/src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.tsx @@ -11,7 +11,7 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { useTranslate } from '@/i18n/use-translate' import { fileArtifactSourceKey } from '@/lib/file-artifact-source-key' -import { openFileInBrowserTab } from '@/lib/file-preview' +import { openFileInBrowserTab } from '@/lib/browser/documents/file-preview' import { basename } from '@/lib/path' import { getRuntimeTargetHostId, diff --git a/src/renderer/src/components/native-chat/messages/actions/NativeChatAgentControls.tsx b/src/renderer/src/components/native-chat/messages/actions/NativeChatAgentControls.tsx index 34e6b81cbf3..5db891afcaf 100644 --- a/src/renderer/src/components/native-chat/messages/actions/NativeChatAgentControls.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/NativeChatAgentControls.tsx @@ -21,7 +21,7 @@ export function NativeChatAgentControls({ }): React.JSX.Element { const t = useTranslate() return ( - // Hover-only row chrome: find skips it rather than counting what the mouse happens to show. + // Row chrome, not transcript: find skips it.
{/* A visual line means nothing pasted outside Orca, so the copy leaves it out. An image-only response has nothing to copy, so it has no Copy. */} diff --git a/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.target.test.tsx b/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.target.test.tsx index 951f3d7f43b..049abc9cb9e 100644 --- a/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.target.test.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/NativeChatRewindAction.target.test.tsx @@ -77,8 +77,6 @@ describe('rewind target after send acceptance', () => { it.each([ ['codex', 'orca'], - ['codex', 'provider'], - ['claude', 'orca'], ['claude', 'provider'] ] as const)('uses the accepted %s row with a %s journal key', async (agent, keySource) => { const hook = renderHook(() => @@ -150,6 +148,5 @@ describe('rewind target after send acceptance', () => { ) ) expect(confirm).toHaveBeenCalledOnce() - expect(confirm).toHaveBeenCalledWith(expect.objectContaining({ title: 'Rewind to here?' })) }) }) diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts index 00c476f9091..5db0cd89263 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-reveal-latest.ts @@ -1,5 +1,7 @@ import { useCallback, useImperativeHandle, useMemo, useRef } from 'react' +import { useAppStore } from '@/store' import { hasAskAnswer } from '../../../../../../shared/native-chat/input/native-chat-ask-answer' +import { nativeChatScrollsToLatestOnSend } from '../../../../../../shared/native-chat/native-chat-appearance-settings' import { nativeChatSlotCopyText } from './native-chat-message-copy-text' import type { NativeChatTranscriptSlot } from '../../conversation/slots/native-chat-transcript-slots' import type { NativeChatInteractiveSend } from '../../session/terminal/send/use-native-chat-interactive-send' @@ -56,7 +58,7 @@ export type NativeChatMessageListHandle = { readerAtEnd: () => boolean /** Bring a find match into view, clear of the find bar; the reader stops following the latest. */ revealFindMatch: (match: Range, bar: DOMRectReadOnly | null) => void - /** What the row drawing this message copies from its hover button; null when none draws it. */ + /** What the row drawing this message copies from its Copy button; null when none draws it. */ messageCopyText: (messageId: string) => string | null /** Open a subagent's activity where it sits in the conversation and bring it into view. */ revealSubagent: (agentId: string) => void @@ -86,22 +88,36 @@ export function useNativeChatRevealLatest(): { return { messageListRef, revealLatest, captureRevealLatest } } -function ignoreFindMatch(): void {} - -function alwaysAtEnd(): boolean { - return true -} - -function ignoreSubagent(): void {} - +/** Own sends follow the latest; with that setting off, only a reader who was at the end does. */ export function useNativeChatMessageListHandle( ref: React.Ref | undefined, - revealLatest: NativeChatMessageListHandle['revealLatest'], - revealFindMatch: NativeChatMessageListHandle['revealFindMatch'] = ignoreFindMatch, - slots: readonly NativeChatTranscriptSlot[] = [], - readerAtEnd: NativeChatMessageListHandle['readerAtEnd'] = alwaysAtEnd, - revealSubagent: NativeChatMessageListHandle['revealSubagent'] = ignoreSubagent + { + readerAtEnd, + beginNavigation, + scrollToBottom, + onSent, + revealFindMatch, + slots, + revealSubagent + }: Pick & { + beginNavigation: () => void + scrollToBottom: (reason: 'send') => void + /** The reader answered, whether or not the view moves. */ + onSent: () => void + slots: readonly NativeChatTranscriptSlot[] + } ): void { + const revealLatest = useCallback( + (readerWasAtEnd = readerAtEnd()) => { + onSent() + if (!nativeChatScrollsToLatestOnSend(useAppStore.getState().settings) && !readerWasAtEnd) { + return + } + beginNavigation() + scrollToBottom('send') + }, + [beginNavigation, onSent, readerAtEnd, scrollToBottom] + ) useImperativeHandle( ref, () => ({ diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx index 6f87e672eef..0138ae9e2e5 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind.test.tsx @@ -11,7 +11,6 @@ import type { AgentJournalRenderItem } from '../../../../../../shared/agent-sess import { AGENT_SESSION_REWIND_RESET_TIMEOUT_MS } from '../../../../../../shared/agent-session/lifecycle/agent-session-rewind-request' import { useNativeChatRewind } from './use-native-chat-rewind' -import { nativeChatRewindReasonCopy, sayNativeChatRewind } from './native-chat-rewind-copy' import type { AgentSessionWriteFailure } from '../../../../../../shared/agent-session/failures/agent-session-write-failure' import { readNativeChatDraftCache, @@ -99,27 +98,6 @@ describe('structured chat rewind', () => { expect([...(view.result.current.surface?.eligibleItemIds ?? [])]).toEqual(['later']) }) - it('offers rewind only below the fork divider', async () => { - const props = input() - const marker: AgentJournalRenderItem = { - ...item('orca:forked-from', 11), - body: { - kind: 'status', - presentation: 'forked-from', - text: 'Forked from Original', - forkedFrom: { sessionId: 'original' } - } - } - const view = render({ - ...props, - state: { ...props.state, items: [...props.state.items, marker] } - }) - expect([...(view.result.current.surface?.eligibleItemIds ?? [])]).toEqual(['later']) - const confirm = vi.fn().mockResolvedValue(true) - await act(() => view.result.current.request('user', confirm)) - expect(confirm).not.toHaveBeenCalled() - }) - it('awaits the suffix sequence in the same epoch before unblocking', async () => { const props = input() props.send.mockResolvedValue({ @@ -167,10 +145,6 @@ describe('structured chat rewind', () => { }) expect(view.result.current.pending).toBe(true) expect(view.result.current.blockedRef.current).toBe(true) - expect(view.result.current.disabledReason).toBe(sayNativeChatRewind('pending')) - // The host's latch covers its own in-flight work; it does not relabel ours. - view.rerender({ ...props, hostBlockedReason: 'outcome-unknown' }) - expect(view.result.current.disabledReason).toBe(sayNativeChatRewind('pending')) await act(async () => { view.rerender({ ...props, state: { ...props.state, epoch: 'new', items: [] } }) response.resolve(done) @@ -201,20 +175,6 @@ describe('structured chat rewind', () => { }) }) - it("lets the host's in-doubt latch disable only the action, never sending", async () => { - const props: Input = { ...input(), hostBlockedReason: 'outcome-unknown' } - const view = render(props) - expect(view.result.current.disabledReason).toBe(nativeChatRewindReasonCopy('outcome-unknown')) - expect(view.result.current.blockedRef.current).toBe(false) - expect(view.result.current.pending).toBe(false) - expect(view.result.current.admitsSend()).toBe(true) - const confirm = vi.fn() - await act(() => view.result.current.request('user', confirm)) - expect(confirm).not.toHaveBeenCalled() - view.rerender({ ...props, hostBlockedReason: undefined }) - expect(view.result.current.disabledReason).toBeNull() - }) - it.each([done, notDone(unknownRefusal)])( 'returns captured content after closure for $kind', async (outcome) => { @@ -262,12 +222,10 @@ describe('structured chat rewind', () => { const view = render(props) await act(() => view.result.current.request('user', async () => true)) expect(view.result.current.blockedRef.current).toBe(true) - await act(() => vi.advanceTimersByTimeAsync(AGENT_SESSION_REWIND_RESET_TIMEOUT_MS - 1)) - expect(view.result.current.pending).toBe(true) - await act(() => vi.advanceTimersByTimeAsync(1)) + await act(() => vi.advanceTimersByTimeAsync(AGENT_SESSION_REWIND_RESET_TIMEOUT_MS)) expect(view.result.current.pending).toBe(false) expect(view.result.current.blockedRef.current).toBe(false) - expect(toastError).toHaveBeenCalledExactlyOnceWith(sayNativeChatRewind('timeout')) + expect(toastError).toHaveBeenCalledOnce() await act(() => vi.advanceTimersByTimeAsync(AGENT_SESSION_REWIND_RESET_TIMEOUT_MS)) expect(toastError).toHaveBeenCalledOnce() } finally { diff --git a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx index be93ea32906..60fd7b7c5cf 100644 --- a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx +++ b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-identity.test.tsx @@ -156,13 +156,6 @@ beforeEach(() => { live: true, activations: 0 }) - feeds.set('remote', { - snapshot: new Map(), - names: new Map(), - listeners: new Set(), - live: true, - activations: 0 - }) useAppStore.setState( { ...initial, activeWorktreeId: RECIPIENT, activeWorkspaceExecutionHostId: 'local' }, true @@ -174,19 +167,6 @@ afterEach(() => { feeds.clear() }) -it('uses the recipient host when identical session text is published by two hosts', () => { - publish('local', [summary(ROOT)]) - publish('remote', [summary(ROOT)]) - useAppStore.setState({ - activeWorkspaceExecutionHostId: 'runtime:remote', - unifiedTabsByWorktree: { - [SENDER]: [tab(ROOT, 'Remote sender', 'runtime:remote'), tab(ROOT, 'Wrong host')] - } - }) - render() - expect(screen.getByText('Remote sender')).toBeInTheDocument() -}) - it('shows a chat sender by its current rename', () => { const renamed = 'Production Release Scan & Compatibility Review' useAppStore.setState({ unifiedTabsByWorktree: { [SENDER]: [tab(ROOT, '')] } }) diff --git a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-source.ts b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-source.ts index 3686d1c0929..010560ee33f 100644 --- a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-source.ts +++ b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-source.ts @@ -9,7 +9,7 @@ import { import { createWorktreeAgentFreshnessSelector } from '@/components/sidebar/workspace-card/activity/worktree-agent-freshness-selector' import '@/components/sidebar/workspace-card/activity/worktree-agent-row-selectors' import { selectWorktreeAgentOrchestration as selectRuntimeAgentOrchestrationForWorktree } from '@/components/sidebar/workspace-card/activity/worktree-agent-orchestration-index' -import { agentRowDisplayDotState } from '@/lib/agent-row-dot-state' +import { agentRowDisplayDotState } from '@/lib/agent-status/presentation/agent-row-dot-state' import { resolveRowProgramStatus } from '@/lib/program-status/agent-row-presentation' import { agentMessageSenderView, diff --git a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-view.test.tsx b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-view.test.tsx index 1f3754cfe84..850b37187a7 100644 --- a/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-view.test.tsx +++ b/src/renderer/src/components/native-chat/messages/agent-senders/native-chat-agent-message-sender-view.test.tsx @@ -7,23 +7,13 @@ import { useAppStore } from '@/store' import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import type { TerminalLayoutSnapshot } from '../../../../../../shared/workspace-layout/terminal-tab-types' import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import type { AgentMessageSenderView } from '../../../../../../shared/agent-session/agent-message-presentation' import { parseOrcaSessionAddress } from '../../../../../../shared/orca-session-address' -import * as presentation from '@/lib/program-status/agent-row-presentation' -import * as senderTargets from './native-chat-agent-message-sender-target' import '@/components/sidebar/workspace-card/activity/worktree-agent-row-selectors' import { useAgentMessageSenderView } from './native-chat-agent-message-sender-view' -import { - initialStore, - LEAF, - status, - resetSenderStore -} from './native-chat-agent-sender.test-fixture' +import { initialStore, status, resetSenderStore } from './native-chat-agent-sender.test-fixture' const renders = new Map() -const views = new Map() function Probe({ id, workspace = 'workspace', @@ -37,7 +27,7 @@ function Probe({ sourceId?: number proof?: 'live' | 'gone' | 'terminal' }) { - const value = useAgentMessageSenderView( + useAgentMessageSenderView( { party: { address: `term_${sourceId}`, @@ -51,7 +41,6 @@ function Probe({ remote ? { kind: 'environment', environmentId: 'remote' } : { kind: 'local' }, proof === 'terminal' ? undefined : `${proof === 'gone' ? 'closed' : 'source'}-${sourceId}` ) - views.set(id, value) renders.set(id, (renders.get(id) ?? 0) + 1) return null } @@ -89,7 +78,6 @@ beforeEach(() => { vi.useFakeTimers({ toFake: ['Date'] }) vi.setSystemTime(2_000_000) renders.clear() - views.clear() resetSenderStore() publishSources(1) publishSources(10, 'runtime:remote', 'remote') @@ -101,115 +89,6 @@ afterEach(() => { vi.useRealTimers() }) -it.each([100, 1000])( - 'bounds proved, gone-proof and plain-terminal cards across %i status rows', - (n) => { - let visits = 0 - const track = (entries: Record) => - new Proxy(entries, { - ownKeys(target) { - const keys = Object.getOwnPropertyNames(target) - visits += keys.length - return keys - } - }) - const live = track( - Object.fromEntries( - Array.from({ length: n }, (_, i) => { - const entry = status(i) - return [entry.paneKey, entry] - }) - ) - ) - useAppStore.setState({ - agentStatusByPaneKey: live, - tabsByWorktree: { - workspace: Array.from({ length: n }, (_, i) => - makeTab({ id: `tab-${i}`, worktreeId: 'workspace' }) - ) - }, - terminalLayoutsByTabId: Object.fromEntries( - Array.from({ length: n }, (_, i): [string, TerminalLayoutSnapshot] => [ - `tab-${i}`, - { root: { type: 'leaf', leafId: LEAF }, activeLeafId: LEAF, expandedLeafId: null } - ]) - ) - }) - publishSources(n, 'local', 'workspace', true) - const normalize = vi.spyOn(presentation, 'resolveRowProgramStatus') - const resolve = vi.spyOn(senderTargets, 'resolveAgentMessageSenderTarget') - const mounted = render( - <> - {Array.from({ length: n }, (_, id) => ( - - - - - - ))} - - ) - // Both fallback cohorts share the existing sender index and row source. - expect(visits).toBeLessThanOrEqual(n * 3) - expect(normalize).toHaveBeenCalledTimes(n) - for (let i = 0; i < n; i++) { - expect(views.get(i)?.dot).toBe('working') - expect(views.get(n + i)).toEqual({ agentType: 'claude' }) - expect(views.get(2 * n + i)).toEqual({ agentType: 'claude' }) - } - const before = new Map(renders) - visits = 0 - normalize.mockClear() - resolve.mockClear() - act(() => useAppStore.setState({ sidebarBody: 'agents' })) - expect(visits).toBe(0) - expect(normalize).not.toHaveBeenCalled() - expect(resolve.mock.calls.length).toBeLessThanOrEqual(n * 4) - expect(renders).toEqual(before) - for (const progress of [40, 60]) { - const state = useAppStore.getState() - const entries = { ...state.agentStatusByPaneKey } - const key = status(0).paneKey - entries[key] = { - ...entries[key], - programStatus: { state: 'working', progress, observedAt: 2_000_000 } - } - visits = 0 - normalize.mockClear() - resolve.mockClear() - const epoch = state.agentStatusEpoch - act(() => useAppStore.setState({ agentStatusByPaneKey: track(entries) })) - expect(visits).toBeLessThanOrEqual(n * 3) - expect(resolve.mock.calls.length).toBeGreaterThanOrEqual(n * 4) - expect(resolve.mock.calls.length).toBeLessThanOrEqual(n * 8) - expect(useAppStore.getState().agentStatusEpoch).toBe(epoch) - expect(normalize).toHaveBeenCalledTimes(n) - expect(views.get(0)?.progress).toBe(progress) - expect(renders.get(0)).toBe(before.get(0)! + (progress === 40 ? 1 : 2)) - for (let i = 1; i < 3 * n; i++) { - expect(renders.get(i)).toBe(before.get(i)) - } - } - const settled = new Map(renders) - visits = 0 - normalize.mockClear() - resolve.mockClear() - act(() => useAppStore.setState({ sidebarBody: 'workspaces' })) - expect(visits).toBe(0) - expect(normalize).not.toHaveBeenCalled() - expect(resolve.mock.calls.length).toBeLessThanOrEqual(n * 4) - expect(renders).toEqual(settled) - write(0, { agentType: 'codex' }) - for (const id of [0, 2 * n]) { - expect(views.get(id)?.agentType).toBe('codex') - expect(renders.get(id)).toBe(settled.get(id)! + 1) - } - expect(views.get(n)).toEqual({ agentType: 'claude' }) - expect(renders.get(n)).toBe(settled.get(n)) - mounted.unmount() - } -) - it.each(['run:coordinator', 'dispatch:past'])( 'never borrows a same-kind successor status for a saved event with only role %s', (address) => { diff --git a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.failures.test.tsx b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.failures.test.tsx new file mode 100644 index 00000000000..f8d2ab5778e --- /dev/null +++ b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.failures.test.tsx @@ -0,0 +1,69 @@ +// @vitest-environment happy-dom +import '@testing-library/jest-dom/vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { agentSessionFailureFact } from '../../../../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureWords } from '../../../../../../shared/agent-session/failures/agent-session-failure-words' +import { NativeChatNoticeRow } from './NativeChatNoticeRow' +import { i18n } from '@/i18n/i18n' + +afterEach(async () => { + cleanup() + await i18n.changeLanguage('en') +}) + +it('localizes canonical failure facts while keeping host advice and diagnostics intact', async () => { + await i18n.changeLanguage('fr') + const diagnostic = 'Internal provider diagnostic: modelNotFound' + const payload = { + head: diagnostic, + byteLength: diagnostic.length, + digest: 'fixture', + truncated: false + } + const kinds = [ + 'modelUnavailable', + 'providerUnavailable', + 'providerSafetyStopped', + 'providerResponseFailed' + ] as const + const { container } = render( + <> + {kinds.map((kind) => ( + + ))} + + + ) + const visibleLines = [...container.querySelectorAll('p')] + .map((node) => node.textContent) + .join('\n') + expect(visibleLines).toContain('le modèle sélectionné') + expect(visibleLines).not.toContain('the selected model') + expect(visibleLines).not.toContain(diagnostic) + expect(screen.getByText('Custom host advice: use the enterprise model.')).toBeInTheDocument() + const details = container.querySelector('details')! + expect(details.open).toBe(false) + fireEvent.click(details.querySelector('summary')!) + expect(details.open).toBe(true) + expect(details.querySelector('pre')).toHaveTextContent(diagnostic) +}) diff --git a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.fixture.tsx b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.fixture.tsx new file mode 100644 index 00000000000..54ff875e949 --- /dev/null +++ b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.fixture.tsx @@ -0,0 +1,94 @@ +import { defineFixture } from '../../../../component-fixtures/component-fixture' +import { i18n } from '../../../../i18n/i18n' +import { agentSessionFailureFact } from '../../../../../../shared/agent-session/failures/agent-session-failure' +import { agentSessionFailureWords } from '../../../../../../shared/agent-session/failures/agent-session-failure-words' +import type { NativeChatTextBlock } from '../../../../../../shared/native-chat/native-chat-types' +import { NativeChatNoticeRow } from './NativeChatNoticeRow' + +export const codexFailures = defineFixture({ + width: 440, + interact: async () => { + await i18n.changeLanguage('fr') + }, + render: () => ( +
+ {( + [ + 'providerUnavailable', + 'providerSafetyStopped', + 'providerResponseFailed', + 'modelUnavailable' + ] as const + ).map((kind) => ( + + ))} +
+ ) +}) + +function guardianReview(text: string): NativeChatTextBlock { + const head = JSON.stringify({ message: text }) + return { + type: 'text', + text, + tone: 'warning', + providerFrame: { + provider: 'codex', + kind: 'notification:guardianWarning', + payload: { head, byteLength: head.length, digest: 'synthetic', truncated: false } + } + } +} + +const reviews = [ + guardianReview( + 'Automatic approval review approved (risk: medium, authorization: high): Read-only status query.' + ), + guardianReview( + 'Automatic approval review denied (risk: high, authorization: low): Writes outside the workspace.' + ) +] + +function GuardianReviewNotices() { + return ( +
+ {reviews.map((block) => ( + + ))} +
+ ) +} + +export const guardianReviewsCollapsed = defineFixture({ + width: 720, + render: () => +}) + +export const guardianReviewsExpanded = defineFixture({ + width: 720, + render: () => , + interact: (frame) => { + frame.querySelectorAll('summary').forEach((summary) => summary.click()) + } +}) diff --git a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.model-fallback.test.tsx b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.model-fallback.test.tsx deleted file mode 100644 index 514559dc2ff..00000000000 --- a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.model-fallback.test.tsx +++ /dev/null @@ -1,64 +0,0 @@ -// @vitest-environment happy-dom -import '@testing-library/jest-dom/vitest' -import { cleanup, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { projectStructuredItemToNativeChat } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' -import type { AgentJournalStatusItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { TooltipProvider } from '@/components/ui/tooltip' -import { MessageRow } from '../rows/NativeChatMessageRow' -import { i18n } from '@/i18n/i18n' - -afterEach(async () => { - cleanup() - await i18n.changeLanguage('en') -}) - -function renderStatus(body: AgentJournalStatusItem) { - const message = projectStructuredItemToNativeChat({ - itemId: 'notice', - sequence: 1, - revision: 1, - observedAt: 1, - body - }) - if (!message) { - throw new Error('expected notice') - } - render( - - - - ) -} - -it.each([ - ['en', 'Claude switched models: Claude Opus 5.5 → Claude Opus 4.8.'], - ['ru', 'Claude переключил модель: Claude Opus 5.5 → Claude Opus 4.8.'] -])( - 'renders the saved fallback as a readable %s notice instead of unknown JSON', - async (locale, words) => { - await i18n.changeLanguage(locale) - const head = JSON.stringify({ - type: 'fallback', - from: { model: 'claude-opus-5-5' }, - to: { model: 'claude-opus-4-8' } - }) - renderStatus({ - kind: 'status', - text: 'Claude sent content Orca cannot display yet', - providerFrame: { - provider: 'claude', - kind: 'message:assistant:content:fallback', - payload: { head, byteLength: head.length, digest: 'fixture', truncated: false } - } - }) - expect(screen.getByText(words)).toBeInTheDocument() - expect(screen.queryByText('Claude sent content Orca cannot display yet')).toBeNull() - expect(screen.queryByText(head)).toBeNull() - } -) diff --git a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx index 80ec2ef8e3a..d77038317c9 100644 --- a/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx +++ b/src/renderer/src/components/native-chat/messages/notices/NativeChatNoticeRow.tsx @@ -24,7 +24,8 @@ import { import type { NativeChatTextBlock } from '../../../../../../shared/native-chat/native-chat-types' import { NATIVE_CHAT_NOTICE_COPY, - nativeChatNoticeLook + nativeChatNoticeLook, + type NativeChatNoticeTone } from '../../../../../../shared/native-chat/native-chat-notice' import { useNativeChatOrcaStopView } from './native-chat-orca-stop-context' import { NativeChatInterruptedContinueButton } from '../../usage/NativeChatInterruptedContinue' @@ -65,6 +66,14 @@ const HOST_STATUS_WORDS: Record string ) } +function toneClass(tone: NativeChatNoticeTone): string { + return tone === 'warning' + ? 'text-chat-warning' + : tone === 'error' + ? 'text-destructive' + : 'text-chat-foreground-faint' +} + export function NativeChatNoticeRow({ block, messageId, @@ -176,23 +185,26 @@ export function NativeChatNoticeRow({ if (look.kind === 'settled-permission') { const agent = agentName ?? look.agent const summary = - look.decision === 'denied' + look.decision === 'approved' ? t( - 'components.native-chat.notices.permissionDenied', - '{{agent}} denied permission. View details.', - { agent } - ) - : t( - 'components.native-chat.notices.safetyReview', - '{{agent}} reported a safety review warning. View details.', + 'components.native-chat.notices.safetyReviewApproved', + '{{agent}} approved this action. View details.', { agent } ) + : look.decision === 'denied' + ? t( + 'components.native-chat.notices.permissionDenied', + '{{agent}} denied permission. View details.', + { agent } + ) + : t( + 'components.native-chat.notices.safetyReview', + '{{agent}} reported a safety review warning. View details.', + { agent } + ) const payload = block.providerFrame?.payload return ( - + {block.text} {payload ? '\n\n' : ''} {payload?.truncated @@ -227,9 +239,16 @@ export function NativeChatNoticeRow({ block.usageLimitTurnItemId === orcaStopView.usageLimitTurnItemId // Reword only text fully described by its fact; other host text may carry command advice. const factSurface = - failure?.kind === 'notSignedIn' || - failure?.kind === 'savedConversationMissing' || - failure?.kind === 'pluginInputRequired' + failure && + [ + 'notSignedIn', + 'savedConversationMissing', + 'pluginInputRequired', + 'modelUnavailable', + 'providerUnavailable', + 'providerSafetyStopped', + 'providerResponseFailed' + ].includes(failure.kind) ? (['row', 'rejection'] as const).find( (surface) => block.text === agentSessionFailureSentence(failure, surface, { agentName }) ) @@ -289,9 +308,7 @@ export function NativeChatNoticeRow({ className={cn( 'space-y-2 text-sm text-chat-foreground', Icon && 'rounded-md border border-border bg-muted/20 p-3', - tone === 'warning' && 'text-chat-warning', - tone === 'error' && 'text-destructive', - tone === 'notice' && 'text-chat-foreground-faint' + tone && toneClass(tone) )} >
diff --git a/src/renderer/src/components/native-chat/messages/notices/agent-session-failure-words-text.ts b/src/renderer/src/components/native-chat/messages/notices/agent-session-failure-words-text.ts index da067b3b101..aa57f4261bb 100644 --- a/src/renderer/src/components/native-chat/messages/notices/agent-session-failure-words-text.ts +++ b/src/renderer/src/components/native-chat/messages/notices/agent-session-failure-words-text.ts @@ -13,6 +13,7 @@ import { STOP_FAILURE_PIECES } from './agent-session-failure-stop-words-text' import { PROVIDER_EXIT_PIECES } from './agent-session-provider-exit-words-text' import { PROVIDER_RETRY_PIECES } from './agent-session-provider-retry-words-text' import { USAGE_LIMIT_PIECES } from './agent-session-usage-limit-words-text' +import { PROVIDER_FAILURE_PIECES } from './agent-session-provider-failure-words-text' import { START_FAILURE_PIECES } from './agent-session-start-failure-words-text' // The pieces a refusal notice says too keep the notice's keys, so each has one translation. @@ -181,6 +182,7 @@ const PIECES: Record translate( 'components.native-chat.failureWords.providerRejected', diff --git a/src/renderer/src/components/native-chat/messages/notices/agent-session-provider-failure-words-text.ts b/src/renderer/src/components/native-chat/messages/notices/agent-session-provider-failure-words-text.ts new file mode 100644 index 00000000000..0aa86372ed6 --- /dev/null +++ b/src/renderer/src/components/native-chat/messages/notices/agent-session-provider-failure-words-text.ts @@ -0,0 +1,31 @@ +import { translate } from '@/i18n/i18n' +import { + AGENT_SESSION_FAILURE_COPY as COPY, + type AgentSessionFailureCopyId, + type AgentSessionFailureCopyValues +} from '../../../../../../shared/agent-session/failures/agent-session-failure-copy' + +export const PROVIDER_FAILURE_PIECES = { + selectedModel: (values) => + translate('components.native-chat.failureWords.selectedModel', COPY.selectedModel, values), + providerUnavailable: (values) => + translate( + 'components.native-chat.failureWords.providerUnavailable', + COPY.providerUnavailable, + values + ), + providerSafetyStopped: (values) => + translate( + 'components.native-chat.failureWords.providerSafetyStopped', + COPY.providerSafetyStopped, + values + ), + providerResponseFailed: (values) => + translate( + 'components.native-chat.failureWords.providerResponseFailed', + COPY.providerResponseFailed, + values + ) +} satisfies Partial< + Record string> +> diff --git a/src/renderer/src/components/native-chat/messages/notices/agent-session-write-notice-text.test.ts b/src/renderer/src/components/native-chat/messages/notices/agent-session-write-notice-text.test.ts deleted file mode 100644 index 4cf37f9c278..00000000000 --- a/src/renderer/src/components/native-chat/messages/notices/agent-session-write-notice-text.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { afterEach, describe, expect, it } from 'vitest' -import { i18n, setRendererPluginLanguagePacks } from '@/i18n/i18n' - -import { pluginLanguageResourceId } from '../../../../../../shared/plugins/artifacts/plugin-language-pack-artifact' -import { agentSessionWriteKindForMethod } from '../../../../../../shared/agent-session/failures/agent-session-write-failure' - -import { - agentSessionWriteFailureText, - agentSessionWriteNoticeText -} from './agent-session-write-notice-text' - -afterEach(async () => { - setRendererPluginLanguagePacks([]) - await i18n.changeLanguage('en') -}) - -describe('desktop words for a write that did not happen', () => { - it('does not promise the old goal survived a refused replacement, including older translations', async () => { - const id = 'plugin:example.older-french/fr' as const - const resourceLanguage = pluginLanguageResourceId(id) - setRendererPluginLanguagePacks([ - { - id, - resourceLanguage, - pluginKey: 'example.older-french', - coverage: 100, - locale: 'fr', - catalog: {} - } - ]) - for (const [language, expected] of [ - ['en', "Couldn't finish changing the goal. Check the chat."], - ['fr', 'Impossible de terminer la modification de l’objectif. Consultez le chat.'], - [resourceLanguage, "Couldn't finish changing the goal. Check the chat."] - ]) { - await i18n.changeLanguage(language) - expect( - agentSessionWriteFailureText( - { - kind: 'refused', - code: 'agent_session_operation_invalid', - details: { reason: 'providerRejected' } - }, - 'goal' - ) - ).toContain(expected) - } - }) - - it("runs on after a plugin language's full stop, and keeps the space after English it left", async () => { - const id = 'plugin:example.chinese/zh-TW' as const - setRendererPluginLanguagePacks([ - { - id, - resourceLanguage: pluginLanguageResourceId(id), - pluginKey: 'example.chinese', - locale: 'zh-TW', - catalog: { - components: { - 'native-chat': { - writeNotice: { - restartFailed: '智能體無法重新啟動。', - notDoneSend: '您的訊息未傳送。' - } - } - } - }, - coverage: 100 - } - ]) - await i18n.changeLanguage(pluginLanguageResourceId(id)) - expect(agentSessionWriteNoticeText(['restartFailed', 'notDoneSend'])).toBe( - '智能體無法重新啟動。您的訊息未傳送。' - ) - // The pack predates the failure words, so they fall back to English. - expect( - agentSessionWriteNoticeText([ - 'notDoneSend', - { failure: { kind: 'startFailed' }, surface: 'rejection', context: { agentName: 'Claude' } } - ]) - ).toBe("您的訊息未傳送。Claude couldn't start. Send your message to try again.") - }) - - it("says a queued card's message wasn't sent only when Orca couldn't confirm its mail", () => { - const send = agentSessionWriteKindForMethod('agentSession.queuedMessageSend', {}) - for (const retryControl of [false, true]) { - expect( - agentSessionWriteFailureText( - { - kind: 'refused', - code: 'execution_owner_reconciling', - details: { reason: 'mailOwnerUnconfirmed' } - }, - send, - { retryControl } - ) - ).toBe( - "Orca couldn't confirm this message is still meant for this chat. Your message was not sent. Try again." - ) - } - // Any other refused Send of a queued card keeps its existing words. - expect( - agentSessionWriteFailureText( - { - kind: 'refused', - code: 'agent_session_checkpoint_stale', - details: { reason: 'fenceStale' } - }, - send - ) - ).toBe("The command didn't run.") - }) -}) diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.tsx index 8bdcbfb653b..0e07ae67a6a 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.tsx @@ -1,7 +1,7 @@ import { useId } from 'react' import { ChevronDown } from 'lucide-react' import { AgentStateDot } from '@/components/AgentStateDot' -import { AgentTypeIcon } from '@/lib/agent-type-icon' +import { AgentTypeIcon } from '@/components/agent/icons/agent-type-icon' import { translate } from '@/i18n/i18n' import { useTranslate, type Translate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx index 8f7fc2045ae..9af89d8fddb 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatAssistantMessageRow.tsx @@ -76,16 +76,11 @@ export function NativeChatAssistantMessageRow({ !message.agentStart && !inSubagentSection && isRootAgentJournalItem(message) - // A row whose fork is opening keeps its controls up so the spinner stays visible. - const revealOnHover = - fork?.pendingItemId === message.id - ? 'mt-1 w-fit select-none' - : 'mt-1 w-fit select-none transition-opacity can-hover:pointer-events-none can-hover:opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 [.group:has(:focus-visible)_&]:pointer-events-auto [.group:has(:focus-visible)_&]:opacity-100' return (
0 ? message.id : undefined} data-native-chat-message-tone={isSystem ? 'faint' : undefined} className={cn( @@ -126,7 +121,7 @@ export function NativeChatAssistantMessageRow({ ) : null } className={cn( - revealOnHover, + 'mt-1 w-fit select-none', // They hang into the gap below; a section keeps them inside its border instead. !inSubagentSection && '-mb-5' )} diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx index fbf666c74ab..11c9bbda907 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatMessageRow.tsx @@ -55,7 +55,7 @@ export type MessageRowProps = { activeTurnIsWorking?: boolean /** This row's tool run is the turn's last, so it is the one still live. */ trailingRun?: boolean - /** Hover controls would overlap the next row. */ + /** Response controls would overlap the next row. */ continuesTurn?: boolean /** In a turn: whether this row holds the response's actions (its last words, else its last images). */ endsResponse?: boolean diff --git a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx index 2a2d3f5090e..3bfadce54b5 100644 --- a/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx +++ b/src/renderer/src/components/native-chat/messages/rows/NativeChatTranscriptRow.tsx @@ -20,6 +20,8 @@ import { nativeChatRowOffersRewind } from '../../../../../../shared/native-chat/ import { NativeChatForkContext } from '../actions/native-chat-fork-context' import { nativeChatSlotOffersFork } from '../actions/native-chat-side-chat-fork-point' import { isActionableStructuredAgentSessionPrompt } from '../../../../../../shared/agent-session/view/structured-agent-session-live-turn' +import { NativeChatNewRowsMarker } from '../../viewport/new-rows/NativeChatNewRowsMarker' +import type { NativeChatNewRowsMarkerState } from '../../viewport/new-rows/native-chat-new-rows-marker' /** Memoize shared context so unchanged rows keep their props during transcript updates. */ export type NativeChatTranscriptRowContext = { @@ -45,10 +47,13 @@ export type NativeChatTranscriptRowContext = { /** Wrap message, status and rollup for one virtualized measurement; internal spacing is the row’s, inter-row gaps the window’s. */ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ slot, - context + context, + newRowsMarker }: { slot: NativeChatTranscriptSlot context: NativeChatTranscriptRowContext + /** The "New" marker, when it draws in this row. */ + newRowsMarker?: NativeChatNewRowsMarkerState }): React.JSX.Element { // Offered only on the conversation's own turn-opening prompts (`nativeChatRowOffersRewind`). const rewind = useContext(NativeChatRewindContext) @@ -84,6 +89,9 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ const deliveryNotice = context.deliveryNotices?.get(message.id) const predecessors = context.taskListPredecessors.get(message.id) const expanded = turnKey ? context.expandedTurnIds.has(turnKey) : undefined + const marker = newRowsMarker ? ( + + ) : null const statusRow = status ? ( + {newRowsMarker?.place === 'above-row' ? marker : null} {/* A turn with no user bubble carries its bar above its first row. */} {slot.statusAbove ? statusRow : null} {!slot.drawsMessage ? null : receipt ? ( @@ -154,6 +163,7 @@ export const NativeChatTranscriptRow = memo(function NativeChatTranscriptRow({ workRun={workRun} /> )} + {newRowsMarker?.place === 'above-turn-bar' ? marker : null} {slot.statusAbove ? null : statusRow} {turnDiff ? : null} {openedPullRequests ? ( diff --git a/src/renderer/src/components/native-chat/pane/actions/NativeChatContextMenuItems.tsx b/src/renderer/src/components/native-chat/pane/actions/NativeChatContextMenuItems.tsx index bd19901886f..c39e388ffc4 100644 --- a/src/renderer/src/components/native-chat/pane/actions/NativeChatContextMenuItems.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/NativeChatContextMenuItems.tsx @@ -9,7 +9,7 @@ import type { NativeChatContextMenuTarget } from './native-chat-context-menu-tar import type { NativeChatRewindSurface } from '../../messages/actions/use-native-chat-rewind-host' function copyText(text: string): void { - // Best-effort, as the hover copy buttons are: the clipboard can reject when unfocused. + // Best-effort, as the row Copy buttons are: the clipboard can reject when unfocused. window.api.ui.writeClipboardText(text).catch(() => {}) } diff --git a/src/renderer/src/components/native-chat/pane/actions/native-chat-quote-focus.test.tsx b/src/renderer/src/components/native-chat/pane/actions/native-chat-quote-focus.test.tsx deleted file mode 100644 index 62b8840ad1e..00000000000 --- a/src/renderer/src/components/native-chat/pane/actions/native-chat-quote-focus.test.tsx +++ /dev/null @@ -1,81 +0,0 @@ -// @vitest-environment happy-dom -import { useRef } from 'react' -import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { TooltipProvider } from '@/components/ui/tooltip' -import { AgentLaunchPromptComposer } from '../../../agent/AgentLaunchPromptComposer' -import type { AgentPickerEntry } from '../../../../../../shared/agent-launch/picker/agent-launch-picker' -import type { NativeChatComposerHandle } from '../../composer/native-chat-composer-types' -import { - emptyNativeChatContextMenuActions, - useNativeChatContextMenu -} from './use-native-chat-context-menu' -import { clearNativeChatComposerDraftsForTests } from '../../drafts/native-chat-draft-reset' -import { - promptEditor, - promptValue -} from '../../composer/editor/native-chat-prompt-editor.test-support' - -const entry: AgentPickerEntry = { - agent: 'claude', - label: 'Claude', - rows: [{ agent: 'claude', kind: 'cli', executionHostId: 'local' }], - surfaces: ['chat'], - defaultSurface: 'chat', - terminal: {}, - structured: {}, - catalog: { origin: 'unknown' } -} - -function Chat() { - const rootRef = useRef(null) - const composerRef = useRef(null) - const { menu, onContextMenuCapture, onPointerDownCapture } = useNativeChatContextMenu({ - rootRef, - composerRef, - showTerminalPaneActions: false, - actions: { ...emptyNativeChatContextMenuActions, onPaste: () => {} } - }) - return ( -
-
-

Reply to quote

-
- false} /> - {menu} -
- ) -} - -afterEach(() => { - cleanup() - clearNativeChatComposerDraftsForTests() - window.getSelection()?.removeAllRanges() - vi.restoreAllMocks() -}) - -it('places the caret after the quote when Add to chat closes the context menu', async () => { - const now = vi.spyOn(Date, 'now').mockReturnValue(0) - render(, { wrapper: TooltipProvider }) - const editor = document.querySelector('[contenteditable][aria-multiline="true"]')! - await waitFor(() => expect(promptEditor(editor)).toBeDefined()) - const reply = screen.getByText('Reply to quote') - window.getSelection()!.selectAllChildren(reply) - fireEvent.contextMenu(reply) - await screen.findByRole('menu') - now.mockReturnValue(1000) - fireEvent.click(screen.getByRole('menuitem', { name: 'Add to chat' })) - - expect(promptValue(editor)).toBe('> Reply to quote\n\n') - expect(document.activeElement).toBe(editor) - await act(async () => {}) - expect(document.activeElement).toBe(editor) - expect(promptEditor(editor).state.selection.empty).toBe(true) - expect(promptEditor(editor).state.selection.to).toBe( - promptEditor(editor).state.doc.content.size - 1 - ) -}) diff --git a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-context-menu.targets.test.tsx b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-context-menu.targets.test.tsx index 732c39a092b..3664153178c 100644 --- a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-context-menu.targets.test.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-context-menu.targets.test.tsx @@ -8,11 +8,9 @@ import type * as HttpLinkDestinations from '@/lib/browser/navigation/http-link-d import type * as TerminalFileOpenRouting from '@/components/terminal-pane/links/files/terminal-file-open-routing' import { createNativeChatFileHref } from '../../../../../../shared/native-chat/native-chat-href-routing' import type { NativeChatComposerHandle } from '../../composer/native-chat-composer-types' -import type { NativeChatRewindSurface } from '../../messages/actions/use-native-chat-rewind-host' import { emptyNativeChatContextMenuActions, - useNativeChatContextMenu, - type NativeChatContextMenuActions + useNativeChatContextMenu } from './use-native-chat-context-menu' const mocks = vi.hoisted(() => ({ @@ -44,25 +42,13 @@ vi.mock('@/components/confirmation-dialog-context', () => ({ const linkContext = { worktreeId: 'wt-1', worktreePath: '/repo', runtimeEnvironmentId: null } -function Chat({ - acceptsText = true, - rewind, - onFind, - actions, - standalone = false -}: { - acceptsText?: boolean - rewind?: NativeChatRewindSurface - onFind?: () => void - actions?: Partial - standalone?: boolean -}): React.JSX.Element { +function Chat({ onFind }: { onFind?: () => void }): React.JSX.Element { const rootRef = useRef(null) const composerRef = useRef({ focus: () => true, insertAgentReferences: () => false, insertTypedText: () => true, - acceptsText: () => acceptsText, + acceptsText: () => true, appendText: mocks.appendText, handlePasteEvent: () => {}, pasteFromClipboard: () => {}, @@ -71,24 +57,9 @@ function Chat({ const { menu, onContextMenuCapture } = useNativeChatContextMenu({ rootRef, composerRef, - actions: { ...emptyNativeChatContextMenuActions, ...actions, onPaste: vi.fn() }, - showTerminalPaneActions: actions !== undefined, - chatPane: standalone - ? { tabId: 'chat-tab', worktreeId: 'wt-1', groupId: 'group-1', sessionId: 'session-1' } - : undefined, - chatSession: standalone - ? { - target: { kind: 'local' }, - sessionId: 'session-1', - worktreeId: 'wt-1', - epoch: 'epoch-1', - agent: 'claude', - messages: [], - focusSource: vi.fn() - } - : undefined, + actions: { ...emptyNativeChatContextMenuActions, onPaste: vi.fn() }, + showTerminalPaneActions: false, fileLinkContext: linkContext, - rewind, onFind }) return ( @@ -127,23 +98,6 @@ afterEach(() => { vi.resetAllMocks() }) -it.each(['terminal-backed', 'standalone'] as const)( - 'omits the whole-session fork action from the %s chat menu', - async (surface) => { - render( - - ) - - await rightClick('Empty area') - - expect(screen.getByRole('menuitem', { name: 'Copy Context' })).toBeInTheDocument() - expect(screen.queryByRole('menuitem', { name: 'Fork Agent Session…' })).not.toBeInTheDocument() - } -) - it.each([ { firstText: 'docs link', diff --git a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx index 20880d307d1..f02a53bffa8 100644 --- a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-hand-off.tsx @@ -9,7 +9,7 @@ import { AgentSessionContinuationDialog } from '@/components/agent-session-conti import { buildAgentSessionContinuationPrompt, type AgentSessionContinuationRequest -} from '@/lib/agent-session-continuation' +} from '@/lib/agent-session/context/agent-session-continuation' import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' import { callStructuredAgentSession } from '@/runtime/native-chat/requests/structured-agent-session-call' import { supportsStructuredAgentSessionContinuationContext } from '@/runtime/native-chat/host-capabilities/structured-agent-session-host-support' diff --git a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-session-context-actions.tsx b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-session-context-actions.tsx index ba947924b33..9e009550ee2 100644 --- a/src/renderer/src/components/native-chat/pane/actions/use-native-chat-session-context-actions.tsx +++ b/src/renderer/src/components/native-chat/pane/actions/use-native-chat-session-context-actions.tsx @@ -2,7 +2,7 @@ import { useCallback, useLayoutEffect, useRef, useState } from 'react' import { executionHostIdForStructuredTarget } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' import { useTranslate } from '@/i18n/use-translate' import type { AgentType } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import { copyAgentSessionContext } from '@/lib/copy-agent-session-context' +import { copyAgentSessionContext } from '@/lib/agent-session/context/copy-agent-session-context' import { resolveNativeChatSessionContext, type NativeChatSessionContextSource diff --git a/src/renderer/src/components/native-chat/pane/ownership/use-structured-agent-session-host-label.ts b/src/renderer/src/components/native-chat/pane/ownership/use-structured-agent-session-host-label.ts index 7226fcf5b48..77447bce7ac 100644 --- a/src/renderer/src/components/native-chat/pane/ownership/use-structured-agent-session-host-label.ts +++ b/src/renderer/src/components/native-chat/pane/ownership/use-structured-agent-session-host-label.ts @@ -1,4 +1,4 @@ -import { selectExecutionHostDisplayLabel } from '@/lib/execution-host-display-label' +import { selectExecutionHostDisplayLabel } from '@/runtime/hosts/display/execution-host-display-label' import { executionHostIdForStructuredTarget } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' import type { RuntimeClientTarget } from '../../../../../../shared/runtime-client-target' import { useAppStore } from '../../../../store/index' diff --git a/src/renderer/src/components/native-chat/pane/routing/native-chat-layout-actions.ts b/src/renderer/src/components/native-chat/pane/routing/native-chat-layout-actions.ts index b7fb3f54697..ceb92e18243 100644 --- a/src/renderer/src/components/native-chat/pane/routing/native-chat-layout-actions.ts +++ b/src/renderer/src/components/native-chat/pane/routing/native-chat-layout-actions.ts @@ -2,7 +2,6 @@ import { toast } from 'sonner' import { translate } from '@/i18n/i18n' import type { AppState } from '@/store/types' import { useAppStore } from '@/store' -import { isTuiAgent } from '../../../../../../shared/agent-launch/catalog/tui-agent-config' import { requestActiveTerminalPaneSplit } from '@/components/tab-bar/request-active-terminal-pane-split' import { openNewTerminalTabInWorkspace } from '@/store/terminals/terminal-active-workspace-creation' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' @@ -53,10 +52,9 @@ function findSplitSource( ) if ( tab?.contentType === 'agent-session' && - isTuiAgent(tab.agentSessionAgent) && state.groupsByWorktree[worktreeId]?.some((group) => group.id === target.groupId) ) { - return { tab, worktreeId, agent: tab.agentSessionAgent } + return { tab, worktreeId } } } return null diff --git a/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.ts b/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.ts index a7a3df7f958..e2de69126dd 100644 --- a/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.ts +++ b/src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.ts @@ -1,4 +1,4 @@ -import { takeRecentWorkspaceSwitchWake } from '@/lib/workspace-switch-user-act' +import { takeRecentWorkspaceSwitchWake } from '@/lib/workspace/activation/workspace-switch-user-act' import type { AppState } from '@/store/types' import { parsePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' import { getTabIdToWorktreeId } from '../../../sidebar/workspace-card/activity/worktree-agent-row-selectors' diff --git a/src/renderer/src/components/native-chat/pane/routing/native-chat-split-flow.test.ts b/src/renderer/src/components/native-chat/pane/routing/native-chat-split-flow.test.ts index 33ff4f8298d..9bf880e44c2 100644 --- a/src/renderer/src/components/native-chat/pane/routing/native-chat-split-flow.test.ts +++ b/src/renderer/src/components/native-chat/pane/routing/native-chat-split-flow.test.ts @@ -3,7 +3,7 @@ import { beforeAll, beforeEach, expect, it, vi } from 'vitest' import { i18n } from '@/i18n/i18n' import type * as importCreation from '@/runtime/hosted-terminals/creation/web-runtime-terminal-creation' import type * as WorktreeRuntimeOwner from '@/lib/workspace/ownership/worktree-runtime-owner' -import type * as WorktreeOperationRoute from '@/lib/worktree-operation-route' +import type * as WorktreeOperationRoute from '@/lib/workspace/ownership/worktree-operation-route' import { createTestStore } from '@/store/testing/app-store-test-fixture' import { createTabsSliceMockApi } from '@/store/slices/tabs/tabs-slice-test-harness' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../../../shared/constants' @@ -32,7 +32,7 @@ vi.mock('@/lib/workspace/ownership/worktree-runtime-owner', async (original) => runtimeEnvironmentIdOrLocalUnlessTwin: (_state: unknown, worktreeId: string) => runtimeOwners.get(worktreeId) ?? null })) -vi.mock('@/lib/worktree-operation-route', async (original) => ({ +vi.mock('@/lib/workspace/ownership/worktree-operation-route', async (original) => ({ ...(await original()), resolveWorktreeOperationRouteResult: (_state: unknown, worktreeId: string) => ({ kind: 'resolved', @@ -64,9 +64,9 @@ beforeEach(async () => { createRemote.mockReset().mockResolvedValue({ status: 'created' }) }) -function sourceChat(worktreeId: string, agent: 'claude' | 'codex' = 'codex') { +function sourceChat(worktreeId: string) { const source = store.getState().createUnifiedTab(worktreeId, 'agent-session', { - agentSessionAgent: agent, + agentSessionAgent: 'codex', executionHostId: 'local' }) return { @@ -75,35 +75,6 @@ function sourceChat(worktreeId: string, agent: 'claude' | 'codex' = 'codex') { } } -it.each([ - ['right', 'claude', null], - ['down', 'codex', 'paired-host'] -] as const)( - 'Split %s from %s opens an empty pane beside the chat (host %s)', - (direction, agent, host) => { - const worktreeId = folderWorkspaceKey('chat-folder') - if (host) { - runtimeOwners.set(worktreeId, host) - } - const { source, target } = sourceChat(worktreeId, agent) - expect(runNativeChatSplitTarget(target, direction)).toBe(true) - const state = store.getState() - const groupId = state.activeGroupIdByWorktree[worktreeId] - expect(groupId).not.toBe(source.groupId) - expect(state.layoutByWorktree[worktreeId]).toMatchObject({ - direction: direction === 'right' ? 'horizontal' : 'vertical', - first: { groupId: source.groupId }, - second: { groupId } - }) - expect(state.groupsByWorktree[worktreeId]).toContainEqual( - expect.objectContaining({ id: groupId, tabOrder: [] }) - ) - expect(state.unifiedTabsByWorktree[worktreeId]).toEqual([source]) - expect(state.tabsByWorktree[worktreeId] ?? []).toEqual([]) - expect(createRemote).not.toHaveBeenCalled() - } -) - it('Close on the empty pane collapses the split back to the chat', () => { const worktreeId = folderWorkspaceKey('chat-folder') const { source, target } = sourceChat(worktreeId) diff --git a/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts b/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts index 22eda004156..03082c34030 100644 --- a/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts +++ b/src/renderer/src/components/native-chat/pane/routing/use-native-chat-toggle-shortcut.ts @@ -18,7 +18,7 @@ import { canToggleNativeChat } from '../../../../../../shared/native-chat/native import { isNativeChatTranscriptLocalReadable } from '../../../../../../shared/native-chat/transcript/native-chat-transcript-readability' import { matchesNativeChatToggleShortcut } from './native-chat-shortcut' import { getShortcutPlatform } from '@/lib/shortcut-platform' -import { getConnectionIdFromState } from '@/lib/connection-owner-resolution' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { resolveKeyboardWorkspaceId } from '@/lib/floating-workspace-terminal-actions' import { isNativeChatTabWideFallbackSafe, diff --git a/src/renderer/src/components/native-chat/paste/NativeChatComposer.paste-remount.test.tsx b/src/renderer/src/components/native-chat/paste/NativeChatComposer.paste-remount.test.tsx index 81b1d096434..2b4a835b094 100644 --- a/src/renderer/src/components/native-chat/paste/NativeChatComposer.paste-remount.test.tsx +++ b/src/renderer/src/components/native-chat/paste/NativeChatComposer.paste-remount.test.tsx @@ -321,51 +321,6 @@ it.each([false, true])( } ) -it.each([true, false])( - 'releases all previews when a paired paste is removed before acceptance, acceptsImages=%s', - async (acceptsImages) => { - const prepare = Promise.withResolvers<{ - ok: true - target: { - environmentId: string - sessionId: string - expectedEnvironmentPairingRevision: number - } - }>() - mocks.prepare.mockReturnValue(prepare.promise) - const finishUpload = holdUpload() - const allocated = new Set() - const released = new Set() - vi.spyOn(URL, 'createObjectURL').mockImplementation(() => { - const url = 'blob:late-acceptance' - allocated.add(url) - return url - }) - vi.spyOn(URL, 'revokeObjectURL').mockImplementation((url) => { - released.add(url) - }) - const view = render(composer(acceptsImages)) - await act(async () => fireEvent(screen.getByRole('textbox'), imagePaste('caption'))) - await act(async () => - fireEvent.click(screen.getByRole('button', { name: 'Remove attachment' })) - ) - await act(async () => - prepare.resolve({ - ok: true, - target: { - environmentId: 'env-1', - sessionId: 'session-1', - expectedEnvironmentPairingRevision: 1 - } - }) - ) - await act(async () => finishUpload(STORED)) - expect(readNativeChatAttachmentCache(PANE)).toEqual([]) - view.unmount() - expect([...allocated].filter((url) => !released.has(url))).toEqual([]) - } -) - it('starts no upload when the composer closes before image presence is known', async () => { mocks.state.owner = { kind: 'local' } mocks.save.mockClear() @@ -493,10 +448,7 @@ it.each([false, true])( // Model another window reconstructing the editor from the saved pending draft. act(() => editor().commands.setContent(promptTextContent(`${raw}!`), { emitUpdate: false })) } - const transaction = vi.fn() - editor().on('transaction', transaction) await act(async () => pending.resolve('/p/saved.txt')) - expect(transaction).not.toHaveBeenCalled() expect(promptValue(field())).toBe(reconstruct ? `${raw}!` : raw) expect(mocks.state.fieldProps?.sendButtonDisabled).toBe(false) act(() => @@ -628,24 +580,3 @@ it.each(['terminal', 'structured', 'goal'] as const)( ) } ) - -it('preserves goal paste-time size refusal on an upload-incapable owner without changing the draft', async () => { - mocks.state.owner = { kind: 'remote' } - const save = vi.fn() - installPreloadApi({ savePastedTextAsFile: save }) - render(composer(true, undefined, 'goal')) - act(() => writeNativeChatDraftCache(PANE, '/goal')) - act(() => mocks.state.fieldProps?.onSend()) - act(() => writeNativeChatDraftCache(PANE, 'keep this objective')) - const data = new DataTransfer() - data.setData('text/plain', 'x'.repeat(300 * 1024)) - await act(async () => - fireEvent( - screen.getByRole('textbox'), - new ClipboardEvent('paste', { clipboardData: data, cancelable: true }) - ) - ) - expect(promptValue(screen.getByRole('textbox'))).toBe('keep this objective') - expect(screen.getByText(/256 KB limit/)).toBeTruthy() - expect(save).not.toHaveBeenCalled() -}) diff --git a/src/renderer/src/components/native-chat/paste/native-chat-remote-image-paste.test.tsx b/src/renderer/src/components/native-chat/paste/native-chat-remote-image-paste.test.tsx deleted file mode 100644 index 23794b62830..00000000000 --- a/src/renderer/src/components/native-chat/paste/native-chat-remote-image-paste.test.tsx +++ /dev/null @@ -1,194 +0,0 @@ -// @vitest-environment happy-dom -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { act, createElement, useEffect, useRef, useState } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import type { NativeChatAttachmentOwner } from '../attachments/uploads/native-chat-attachment-owner' -import type * as RemoteRuntimePtyIdModule from '../../../../../shared/remote-runtime/remote-runtime-pty-id' - -const mocks = vi.hoisted(() => ({ - saveClipboardImageAsTempFile: vi.fn(), - readClipboardText: vi.fn(), - readClipboardImageThumbnail: vi.fn(), - clipboardHasImage: vi.fn(), - readClipboardFilePaths: vi.fn() -})) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback -})) -vi.mock('../../../../../shared/remote-runtime/remote-runtime-pty-id', async (importOriginal) => ({ - ...(await importOriginal()), - isRemoteRuntimePtyId: () => true -})) - -vi.stubGlobal('window', { - ...window, - api: { - ui: { - saveClipboardImageAsTempFile: mocks.saveClipboardImageAsTempFile, - readClipboardText: mocks.readClipboardText, - readClipboardImageThumbnail: mocks.readClipboardImageThumbnail, - clipboardHasImage: mocks.clipboardHasImage, - readClipboardFilePaths: mocks.readClipboardFilePaths - } - } -}) -vi.stubGlobal('URL', { - ...URL, - createObjectURL: () => 'blob:clipboard-image', - revokeObjectURL: () => {} -}) - -import { clearNativeChatAttachmentCacheForTests } from '../drafts/native-chat-draft-reset' -import { useNativeChatComposerAttachments } from '../attachments/chips/use-native-chat-composer-attachments' -import { useNativeChatComposerPaste } from './use-native-chat-composer-paste' -import { hydrateNativeChatComposerDrafts } from '../drafts/native-chat-composer-draft-load' - -type Api = { - attachments: ReturnType - paste: ReturnType - draft: string - notice: string | null -} - -function Probe({ - acceptsImages, - owner, - onReady -}: { - acceptsImages: boolean - owner: () => NativeChatAttachmentOwner - onReady: (api: Api) => void -}): React.JSX.Element { - const [caret, setCaret] = useState(0) - const [draft, setDraft] = useState('') - const [notice, setNotice] = useState(null) - const textareaRef = useRef(null) - const attachments = useNativeChatComposerAttachments({ - attachmentScopeKey: 'remote-scope', - acceptsImages, - caret, - disabled: false, - isComposing: () => false, - resolveTarget: () => ({ ptyId: 'remote:env-1@@pty-1' }), - textareaRef, - setCaret, - setDraft: (updater) => setDraft((previous) => updater(previous)), - setNotice - }) - const paste = useNativeChatComposerPaste({ - targetKey: 'remote-scope', - attachmentScopeKey: 'remote-scope', - agent: 'claude', - disabled: false, - caret, - resolveAttachmentOwner: owner, - attachResolvedPaths: attachments.attachResolvedPaths, - attachCopiedFiles: () => {}, - captureCopiedFiles: () => async () => {}, - beginPendingImageAttachment: attachments.beginPendingImageAttachment, - resolvePendingImageAttachment: attachments.resolvePendingImageAttachment, - revealPendingImageAttachment: attachments.revealPendingImageAttachment, - dropPendingImageAttachment: attachments.dropPendingImageAttachment, - insertTypedText: () => true, - setCaret, - setNotice - }) - useEffect(() => { - onReady({ attachments, paste, draft, notice }) - }) - return createElement('textarea', { ref: textareaRef }) -} - -let root: Root | null = null - -async function render( - owner: () => NativeChatAttachmentOwner, - acceptsImages = true -): Promise<() => Api> { - const container = document.createElement('div') - document.body.append(container) - let api: Api | null = null - root = createRoot(container) - await act(async () => { - root?.render(createElement(Probe, { acceptsImages, owner, onReady: (next) => (api = next) })) - }) - return () => { - if (!api) { - throw new Error('Probe did not render') - } - return api - } -} - -function imagePasteEvent(): ClipboardEvent { - const data = new DataTransfer() - data.items.add(new File(['image'], 'image.png', { type: 'image/png' })) - return new ClipboardEvent('paste', { clipboardData: data, cancelable: true }) -} - -const SERVER_OWNER: NativeChatAttachmentOwner = { - kind: 'remote', - clipboardImageEnvironmentId: 'env-1' -} - -beforeEach(async () => { - // Hydrate before paste as the app does; pre-load drafts retain remote images by name only. - await hydrateNativeChatComposerDrafts() - vi.resetAllMocks() - mocks.readClipboardText.mockResolvedValue('') - mocks.readClipboardImageThumbnail.mockResolvedValue(null) - mocks.clipboardHasImage.mockResolvedValue(true) - mocks.readClipboardFilePaths.mockResolvedValue([]) - mocks.saveClipboardImageAsTempFile.mockResolvedValue('/tmp/orca-paste-remote.png') -}) - -afterEach(() => { - act(() => root?.unmount()) - root = null - clearNativeChatAttachmentCacheForTests() -}) - -describe('clipboard image paste into a remote terminal-backed chat', () => { - it.each(['event', 'menu'] as const)( - 'attaches the image saved on the server via %s paste', - async (source) => { - const latest = await render(() => SERVER_OWNER) - await act(async () => - source === 'event' - ? latest().paste.handlePaste(imagePasteEvent()) - : latest().paste.pasteFromClipboard() - ) - expect(mocks.saveClipboardImageAsTempFile).toHaveBeenCalledWith({ - runtimeEnvironmentId: 'env-1' - }) - expect(latest().attachments.imageAttachments).toMatchObject([ - { path: '/tmp/orca-paste-remote.png' } - ]) - expect(latest().attachments.imageAttachments[0]?.pending).toBeUndefined() - expect(latest().notice).toBeNull() - } - ) - - it('inserts the server path as a reference for an agent that takes no images', async () => { - const latest = await render(() => SERVER_OWNER, false) - await act(async () => latest().paste.handlePaste(imagePasteEvent())) - expect(latest().draft).toContain('/tmp/orca-paste-remote.png') - expect(latest().notice).toBeNull() - }) - - it('still refuses a nested SSH host the server does not serve', async () => { - const latest = await render(() => ({ kind: 'remote' })) - await act(async () => latest().paste.pasteFromClipboard()) - expect(mocks.saveClipboardImageAsTempFile).not.toHaveBeenCalled() - expect(latest().attachments.imageAttachments).toHaveLength(0) - expect(latest().notice).toBe('Local attachments are not available for remote sessions.') - }) - - it('still refuses client files dropped onto the remote target', async () => { - const latest = await render(() => SERVER_OWNER) - act(() => latest().attachments.attachResolvedPaths(['/Users/me/local.png'], null)) - expect(latest().attachments.imageAttachments).toHaveLength(0) - expect(latest().notice).toBe('Local attachments are not available for remote sessions.') - }) -}) diff --git a/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.test.tsx b/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.test.tsx index e0d3889c428..ffb34475194 100644 --- a/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.test.tsx +++ b/src/renderer/src/components/native-chat/paste/use-native-chat-composer-paste.test.tsx @@ -8,18 +8,13 @@ const mocks = vi.hoisted(() => ({ readClipboardText: vi.fn(), readClipboardImageThumbnail: vi.fn(), clipboardHasImage: vi.fn(), - readClipboardFilePaths: vi.fn(), - getPathForFile: vi.fn() + readClipboardFilePaths: vi.fn() })) vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) -vi.mock('./native-chat-context-paste-limit', () => ({ - NATIVE_CHAT_CONTEXT_PASTE_MAX_BYTES: 1024 -})) - vi.mock('../attachments/intake/native-chat-attachment-notices', () => ({ nativeChatLocalAttachmentUnsupportedNotice: () => 'Local attachments are not available for remote sessions.', @@ -34,8 +29,7 @@ vi.stubGlobal('window', { readClipboardImageThumbnail: mocks.readClipboardImageThumbnail, clipboardHasImage: mocks.clipboardHasImage, readClipboardFilePaths: mocks.readClipboardFilePaths - }, - fs: { getPathForFile: mocks.getPathForFile } + } } }) vi.stubGlobal('URL', { @@ -60,12 +54,10 @@ function imagePasteEvent(text = ''): ClipboardEvent { beforeEach(() => { vi.resetAllMocks() - vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Mozilla/5.0 (X11; Linux x86_64)') mocks.readClipboardText.mockResolvedValue('') mocks.readClipboardImageThumbnail.mockResolvedValue(null) mocks.clipboardHasImage.mockResolvedValue(true) mocks.readClipboardFilePaths.mockResolvedValue([]) - mocks.getPathForFile.mockReturnValue('') mocks.saveClipboardImageAsTempFile.mockResolvedValue(null) }) @@ -76,30 +68,6 @@ afterEach(() => { }) describe('useNativeChatComposerPaste', () => { - it('shows a pending chip before the save resolves', async () => { - let resolveSave: (path: string) => void = () => {} - mocks.saveClipboardImageAsTempFile.mockReturnValue( - new Promise((resolve) => { - resolveSave = resolve - }) - ) - const store = createChipStore() - const probe = await renderProbe({ - resolveAttachmentOwner: () => ({ kind: 'local' }), - store - }) - await act(async () => { - probe.latest().handlePaste(imagePasteEvent()) - }) - expect(store.chips).toEqual([ - { id: 'chip-1', path: '', previewUrl: 'blob:clipboard-image', pending: true } - ]) - await act(async () => { - resolveSave('/tmp/orca-paste-1.png') - }) - expect(store.chips[0]).toMatchObject({ path: '/tmp/orca-paste-1.png', pending: false }) - }) - it('does not settle a local path after the attachment owner changes', async () => { let resolveSave: (path: string) => void = () => {} let owner: NativeChatAttachmentOwner = { kind: 'local' } @@ -132,49 +100,6 @@ describe('useNativeChatComposerPaste', () => { }) describe('composer paste intake regressions', () => { - it.each(['local', 'remote', 'not-ready'] as const)( - 'inserts text without waiting for an image operation on %s', - async (kind) => { - mocks.readClipboardText.mockResolvedValue('안녕하세요\nhello') - mocks.saveClipboardImageAsTempFile.mockReturnValue(new Promise(() => {})) - mocks.clipboardHasImage.mockReturnValue(new Promise(() => {})) - const insertTypedText = vi.fn(() => true) - const setNotice = vi.fn() - const probe = await renderProbe({ - resolveAttachmentOwner: () => ({ kind }), - insertTypedText, - setNotice - }) - await act(async () => probe.latest().pasteFromClipboard()) - expect(insertTypedText).toHaveBeenCalledExactlyOnceWith('안녕하세요\nhello') - expect(setNotice.mock.calls.filter(([notice]) => notice !== null)).toHaveLength(0) - if (kind === 'remote' || kind === 'not-ready') { - expect(mocks.saveClipboardImageAsTempFile).not.toHaveBeenCalled() - } - } - ) - - it.each(['local', 'remote', 'not-ready'] as const)( - 'preserves mixed event text with %s attachments and deduplicates capture', - async (kind) => { - const insertTypedText = vi.fn(() => true) - const setNotice = vi.fn() - const probe = await renderProbe({ - resolveAttachmentOwner: () => ({ kind }), - insertTypedText, - setNotice - }) - const event = imagePasteEvent('caption') - await act(async () => { - probe.latest().handlePaste(event) - probe.latest().handlePaste(event) - }) - expect(insertTypedText).toHaveBeenCalledExactlyOnceWith('caption') - expect(mocks.readClipboardText).not.toHaveBeenCalled() - expect(setNotice.mock.calls.filter(([notice]) => notice !== null)).toHaveLength(0) - } - ) - it.each(['unmount', 'replace', 'disable'] as const)( 'drops late text and pending images after target %s', async (change) => { @@ -224,75 +149,3 @@ describe('composer paste intake regressions', () => { } ) }) - -it('refuses oversized event text without inserting it', async () => { - const insertTypedText = vi.fn(() => true) - const setNotice = vi.fn() - const probe = await renderProbe({ - resolveAttachmentOwner: () => ({ kind: 'remote' }), - insertTypedText, - setNotice - }) - const data = new DataTransfer() - data.setData('text/plain', 'x'.repeat(1025)) - await act(async () => - probe - .latest() - .handlePaste(new ClipboardEvent('paste', { clipboardData: data, cancelable: true })) - ) - expect(insertTypedText).not.toHaveBeenCalled() - expect(setNotice).toHaveBeenCalledWith(expect.stringContaining('too large')) -}) - -describe('file-manager copies', () => { - function fileCopyEvent(files: File[], text: string): ClipboardEvent { - const data = new DataTransfer() - for (const file of files) { - data.items.add(file) - } - data.setData('text/plain', text) - return new ClipboardEvent('paste', { clipboardData: data, cancelable: true }) - } - const png = (name: string): File => new File(['image'], name, { type: 'image/png' }) - - it.each([ - ['a screenshot picture beside its saved file', '', false], - ['a Finder copy, whose clipboard text names the file', 'Screenshot.png', true] - ])( - 'on macOS, holds a chip at once for %s, then lets the clipboard decide', - async (_label, nativeText, attachesFiles) => { - vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('Mozilla/5.0 (Macintosh)') - mocks.getPathForFile.mockImplementation((file: File) => `/Users/me/Desktop/${file.name}`) - let finishRead: (text: string) => void = () => {} - mocks.readClipboardText.mockReturnValue( - new Promise((resolve) => { - finishRead = resolve - }) - ) - mocks.saveClipboardImageAsTempFile.mockResolvedValue('/tmp/shot.png') - const attachCopiedFiles = vi.fn() - const continueCopiedFiles = vi.fn(async () => {}) - const store = createChipStore() - const probe = await renderProbe({ - resolveAttachmentOwner: () => ({ kind: 'local' }), - attachCopiedFiles, - continueCopiedFiles, - store - }) - await act(async () => probe.latest().handlePaste(fileCopyEvent([png('Screenshot.png')], ''))) - expect(store.chips).toEqual([expect.objectContaining({ pending: true })]) - await act(async () => finishRead(nativeText)) - // Files continue the chip reserved at paste time; no new attach starts. - expect(attachCopiedFiles).not.toHaveBeenCalled() - expect(continueCopiedFiles.mock.calls).toEqual( - attachesFiles ? [[[{ path: '/Users/me/Desktop/Screenshot.png', chipId: 'chip-1' }]]] : [] - ) - expect(store.chips).toEqual([ - attachesFiles - ? expect.objectContaining({ id: 'chip-1', pending: true }) - : expect.objectContaining({ path: '/tmp/shot.png', pending: false }) - ]) - expect(mocks.saveClipboardImageAsTempFile).toHaveBeenCalledTimes(attachesFiles ? 0 : 1) - } - ) -}) diff --git a/src/renderer/src/components/native-chat/paste/use-native-chat-pasted-text-file.test.tsx b/src/renderer/src/components/native-chat/paste/use-native-chat-pasted-text-file.test.tsx deleted file mode 100644 index c3aa7833bca..00000000000 --- a/src/renderer/src/components/native-chat/paste/use-native-chat-pasted-text-file.test.tsx +++ /dev/null @@ -1,113 +0,0 @@ -// @vitest-environment happy-dom -import { useRef } from 'react' -import { act, cleanup, render } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' -import { NativeChatPromptEditor } from '../composer/editor/NativeChatPromptEditor' -import { - insertNativeChatPastedText, - type NativeChatComposerInput -} from '../composer/editor/native-chat-composer-input' -import { useNativeChatPastedTextFile } from './use-native-chat-pasted-text-file' -import { clearNativeChatComposerDraftsForTests } from '../drafts/native-chat-draft-reset' -import { updateNativeChatComposerDraft } from '../drafts/native-chat-composer-draft-store' -import { - promptEditor, - promptValue -} from '../composer/editor/native-chat-prompt-editor.test-support' -import { - nativeChatPastedTextOperations, - nativeChatPastedTextToken -} from './native-chat-pasted-text-reference' -import { imageReferencesToPromptMarkers } from '../../../../../shared/native-chat/transcript/native-chat-image-transcript-markers' -import { structuredAgentSessionSendBody } from '../../../../../shared/agent-session/requests/structured-agent-session-send-mutation' -import { structuredAgentSessionBlocksTooLarge } from '../../../../../shared/rpc-contract/structured-agent-session-message-params' - -const save = vi.fn(() => new Promise(() => {})) -const notice = vi.fn() -let paste: (text: string) => boolean -const SCOPE = 'agent-session:sizing' -const ID = '00000000-0000-4000-8000-000000000000' -function Composer({ text }: { text: string }) { - const input = useRef(null) - paste = useNativeChatPastedTextFile({ - scopeKey: SCOPE, - scopeEditor: () => input.current, - resolveAttachmentOwner: () => ({ - kind: 'runtime-session', - environmentId: 'e1', - sessionId: 's1', - pairingRevision: 7 - }), - insertTypedText: (value) => insertNativeChatPastedText(input.current, value), - setNotice: notice - }) - return ( - {}} - onSelect={() => {}} - /> - ) -} -afterEach(() => { - cleanup() - clearNativeChatComposerDraftsForTests() - nativeChatPastedTextOperations.clear() - vi.clearAllMocks() -}) -it.each([ - { draft: 'a'.repeat(200 * 1024), text: '"'.repeat(30 * 1024) }, - { draft: 'z'.repeat(240 * 1024), text: 'q'.repeat(50 * 1024), replace: 200 * 1024 }, - { draft: '', text: 'é'.repeat(16 * 1024 + 1) }, - { draft: '', text: "$& $$ $` $'".repeat(4000) }, - { draft: '', text: 'c'.repeat(20 * 1024), image: 'p'.repeat(240 * 1024) }, - { - draft: nativeChatPastedTextToken(ID), - text: 'q', - path: `/p/${'a'.repeat(256 * 1024 - 32)}` - } -])( - 'matches the actual JSON/UTF-8 send body, including selection and path bytes', - ({ draft, text, replace = 0, image = '', path = '' }) => { - useAppStore.setState({ runtimeStatusByEnvironmentId: new Map() }) - vi.stubGlobal('api', { ui: { savePastedTextAsFile: save } }) - updateNativeChatComposerDraft( - SCOPE, - { - text: draft, - images: image ? [{ id: 'i1', path: image }] : [], - pastedTextFiles: path ? { [ID]: path } : {} - }, - 'immediate' - ) - const view = render() - const editor = promptEditor(view.getByRole('textbox')) - act(() => { - if (replace) { - editor.commands.setTextSelection({ from: 1, to: replace + 1 }) - } else { - editor.commands.focus('end') - } - }) - const input = promptValue(view.getByRole('textbox')) - const candidate = replace ? text + input.slice(replace) : input + text - const projected = path - ? candidate.replace(nativeChatPastedTextToken(ID), () => `@${path} `) - : candidate - const body = structuredAgentSessionSendBody( - imageReferencesToPromptMarkers(projected, ['i1']), - image ? [{ path: image, previewUri: '' }] : [] - ) - const tooLarge = structuredAgentSessionBlocksTooLarge(body.blocks) - expect(tooLarge).toBe(Buffer.byteLength(JSON.stringify(body.blocks), 'utf8') > 256 * 1024) - act(() => void paste(text)) - expect(promptValue(view.getByRole('textbox'))).toBe(tooLarge ? input : candidate) - expect(save).not.toHaveBeenCalled() - expect(notice).toHaveBeenCalledTimes(tooLarge ? 1 : 0) - } -) diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.fixture.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.fixture.tsx index df35dd0e807..5e68681bfc9 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.fixture.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.fixture.tsx @@ -231,3 +231,44 @@ export const historyLinks = defineFixture({ ), interact: (frame) => frame.querySelector('button[aria-expanded]')?.click() }) + +export const previews = defineFixture({ + width: 560, + render: () => ( +
+ {}} + onCancel={() => {}} + /> +
+ ), + interact: async (frame) => { + frame.querySelectorAll('button[aria-pressed]')[0]?.click() + await new Promise(requestAnimationFrame) + } +}) diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx index cf50c7ec441..1e89b19d5aa 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.test.tsx @@ -86,4 +86,44 @@ describe('NativeChatQuestionCard', () => { expect(pressAt(10, 10, 'ArrowDown')).toBe(true) expect(document.activeElement).toBe(rows[0]) }) + + it('shows a picked preview, keeps it on a second click, and confirms the digit-named option with Enter', () => { + vi.useFakeTimers() + container.setAttribute('data-native-chat-root', 'true') + const onAnswer = vi.fn() + act(() => { + root.render( + {}} + shouldFocus + /> + ) + }) + const rows = container.querySelectorAll('button[aria-pressed]') + act(() => rows[0]!.focus()) + pressKey({ key: '2' }, rows[0]!) + act(() => rows[1]!.click()) + act(() => vi.runAllTimers()) + expect(container.querySelector('pre')?.textContent).toBe('| nav |\n| main |') + expect(document.activeElement).toBe(rows[1]) + expect(onAnswer).not.toHaveBeenCalled() + pressKey({ key: 'ArrowUp' }, rows[1]!) + pressKey({ key: '2' }, rows[0]!) + expect(document.activeElement).toBe(rows[1]) + pressKey({ key: 'Enter' }, rows[1]!) + expect(onAnswer).toHaveBeenCalledWith([{ indices: [1], other: '' }]) + }) }) diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx index 91986107d6e..0f2e27541f1 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionCard.tsx @@ -18,6 +18,7 @@ import type { AgentJournalFreeTextInput } from '../../../../../shared/agent-sess import { askAcceptsEmptyAnswer, askConfirmAction, + askQuestionShowsPreviews, askConfirmLabel, askTypedText, toggleAskOption @@ -82,6 +83,7 @@ export function NativeChatQuestionCard({ const questionAllowsOther = Array.isArray(allowOther) ? (allowOther[index] ?? false) : allowOther const freeTextInput = freeTextInputs?.[index] const fieldTakesFocus = q.options.length === 0 || undefined + const showsPreviews = askQuestionShowsPreviews(q) const answerPlaceholder = freeTextInput?.placeholder ?? t('components.native-chat.question.otherPlaceholder', 'Type your answer') @@ -156,15 +158,31 @@ export function NativeChatQuestionCard({ } } - // Briefly show a single-select pick before advancing; picking again retracts it. - const pickOption = (optionIndex: number): void => { + // Briefly show a single-select pick before advancing; picking again retracts it. With previews, + // a pick stays put: a digit focuses its row, and Enter on the chosen row confirms. + const pickOption = ( + optionIndex: number, + via: 'pointer' | 'digit' | 'enter' = 'pointer' + ): void => { const cur = selections[index] ?? [] + // Focus first, so Enter after any digit acts on the row that digit named. + if (showsPreviews && via === 'digit') { + cardRef.current + ?.querySelectorAll('button[aria-pressed]') + [optionIndex]?.focus() + } + if (showsPreviews && cur.includes(optionIndex)) { + if (via === 'enter') { + confirm(true) + } + return + } const picked = !cur.includes(optionIndex) const chosen = toggleAskOption(cur, optionIndex, q.multiSelect) const next = selections.map((s, i) => (i === index ? chosen : s)) setSelections(next) autoAdvance.cancel() - if (picked && !q.multiSelect) { + if (picked && !q.multiSelect && !showsPreviews) { autoAdvance.schedule(() => advanceOrSubmit(next, otherText)) } } @@ -298,6 +316,7 @@ export function NativeChatQuestionCard({ initialFocus={i === 0} label={opt.label} description={opt.description} + preview={opt.preview} selected={(selections[index] ?? []).includes(i)} disabled={isSubmitting} onSelect={() => pickOption(i)} diff --git a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx index 9887464590f..ef575dc5ba4 100644 --- a/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx +++ b/src/renderer/src/components/native-chat/prompts/NativeChatQuestionOption.tsx @@ -1,11 +1,17 @@ import { Check } from 'lucide-react' import { cn } from '@/lib/utils' +// Stable, so it runs when the preview opens rather than on every render; the option list is height-capped. +function revealPreview(element: HTMLPreElement | null): void { + element?.scrollIntoView?.({ block: 'nearest' }) +} + export function NativeChatQuestionOption({ badge, initialFocus, label, description, + preview, selected, disabled, onSelect @@ -14,47 +20,60 @@ export function NativeChatQuestionOption({ initialFocus: boolean label: string description?: string + /** Shown under the row while it is selected, as the agent wrote it. */ + preview?: string selected: boolean disabled: boolean onSelect: () => void }): React.JSX.Element { return ( - + + {selected ? : badge} + + + {label} + {description ? ( + + {description} + + ) : null} + + + {preview && selected ? ( +
+          {preview}
+        
+ ) : null} +
) } diff --git a/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts b/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts index e0696c342d2..39f41cdb290 100644 --- a/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts +++ b/src/renderer/src/components/native-chat/prompts/use-native-chat-question-keys.ts @@ -7,7 +7,7 @@ export function useNativeChatQuestionKeys( cardRef: RefObject, enabled: boolean, optionCount: number, - onPick: (optionIndex: number) => void, + onPick: (optionIndex: number, via: 'digit' | 'enter') => void, onStep: (delta: 1 | -1) => boolean ): void { const onKeyDown = useEffectEvent((event: KeyboardEvent): void => { @@ -48,7 +48,7 @@ export function useNativeChatQuestionKeys( return } event.preventDefault() - onPick(optionIndex) + onPick(optionIndex, 'digit') } else if (isArrow) { const up = event.key === 'ArrowUp' if ( @@ -82,7 +82,7 @@ export function useNativeChatQuestionKeys( } } else if (event.key === 'Enter' && focusedIndex !== -1) { event.preventDefault() - onPick(focusedIndex) + onPick(focusedIndex, 'enter') } }) useEffect(() => { diff --git a/src/renderer/src/components/native-chat/selection-quotes/NativeChatSelectionQuote.test.tsx b/src/renderer/src/components/native-chat/selection-quotes/NativeChatSelectionQuote.test.tsx index 42a5e212585..6010d9e6127 100644 --- a/src/renderer/src/components/native-chat/selection-quotes/NativeChatSelectionQuote.test.tsx +++ b/src/renderer/src/components/native-chat/selection-quotes/NativeChatSelectionQuote.test.tsx @@ -88,18 +88,6 @@ describe('NativeChatSelectionQuote', () => { vi.useRealTimers() }) - it('quotes a selection from an agent reply into the composer as a blockquote', () => { - render() - releaseSelection(screen.getByTestId('first')) - - const quote = screen.getByRole('button', { name: 'Add to chat' }) - fireEvent.pointerDown(quote, { button: 0 }) - fireEvent.click(quote) - - expect(appendText).toHaveBeenCalledWith('> Use the draft store.\n>\n> It already appends.\n\n') - expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull() - }) - it('takes a selection that runs on over text that cannot be selected', () => { render() releaseSelection(screen.getByTestId('first'), screen.getByTestId('time')) @@ -112,28 +100,6 @@ describe('NativeChatSelectionQuote', () => { releaseSelection(screen.getByTestId('first'), screen.getByTestId('next')) expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull() }) - - it('offers nothing when a press leaves the selection as it was', () => { - render() - releaseSelection(screen.getByTestId('first')) - fireEvent.pointerDown(screen.getByTestId('time'), { button: 0 }) - fireEvent.mouseUp(screen.getByTestId('time'), { button: 0 }) - settle() - - expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull() - }) - - it('withdraws the offer once the selection is gone', () => { - render() - releaseSelection(screen.getByTestId('first')) - expect(screen.getByRole('button', { name: 'Add to chat' })).toBeTruthy() - - act(() => { - window.getSelection()!.removeAllRanges() - document.dispatchEvent(new Event('selectionchange')) - }) - expect(screen.queryByRole('button', { name: 'Add to chat' })).toBeNull() - }) }) describe('NativeChatSelectionQuote copy on select', () => { diff --git a/src/renderer/src/components/native-chat/selection-quotes/SelectionAddToChatPopover.tsx b/src/renderer/src/components/native-chat/selection-quotes/SelectionAddToChatPopover.tsx index 26fce939a9a..95793fed260 100644 --- a/src/renderer/src/components/native-chat/selection-quotes/SelectionAddToChatPopover.tsx +++ b/src/renderer/src/components/native-chat/selection-quotes/SelectionAddToChatPopover.tsx @@ -1,4 +1,5 @@ import { useEffect, useEffectEvent, useMemo, useRef, useState, type RefObject } from 'react' +import { flushSync } from 'react-dom' import { Quote } from 'lucide-react' import { Button } from '@/components/ui/button' import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover' @@ -149,9 +150,11 @@ export function SelectionAddToChatPopover({ variant="ghost" size="xs" onClick={(event) => { + const button = event.currentTarget.getBoundingClientRect() + // Why: the composer refuses focus while an overlay, including this one, is open. // Taken or not (the composer may have locked since), the offer is spent. - onAdd(request.text, event.currentTarget.getBoundingClientRect()) - setRequest(null) + flushSync(() => setRequest(null)) + onAdd(request.text, button) }} > diff --git a/src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.ts b/src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.ts index 38e96f99d6a..3dc5e65160c 100644 --- a/src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.ts +++ b/src/renderer/src/components/native-chat/selection-quotes/native-chat-workspace-selection.ts @@ -7,12 +7,12 @@ import { } from '../../../../../shared/workspace-layout/stable-pane-id' import type { AppState } from '@/store/types' import { useAppStore } from '@/store' -import type { AgentMessageTarget } from '@/lib/agent-message-target' -import { sendMessageToAgent } from '@/lib/agent-message-send' -import type { ActiveAgentNotesSendResult } from '@/lib/active-agent-note-send-result' +import type { AgentMessageTarget } from '@/lib/agent-session/messaging/agent-message-target' +import { sendMessageToAgent } from '@/lib/agent-session/messaging/agent-message-send' +import type { ActiveAgentNotesSendResult } from '@/lib/agent-session/messaging/terminal/active-agent-note-send-result' import { activateStructuredAgentSessionTab } from '@/lib/agent-session/structured-agent-session-tab-activation' -import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane' -import { activateTerminalTabOnOwner } from '@/lib/terminal-tab-owner-activation' +import { activateTabAndFocusPane } from '@/lib/workspace/tabs/activate-tab-and-focus-pane' +import { activateTerminalTabOnOwner } from '@/lib/workspace/tabs/terminal-tab-owner-activation' import { requestNativeChatComposerFocus } from '../composer/focus/native-chat-composer-focus-intent' import { structuredAgentSessionDraftScopeKey } from '../drafts/native-chat-draft-scope' import { appendQuoteToChatDraft } from '../drafts/native-chat-selection-quote-draft' diff --git a/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts b/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts index 0f7b6e36459..82083821e4e 100644 --- a/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts +++ b/src/renderer/src/components/native-chat/session/options/catalog/native-chat-session-option-discovery.ts @@ -7,9 +7,9 @@ import { getCommitMessageModelDiscoveryHostKeyForScope, LOCAL_COMMIT_MESSAGE_HOST_KEY } from '../../../../../../../shared/source-control/ai/generation/commit-message-host-key' -import { runtimeTargetForWorkspaceOwner } from '@/lib/resolve-owner' +import { runtimeTargetForWorkspaceOwner } from '@/lib/workspace/ownership/resolve-owner' import { hasExplicitTuiLaunchCommand } from '../../../../../../../shared/agent-launch/startup/tui-agent-launch-command-override' -import { getConnectionIdFromState } from '@/lib/connection-owner-resolution' +import { getConnectionIdFromState } from '@/lib/workspace/ownership/connection-owner-resolution' import { getLocalProjectExecutionRuntimeContext, getWslDistroFromPath diff --git a/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.test.ts b/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.test.ts index aa543c8b397..f2879c0d4e6 100644 --- a/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.test.ts +++ b/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.test.ts @@ -4,6 +4,38 @@ import { describe, expect, it, vi } from 'vitest' import { createClaudeModelSwitchConfirmationObserver } from './claude-model-switch-confirmation' describe('Claude model switch confirmation detection', () => { + it.each([ + [ + 'quoted model name', + 'Claude Opus 5.5', + 'Set model to `Opus 5.5` and saved as your default for new sessions' + ], + [ + 'matching requested context variant', + 'Claude Opus 5.5 (1M context)', + 'Set model to `Opus 5.5 (1M context)` and saved as your default for new sessions' + ], + ['raw model id fallback', 'claude-opus-5-5', 'Set model to Opus 5.5'], + ['alias picker row', 'Opus alias', 'Set model to Opus 5.5'] + ])('confirms a picker label with %s', async (_name, label, output) => { + const dataObserver = { current: (_data: string): void => {} } + const observer = createClaudeModelSwitchConfirmationObserver({ + ptyId: 'pty-1', + expectedModelLabel: label, + subscribeToData: (watcher) => { + dataObserver.current = watcher + return () => {} + } + }) + + await observer.ready + observer.arm() + observer.startDetection() + dataObserver.current(output) + + await expect(observer.result).resolves.toBe('applied') + }) + it('reports matching success output split across PTY chunks', async () => { const dataObserver = { current: (_data: string): void => {} } const unsubscribe = vi.fn(() => {}) diff --git a/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.ts b/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.ts index 3c614586f10..803430cad19 100644 --- a/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.ts +++ b/src/renderer/src/components/native-chat/session/options/terminal/claude-model-switch-confirmation.ts @@ -33,12 +33,14 @@ function compactTerminalText(buffer: string): string { function hasClaudeModelSwitchSuccess(buffer: string, modelLabel: string): boolean { const text = compactTerminalText(buffer) - const marker = `setmodelto${modelLabel.replace(/\s+/g, '').toLowerCase()}` + // Claude echoes neither the vendor prefix nor Orca's picker-only `alias` suffix. + const label = modelLabel.replace(/^claude[\s-]+/i, '').replace(/\s+alias$/i, '') + const marker = `setmodelto${label.replace(/\s+/g, '').toLowerCase()}` if (text.includes(marker)) { return true } // Match every picker token so a versioned echo cannot confirm the wrong context variant. - const labelTokens = modelLabel.toLowerCase().match(/[a-z]+|\d+[a-z]*/g) ?? [] + const labelTokens = label.toLowerCase().match(/[a-z]+|\d+[a-z]*/g) ?? [] const successStart = text.lastIndexOf('setmodelto') if (successStart === -1 || labelTokens.length === 0) { return false diff --git a/src/renderer/src/components/native-chat/session/options/terminal/serialized-screen-background-rows.test.ts b/src/renderer/src/components/native-chat/session/options/terminal/serialized-screen-background-rows.test.ts index a4549bc9abe..ff50d589d04 100644 --- a/src/renderer/src/components/native-chat/session/options/terminal/serialized-screen-background-rows.test.ts +++ b/src/renderer/src/components/native-chat/session/options/terminal/serialized-screen-background-rows.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import { Terminal } from '@xterm/headless' import { SerializeAddon } from '@xterm/addon-serialize' import { readClaudeSessionOptionsFromTerminalScreen } from './claude-terminal-session-options' -import { buildBoundedSessionTranscript } from '@/lib/agent-session-fork-context' +import { buildBoundedSessionTranscript } from '@/lib/agent-session/context/agent-session-fork-context' const CLAUDE_FRAME = [ '╭─ Claude Code ───╮', diff --git a/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx b/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx index f6346cceb1a..231300f0d93 100644 --- a/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx +++ b/src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx @@ -1,6 +1,4 @@ import { useEffect } from 'react' -import type { AgentSessionStatusSummary } from '../../../../../../shared/agent-session/agent-session-wire' -import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' import { projectStatus } from './structured-agent-session-status-projection' import { getStructuredAgentSessionLaunchLifecycle, @@ -9,52 +7,36 @@ import { import { getStructuredAgentSessionLaunchFailedAt } from '@/lib/agent-session/launch/structured-agent-session-launch-failed-at' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' +import type { StructuredChatCompanionWrite } from '@/store/slices/agent-status/structured-chat-companion-writes' import { structuredAgentSessionTargetForHost } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' import { getStructuredAgentSessionStatusFeed, - structuredAgentSessionStatusFeedKey, - type StructuredAgentSessionStatusFeedOwner + structuredAgentSessionStatusFeedKey } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import { getStructuredAgentSessionTabs, type StructuredTab } from './structured-agent-session-tabs' +import { + getStructuredAgentSessionTabs, + getStructuredAgentSessionTabsInWorkspace, + type StructuredTab +} from './structured-agent-session-tabs' +import { readTabMapChanges } from '@/store/keyed-record-change-reads' import { createTabOwnerCache, ownerInputChanged, ownerInputs } from './structured-agent-session-tab-owner-cache' +import { + createStructuredSessionMembership, + type HostGroup, + type Member, + type ProjectionInput, + sameSemanticTab +} from './structured-agent-session-status-membership' -// Re-exported so the bridge stays the one import site its consumers already know. - -type HostGroup = { - members: Member[] - /** A host tick names its sessions; this finds their tabs without walking every member. */ - membersBySession: Map - /** Captured but not yet projected (a throwing commit); retried on this host's next tick. */ - owed: Set - feed: StructuredAgentSessionStatusFeedOwner - unsubscribe: () => void - release?: () => void -} -type ProjectionInput = { - tab: StructuredTab - member: Member - summary: AgentSessionStatusSummary | null - observation: 'live' | 'unverifiable' - failedAt: number | null - sleptAt: number | null | undefined - directory: string | undefined -} -type Member = { - paneKey: string - tab: StructuredTab - hostKey: string | null - group: HostGroup | null - status?: ProjectionInput - captured?: ProjectionInput -} /** Unchanged feed facts for an unchanged tab cannot change its projection or companions. */ function sameCapturedInput(previous: ProjectionInput | undefined, next: ProjectionInput): boolean { return ( - previous?.tab === next.tab && + previous !== undefined && + sameSemanticTab(previous.tab, next.tab) && previous.summary === next.summary && previous.observation === next.observation && previous.failedAt === next.failedAt && @@ -65,7 +47,8 @@ function sameCapturedInput(previous: ProjectionInput | undefined, next: Projecti function sameStatusInput(previous: ProjectionInput | undefined, next: ProjectionInput): boolean { return ( - previous?.tab === next.tab && + previous !== undefined && + sameSemanticTab(previous.tab, next.tab) && previous.summary === next.summary && previous.observation === next.observation && previous.failedAt === next.failedAt @@ -73,9 +56,11 @@ function sameStatusInput(previous: ProjectionInput | undefined, next: Projection } function installStatusProjection(): () => void { - const members = new Map() - const membersByTabId = new Map() + const membership = createStructuredSessionMembership() + const { members, membersByTabId, legacy } = membership const retired = new Set() + let tabs: readonly StructuredTab[] | null = null + let tabsSource: AppState['unifiedTabsByWorktree'] | null = null const groups = new Map() const queue: (() => void)[] = [] const ownerForTab = createTabOwnerCache() @@ -120,20 +105,17 @@ function installStatusProjection(): () => void { const target = tab && structuredAgentSessionTargetForHost(ownerForTab(useAppStore.getState(), tab)) return ( - tab === input.tab && + sameSemanticTab(tab, input.tab) && (target ? structuredAgentSessionStatusFeedKey(target) : null) === input.member.hostKey ) } - const companions = (input: ProjectionInput): void => { + const companions = (input: ProjectionInput, writes: StructuredChatCompanionWrite[]): void => { const { member, tab, sleptAt, directory } = input if ( current(input) && (member.group ? member.group.feed.getSessionSleepState(tab.entityId) : null) === sleptAt ) { - const store = useAppStore.getState() - if (store.structuredChatSleptAtByPaneKey[member.paneKey] !== sleptAt) { - store.setStructuredChatSleptAt(member.paneKey, sleptAt) - } + writes.push({ kind: 'slept-at', paneKey: member.paneKey, sleptAt }) } if (!current(input)) { return @@ -145,19 +127,16 @@ function installStatusProjection(): () => void { if (latestDirectory !== directory) { return } - const store = useAppStore.getState() - const pin = store.structuredSessionLaunchDirectoryByTabId[tab.id] - if ( + writes.push( directory - ? pin?.sessionId !== tab.entityId || pin.launchDirectory !== directory - : pin?.sessionId === tab.entityId - ) { - if (directory) { - store.setStructuredSessionLaunchDirectory(tab.id, tab.entityId, directory) - } else { - store.clearStructuredSessionLaunchDirectory(tab.id, tab.entityId) - } - } + ? { + kind: 'launch-directory', + tabId: tab.id, + sessionId: tab.entityId, + launchDirectory: directory + } + : { kind: 'clear-launch-directory', tabId: tab.id, sessionId: tab.entityId } + ) } const project = (inputs: ProjectionInput[]): void => { const removed = [...retired] @@ -165,18 +144,26 @@ function installStatusProjection(): () => void { (input) => current(input) && !sameStatusInput(input.member.status, input) ) const clean = (): void => { + const writes: StructuredChatCompanionWrite[] = [] for (const old of removed) { if (!members.has(old.paneKey)) { - useAppStore.getState().setStructuredChatSleptAt(old.paneKey, undefined) + writes.push({ kind: 'slept-at', paneKey: old.paneKey, sleptAt: undefined }) } - const replacement = membersByTabId.get(old.tab.id) - if (!replacement || replacement.tab.entityId !== old.tab.entityId) { - useAppStore.getState().clearStructuredSessionLaunchDirectory(old.tab.id, old.tab.entityId) + const replacements = membersByTabId.get(old.tab.id) ?? [] + if (![...replacements].some((member) => member.tab.entityId === old.tab.entityId)) { + writes.push({ + kind: 'clear-launch-directory', + tabId: old.tab.id, + sessionId: old.tab.entityId + }) } - retired.delete(old) } for (const input of inputs) { - companions(input) + companions(input, writes) + } + useAppStore.getState().applyStructuredChatCompanionWrites(writes) + for (const old of removed) { + retired.delete(old) } } if (dirty.length || removed.length) { @@ -204,14 +191,14 @@ function installStatusProjection(): () => void { // Mark consumed only after a normal return: a throwing commit leaves the input for the next emission to retry. for (const input of inputs) { input.member.captured = input - input.member.group?.owed.delete(input.member) + membership.settle(input.member) } } const activateGroups = (): void => { for (const [hostKey, group] of groups) { - if (groups.get(hostKey) === group && group.members.length && !group.release) { + if (groups.get(hostKey) === group && group.members.size && !group.release) { const release = group.feed.activate() - if (disposed || groups.get(hostKey) !== group || !group.members.length) { + if (disposed || groups.get(hostKey) !== group || !group.members.size) { release() } else { group.release = release @@ -240,7 +227,9 @@ function installStatusProjection(): () => void { // Launch ticks and full host ticks carry every member; skip the unchanged ones. if (!sameCapturedInput(member.captured, input)) { inputs.push(input) - member.group?.owed.add(member) + membership.owe(member) + } else { + membership.settle(member) } } enqueue( @@ -251,125 +240,145 @@ function installStatusProjection(): () => void { inputs.map(({ member }) => ({ host: member.hostKey, paneKey: member.paneKey })) ) } - const reconcile = (): void => { + const withOwed = (selected: Iterable) => membership.withDebt(selected, groups.values()) + const groupFor = ( + state: AppState, + tab: StructuredTab + ): { hostKey: string | null; group: HostGroup | null } => { + const target = structuredAgentSessionTargetForHost(ownerForTab(state, tab)) + const hostKey = target ? structuredAgentSessionStatusFeedKey(target) : null + const existing = hostKey ? groups.get(hostKey) : undefined + if (existing || !target || !hostKey) { + return { hostKey, group: existing ?? null } + } + const feed = getStructuredAgentSessionStatusFeed(target) + const created: HostGroup = { + members: new Set(), + membersBySession: new Map(), + owed: new Set(), + feed, + unsubscribe: () => {} + } + groups.set(hostKey, created) + created.unsubscribe = feed.subscribe((change) => + boundary(() => { + if (disposed) { + return + } + if (change === null) { + capture(created.members) + return + } + const selected = new Set() + for (const sessionId of change) { + created.membersBySession.get(sessionId)?.forEach((member) => selected.add(member)) + } + // Membership changes prune superseded members, so the debt holds only current tabs. + created.owed.forEach((member) => selected.add(member)) + capture(selected) + }) + ) + return { hostKey, group: created } + } + const place = (state: AppState, tab: StructuredTab, paneKey: string, changed: Set) => { + const { hostKey, group } = groupFor(state, tab) + const member = membership.place(tab, paneKey, hostKey, group) + if (member) { + changed.add(member) + } + } + // Cold path (bootstrap, hydration, unannotated replacement): the whole projected chat list. + const reconcileFromSnapshot = ( + source: AppState['unifiedTabsByWorktree'], + placeTab: (tab: StructuredTab, paneKey: string) => void + ): Member[] => { + const nextTabs = getStructuredAgentSessionTabs(source) + if (nextTabs === tabs) { + return [] + } + const retiring = membership.reconcileTabs(nextTabs, null, placeTab) + tabs = nextTabs + return retiring + } + const reconcile = (ownersChanged: boolean): void => { const state = useAppStore.getState() - const next = new Map() - for (const tab of getStructuredAgentSessionTabs(state.unifiedTabsByWorktree)) { - const paneKey = structuredAgentSessionPaneKey(tab.id, tab.entityId) - const target = structuredAgentSessionTargetForHost(ownerForTab(state, tab)) - const hostKey = target ? structuredAgentSessionStatusFeedKey(target) : null - let group = hostKey ? groups.get(hostKey) : undefined - if (!group && target && hostKey) { - const feed = getStructuredAgentSessionStatusFeed(target) - const created: HostGroup = { - members: [], - membersBySession: new Map(), - owed: new Set(), - feed, - unsubscribe: () => {} - } - groups.set(hostKey, created) - created.unsubscribe = feed.subscribe((change) => - boundary(() => { - if (disposed) { - return - } - if (change === null) { - capture(created.members) - return - } - const selected = new Set() - for (const sessionId of change) { - for (const member of created.membersBySession.get(sessionId) ?? []) { - selected.add(member) - } - } - // Reconcile prunes superseded members, so the debt holds only current tabs. - created.owed.forEach((member) => selected.add(member)) - capture(selected) - }) - ) - group = created - } - const old = members.get(paneKey) - const member: Member = - old?.group === (group ?? null) - ? old - : { - paneKey, - tab, - hostKey, - group: group ?? null - } - member.tab = tab - next.set(paneKey, member) - } - for (const member of members.values()) { - if (!next.has(member.paneKey)) { - retired.add(member) + const source = state.unifiedTabsByWorktree + const changed = new Set() + const retiring: Member[] = [] + const placeTab = (tab: StructuredTab, paneKey: string) => place(state, tab, paneKey, changed) + if (source !== tabsSource) { + const changes = tabsSource ? readTabMapChanges(source, tabsSource) : null + if (changes?.kind === 'addressed') { + const listed = [...changes.workspaceIds].flatMap((workspaceId) => [ + ...getStructuredAgentSessionTabsInWorkspace(source, workspaceId) + ]) + retiring.push(...membership.reconcileTabs(listed, changes.tabIds, placeTab)) + tabs = null + } else { + retiring.push(...reconcileFromSnapshot(source, placeTab)) } } - members.clear() - membersByTabId.clear() - for (const group of groups.values()) { - group.members = [] - group.membersBySession = new Map() - // A rebound pane gets a new member without retiring the old one; drop every superseded identity. - for (const member of group.owed) { - if (next.get(member.paneKey) !== member) { - group.owed.delete(member) - } - } + for (const member of retiring) { + membership.detach(member) + retired.add(member) } - for (const [key, member] of next) { - members.set(key, member) - membersByTabId.set(member.tab.id, member) - if (member.group) { - member.group.members.push(member) - const sessionMembers = member.group.membersBySession.get(member.tab.entityId) - if (sessionMembers) { - sessionMembers.push(member) - } else { - member.group.membersBySession.set(member.tab.entityId, [member]) - } + // Advanced only after a normal return, so a throwing pass is retried by the next tab write. + tabsSource = source + if (ownersChanged) { + for (const member of legacy) { + place(state, member.tab, member.paneKey, changed) } } for (const [key, group] of groups) { - if (groups.get(key) === group && !group.members.length) { + if (groups.get(key) === group && !group.members.size) { groups.delete(key) - group.members = [] group.unsubscribe() group.release?.() } } - enqueue(() => { - activateGroups() - capture(members.values()) - }) + // Existing projection or retirement debt drains on any reconciliation, not only on new changes. + if (changed.size || retired.size || membership.hasDebt(groups.values())) { + enqueue(() => { + activateGroups() + capture(withOwed(changed)) + }) + } } const unsubscribeApp = useAppStore.subscribe((state: AppState, previous: AppState) => { - if ( - !disposed && - (state.unifiedTabsByWorktree !== previous.unifiedTabsByWorktree || - ownerInputs.some((key) => ownerInputChanged(state, previous, key))) - ) { - boundary(reconcile) + if (disposed) { + return + } + const ownersChanged = ownerInputs.some((key) => ownerInputChanged(state, previous, key)) + if (ownersChanged || useAppStore.getState().unifiedTabsByWorktree !== tabsSource) { + boundary(() => reconcile(ownersChanged)) } }) - const unsubscribeLaunch = subscribeStructuredAgentLaunchStatus(() => + const unsubscribeLaunch = subscribeStructuredAgentLaunchStatus((sessionIds) => boundary(() => { - if (!disposed) { - capture(members.values()) + if (disposed) { + return } + // Full resync: the writer could not name its sessions. + if (sessionIds === null) { + capture(members.values()) + return + } + const selected = new Set() + for (const group of groups.values()) { + for (const sessionId of sessionIds) { + group.membersBySession.get(sessionId)?.forEach((member) => selected.add(member)) + } + } + capture(withOwed(selected)) }) ) - boundary(reconcile) + boundary(() => reconcile(false)) return () => { disposed = true unsubscribeApp() unsubscribeLaunch() for (const group of groups.values()) { - group.members = [] + group.members.clear() group.unsubscribe() boundary(() => group.release?.()) } @@ -377,8 +386,7 @@ function installStatusProjection(): () => void { for (const member of members.values()) { retired.add(member) } - members.clear() - membersByTabId.clear() + membership.clear() enqueue(() => project([])) } } diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-tab-actions.test.tsx b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-tab-actions.test.tsx new file mode 100644 index 00000000000..61bf01b6e34 --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-bridge-tab-actions.test.tsx @@ -0,0 +1,234 @@ +import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof' +// @vitest-environment happy-dom + +import { act, cleanup, render, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + AgentSessionStatusEvent, + AgentSessionStatusSummary +} from '../../../../../../shared/agent-session/agent-session-wire' +import { + LOCAL_EXECUTION_HOST_ID, + type ExecutionHostId +} from '../../../../../../shared/execution-host' +import type { Tab } from '../../../../../../shared/tab-types' +import type { AppState } from '@/store/types' + +import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' + +type TestStore = { + getState: () => AppState + setState: (state: Partial) => void +} + +const mocks = vi.hoisted(() => { + const hoisted: { + store: TestStore | null + subscribeStatus: ReturnType + supportsCapability: ReturnType + unsubscribe: ReturnType + applyStatus: ReturnType void>> + } = { + store: null, + subscribeStatus: vi.fn(), + supportsCapability: vi.fn(), + unsubscribe: vi.fn(), + applyStatus: vi.fn() + } + return hoisted +}) + +vi.mock('@/store', async () => { + const { createTestStore } = await import('@/store/testing/app-store-test-fixture') + const useAppStore = createTestStore() + const { transactAgentStatuses } = useAppStore.getState() + useAppStore.setState({ + transactAgentStatuses: (operation) => + transactAgentStatuses((transaction) => + operation({ + ...transaction, + apply: (update) => { + mocks.applyStatus(update) + return transaction.apply(update) + } + }) + ) + }) + mocks.store = useAppStore + return { useAppStore } +}) + +vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (importOriginal) => ({ + ...(await importOriginal()), + runtimeEnvironmentSupportsCapability: mocks.supportsCapability +})) + +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => ({ + callStructuredAgentSession: vi.fn() +})) + +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ + subscribeStructuredAgentSession: vi.fn(), + subscribeStructuredAgentSessionStatus: mocks.subscribeStatus +})) + +import { useAppStore } from '@/store' + +import { StructuredAgentSessionStatusBridge } from './StructuredAgentSessionStatusBridge' +import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' + +import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' + +function summary(overrides: Partial = {}): AgentSessionStatusSummary { + return { + sessionId: 'session-1', + workspaceId: 'wt-1', + agent: 'codex', + status: 'idle', + latestPrompt: 'hello', + updatedAt: 1, + ...overrides + } +} + +function feed(index = 0): { target: unknown; emit: (event: AgentSessionStatusEvent) => void } { + const calls = mocks.subscribeStatus.mock.calls + const call = calls[index < 0 ? calls.length + index : index] + return { target: call[0], emit: call[1] } +} + +function statusFor(tabId: string, sessionId: string) { + return useAppStore.getState().agentStatusByPaneKey[ + structuredAgentSessionPaneKey(tabId, sessionId) + ] +} + +function openChat(id: string, sessionId: string, executionHostId?: ExecutionHostId): void { + useAppStore.getState().createUnifiedTab('wt-1', 'agent-session', { + id, + entityId: sessionId, + agentSessionAgent: 'codex', + label: 'Codex Chat', + ...(executionHostId ? { executionHostId } : {}) + }) +} + +// Real tab actions annotate their writes, so these reach the bridge's addressed reconciliation. +describe('StructuredAgentSessionStatusBridge with tab actions', () => { + beforeEach(() => { + vi.clearAllMocks() + resetStructuredAgentSessionStatusFeedsForTests() + mocks.subscribeStatus.mockResolvedValue({ unsubscribe: mocks.unsubscribe }) + mocks.supportsCapability.mockResolvedValue(true) + mocks.store?.setState({ + agentStatusByPaneKey: {}, + structuredChatSleptAtByPaneKey: {}, + structuredSessionLaunchDirectoryByTabId: {}, + unifiedTabsByWorktree: {}, + groupsByWorktree: {}, + activeGroupIdByWorktree: {}, + layoutByWorktree: {} + }) + }) + + afterEach(() => { + cleanup() + resetStructuredAgentSessionStatusFeedsForTests() + }) + + it('removes a closed chat status and keeps an unrelated tab write quiet', async () => { + render() + act(() => openChat('chat-1', 'session-1', LOCAL_EXECUTION_HOST_ID)) + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledOnce()) + act(() => + feed().emit({ type: 'snapshot', sessions: [summary({ status: 'working', updatedAt: 5 })] }) + ) + expect(statusFor('chat-1', 'session-1')).toEqual( + expect.objectContaining({ state: 'working', updatedAt: 5 }) + ) + + act(() => useAppStore.getState().setTabLabel('chat-1', 'Renamed')) + expect(statusFor('chat-1', 'session-1')).toEqual( + expect.objectContaining({ state: 'working', terminalTitle: 'Renamed' }) + ) + + act(() => useAppStore.getState().closeUnifiedTab('chat-1')) + expect(statusFor('chat-1', 'session-1')).toBeUndefined() + }) + + it('retires the old pane when a tab is rebound to another session and ignores its late tick', async () => { + render() + act(() => openChat('chat-1', 'session-1', LOCAL_EXECUTION_HOST_ID)) + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledOnce()) + act(() => feed().emit({ type: 'snapshot', sessions: [summary()] })) + expect(statusFor('chat-1', 'session-1')).toBeDefined() + + act(() => { + useAppStore.getState().closeUnifiedTab('chat-1') + openChat('chat-1', 'session-2', LOCAL_EXECUTION_HOST_ID) + }) + // The last chat's close released the host feed, so the rebound chat subscribes afresh. + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledTimes(2)) + act(() => + feed(-1).emit({ + type: 'snapshot', + sessions: [summary({ sessionId: 'session-2', status: 'working', updatedAt: 9 })] + }) + ) + act(() => + feed(-1).emit({ type: 'status', session: summary({ status: 'working', updatedAt: 10 }) }) + ) + expect(statusFor('chat-1', 'session-1')).toBeUndefined() + expect(statusFor('chat-1', 'session-2')).toEqual( + expect.objectContaining({ state: 'working', updatedAt: 9 }) + ) + }) + + it('rebinds an unstamped chat to its new owner host without changing membership', async () => { + useAppStore.setState({ + unifiedTabsByWorktree: { + 'wt-1': [ + { + id: 'chat-1', + worktreeId: 'wt-1', + groupId: 'group-1', + contentType: 'agent-session', + entityId: 'session-1', + label: 'Codex Chat', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0, + isPinned: false, + agentSessionAgent: 'codex' + } satisfies Tab + ] + } + }) + render() + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledOnce()) + act(() => feed().emit({ type: 'snapshot', sessions: [summary({ updatedAt: 2 })] })) + act(() => + useAppStore.setState({ + worktreesByRepo: { + repo: [ + makeWorktree({ + id: 'wt-1', + repoId: 'repo', + hostId: 'runtime:env-1', + runtimeOwnerEnvironmentId: 'env-1' + }) + ] + } + }) + ) + await waitFor(() => expect(mocks.subscribeStatus).toHaveBeenCalledTimes(2)) + expect(feed(1).target).toEqual({ kind: 'environment', environmentId: 'env-1' }) + act(() => feed(1).emit({ type: 'snapshot', sessions: [summary({ updatedAt: 20 })] })) + act(() => feed().emit({ type: 'status', session: summary({ updatedAt: 30 }) })) + expect(Object.keys(useAppStore.getState().agentStatusByPaneKey)).toEqual([ + structuredAgentSessionPaneKey('chat-1', 'session-1') + ]) + expect(statusFor('chat-1', 'session-1')?.updatedAt).toBe(20) + }) +}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-membership.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-membership.ts new file mode 100644 index 00000000000..abe86d9f200 --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-status-membership.ts @@ -0,0 +1,199 @@ +import type { AgentSessionStatusSummary } from '../../../../../../shared/agent-session/agent-session-wire' +import type { StructuredAgentSessionStatusFeedOwner } from '@/runtime/native-chat/status/structured-agent-session-status-feed' +import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' +import type { StructuredTab } from './structured-agent-session-tabs' + +export type HostGroup = { + members: Set + /** A host tick names its sessions; this finds their tabs without walking every member. */ + membersBySession: Map> + /** Captured but not yet projected (a throwing commit); retried on this host's next tick. */ + owed: Set + feed: StructuredAgentSessionStatusFeedOwner + unsubscribe: () => void + release?: () => void +} +export type ProjectionInput = { + tab: StructuredTab + member: Member + summary: AgentSessionStatusSummary | null + observation: 'live' | 'unverifiable' + failedAt: number | null + sleptAt: number | null | undefined + directory: string | undefined +} +export type Member = { + paneKey: string + tab: StructuredTab + hostKey: string | null + group: HostGroup | null + status?: ProjectionInput + captured?: ProjectionInput +} + +/** The tab fields a status projection reads; focus, preview and order metadata never change it. */ +export function sameSemanticTab(previous: StructuredTab, next: StructuredTab): boolean { + return ( + previous === next || + (previous.id === next.id && + previous.entityId === next.entityId && + previous.worktreeId === next.worktreeId && + previous.label === next.label && + previous.agentSessionAgent === next.agentSessionAgent && + previous.createdAt === next.createdAt && + previous.executionHostId === next.executionHostId) + ) +} + +/** Which chat tabs the status bridge projects, updated per changed tab rather than rebuilt. */ +export function createStructuredSessionMembership() { + const members = new Map() + /** Every member per tab; a tab rebound to another session briefly has two until the old retires. */ + const membersByTabId = new Map>() + const indexTab = (member: Member): void => { + const tabMembers = membersByTabId.get(member.tab.id) + if (tabMembers) { + tabMembers.add(member) + } else { + membersByTabId.set(member.tab.id, new Set([member])) + } + } + /** Unstamped tabs resolve their host from workspace owner inputs; stamped tabs never do. */ + const legacy = new Set() + /** Projection debt of members no host feed owns (SSH, unresolved); grouped debt lives on the group. */ + const ungroupedOwed = new Set() + const owe = (member: Member): void => { + if (member.group) { + member.group.owed.add(member) + } else { + ungroupedOwed.add(member) + } + } + const settle = (member: Member): void => { + member.group?.owed.delete(member) + ungroupedOwed.delete(member) + } + const withDebt = (selected: Iterable, groups: Iterable): Set => { + const result = new Set([...selected, ...ungroupedOwed]) + for (const group of groups) { + group.owed.forEach((member) => result.add(member)) + } + return result + } + const hasDebt = (groups: Iterable): boolean => + ungroupedOwed.size > 0 || [...groups].some((group) => group.owed.size > 0) + + const attach = (member: Member): void => { + members.set(member.paneKey, member) + indexTab(member) + const group = member.group + if (group) { + group.members.add(member) + const sessionMembers = group.membersBySession.get(member.tab.entityId) + if (sessionMembers) { + sessionMembers.add(member) + } else { + group.membersBySession.set(member.tab.entityId, new Set([member])) + } + } + } + const detach = (member: Member): void => { + if (members.get(member.paneKey) === member) { + members.delete(member.paneKey) + } + const tabMembers = membersByTabId.get(member.tab.id) + tabMembers?.delete(member) + if (tabMembers && !tabMembers.size) { + membersByTabId.delete(member.tab.id) + } + legacy.delete(member) + ungroupedOwed.delete(member) + const group = member.group + if (group) { + group.members.delete(member) + group.owed.delete(member) + const sessionMembers = group.membersBySession.get(member.tab.entityId) + sessionMembers?.delete(member) + if (sessionMembers && !sessionMembers.size) { + group.membersBySession.delete(member.tab.entityId) + } + } + } + /** Same host keeps the member, null when nothing it projects changed; a new host rebinds the pane. */ + const place = ( + tab: StructuredTab, + paneKey: string, + hostKey: string | null, + group: HostGroup | null + ): Member | null => { + const old = members.get(paneKey) + let member: Member + let semanticChange = true + if (old?.group === group) { + if (old.tab === tab) { + return null + } + semanticChange = !sameSemanticTab(old.tab, tab) + member = old + } else { + if (old) { + detach(old) + } + member = { paneKey, tab, hostKey, group } + attach(member) + } + member.tab = tab + if (tab.executionHostId) { + legacy.delete(member) + } else { + legacy.add(member) + } + if (!semanticChange) { + return null + } + // Owed from attach or change on, so a pass that throws before capturing still retries it. + owe(member) + return member + } + /** Places listed tabs that changed and returns members no longer listed: all of them, or within `tabIds`. */ + const reconcileTabs = ( + listedTabs: Iterable, + tabIds: ReadonlySet | null, + placeTab: (tab: StructuredTab, paneKey: string) => void + ): Member[] => { + const listed = new Set() + for (const tab of listedTabs) { + if (tabIds && !tabIds.has(tab.id)) { + continue + } + const paneKey = structuredAgentSessionPaneKey(tab.id, tab.entityId) + listed.add(paneKey) + if (members.get(paneKey)?.tab !== tab) { + placeTab(tab, paneKey) + } + } + const candidates = tabIds + ? [...tabIds].flatMap((tabId) => [...(membersByTabId.get(tabId) ?? [])]) + : members.values() + return [...candidates].filter((member) => !listed.has(member.paneKey)) + } + const clear = (): void => { + members.clear() + membersByTabId.clear() + legacy.clear() + ungroupedOwed.clear() + } + return { + members, + membersByTabId, + legacy, + owe, + settle, + withDebt, + hasDebt, + place, + detach, + reconcileTabs, + clear + } +} diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tab-owner-cache.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tab-owner-cache.ts index c6c4349c881..fd63dc30e83 100644 --- a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tab-owner-cache.ts +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tab-owner-cache.ts @@ -1,7 +1,7 @@ import type { ExecutionHostId } from '../../../../../../shared/execution-host' import type { AppState } from '@/store/types' import type { WorktreeRuntimeOwnerState } from '@/lib/workspace/ownership/worktree-runtime-owner-state' -import { worktreeOwnerRowsTokenOf } from '@/lib/worktree-owner-rows-token' +import { worktreeOwnerRowsTokenOf } from '@/lib/workspace/ownership/worktree-owner-rows-token' import { selectWorktreesByRepo } from '@/store/workspaces/catalog/workspace-record-fields' import { structuredAgentSessionOwnerForTab } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' import type { StructuredTab } from './structured-agent-session-tabs' diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts new file mode 100644 index 00000000000..c4ffc2bb913 --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs-hydration-order.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest' +import type { Tab } from '../../../../../../shared/tab-types' +import type { WorkspaceSessionState } from '../../../../../../shared/workspace-session/workspace-session-state-types' +import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope' +import { createTestStore } from '@/store/testing/app-store-test-fixture' +import { getStructuredAgentSessionTabs } from './structured-agent-session-tabs' + +function chat(id: string, worktreeId: string): Tab { + return { + id, + entityId: 'session-shared', + groupId: `group-${worktreeId}`, + worktreeId, + contentType: 'agent-session', + agentSessionAgent: 'codex', + label: id, + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0 + } +} + +function session(worktreeIds: readonly string[]): WorkspaceSessionState { + const entries = (value: (worktreeId: string) => V): Record => + Object.fromEntries(worktreeIds.map((worktreeId) => [worktreeId, value(worktreeId)])) + return { + activeRepoId: null, + activeWorktreeId: null, + activeTabId: null, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + unifiedTabs: entries((worktreeId) => [chat(`chat-${worktreeId}`, worktreeId)]), + tabGroups: entries((worktreeId) => [ + { + id: `group-${worktreeId}`, + worktreeId, + activeTabId: `chat-${worktreeId}`, + tabOrder: [`chat-${worktreeId}`], + recentTabIds: [`chat-${worktreeId}`] + } + ]), + activeGroupIdByWorktree: entries((worktreeId) => `group-${worktreeId}`) + } +} + +const ids = (tabs: readonly Tab[]) => tabs.map((tab) => tab.id) +// Folder workspace keys are real tab-map keys and valid hydration workspace keys. +const EARLY = folderWorkspaceKey('early') +const LATER = folderWorkspaceKey('later') + +// Scoped hydration rebuilds the workspaces it names; the warm chat list must match a cold read. +describe('chat-tab list after scoped session hydration', () => { + it('follows the hydrated source order for the shared session first match', () => { + const store = createTestStore() + const keys = [EARLY, LATER] + store.getState().hydrateTabsSession(session(keys), { additionalValidWorkspaceKeys: keys }) + expect(ids(getStructuredAgentSessionTabs(store.getState().unifiedTabsByWorktree))).toEqual([ + `chat-${EARLY}`, + `chat-${LATER}` + ]) + + store.getState().hydrateTabsSession(session([EARLY]), { + additionalValidWorkspaceKeys: keys, + replaceWorkspaceKeys: [EARLY] + }) + const source = store.getState().unifiedTabsByWorktree + expect(Object.keys(source)).toEqual([LATER, EARLY]) + const warm = getStructuredAgentSessionTabs(source) + expect(ids(warm)).toEqual([`chat-${LATER}`, `chat-${EARLY}`]) + expect(ids(getStructuredAgentSessionTabs({ ...source }))).toEqual(ids(warm)) + expect(warm.find((tab) => tab.entityId === 'session-shared')?.worktreeId).toBe(LATER) + }) + + it('takes hydrated record order over the selection order', () => { + const store = createTestStore() + const keys = [EARLY, LATER] + store.getState().hydrateTabsSession(session([LATER, EARLY]), { + additionalValidWorkspaceKeys: keys + }) + expect(ids(getStructuredAgentSessionTabs(store.getState().unifiedTabsByWorktree))).toEqual([ + `chat-${LATER}`, + `chat-${EARLY}` + ]) + + store.getState().hydrateTabsSession(session([EARLY, LATER]), { + additionalValidWorkspaceKeys: keys, + replaceWorkspaceKeys: [LATER, EARLY] + }) + const source = store.getState().unifiedTabsByWorktree + expect(Object.keys(source)).toEqual([EARLY, LATER]) + const warm = getStructuredAgentSessionTabs(source) + expect(ids(warm)).toEqual([`chat-${EARLY}`, `chat-${LATER}`]) + expect(ids(getStructuredAgentSessionTabs({ ...source }))).toEqual(ids(warm)) + }) +}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts new file mode 100644 index 00000000000..4eb18bec2be --- /dev/null +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import type { Tab } from '../../../../../../shared/tab-types' +import { replaceTabBuckets } from '@/store/keyed-record-transitions' +import { getStructuredAgentSessionTabs } from './structured-agent-session-tabs' + +function tab(id: string, worktreeId: string, contentType: Tab['contentType']): Tab { + return { + id, + worktreeId, + groupId: 'group', + contentType, + entityId: contentType === 'agent-session' ? 'session-shared' : id, + label: id, + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 0, + isPinned: false, + ...(contentType === 'agent-session' ? { agentSessionAgent: 'codex' as const } : {}) + } +} + +const ids = (map: Record) => getStructuredAgentSessionTabs(map).map((t) => t.id) + +describe('getStructuredAgentSessionTabs order', () => { + it('keeps source workspace order through addressed close and reopen', () => { + const start = { + early: [tab('t1', 'early', 'terminal'), tab('c1', 'early', 'agent-session')], + later: [tab('c2', 'later', 'agent-session')] + } + expect(ids(start)).toEqual(['c1', 'c2']) + const closed = replaceTabBuckets(start, [['early', [start.early[0]]]]) + expect(ids(closed)).toEqual(['c2']) + const reopened = replaceTabBuckets(closed, [ + ['early', [start.early[0], tab('c1b', 'early', 'agent-session')]] + ]) + expect(ids(reopened)).toEqual(['c1b', 'c2']) + expect(ids({ ...reopened })).toEqual(['c1b', 'c2']) + }) + + it('follows source order when a workspace is deleted and added back', () => { + const start = { + early: [tab('c1', 'early', 'agent-session')], + later: [tab('c2', 'later', 'agent-session')] + } + expect(ids(start)).toEqual(['c1', 'c2']) + const removed = replaceTabBuckets(start, [['early', null]]) + const restored = replaceTabBuckets(removed, [['early', start.early]]) + expect(ids(restored)).toEqual(['c2', 'c1']) + expect(ids({ ...restored })).toEqual(['c2', 'c1']) + }) + + it('keeps the list through chatless workspace changes and places new workspaces last', () => { + const start = { a: [tab('c1', 'a', 'agent-session')] } + const list = getStructuredAgentSessionTabs(start) + const added = replaceTabBuckets(start, [['b', [tab('t1', 'b', 'terminal')]]]) + expect(getStructuredAgentSessionTabs(added)).toBe(list) + const chat = replaceTabBuckets(added, [ + ['b', [tab('t1', 'b', 'terminal'), tab('cb', 'b', 'agent-session')]] + ]) + expect(ids(chat)).toEqual(['c1', 'cb']) + const removed = replaceTabBuckets(chat, [['a', null]]) + expect(ids(removed)).toEqual(['cb']) + expect(ids({ ...removed })).toEqual(['cb']) + }) +}) diff --git a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts index ab6c1273c59..c59c783c480 100644 --- a/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts +++ b/src/renderer/src/components/native-chat/session/status/structured-agent-session-tabs.ts @@ -1,49 +1,207 @@ import { structuredAgentSessionPaneKey } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' import { isStructuredTab } from '../../../../../../shared/agent-session/view/structured-agent-session-tab' import type { Tab } from '../../../../../../shared/tab-types' +import { readTabMapChanges } from '@/store/keyed-record-change-reads' export type StructuredTab = Tab & { contentType: 'agent-session' } -const structuredTabsByUnifiedTabsSnapshot = new WeakMap< - Record, - readonly StructuredTab[] ->() +type TabsByWorktree = Record -/** Project structured-session tabs once per immutable tab-map snapshot. */ -export function getStructuredAgentSessionTabs( - unifiedTabsByWorktree: Record +const NO_TABS: readonly StructuredTab[] = Object.freeze([]) +const structuredTabsByBucket = new WeakMap() +const listsBySnapshot = new WeakMap() +const INDEX_KEY = /^(?:0|[1-9]\d*)$/ + +/** + * The latest source's chat subsets, kept only for chat-bearing workspaces, plus each source + * workspace's rank. Ranks change only when a workspace is added or deleted, so a focus, label or + * title write costs O(that workspace) and the list keeps source order. + */ +type Lineage = { + source: TabsByWorktree + rank: Map + nextRank: number + chats: Map + /** Chat-bearing workspaces in rank order; changes only when one gains its first or loses its last chat. */ + order: string[] | null + list: readonly StructuredTab[] | null + /** The last materialized list, reused when a rebuild yields the same chats. */ + stale: readonly StructuredTab[] | null +} +let lineage: Lineage | null = null + +function sameTabs(previous: readonly StructuredTab[], next: readonly StructuredTab[]): boolean { + return previous.length === next.length && previous.every((tab, index) => tab === next[index]) +} + +// A terminal title or focus write replaces its bucket; keep the chat subset when no chat changed. +function structuredTabsOf( + bucket: readonly Tab[], + previous: readonly StructuredTab[] | undefined ): readonly StructuredTab[] { - const cached = structuredTabsByUnifiedTabsSnapshot.get(unifiedTabsByWorktree) + const cached = structuredTabsByBucket.get(bucket) if (cached) { return cached } - - const tabs: StructuredTab[] = [] - for (const worktreeTabs of Object.values(unifiedTabsByWorktree)) { - for (const tab of worktreeTabs) { - if (isStructuredTab(tab)) { - tabs.push(tab) - } - } - } - structuredTabsByUnifiedTabsSnapshot.set(unifiedTabsByWorktree, tabs) - return tabs + const tabs = bucket.filter(isStructuredTab) + const result = !tabs.length ? NO_TABS : previous && sameTabs(previous, tabs) ? previous : tabs + structuredTabsByBucket.set(bucket, result) + return result } -const paneTabs = new WeakMap, ReadonlyMap>() +function rankOf(target: Lineage, worktreeId: string): number { + return target.rank.get(worktreeId) ?? 0 +} + +// Insert or drop one workspace in the cached order: O(log K) to find, one splice to place. +function placeInOrder(target: Lineage, worktreeId: string, present: boolean): void { + const order = target.order + if (!order) { + return + } + const rank = rankOf(target, worktreeId) + let low = 0 + let high = order.length + while (low < high) { + const middle = (low + high) >> 1 + if (rankOf(target, order[middle]) < rank) { + low = middle + 1 + } else { + high = middle + } + } + if (present) { + order.splice(low, 0, worktreeId) + } else if (order[low] === worktreeId) { + order.splice(low, 1) + } else { + target.order = null + } +} + +function setChats(target: Lineage, worktreeId: string, tabs: readonly StructuredTab[]): void { + const before = target.chats.get(worktreeId) ?? NO_TABS + if (tabs === before) { + return + } + if (!before.length !== !tabs.length) { + placeInOrder(target, worktreeId, tabs.length > 0) + } + if (tabs.length) { + target.chats.set(worktreeId, tabs) + } else { + target.chats.delete(worktreeId) + } + target.stale = target.list ?? target.stale + target.list = null +} + +// Cold path: bootstrap, hydration, an unannotated or reordering replacement; the only whole-map walk. +function rebuildFromSnapshot(source: TabsByWorktree, previous: Lineage | null): Lineage { + const rebuilt: Lineage = { + source, + rank: new Map(), + nextRank: 0, + chats: new Map(), + order: null, + list: null, + stale: previous?.list ?? previous?.stale ?? null + } + for (const worktreeId of Object.keys(source)) { + rebuilt.rank.set(worktreeId, rebuilt.nextRank++) + const tabs = structuredTabsOf(source[worktreeId] ?? [], previous?.chats.get(worktreeId)) + if (tabs.length) { + rebuilt.chats.set(worktreeId, tabs) + } + } + return rebuilt +} + +/** False when the change can't be placed by ranks alone (an index-like workspace key). */ +function applyAddressed( + target: Lineage, + source: TabsByWorktree, + changes: Extract, { kind: 'addressed' }> +): boolean { + if (changes.addedWorkspaceIds.some((worktreeId) => INDEX_KEY.test(worktreeId))) { + return false + } + for (const worktreeId of changes.addedWorkspaceIds) { + target.rank.set(worktreeId, target.nextRank++) + } + for (const worktreeId of changes.workspaceIds) { + const bucket = Object.hasOwn(source, worktreeId) ? source[worktreeId] : undefined + setChats( + target, + worktreeId, + bucket ? structuredTabsOf(bucket, target.chats.get(worktreeId)) : NO_TABS + ) + } + // Ranks of deleted workspaces go after their chats leave the cached order. + for (const worktreeId of changes.deletedWorkspaceIds) { + target.rank.delete(worktreeId) + } + target.source = source + return true +} + +function advance(source: TabsByWorktree): Lineage { + if (lineage?.source === source) { + return lineage + } + const changes = lineage ? readTabMapChanges(source, lineage.source) : null + if (!(lineage && changes?.kind === 'addressed' && applyAddressed(lineage, source, changes))) { + lineage = rebuildFromSnapshot(source, lineage) + } + return lineage +} + +function materialize(current: Lineage): readonly StructuredTab[] { + if (!current.list) { + // Sorted only after a full resync; ordinary chat edits reuse the cached order. + current.order ??= [...current.chats.keys()].sort( + (a, b) => rankOf(current, a) - rankOf(current, b) + ) + const built = current.order.flatMap((worktreeId) => current.chats.get(worktreeId) ?? NO_TABS) + current.list = current.stale && sameTabs(current.stale, built) ? current.stale : built + current.stale = null + } + return current.list +} + +/** Structured-session tabs; the same list while no chat tab changed, so non-chat tab writes stay quiet. */ +export function getStructuredAgentSessionTabs( + unifiedTabsByWorktree: TabsByWorktree +): readonly StructuredTab[] { + const cached = listsBySnapshot.get(unifiedTabsByWorktree) + if (cached) { + return cached + } + const list = materialize(advance(unifiedTabsByWorktree)) + listsBySnapshot.set(unifiedTabsByWorktree, list) + return list +} + +const paneTabs = new WeakMap>() export function getStructuredAgentSessionTabsByPaneKey( - tabs: Record + tabs: TabsByWorktree ): ReadonlyMap { - const cached = paneTabs.get(tabs) + const structuredTabs = getStructuredAgentSessionTabs(tabs) + const cached = paneTabs.get(structuredTabs) if (cached) { return cached } const result = new Map( - getStructuredAgentSessionTabs(tabs).map((tab) => [ - structuredAgentSessionPaneKey(tab.id, tab.entityId), - tab - ]) + structuredTabs.map((tab) => [structuredAgentSessionPaneKey(tab.id, tab.entityId), tab]) ) - paneTabs.set(tabs, result) + paneTabs.set(structuredTabs, result) return result } + +/** One workspace's structured tabs, from the same addressed projection. */ +export function getStructuredAgentSessionTabsInWorkspace( + unifiedTabsByWorktree: TabsByWorktree, + worktreeId: string +): readonly StructuredTab[] { + return advance(unifiedTabsByWorktree).chats.get(worktreeId) ?? NO_TABS +} diff --git a/src/renderer/src/components/native-chat/session/terminal/send/use-native-chat-send-lifecycle.test.tsx b/src/renderer/src/components/native-chat/session/terminal/send/use-native-chat-send-lifecycle.test.tsx deleted file mode 100644 index 5b0eaee8290..00000000000 --- a/src/renderer/src/components/native-chat/session/terminal/send/use-native-chat-send-lifecycle.test.tsx +++ /dev/null @@ -1,62 +0,0 @@ -// @vitest-environment happy-dom - -import { act, renderHook } from '@testing-library/react' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { useNativeChatSendLifecycle } from './use-native-chat-send-lifecycle' - -function handle(settleAfterMs = 500) { - return { cancel: vi.fn<() => void>(), settleAfterMs } -} - -describe('useNativeChatSendLifecycle', () => { - afterEach(() => { - vi.useRealTimers() - }) - - it('cancels owned writes when the PTY target changes and when the composer unmounts', () => { - vi.useFakeTimers() - const first = handle() - const second = handle() - const onPendingSendCanceled = vi.fn() - const { result, rerender, unmount } = renderHook( - ({ targetPtyId }) => useNativeChatSendLifecycle('tab-1', targetPtyId, onPendingSendCanceled), - { initialProps: { targetPtyId: 'pty-1' as string | null } } - ) - - act(() => result.current.trackPendingSend(first, 'pending-1')) - rerender({ targetPtyId: 'pty-2' }) - expect(first.cancel).toHaveBeenCalledOnce() - expect(onPendingSendCanceled).toHaveBeenCalledWith('pending-1') - - act(() => result.current.trackPendingSend(second, 'pending-2')) - unmount() - expect(second.cancel).toHaveBeenCalledOnce() - expect(onPendingSendCanceled).toHaveBeenCalledWith('pending-2') - }) - - it('keeps a renderer-stalled send cancelable past its nominal schedule', async () => { - vi.useFakeTimers() - let resolveSettled!: () => void - const stalled = { - ...handle(640), - settled: new Promise((resolve) => { - resolveSettled = resolve - }) - } - const onPendingSendCanceled = vi.fn() - const { result, rerender } = renderHook( - ({ targetPtyId }) => useNativeChatSendLifecycle('tab-1', targetPtyId, onPendingSendCanceled), - { initialProps: { targetPtyId: 'pty-1' as string | null } } - ) - - act(() => result.current.trackPendingSend(stalled, 'pending-1')) - act(() => vi.advanceTimersByTime(stalled.settleAfterMs + 1_000)) - rerender({ targetPtyId: 'pty-2' }) - - expect(stalled.cancel).toHaveBeenCalledOnce() - expect(onPendingSendCanceled).toHaveBeenCalledWith('pending-1') - await act(async () => { - resolveSettled() - }) - }) -}) diff --git a/src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx b/src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx index e707460e927..78427ceae40 100644 --- a/src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx +++ b/src/renderer/src/components/native-chat/subagents/NativeChatMessageList.subagent-sections.test.tsx @@ -22,11 +22,6 @@ vi.mock('../media/visuals/NativeChatInlineVisual', () => ({ vi.mock('@/lib/open-agent-message-sender', () => ({ openAgentMessageSender: unusedChatLeaves.openSender })) -afterEach(() => { - expect(unusedChatLeaves.inlineVisual).not.toHaveBeenCalled() - expect(unusedChatLeaves.openSender).not.toHaveBeenCalled() -}) - import type { AgentJournalItemBody, AgentJournalProducerLinkage, @@ -132,60 +127,6 @@ import { session, stubLayout } from '../viewport/virtualization/native-chat-wind vi.restoreAllMocks() }) - it("draws an open agent's rows between its entry and the next one", () => { - const agents = [ - { id: 'task-a', label: 'lane a', state: 'completed' as const }, - { id: 'task-b', label: 'lane b', state: 'completed' as const }, - { id: 'task-c', label: 'lane c', state: 'completed' as const } - ] - const items = [ - itemsWith('completed', false)[0]!, - journalItem( - 'spawn', - { - kind: 'message', - role: 'system', - blocks: [{ type: 'subagent-group', groupId: 'group-1', agents }] - }, - 2 - ), - ...agents.map(({ id, label }, index) => - journalItem( - `${id}-said`, - { - kind: 'message', - role: 'assistant', - blocks: [{ type: 'text', text: `Read ${label}.` }] - }, - 3 + index, - { agentId: id, producerKind: 'agent' } - ) - ) - ] - render( - - ) - fireEvent.click(screen.getByRole('button', { name: /Ran 3 subagents/ })) - fireEvent.click(screen.getByRole('button', { name: /lane b/ })) - - const order = [ - screen.getByRole('button', { name: /lane a/, expanded: false }), - screen.getByRole('button', { name: /lane b/, expanded: true }), - screen.getByText('Read lane b.'), - screen.getByRole('button', { name: /lane c/, expanded: false }) - ] - for (const [index, node] of order.slice(1).entries()) { - expect(order[index]!.compareDocumentPosition(node)).toBe(Node.DOCUMENT_POSITION_FOLLOWING) - } - expect(screen.queryByText('Read lane a.')).toBeNull() - expect(screen.getAllByText(/^lane [abc]$/)).toHaveLength(3) - }) - // Journal turn records own subagent edits, even when a newer send is queued or the opener is unloaded. it("counts a subagent's edit in the turn the journal says it was made in", () => { const say = (itemId: string, role: 'user' | 'assistant', text: string, sequence: number) => @@ -275,16 +216,6 @@ import { session, stubLayout } from '../viewport/virtualization/native-chat-wind expect(screen.getByText('The PR is CLEAN.')).toBeInTheDocument() }) - it('opens a working subagent while the session waits on it, and closes it once the parent moves on', () => { - const { rerender } = render(listOf('working', true)) - expect(screen.getByText('The PR is CLEAN.')).toBeInTheDocument() - expect(screen.getByRole('button', { name: /explore the lane/, expanded: true })).toBeVisible() - expect(screen.getAllByText('explore the lane')).toHaveLength(1) - rerender(listOf('working')) - expect(screen.queryByText('The PR is CLEAN.')).toBeNull() - expect(screen.getByRole('button', { name: /Kicked off 1 subagent/ })).toBeInTheDocument() - }) - it("keeps the reader's choice over the frontier, in either direction", () => { const { rerender } = render(listOf('working', true)) fireEvent.click(screen.getByRole('button', { name: /explore the lane/, expanded: true })) diff --git a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-work-runs.test.ts b/src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-work-runs.test.ts deleted file mode 100644 index 217105afe20..00000000000 --- a/src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-work-runs.test.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - NativeChatMessage, - NativeChatSubagentState -} from '../../../../../shared/native-chat/native-chat-types' -import { projectNativeChatTranscript } from '../../../../../shared/native-chat/transcript/native-chat-transcript-projection' -import { nativeChatTurnMembership } from '../../../../../shared/native-chat/transcript/native-chat-turn-membership' -import { compareNativeChatDisplayMessages as compareMessages } from '../../../../../shared/native-chat/transcript/native-chat-message-order' -import { nativeChatSubagentSections } from './native-chat-subagent-sections' -import { - buildNativeChatTranscriptSlots, - type NativeChatTranscriptSlot -} from '../conversation/slots/native-chat-transcript-slots' - -let sequence = 0 - -function row( - id: string, - blocks: NativeChatMessage['blocks'], - overrides: Partial = {} -): NativeChatMessage { - sequence += 1 - return { - id, - role: 'assistant', - blocks, - timestamp: 1, - source: 'transcript', - journalPosition: { sequence, index: 0 }, - ...overrides - } -} - -const say = (value: string) => [{ type: 'text' as const, text: value }] -const call = (name: string) => [{ type: 'tool-call' as const, name, input: { name } }] -const by = (agentId: string) => ({ agentId, producerKind: 'agent' as const }) -const thought = (id: string, agentId?: string, state: 'running' | 'completed' = 'completed') => - row(id, say(`thinking ${id}`), { - role: 'reasoning', - state, - ...(agentId ? by(agentId) : {}) - }) -const roster = (id: string, agentId: string, state: NativeChatSubagentState) => - row( - id, - [ - { - type: 'subagent-group', - groupId: `group-${id}`, - agents: [{ id: agentId, label: agentId, state }] - } - ], - { role: 'system' } - ) - -function slotsOf(rows: NativeChatMessage[], open: Record) { - const { conversation, subagentRows } = projectNativeChatTranscript(rows, compareMessages) - const { turnKeys, liveTurnKey } = nativeChatTurnMembership(conversation) - return buildNativeChatTranscriptSlots({ - messages: conversation, - turnKeys, - liveTurnKey, - receipts: new Map(), - turnStatuses: { active: null, completedByTurn: {} }, - turnDiffs: new Map(), - expandedTurnKeys: new Set(), - isWorking: false, - lifecycleWorking: false, - subagentSections: nativeChatSubagentSections(conversation, subagentRows), - subagentChoices: { sections: new Map(Object.entries(open)), rosters: new Map() } - }) -} - -/** `>` per section a row sits in, then its id, its run's member ids, or `[agent]` for a head. */ -function outline(slots: readonly NativeChatTranscriptSlot[]): string[] { - return slots.map((slot) => { - const indent = '>'.repeat(slot.depth) - if (slot.kind === 'subagent') { - return `${indent}[${slot.agentId}]` - } - if (slot.kind === 'subagent-entries') { - return `${indent}${slot.agents.map((agent) => agent.id).join()}` - } - return `${indent}${slot.workRun?.map((member) => member.id).join('+') ?? slot.message.id}` - }) -} - -describe('work runs and subagent sections', () => { - it('never runs across a section head', () => { - const rows = [ - row('ask', say('go'), { role: 'user' }), - row('a', call('Read')), - row('s-a', call('Bash'), by('helper')), - thought('r1'), - row('c', call('Grep')) - ] - expect(outline(slotsOf(rows, { helper: false }))).toEqual(['ask', 'a', '[helper]', 'r1+c']) - expect(outline(slotsOf(rows, { helper: true }))).toEqual([ - 'ask', - 'a', - '[helper]', - '>s-a', - 'r1+c' - ]) - }) - - it("keeps a working section's open thought out of its run until it ends", () => { - const rows = (state: NativeChatSubagentState, last: 'running' | 'completed') => { - sequence = 0 - return [ - row('ask', say('go'), { role: 'user' }), - roster('spawn', 'helper', state), - thought('s-r1', 'helper'), - row('s-a', call('Read'), by('helper')), - thought('s-r2', 'helper', last) - ] - } - expect(outline(slotsOf(rows('working', 'running'), { helper: true }))).toEqual([ - 'ask', - 'spawn', - '>s-r1+s-a', - '>s-r2' - ]) - expect(outline(slotsOf(rows('working', 'completed'), { helper: true }))).toEqual([ - 'ask', - 'spawn', - '>s-r1+s-a+s-r2' - ]) - // A thought its finished agent never closed is not still being thought. - expect(outline(slotsOf(rows('completed', 'running'), { helper: true }))).toEqual([ - 'ask', - 'spawn', - '>s-r1+s-a+s-r2' - ]) - }) -}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx deleted file mode 100644 index f5769543dcb..00000000000 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx +++ /dev/null @@ -1,163 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import type { NativeChatLiveSession } from '../../session/terminal/read/native-chat-live-session-contract' -import type { NativeChatComposerProps } from '../../composer/native-chat-composer-types' -import type { AgentStatusPayload } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import type * as StreamingModule from '../../../../../../shared/native-chat/native-chat-streaming' -import { clearPendingSendCacheForTests } from '../../session/terminal/delivery/native-chat-pending' - -const probe = vi.hoisted<{ - session: NativeChatLiveSession | null - inputs: (readonly NativeChatMessage[])[] - shown: NativeChatMessage[] -}>(() => ({ session: null, inputs: [], shown: [] })) -vi.mock('../../session/terminal/read/use-native-chat-retained-session', () => ({ - useNativeChatRetainedSession: () => probe.session -})) -vi.mock('../../NativeChatMessageList', () => ({ - NativeChatMessageList: ({ session }: { session: NativeChatLiveSession }) => { - probe.shown = session.messages - return null - } -})) -vi.mock('../../composer/NativeChatComposer', () => ({ - NativeChatComposer: ({ onOptimisticSend }: NativeChatComposerProps) => ( - - ) -})) -vi.mock('../../../../../../shared/native-chat/native-chat-streaming', async (importOriginal) => { - const original = await importOriginal() - return { - ...original, - deriveNativeChatStreamingText: ( - args: Parameters[0] - ) => { - probe.inputs.push(args.messages) - return original.deriveNativeChatStreamingText(args) - } - } -}) - -const { NativeChatResolvedView } = await import('../../NativeChatResolvedView') -const { TooltipProvider } = await import('@/components/ui/tooltip') -const { useAppStore } = await import('../../../../store/index') -const paneKey = 'preview-perf:leaf' -const message = (id: string, role: 'user' | 'assistant', text: string): NativeChatMessage => ({ - id, - role, - blocks: [{ type: 'text', text }], - timestamp: 1, - source: 'transcript' -}) - -function setPreview(text: string, extra: Partial = {}): void { - useAppStore.getState().setAgentStatus(paneKey, { - prompt: 'Prompt', - agentType: 'claude', - state: 'working', - lastAssistantMessage: text, - ...extra - }) -} - -function previewTicks(expected: readonly NativeChatMessage[], extra = {}): void { - probe.inputs = [] - for (let tick = 0; tick < 20; tick += 1) { - act(() => setPreview(`Current reply ${tick}`, extra)) - } - expect(probe.inputs.length).toBeGreaterThanOrEqual(20) - expect(new Set(probe.inputs).size).toBe(1) - expect(probe.inputs[0]).toBe(expected) -} - -beforeEach(() => { - vi.useFakeTimers({ toFake: ['Date'] }) - vi.setSystemTime(1_000) - clearPendingSendCacheForTests() - probe.inputs = [] - probe.shown = [] - useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} }) -}) -afterEach(() => { - cleanup() - vi.useRealTimers() - clearPendingSendCacheForTests() - useAppStore.setState({ agentStatusByPaneKey: {}, nativeChatLaunchPromptByTabId: {} }) -}) - -describe('preview input allocation at realistic history sizes', () => { - it.each([1_000, 10_000])('reuses input across ticks with %i loaded messages', (size) => { - const transcript = Array.from({ length: size }, (_, index) => - message(`history-${index}`, index % 2 ? 'assistant' : 'user', `History ${index}`) - ) - probe.session = { - messages: transcript, - status: 'working', - sessionId: 'preview-perf', - agent: 'claude', - hasMore: false, - loadingEarlier: false, - olderHistoryGeneration: 0, - loadEarlier: vi.fn(), - readPhase: 'ready' - } - setPreview('Current reply') - render( - - - - ) - previewTicks(transcript) - act(() => fireEvent.click(screen.getByRole('button', { name: 'send' }))) - const queued = probe.inputs.at(-1)! - expect(queued).toHaveLength(size + 1) - expect(queued.at(-1)?.pendingSend).toBe('queued') - previewTicks(queued) - expect(probe.shown.at(-2)?.id).toBe('streaming') - expect(probe.shown.at(-1)?.pendingSend).toBe('queued') - previewTicks(queued, { lastAssistantMessageIsToolOutput: true }) - - const caughtUp = [...transcript, message('reply', 'assistant', 'Current reply 19')] - act(() => { - probe.session = { ...probe.session!, messages: caughtUp } - setPreview('Current reply 19') - }) - const updated = probe.inputs.at(-1)! - expect(updated).not.toBe(queued) - expect(updated.at(-2)?.id).toBe('reply') - expect(updated.at(-1)?.pendingSend).toBe('queued') - previewTicks(updated) - - act(() => { - probe.session = { ...probe.session!, status: 'ready' } - setPreview('Idle', { state: 'done' }) - }) - const idle = probe.inputs.at(-1)! - expect(idle).not.toBe(updated) - previewTicks(idle, { state: 'done' }) - - const retired = [ - ...caughtUp, - { ...message('follow-up', 'user', 'Follow up'), timestamp: 1_001 }, - { ...message('next-reply', 'assistant', 'Done'), timestamp: 1_002 } - ] - act(() => { - probe.session = { ...probe.session!, messages: retired } - setPreview('Done', { state: 'done' }) - }) - previewTicks(retired, { state: 'done' }) - }) -}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.availability-notice.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.availability-notice.test.tsx index 3ff5042c5f5..361334ba5f8 100644 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.availability-notice.test.tsx +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.availability-notice.test.tsx @@ -140,15 +140,6 @@ function turnRow(): AgentJournalRenderItem { } } -it('leaves an auth turn row as the explanation when the catalog also says signed out', () => { - mocks.unavailable = { reason: 'notSignedIn', account: 'system' } - const row = startFailureRow({ kind: 'notSignedIn', account: 'system' }) - mocks.journalItems = [turnRow(), { ...row, itemId: 'codex-unauthorized-error', sequence: 3 }] - render(pane()) - expect(screen.queryByText(CODEX_SIGNED_OUT)).toBeNull() - expect(mocks.composerProps?.structuredTransport).not.toHaveProperty('unavailable') -}) - it('stays dismissed for the same verdict, and shows again when it changes or comes back', () => { mocks.unavailable = { reason: 'notSignedIn', account: 'system' } const view = render(pane()) @@ -175,21 +166,6 @@ it('stays dismissed for the same verdict, and shows again when it changes or com expect(screen.getByText(CODEX_SIGNED_OUT)).toBeTruthy() }) -it('says a reason once when the failed start already says it, keeping its Retry', () => { - mocks.launchLifecycle = 'failed' - mocks.launchFailure = { - kind: 'refused', - code: 'agent_session_operation_invalid', - details: { reason: 'notSignedIn' } - } - mocks.unavailable = { reason: 'notSignedIn', account: 'system' } - render(pane()) - - expect(screen.getAllByText(new RegExp(CODEX_SIGNED_OUT.replace(/[.`]/g, '\\$&')))).toHaveLength(1) - expect(screen.getByText(`Chat could not be started. ${CODEX_SIGNED_OUT}`)).toBeTruthy() - expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy() -}) - it("leaves the reason to the transcript's start-failure row, but not a different one", () => { mocks.journalItems = [startFailureRow({ kind: 'notSignedIn' })] mocks.unavailable = { reason: 'notSignedIn', account: 'system' } diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx index 5129b5dab76..1fc8490b19f 100644 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx @@ -61,7 +61,6 @@ vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChat vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) import { NativeChatStructuredSession } from '../../NativeChatStructuredSession' -import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' import type { NativeChatStructuredComposerTransport } from '../../composer/submit/native-chat-structured-composer-transport' const SESSION_ID = 'notice-card-session' @@ -118,29 +117,3 @@ it('keeps a send failure’s raw error apart and lets the user dismiss it', () = fireEvent.click(screen.getByRole('button', { name: 'Dismiss' })) expect(screen.queryByText('Your message was not sent.')).toBeNull() }) - -const APPROVAL: AgentJournalRenderItem = JSON.parse( - JSON.stringify({ - itemId: 'approval-item', - revision: 1, - sequence: 1, - observedAt: 1, - body: { - kind: 'approval', - title: 'Run the plan?', - detail: null, - subject: { kind: 'plan', text: 'x' }, - options: [{ id: 'allow', label: 'Approve' }], - resolution: { state: 'pending', selectedOptionId: null, resolvedBy: null, resolvedAt: null } - } - }) -) - -it("keeps the notices above an approval card that takes the composer's place", () => { - mocks.launchLifecycle = 'failed' - mocks.promptItems = [APPROVAL] - renderPane() - expect(screen.queryByTestId('structured-composer')).toBeNull() - expect(screen.getByText('Chat could not be started.')).toBeTruthy() - expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy() -}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx index 5a35fcca991..446452ff451 100644 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx @@ -35,72 +35,6 @@ afterEach(() => { resetStructuredSessionMocks() }) -{ - function renderPane(): void { - render( - - ) - } - - function journalRefusal( - reason: 'journalCorrupt' | 'journalUnavailable' | 'journalWrittenByNewerOrca' - ) { - return { code: 'agent_session_journal_unreadable', details: { reason } } as const - } - - it('says a damaged history cannot load in one line, without claiming Orca keeps trying', () => { - mocks.status = 'error' - mocks.readRefusal = journalRefusal('journalCorrupt') - mocks.messages = [] - - renderPane() - - expect(screen.getAllByText('Unable to load this chat.')).toHaveLength(1) - expect(screen.queryByText('Could not load conversation')).toBeNull() - expect(screen.queryByText(/keeps trying/)).toBeNull() - expect(screen.queryByText(/agent_session_/)).toBeNull() - // Nothing to send into: a send would only be refused and say it again. - expect(mocks.composerProps).toBeNull() - }) - - it("names a history that couldn't open right now once, in its one line", () => { - mocks.status = 'error' - mocks.readRefusal = journalRefusal('journalUnavailable') - mocks.messages = [] - - renderPane() - - expect(screen.getAllByText("Orca couldn't open this chat's history right now.")).toHaveLength(1) - expect(screen.queryByText('Could not load conversation')).toBeNull() - expect(screen.queryByText(/keeps trying/)).toBeNull() - expect(screen.queryByText(/Try again/)).toBeNull() - // It can clear, so the composer stays and a send waits for the read. - expect(mocks.composerProps).not.toBeNull() - }) - - it('says once that a newer Orca saved the chat and only an update opens it, with no composer', () => { - mocks.status = 'error' - mocks.readRefusal = journalRefusal('journalWrittenByNewerOrca') - mocks.messages = [] - - renderPane() - - expect( - screen.getAllByText('This chat was saved by a newer Orca. Update Orca to open it.') - ).toHaveLength(1) - expect(screen.queryByText('Could not load conversation')).toBeNull() - expect(screen.queryByText(/keeps trying/)).toBeNull() - expect(mocks.composerProps).toBeNull() - }) -} - { const STILL_WORKING = "The agent is still working. Run /clear when it's done." const BACKGROUND = @@ -158,15 +92,4 @@ afterEach(() => { pane.rerender() expect(screen.queryByText(BACKGROUND)).toBeNull() }) - - it('a line naming nothing the chat shows stays until the next send, as before', () => { - mocks.turnId = 'turn-1' - const pane = renderPane() - composerSays('Remove attachments before using a chat-session command.') - mocks.turnId = null - pane.rerender() - expect(screen.getByText('Remove attachments before using a chat-session command.')).toBeTruthy() - composerSays(null) - expect(screen.queryByText('Remove attachments before using a chat-session command.')).toBeNull() - }) } diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.retained-draft.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.retained-draft.test.tsx deleted file mode 100644 index aeae740f719..00000000000 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.retained-draft.test.tsx +++ /dev/null @@ -1,164 +0,0 @@ -// @vitest-environment happy-dom - -import type * as LaunchRegistry from '@/lib/agent-session/launch/structured-agent-session-launch-registry' -import type * as LaunchOptions from '@/lib/agent-session/launch/structured-agent-session-launch-options' -import { act, cleanup, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { ManagedRuntimeInstallObservation } from '@/runtime/hosts/installation/use-managed-runtime-install' - -const { mocks, moduleFactories, resetStructuredSessionMocks, launchModule } = await vi.hoisted( - async () => { - const setup = ( - await import('./NativeChatStructuredSession.test-harness') - ).createStructuredSessionMocks() - return { - ...setup, - launchModule: setup.moduleFactories.structuredAgentSessionLaunch() - } - } -) -const install = vi.hoisted((): { observation: ManagedRuntimeInstallObservation } => ({ - observation: { kind: 'inactive' } -})) - -vi.mock('@/lib/agent-session/launch/structured-agent-session-launch', () => ({ - retryStructuredAgentSessionLaunch: launchModule.retryStructuredAgentSessionLaunch, - relaunchFailedStructuredAgentSessionForMessage: - launchModule.relaunchFailedStructuredAgentSessionForMessage -})) -vi.mock( - '@/lib/agent-session/launch/structured-agent-session-launch-registry', - async (importOriginal) => ({ - ...(await importOriginal()), - getStructuredAgentSessionLaunchLifecycle: launchModule.getStructuredAgentSessionLaunchLifecycle, - getStructuredAgentSessionLaunchResumes: launchModule.getStructuredAgentSessionLaunchResumes, - useStructuredAgentSessionLaunchLifecycle: launchModule.useStructuredAgentSessionLaunchLifecycle, - useStructuredAgentSessionLaunchFailure: launchModule.useStructuredAgentSessionLaunchFailure - }) -) -vi.mock( - '@/lib/agent-session/launch/structured-agent-session-launch-options', - async (importOriginal) => ({ - ...(await importOriginal()), - useStructuredAgentSessionLaunchSelection: launchModule.useStructuredAgentSessionLaunchSelection - }) -) -vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-message', () => - moduleFactories.structuredAgentSessionLaunchMessage() -) -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => - moduleFactories.structuredAgentSessionCall() -) -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => - moduleFactories.structuredAgentSessionSubscriptions() -) -vi.mock('@/components/machine-identity/use-published-machine-name', () => ({ - usePublishedMachineName: () => null -})) -vi.mock('../../session/structured/use-structured-agent-session', () => - moduleFactories.useStructuredAgentSession() -) -vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize()) -vi.mock('../../links/actions/use-native-chat-file-link-context', () => - moduleFactories.useNativeChatFileLinkContext() -) -vi.mock('../../pane/ownership/use-native-chat-tab-owner', () => - moduleFactories.useNativeChatTabOwner() -) -vi.mock('../../links/actions/use-native-chat-file-link-click', () => - moduleFactories.useNativeChatFileLinkClick() -) -vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList()) -vi.mock('../../host-access/NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState()) -vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard()) -vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) -vi.mock('@/runtime/hosts/installation/use-managed-runtime-install', () => ({ - useManagedRuntimeInstall: () => install.observation -})) - -import { NativeChatStructuredSession } from '../../NativeChatStructuredSession' -import { clearNativeChatComposerDraftsForTests } from '../../drafts/native-chat-draft-reset' -import { hydrateNativeChatComposerDrafts } from '../../drafts/native-chat-composer-draft-load' -import { - readNativeChatComposerDraft, - updateNativeChatComposerDraft -} from '../../drafts/native-chat-composer-draft-store' -import { structuredAgentSessionDraftScopeKey } from '../../drafts/native-chat-draft-scope' - -import { TooltipProvider } from '@/components/ui/tooltip' -import { promptEditor } from '../../composer/editor/native-chat-prompt-editor.test-support' -import { promptTextContent } from '../../composer/editor/native-chat-prompt-document-text' -import { - createMemoryNativeChatComposerDraftStorage, - setNativeChatComposerDraftStorageForTests -} from '../../drafts/native-chat-composer-draft-storage' - -afterEach(() => { - cleanup() - resetStructuredSessionMocks() - clearNativeChatComposerDraftsForTests() -}) -it('shows and copies the ordinary source of an unsupported installed launch', async () => { - const text = 'Hand Off context\nwith trailing bytes ' - clearNativeChatComposerDraftsForTests() - setNativeChatComposerDraftStorageForTests(createMemoryNativeChatComposerDraftStorage()) - await hydrateNativeChatComposerDrafts() - mocks.launchLifecycle = 'failed' - mocks.launchFailure = { kind: 'refused', code: 'structured_agent_session_unsupported' } - mocks.messages = [] - install.observation = { - kind: 'active', - subject: { target: { kind: 'local' }, runtimeId: null, agent: 'codex' }, - snapshot: { - kind: 'known', - state: { - agent: 'codex', - revision: 1, - available: true, - version: '1.3.0', - installedVersion: '1.3.0', - installedCurrent: true, - downloadBytes: 0, - source: 'external', - operation: null - } - }, - removable: false - } - updateNativeChatComposerDraft( - structuredAgentSessionDraftScopeKey('session-1'), - { text, document: promptTextContent(text) }, - 'immediate' - ) - render( - - - - ) - const field = await screen.findByRole('textbox') - expect(field.getAttribute('contenteditable')).toBe('true') - const editor = promptEditor(field) - act(() => { - editor.commands.selectAll() - }) - let copied: string | undefined - editor.view.someProp('clipboardTextSerializer', (serializer) => { - copied = serializer( - editor.state.doc.slice(editor.state.selection.from, editor.state.selection.to), - editor.view - ) - return true - }) - expect(copied).toBe(text) - expect(editor.state.doc.textBetween(0, editor.state.doc.content.size, '\n')).toBe(text) - expect(readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey('session-1')).text).toBe( - text - ) -}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx index a87070dc4c9..a87e02f97b4 100644 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx @@ -1,11 +1,8 @@ -import { getDefaultSettings } from '../../../../../../shared/constants' // @vitest-environment happy-dom import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' - const { mocks, moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () => (await import('./NativeChatStructuredSession.test-harness')).createStructuredSessionMocks() ) @@ -38,59 +35,6 @@ vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChat import { NativeChatStructuredSession } from '../../NativeChatStructuredSession' describe('NativeChatStructuredSession', () => { - it('isolates mounted chats from unrelated settings and renders their live follow-up choice', async () => { - const original = useAppStore.getState().settings - const settings = { ...getDefaultSettings('/tmp'), nativeChatQueueFollowUps: false } - useAppStore.setState({ settings }) - const view = render( - <> - {['local-chat', 'ssh-chat'].map((sessionId) => ( - - ))} - - ) - try { - await act(async () => {}) - mocks.controllerRender.mockClear() - act(() => - useAppStore.setState({ settings: { ...settings, nativeChatQueueFollowUps: false } }) - ) - expect(mocks.controllerRender).not.toHaveBeenCalled() - act(() => - useAppStore.setState({ - settings: { ...settings, showTasksButton: !settings.showTasksButton } - }) - ) - expect(mocks.controllerRender).not.toHaveBeenCalled() - act(() => useAppStore.setState({ settings: { ...settings, nativeChatQueueFollowUps: true } })) - expect(new Set(mocks.controllerRender.mock.calls.map(([sessionId]) => sessionId))).toEqual( - new Set(['local-chat', 'ssh-chat']) - ) - expect(mocks.controllerRender.mock.calls.every(([, queue]) => queue === true)).toBe(true) - mocks.controllerRender.mockClear() - act(() => useAppStore.setState({ settings })) - expect(new Set(mocks.controllerRender.mock.calls.map(([sessionId]) => sessionId))).toEqual( - new Set(['local-chat', 'ssh-chat']) - ) - expect(mocks.controllerRender.mock.calls.every(([, queue]) => queue === false)).toBe(true) - } finally { - view.unmount() - useAppStore.setState({ settings: original }) - } - }) - afterEach(() => { cleanup() resetStructuredSessionMocks() diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.wsl-host-stopped.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.wsl-host-stopped.test.tsx deleted file mode 100644 index 0a02fc94b7e..00000000000 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.wsl-host-stopped.test.tsx +++ /dev/null @@ -1,83 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import type { WslHostStatus } from '../../../../../../shared/wsl-host-types' - -const { moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () => - (await import('./NativeChatStructuredSession.test-harness')).createStructuredSessionMocks() -) -const reconnectHost = vi.hoisted(() => - vi.fn<(environmentId: string, failureMessage?: string) => Promise>() -) - -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => - moduleFactories.structuredAgentSessionCall() -) -vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => - moduleFactories.structuredAgentSessionSubscriptions() -) -vi.mock('../../session/structured/use-structured-agent-session', () => - moduleFactories.useStructuredAgentSession() -) -vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize()) -vi.mock('../../links/actions/use-native-chat-file-link-context', () => - moduleFactories.useNativeChatFileLinkContext() -) -vi.mock('../../links/actions/use-native-chat-file-link-click', () => - moduleFactories.useNativeChatFileLinkClick() -) -vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList()) -vi.mock('../../composer/NativeChatComposer', () => moduleFactories.nativeChatComposer()) -vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard()) -vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) -vi.mock('@/components/status-bar/runtime-environment-explicit-connect', () => ({ - connectRuntimeHostAndReloadProjects: reconnectHost -})) - -import { useAppStore } from '@/store/index' -import { NativeChatStructuredSession } from '../../NativeChatStructuredSession' - -const initialState = useAppStore.getState() - -function setWslStatus(state: WslHostStatus['state']): void { - act(() => { - useAppStore.setState({ - wslHostStatuses: { - 'wsl:ubuntu': { environmentId: 'wsl:ubuntu', distro: 'Ubuntu', state, detail: null } - } - }) - }) -} - -function renderPane() { - return render( - - ) -} - -afterEach(() => { - cleanup() - resetStructuredSessionMocks() - reconnectHost.mockReset() - useAppStore.setState({ wslHostStatuses: initialState.wslHostStatuses }) -}) - -it('still offers Start after a start that failed', async () => { - renderPane() - setWslStatus('distro-stopped') - reconnectHost.mockResolvedValue(false) - await act(async () => { - fireEvent.click(screen.getByRole('button', { name: 'Start' })) - }) - expect(screen.getByText('Ubuntu is stopped')).toBeInTheDocument() - expect(screen.getByRole('button', { name: 'Start' })).toBeEnabled() -}) diff --git a/src/renderer/src/components/native-chat/tools/diffs/native-chat-turn-diffs.test.ts b/src/renderer/src/components/native-chat/tools/diffs/native-chat-turn-diffs.test.ts index c13467f3274..9be1f94c686 100644 --- a/src/renderer/src/components/native-chat/tools/diffs/native-chat-turn-diffs.test.ts +++ b/src/renderer/src/components/native-chat/tools/diffs/native-chat-turn-diffs.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from 'vitest' import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' -import { - buildEditSummaries, - buildEditCards -} from '../../../../../../shared/native-chat/tools/native-chat-edit-cards' import { nativeChatTurnDiffs } from '../../../../../../shared/native-chat/tools/native-chat-turn-diffs' function diff(id: string, path: string, patch = '@@ -1 +1 @@\n-old\n+new'): NativeChatMessage { @@ -82,23 +78,4 @@ describe('turn diff rollups', () => { expect(result.get('one')?.added).toBe(1) expect(result.get('two')?.files).toHaveLength(1) }) - - it('caches counts and deferred card models separately and refreshes new results', () => { - const message = diff('a', 'a.ts') - const summary = [...buildEditSummaries(message.blocks).values()][0]!.files - expect([...buildEditSummaries([...message.blocks]).values()][0]!.files).toBe(summary) - expect(summary[0]).not.toHaveProperty('lines') - const first = [...buildEditCards(message.blocks).editCards.values()][0]!.files - expect([...buildEditCards([...message.blocks]).editCards.values()][0]!.files).toBe(first) - message.blocks = [ - message.blocks[0]!, - { type: 'tool-result', output: '@@ -0,0 +1,2 @@\n+one\n+two' } - ] - const updated = [...buildEditCards(message.blocks).editCards.values()][0]!.files - expect(updated).not.toBe(first) - expect(updated[0]?.added).toBe(2) - const updatedSummary = [...buildEditSummaries(message.blocks).values()][0]!.files - expect(updatedSummary).not.toBe(summary) - expect(updatedSummary[0]?.added).toBe(2) - }) }) diff --git a/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRunCallCounts.test.tsx b/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRunCallCounts.test.tsx deleted file mode 100644 index c7f2247c142..00000000000 --- a/src/renderer/src/components/native-chat/tools/runs/NativeChatToolRunCallCounts.test.tsx +++ /dev/null @@ -1,70 +0,0 @@ -// @vitest-environment happy-dom - -import '@testing-library/jest-dom/vitest' - -import { cleanup, render } from '@testing-library/react' -import { afterEach, describe, expect, it } from 'vitest' -import type { AgentJournalToolCallItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' -import { interruptedAgentJournalToolCall } from '../../../../../../shared/agent-journal-tool-call-lifecycle' -import type { NativeChatBlock } from '../../../../../../shared/native-chat/native-chat-types' -import { projectStructuredItemToNativeChat } from '../../../../../../shared/agent-session/view/structured-agent-session-projection' -import { NativeChatToolRun } from './NativeChatToolRun' - -afterEach(cleanup) - -function runHeader(container: HTMLElement): HTMLElement { - const header = container.querySelector('button') - if (!header) { - throw new Error('run header did not render') - } - return header -} - -function projected(itemId: string, body: AgentJournalToolCallItem): NativeChatBlock[] { - return ( - projectStructuredItemToNativeChat({ itemId, sequence: 1, revision: 1, observedAt: 1, body }) - ?.blocks ?? [] - ) -} - -const output = (head: string) => ({ head, digest: 'd', byteLength: head.length, truncated: false }) - -function shell( - command: string, - state: AgentJournalToolCallItem['state'] -): AgentJournalToolCallItem { - return { kind: 'tool-call', name: 'shell', input: { command }, state } -} - -describe('NativeChatToolRun call counts', () => { - it('says a call a stop cut short was interrupted, not failed, and marks no success', () => { - const blocks = projected( - 'sleep', - interruptedAgentJournalToolCall({ - ...shell('sleep 20', 'running'), - output: output('partial') - }) - ) - const { container } = render( - - ) - const header = runHeader(container) - expect(header).toHaveTextContent('1 interrupted') - expect(header).not.toHaveTextContent('failed') - expect(header).toHaveAccessibleName(/Interrupted tool calls: 1/) - expect(header.querySelector('.lucide-check')).toBeNull() - }) - - it('names a failure and an interruption in one quiet mark', () => { - const blocks = [ - ...projected('false', { ...shell('false', 'failed'), output: output('exit 1') }), - ...projected('sleep', interruptedAgentJournalToolCall(shell('sleep 20', 'running'))) - ] - const { container } = render( - - ) - const header = runHeader(container) - expect(header).toHaveTextContent('1 failed, 1 interrupted') - expect(header).toHaveAccessibleName(/Failed tool calls: 1, Interrupted tool calls: 1/) - }) -}) diff --git a/src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts b/src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts index a0773e8eb9f..1821a4904ca 100644 --- a/src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts +++ b/src/renderer/src/components/native-chat/tools/runs/native-chat-tool-fold.test.ts @@ -16,42 +16,6 @@ function msg( } describe('foldToolMessages', () => { - // Invisible provider events must not split visible runs; rendered plan updates do. - it('keeps one run across a wordless provider event, but not across a plan update', () => { - const frameRow = (id: string, kind: string): NativeChatMessage => - msg({ - id, - role: 'system', - blocks: [ - { - type: 'text', - text: `codex · ${kind}`, - providerFrame: { - provider: 'codex', - kind, - payload: { head: '{}', byteLength: 2, digest: 'digest', truncated: false } - } - } - ] - }) - const run = (between: NativeChatMessage): string[] => - foldToolMessages([ - msg({ - id: 'a1', - blocks: [ - { type: 'text', text: 'go' }, - { type: 'tool-call', name: 'Bash', input: {} } - ] - }), - msg({ id: 'r1', role: 'tool', blocks: [{ type: 'tool-result', output: 'ok' }] }), - between, - msg({ id: 'a2', blocks: [{ type: 'tool-call', name: 'Bash', input: {} }] }), - msg({ id: 'r2', role: 'tool', blocks: [{ type: 'tool-result', output: 'ok' }] }) - ]).map((message) => message.id) - expect(run(frameRow('frame', 'notification:future/event'))).toEqual(['a1', 'frame']) - expect(run(frameRow('plan', 'notification:turn/plan/updated'))).toEqual(['a1', 'plan', 'a2']) - }) - it('drops a result after a user turn abandons the pending call', () => { const folded = foldToolMessages([ msg({ id: 'c', role: 'assistant', blocks: [{ type: 'tool-call', name: 'Bash', input: {} }] }), @@ -61,21 +25,6 @@ describe('foldToolMessages', () => { expect(folded.map((m) => m.id)).toEqual(['c', 'u']) }) - it('does not fold a message carrying prose alongside a tool block', () => { - const folded = foldToolMessages([ - msg({ id: 'a', role: 'assistant', blocks: [{ type: 'text', text: 'first' }] }), - msg({ - id: 'b', - role: 'assistant', - blocks: [ - { type: 'text', text: 'more' }, - { type: 'tool-call', name: 'Read', input: {} } - ] - }) - ]) - expect(folded.map((m) => m.id)).toEqual(['a', 'b']) - }) - it('attributes a Claude tool result carried with a harness sidecar', () => { const folded = foldToolMessages([ msg({ @@ -136,54 +85,4 @@ describe('foldToolMessages', () => { }) ]) }) - - it('folds through a harness noise boundary but not a real user turn', () => { - const folded = foldToolMessages([ - msg({ id: 'a', role: 'assistant', blocks: [{ type: 'tool-call', name: 'Read', input: {} }] }), - msg({ id: 'n', role: 'user', blocks: [{ type: 'text', text: 'done' }] }), - msg({ id: 'r', role: 'tool', blocks: [{ type: 'tool-result', output: 'ok' }] }) - ]) - - expect(folded.find((message) => message.id === 'a')?.blocks).toEqual([ - { type: 'tool-call', name: 'Read', input: {} }, - { type: 'tool-result', output: 'ok' } - ]) - }) -}) - -describe('spawn-group roster rows', () => { - const roster = msg({ - id: 'roster', - role: 'system', - blocks: [ - { type: 'text', text: 'Kicked off 1 subagent — 1 working' }, - { - type: 'subagent-group', - groupId: 'thread:turn-1', - agents: [{ id: 'child-1', label: 'read', state: 'working' }] - } - ] - }) - - it('does not end the assistant run the following tool messages fold into', () => { - const folded = foldToolMessages([ - msg({ - id: 'a', - role: 'assistant', - blocks: [ - { type: 'text', text: 'working' }, - { type: 'tool-call', name: 'Bash', input: {} } - ] - }), - roster, - msg({ id: 't', role: 'tool', blocks: [{ type: 'tool-result', output: 'done' }] }) - ]) - - expect(folded.map((message) => message.id)).toEqual(['a', 'roster']) - expect(folded[0]?.blocks.map((block) => block.type)).toEqual([ - 'text', - 'tool-call', - 'tool-result' - ]) - }) }) diff --git a/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.test.tsx b/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.test.tsx index d39bcee6f19..311c195e851 100644 --- a/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.test.tsx +++ b/src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.test.tsx @@ -2,62 +2,12 @@ import '@testing-library/jest-dom/vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { Profiler } from 'react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' import { NativeChatBackgroundTasksStatus } from './NativeChatBackgroundTasksStatus' -afterEach(() => { - cleanup() - vi.useRealTimers() -}) - -/** Own disclosure outside the strip so temporary roster gaps cannot reset expansion. */ - -it('lets the 1 Hz tick sleep while every row has settled, with each run frozen', () => { - vi.useFakeTimers() - vi.setSystemTime(1_000_000) - const committed = vi.fn() - const finished = (id: string, firstObservedAt: number, settledAt: number) => ({ - id, - providerId: `task-${id}`, - kind: 'agent' as const, - description: `child ${id}`, - state: 'done' as const, - membership: 'settled' as const, - outcome: 'succeeded' as const, - firstObservedAt, - observedAt: settledAt, - settledAt, - stoppable: false, - invocation: { invocationId: `spawn-${id}`, generation: 1 } - }) - render( - - {}} - isVisible - tasks={[]} - settledTasks={[]} - childViews={[finished('a', 400_000, 520_000), finished('b', 700_000, 760_000)]} - indicatorActive - supportsTaskStop - offersStopAll={false} - stoppingTaskIds={new Set()} - stoppingAll={false} - onStop={() => {}} - /> - - ) - const rows = screen.getAllByRole('listitem').map((row) => row.textContent) - expect(rows).toEqual(['child a · Agent2m 0s', 'child b · Agent1m 0s']) - committed.mockClear() - act(() => vi.advanceTimersByTime(5_000)) - expect(committed).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) -}) +afterEach(cleanup) it("shows an agent by the provider's id, beside its own Stop, and leaves command rows inert", () => { const running = (id: string, kind: 'agent' | 'command') => ({ diff --git a/src/renderer/src/components/native-chat/tools/tasks/use-structured-session-child-row-context.ts b/src/renderer/src/components/native-chat/tools/tasks/use-structured-session-child-row-context.ts index 22930f93360..a8d6e7b4fca 100644 --- a/src/renderer/src/components/native-chat/tools/tasks/use-structured-session-child-row-context.ts +++ b/src/renderer/src/components/native-chat/tools/tasks/use-structured-session-child-row-context.ts @@ -3,10 +3,13 @@ import { agentChildRowContextForParent, type AgentChildRowContext } from '../../../../../../shared/agent-status/presentation/agent-child-row-model' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../../shared/agent-status/contracts/agent-status-freshness' +import { + AGENT_STATUS_STALE_AFTER_MS, + isAgentStatusFresh +} from '../../../../../../shared/agent-status/contracts/agent-status-freshness' import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' import { useNow } from '@/hooks/use-now' -import { isExplicitAgentStatusFresh } from '@/lib/pane-agent-evidence' + import { useAppStore } from '@/store' /** The verdict a session's status row gives its children, exactly as the sidebar derives it. */ @@ -16,7 +19,7 @@ export function structuredSessionChildRowContext( ): AgentChildRowContext { return agentChildRowContextForParent( parent, - isExplicitAgentStatusFresh(parent, now, AGENT_STATUS_STALE_AFTER_MS) + isAgentStatusFresh(parent, now, AGENT_STATUS_STALE_AFTER_MS) ) } diff --git a/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.fixture.tsx b/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.fixture.tsx new file mode 100644 index 00000000000..7c49175a30d --- /dev/null +++ b/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.fixture.tsx @@ -0,0 +1,32 @@ +import { defineFixture } from '../../../component-fixtures/component-fixture' +import { summarizeContextUsage } from '../../../../../shared/native-chat/native-chat-context-usage-summary' +import { NativeChatContextUsageRing } from './NativeChatContextUsageRing' + +const usage = summarizeContextUsage({ + usedTokens: 607_700, + windowTokens: 1_000_000, + percentage: 61, + estimated: false, + categories: [ + { name: 'System prompt', tokens: 4_100 }, + { name: 'System tools', tokens: 8_900 }, + { name: 'MCP tools (deferred)', tokens: 542_000, deferred: true }, + { name: 'System tools (deferred)', tokens: 17_000, deferred: true }, + { name: 'Memory files', tokens: 5_700 }, + { name: 'Messages', tokens: 589_000 }, + { name: 'Free space', tokens: 359_300 }, + { name: 'Autocompact buffer', tokens: 33_000 } + ] +}) + +export const deferredTools = defineFixture({ + width: 360, + render: () => ( +
+ +
+ ), + interact: (frame) => { + frame.querySelector('button[data-native-chat-context-usage]')?.click() + } +}) diff --git a/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.test.tsx b/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.test.tsx index 6b36475d07e..82a2717fc0c 100644 --- a/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.test.tsx +++ b/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.test.tsx @@ -3,7 +3,10 @@ import { act } from 'react' import { createRoot, type Root } from 'react-dom/client' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { NativeChatContextUsageSummary } from '../../../../../shared/native-chat/native-chat-context-usage-summary' +import { + summarizeContextUsage, + type NativeChatContextUsageSummary +} from '../../../../../shared/native-chat/native-chat-context-usage-summary' globalThis.IS_REACT_ACT_ENVIRONMENT = true @@ -95,6 +98,26 @@ function pointer(type: 'pointerover' | 'pointerout', pointerType: string): Point } describe('NativeChatContextUsageRing', () => { + it('lists deferred rows apart from the used total, in tokens rather than a share of the window', async () => { + const usage = summarizeContextUsage({ + usedTokens: 607_700, + windowTokens: 1_000_000, + percentage: 61, + estimated: false, + categories: [ + { name: 'Messages', tokens: 589_000 }, + { name: 'MCP tools (deferred)', tokens: 542_000, deferred: true }, + { name: 'System prompt', tokens: 18_700 } + ] + }) + await click(await renderRing(usage)) + + const groups = [...card()!.querySelectorAll('ul')].map((list) => + [...list.querySelectorAll('li')].map((row) => row.textContent) + ) + expect(groups).toEqual([['Messages58.9%', 'System prompt1.9%'], ['MCP tools (deferred)542k']]) + }) + it('stays open while the pointer crosses the gap from the ring into the card', async () => { const trigger = await renderRing() const hoverTarget = trigger.parentElement! diff --git a/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.tsx b/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.tsx index 57c26cd143a..02235f722b7 100644 --- a/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.tsx +++ b/src/renderer/src/components/native-chat/usage/NativeChatContextUsageRing.tsx @@ -5,6 +5,7 @@ import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' import { contextUsageRingReadout, + formatContextTokenCount, keyContextUsageRows, type NativeChatContextUsageSummary } from '../../../../../shared/native-chat/native-chat-context-usage-summary' @@ -62,6 +63,35 @@ function useContextCardOpen(): { return { open, setOpen, setOpenAfterHover } } +/** Deferred rows sit outside the window, so they show tokens rather than a share of it. */ +function ContextUsageRowList({ + rows, + className +}: { + rows: ReturnType + className: string +}): React.JSX.Element { + return ( +
    + {rows.map(({ key, row }) => ( +
  • + + {row.name} + + + {row.deferred ? formatContextTokenCount(row.tokens) : `${row.percentage}%`} + +
  • + ))} +
+ ) +} + /** Composer ring for context-window usage; hover, click, tap, or Enter shows the provider's breakdown. */ export function NativeChatContextUsageRing({ usage @@ -77,6 +107,8 @@ export function NativeChatContextUsageRing({ ) const { open, setOpen, setOpenAfterHover } = useContextCardOpen() const rows = keyContextUsageRows(usage.rows) + const counted = rows.filter(({ row }) => !row.deferred) + const deferred = rows.filter(({ row }) => row.deferred) return (
- {rows.length > 0 ? ( -
    - {rows.map(({ key, row }) => ( -
  • - {row.name} - - {row.percentage}% - -
  • - ))} -
+ {counted.length > 0 ? : null} + {deferred.length > 0 ? ( +
+

+ {t( + 'components.native-chat.contextUsage.deferredNote', + 'Loaded on demand. Not counted in the used total.' + )} +

+ +
) : null} {usage.estimated ? (

diff --git a/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx b/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx index 41b38c61586..5621382fb1a 100644 --- a/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx +++ b/src/renderer/src/components/native-chat/usage/NativeChatUsageLimitActions.tsx @@ -18,7 +18,7 @@ import { AgentSessionContinuationDialog } from '@/components/agent-session-conti import { buildAgentSessionContinuationPrompt, type AgentSessionContinuationRequest -} from '@/lib/agent-session-continuation' +} from '@/lib/agent-session/context/agent-session-continuation' import { ClaudeSwitcherMenu } from '@/components/status-bar/ClaudeSwitcherMenu' import { ProviderAccountChatButton } from '@/components/status-bar/ProviderAccountChatButton' import { isTuiAgent } from '../../../../../shared/agent-launch/catalog/tui-agent-config' diff --git a/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find-matches.ts b/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find-matches.ts index b0dcadc3168..2801dd93655 100644 --- a/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find-matches.ts +++ b/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find-matches.ts @@ -15,7 +15,7 @@ const chatFindHighlights = createDomTextSearchHighlights({ const TRANSCRIPT_COLUMN_SELECTOR = '[data-native-chat-transcript-column]' const TRANSCRIPT_SCROLL_SELECTOR = '[data-native-chat-scroll]' -/** Row chrome that only shows on hover (timestamps, copy): marked, so counts never follow the mouse. */ +/** Row chrome, not transcript (timestamps, copy): marked, so find counts only message text. */ const SKIPPED_TEXT_SELECTOR = '.sr-only, [hidden], [data-native-chat-find-skip]' /** A streamed reply's text node while its words fade in: each new word is its own element. */ const WORD_GROUP_SELECTOR = '[data-word-group]' diff --git a/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find.test.tsx b/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find.test.tsx index 0e6b3efe4b9..fb14de901d8 100644 --- a/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find.test.tsx +++ b/src/renderer/src/components/native-chat/viewport/find/use-native-chat-find.test.tsx @@ -1,5 +1,5 @@ // @vitest-environment happy-dom -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { act, cleanup, render, screen } from '@testing-library/react' import { useRef, type ReactNode } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { KeybindingOverrides } from '../../../../../../shared/keybindings/types' @@ -193,18 +193,6 @@ function findInput(): HTMLInputElement | null { return inputs.find((input) => input === document.activeElement) ?? inputs[0] ?? null } -function typeQuery(value: string): void { - const input = findInput() - if (!input) { - throw new Error('find bar is not open') - } - fireEvent.change(input, { target: { value } }) -} - -function status(): string | null | undefined { - return findInput()?.parentElement?.querySelector('[aria-live]')?.textContent -} - const TRANSCRIPT = ( <>

alpha one

@@ -231,26 +219,6 @@ afterEach(() => { }) describe('native chat find', () => { - it('refocuses on Mod+F without moving the match, and keeps the query on reopen', () => { - const composer = composerHandle() - render() - pressModF(composer.element) - typeQuery('alpha') - press(findInput()!, 'Enter') - composer.element.focus() - - expect(pressModF(composer.element).defaultPrevented).toBe(true) - const input = findInput()! - expect(document.activeElement).toBe(input) - expect([input.selectionStart, input.selectionEnd]).toEqual([0, 5]) - expect(status()).toBe('2/2') - - press(input, 'Escape') - expect(findInput()).toBeNull() - pressModF(composer.element) - expect(findInput()?.value).toBe('alpha') - }) - it('falls back to the composer when the element find was opened from is gone', () => { const composer = composerHandle() const view = render( diff --git a/src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx b/src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx index 1bf00fb4bfb..14df9d4defa 100644 --- a/src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx +++ b/src/renderer/src/components/native-chat/viewport/history/NativeChatMessageList.older-history.test.tsx @@ -134,7 +134,6 @@ function flowAboveSpacer(spacer: HTMLElement): number { } type LoadEarlier = () => Promise -const lands = (): LoadEarlier => vi.fn(async (): Promise => 'applied') function paging({ messages, @@ -359,23 +358,6 @@ describe('older history auto-load', () => { } }) - it('stops, and shows neither status nor button, once history runs out', async () => { - const loadEarlier = lands() - const base = markers(100, 150) - const { rerender } = render(paging({ messages: base, loadEarlier })) - sentinelInRange = true - deliverIntersections() - rerender(paging({ messages: base, loadEarlier, loadingEarlier: true })) - await settle() - rerender(paging({ messages: [...markers(90, 100), ...base], loadEarlier, hasMore: false })) - deliverIntersections() - - expect(loadEarlier).toHaveBeenCalledTimes(1) - expect(observations.size).toBe(0) - expect(screen.queryByRole('status')).not.toBeInTheDocument() - expect(screen.queryByRole('button', { name: /load earlier/i })).not.toBeInTheDocument() - }) - it('offers a manual load after a failed page, and resumes auto-loading once it succeeds', async () => { const loadEarlier = vi .fn() diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx new file mode 100644 index 00000000000..ca44f3e5740 --- /dev/null +++ b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatMessageList.new-rows-marker.test.tsx @@ -0,0 +1,172 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' + +import { act, cleanup, screen } from '@testing-library/react' +import { render } from '../../messages/actions/native-chat-tooltip-test-harness' +import { createRef } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { NativeChatMessage } from '../../../../../../shared/native-chat/native-chat-types' +import { getDefaultSettings } from '../../../../../../shared/constants' +import { useAppStore } from '@/store' +import { NativeChatMessageList } from '../../NativeChatMessageList' +import type { NativeChatMessageListHandle } from '../../messages/actions/use-native-chat-reveal-latest' +import { + deliverResizes, + layout, + marker, + ROW_PITCH_PX, + scrollTranscript, + session, + stubLayout, + stubResizeObserver, + TRANSCRIPT_LENGTH +} from '../virtualization/native-chat-windowing-test-harness' + +// Pacing is not this test's subject. +vi.mock('../../markdown/use-native-chat-paced-text', async (importOriginal) => + (await import('../../markdown/native-chat-unpaced-text-fixture')).unpacedTextModule( + importOriginal + ) +) + +afterEach(cleanup) + +function chat( + length: number, + isVisible: boolean, + { + ref, + readCurrent = true + }: { ref?: React.Ref; readCurrent?: boolean } = {} +): React.JSX.Element { + const messages: NativeChatMessage[] = Array.from({ length }, (_, index) => ({ + ...marker(index), + journalPosition: { sequence: index + 1, index: 0 } + })) + return ( + + ) +} + +describe('the "New" marker in the transcript', () => { + let paneShown = true + let restore: (() => void)[] = [] + beforeEach(() => { + paneShown = true + vi.spyOn(document, 'hasFocus').mockReturnValue(true) + restore = [ + stubLayout({ scrollGeometry: true, offsetChain: true, isVisible: () => paneShown }), + stubResizeObserver() + ] + }) + afterEach(() => { + for (const undo of restore.toReversed()) { + undo() + } + layout.measuredRowHeights = [] + vi.restoreAllMocks() + }) + + // The window mounts only rows near the view; the marker's row is far from the end it opens at. + it('is drawn above the first row that came while the chat was hidden, however far back', () => { + const { rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + rerender(chat(TRANSCRIPT_LENGTH, false)) + rerender(chat(TRANSCRIPT_LENGTH + 60, true)) + + const row = screen.getByRole('separator', { name: 'New' }).closest('[data-index]') + expect(row?.dataset.index).toBe(String(TRANSCRIPT_LENGTH)) + }) + + it('tells a screen reader that new messages came, in a region that was already there', () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + const region = container.querySelector('[data-native-chat-scroll] ~ [aria-live="polite"]') + expect(region).toBeEmptyDOMElement() + + rerender(chat(TRANSCRIPT_LENGTH, false)) + rerender(chat(TRANSCRIPT_LENGTH + 60, true)) + expect(region).toHaveTextContent('New messages arrived while you were away') + }) + + it('is neither drawn nor announced when the reader turned it off', () => { + const settings = useAppStore.getState().settings + useAppStore.setState({ + settings: { ...getDefaultSettings('/tmp'), nativeChatMarkNewMessages: false } + }) + try { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + rerender(chat(TRANSCRIPT_LENGTH, false)) + rerender(chat(TRANSCRIPT_LENGTH + 60, true)) + + expect(screen.queryByRole('separator', { name: 'New' })).toBeNull() + expect( + container.querySelector('[data-native-chat-scroll] ~ [aria-live="polite"]') + ).toBeEmptyDOMElement() + } finally { + useAppStore.setState({ settings }) + } + }) + + it('goes once the reader sends something', () => { + const ref = createRef() + const { rerender } = render(chat(TRANSCRIPT_LENGTH, true, { ref })) + rerender(chat(TRANSCRIPT_LENGTH, false, { ref })) + rerender(chat(TRANSCRIPT_LENGTH + 60, true, { ref })) + expect(screen.getByRole('separator', { name: 'New' })).toBeInTheDocument() + + act(() => ref.current?.revealLatest()) + + expect(screen.queryByRole('separator', { name: 'New' })).toBeNull() + }) + + describe('when the reader comes back to new rows', () => { + /** Catch up after restoring the hidden pane’s scroll position. */ + function returnToNewRows(rerender: (ui: React.JSX.Element) => void, count = 60): void { + paneShown = false + rerender(chat(TRANSCRIPT_LENGTH, false, { readCurrent: false })) + paneShown = true + rerender(chat(TRANSCRIPT_LENGTH, true, { readCurrent: false })) + rerender(chat(TRANSCRIPT_LENGTH + count, true)) + } + const scrollTop = (container: HTMLElement): number | undefined => + container.querySelector('[data-native-chat-scroll]')?.scrollTop + + it('brings a reader who was at the end to where the new rows begin', () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + returnToNewRows(rerender) + + expect(scrollTop(container)).toBe(TRANSCRIPT_LENGTH * ROW_PITCH_PX) + }) + + it('keeps the reader where the new rows begin while a reply is still being drawn', async () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + returnToNewRows(rerender, 1) + + const drawn: number[] = [] + drawn[TRANSCRIPT_LENGTH] = 2_000 + layout.measuredRowHeights = drawn + act(() => void deliverResizes()) + await act(async () => { + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + }) + + expect(scrollTop(container)).toBe(TRANSCRIPT_LENGTH * ROW_PITCH_PX) + }) + + it('leaves a reader who was parked further up where they were', () => { + const { container, rerender } = render(chat(TRANSCRIPT_LENGTH, true)) + const readingAt = 2_000 + scrollTranscript(container, readingAt) + returnToNewRows(rerender) + + expect(screen.getByRole('separator', { name: 'New' })).toBeInTheDocument() + expect(scrollTop(container)).toBe(readingAt) + }) + }) +}) diff --git a/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx new file mode 100644 index 00000000000..b90a1ddb8af --- /dev/null +++ b/src/renderer/src/components/native-chat/viewport/new-rows/NativeChatNewRowsMarker.test.tsx @@ -0,0 +1,92 @@ +// @vitest-environment happy-dom + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { NativeChatNewRowsMarker } from './NativeChatNewRowsMarker' +import type { NativeChatNewRowsMarkerState as Marker } from './native-chat-new-rows-marker' +import { overrideLayoutProperty } from '../virtualization/native-chat-windowing-test-harness' + +afterEach(cleanup) + +function marker(overrides: Partial = {}): Marker { + return { + key: 'answer', + place: 'above-row', + arriving: true, + onArrived: vi.fn(), + onDismiss: vi.fn(), + ...overrides + } +} + +const VIEWPORT_PX = 600 +const ROW_TOP_PX = 1_000 + +let restoreLayout: (() => void)[] = [] + +/** Place the view bottom aboveMarkerPx short of a marker positioned intoRowPx within its row. */ +function pane( + value: Marker, + { intoRowPx = 0, aboveMarkerPx = 0 }: { intoRowPx?: number; aboveMarkerPx?: number } = {} +) { + const isRow = (element: HTMLElement): boolean => element.hasAttribute('data-index') + const isMarker = (element: HTMLElement): boolean => element.getAttribute('role') === 'separator' + const layout = (name: string, get: (this: HTMLElement) => unknown) => + overrideLayoutProperty(name, { get }) + restoreLayout = [ + layout('clientHeight', () => VIEWPORT_PX), + layout('scrollTop', () => ROW_TOP_PX + intoRowPx - VIEWPORT_PX - aboveMarkerPx), + layout('offsetTop', function () { + return isRow(this) ? ROW_TOP_PX : isMarker(this) ? intoRowPx : 0 + }), + layout('offsetParent', function () { + return isRow(this) || isMarker(this) ? this.parentElement : null + }) + ] + const onReveal = vi.fn() + const view = render( +
+
+ +
+
+
+ +
+
+