diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index d9f19dcc1..2f91c946b 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -69,6 +69,14 @@ jobs: - name: Check reliability gate manifest run: pnpm run check:reliability-gates + # Why: oxlint fails any file over max-lines that is NOT suppressed, so this + # ratchet forbids ADDING a new suppression (inline disable or mobile max + # bump). Existing oversized files are grandfathered in + # config/max-lines-baseline.txt, which may only shrink — new bypasses fail + # here with a clear message instead of silently growing the debt. + - name: Enforce max-lines ratchet (no new bypasses) + run: pnpm run check:max-lines-ratchet + # Why: project-owned type declarations must live in .ts so tsc # actually checks them. TypeScript's skipLibCheck: true (inherited # from @electron-toolkit/tsconfig) silently widens unresolved names diff --git a/.gitignore b/.gitignore index 7cdf33740..24595e4c7 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,7 @@ coverage/ # Benchmark run output /tools/benchmarks/results/*.json +/.bench-fixtures/ # Temp tmp/ diff --git a/AGENTS.md b/AGENTS.md index 647c598a2..b10035e9b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,9 @@ Keep comments short — one or two lines. Capture only the non-obvious reason (s ## Lint Rules: Do Not Disable Max Lines -Never add a `max-lines` disable (`eslint-disable max-lines`, `oxlint-disable max-lines`, or line-specific variants). Split the file, extract focused modules, move fixtures/builders into named files, or otherwise reduce the counted lines instead. +Never add a `max-lines` disable (`eslint-disable max-lines`, `oxlint-disable max-lines`, or line-specific variants), and never add a per-file `max-lines` bump in `mobile/.oxlintrc.json`. Split the file, extract focused modules, move fixtures/builders into named files, or otherwise reduce the counted lines instead. + +This is enforced in CI by `pnpm check:max-lines-ratchet` (`config/scripts/check-max-lines-ratchet.mjs`). Files already over the limit are grandfathered in `config/max-lines-baseline.txt`; that list may only **shrink**. Adding a new suppression fails the build. If you remove a suppression (great — split it!), run `pnpm check:max-lines-ratchet --prune` to drop its baseline line. ## File and Module Naming diff --git a/README.md b/README.md index 1043bc9d6..8e9bc05d3 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Monitor and steer your agents from your phone — get notified when an agent finishes and send follow-ups from anywhere. -[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [Android APK 0.0.22](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) +[iOS App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) · [TestFlight](https://testflight.apple.com/join/YjeGMQBA) · [Android APK 0.0.24](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) · [Docs →](https://www.onorca.dev/docs/mobile) @@ -230,7 +230,7 @@ yay -S stably-orca-bin Pair with your desktop app to monitor and steer your agents from your phone. - **iOS:** [Download on the App Store](https://apps.apple.com/us/app/orca-ide/id6766130217) or [join TestFlight](https://testflight.apple.com/join/YjeGMQBA) -- **Android:** [Download APK 0.0.22](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.22/app-release.apk) +- **Android:** [Download APK 0.0.24](https://github.com/stablyai/orca/releases/download/mobile-android-v0.0.24/app-release.apk) --- diff --git a/config/max-lines-baseline.txt b/config/max-lines-baseline.txt new file mode 100644 index 000000000..543ff2e6a --- /dev/null +++ b/config/max-lines-baseline.txt @@ -0,0 +1,359 @@ +# Files/globs currently allowed to exceed the oxlint `max-lines` budget. +# This is a RATCHET: the list may only SHRINK. Do NOT add entries to get CI green — +# split the oversized file instead (AGENTS.md → "Do Not Disable Max Lines"). +# Regenerate/prune: pnpm check:max-lines-ratchet --prune (removes stale entries only) +inline mobile/src/constants/marine-creatures.ts +inline src/cli/handlers/automations.ts +inline src/cli/handlers/orchestration.ts +inline src/cli/help.ts +inline src/cli/index.test.ts +inline src/main/agent-hooks/server.test.ts +inline src/main/agent-hooks/server.ts +inline src/main/amp/hook-service.ts +inline src/main/antigravity/hook-service.ts +inline src/main/attribution/terminal-attribution.ts +inline src/main/automations/external-manager.ts +inline src/main/automations/hermes-cron-output.ts +inline src/main/browser/agent-browser-bridge.test.ts +inline src/main/browser/agent-browser-bridge.ts +inline src/main/browser/browser-cookie-import.ts +inline src/main/browser/browser-guest-ui.ts +inline src/main/browser/browser-manager-grab.test.ts +inline src/main/browser/browser-manager.test.ts +inline src/main/browser/browser-manager.ts +inline src/main/browser/browser-screencast-stream.ts +inline src/main/browser/browser-session-registry.ts +inline src/main/browser/cdp-bridge.ts +inline src/main/browser/cdp-ws-proxy.ts +inline src/main/browser/grab-guest-script.ts +inline src/main/browser/snapshot-engine.ts +inline src/main/claude-accounts/runtime-auth-service.test.ts +inline src/main/claude-accounts/runtime-auth-service.ts +inline src/main/claude-accounts/service.test.ts +inline src/main/claude-accounts/service.ts +inline src/main/claude-usage/scanner.ts +inline src/main/claude-usage/store.ts +inline src/main/cli/cli-installer.test.ts +inline src/main/cli/cli-installer.ts +inline src/main/cli/wsl-cli-installer.ts +inline src/main/codex-accounts/runtime-home-service.test.ts +inline src/main/codex-accounts/runtime-home-service.ts +inline src/main/codex-accounts/service.test.ts +inline src/main/codex-accounts/service.ts +inline src/main/codex-usage/scanner.ts +inline src/main/codex-usage/store.test.ts +inline src/main/codex-usage/store.ts +inline src/main/codex/config-toml-trust.test.ts +inline src/main/codex/config-toml-trust.ts +inline src/main/codex/hook-service.test.ts +inline src/main/codex/hook-service.ts +inline src/main/copilot/hook-service.ts +inline src/main/daemon/client.ts +inline src/main/daemon/daemon-health.ts +inline src/main/daemon/daemon-init.test.ts +inline src/main/daemon/daemon-init.ts +inline src/main/daemon/daemon-pty-adapter.test.ts +inline src/main/daemon/daemon-pty-adapter.ts +inline src/main/daemon/daemon-server.ts +inline src/main/daemon/pty-subprocess.test.ts +inline src/main/daemon/pty-subprocess.ts +inline src/main/daemon/session.ts +inline src/main/daemon/shell-ready.ts +inline src/main/git/remove-worktree.test.ts +inline src/main/git/repo.ts +inline src/main/git/runner.ts +inline src/main/git/status.test.ts +inline src/main/git/status.ts +inline src/main/git/worktree.test.ts +inline src/main/git/worktree.ts +inline src/main/github/client.test.ts +inline src/main/github/client.ts +inline src/main/github/issues.ts +inline src/main/github/pr-refresh-coordinator.test.ts +inline src/main/github/pr-refresh-coordinator.ts +inline src/main/github/project-view.ts +inline src/main/github/project-view/mutations.ts +inline src/main/github/work-item-details.ts +inline src/main/gitlab/client-mr.test.ts +inline src/main/gitlab/client.ts +inline src/main/gitlab/issues.ts +inline src/main/gitlab/work-item-details.ts +inline src/main/hermes/hook-service.ts +inline src/main/hooks.test.ts +inline src/main/hooks.ts +inline src/main/index.ts +inline src/main/ipc/browser.ts +inline src/main/ipc/crash-reporting.ts +inline src/main/ipc/filesystem-auth.ts +inline src/main/ipc/filesystem-mutations.ts +inline src/main/ipc/filesystem-watcher.ts +inline src/main/ipc/filesystem.test.ts +inline src/main/ipc/filesystem.ts +inline src/main/ipc/github.test.ts +inline src/main/ipc/github.ts +inline src/main/ipc/gitlab.ts +inline src/main/ipc/linear.ts +inline src/main/ipc/notifications.test.ts +inline src/main/ipc/notifications.ts +inline src/main/ipc/pet.ts +inline src/main/ipc/preflight.test.ts +inline src/main/ipc/pty.test.ts +inline src/main/ipc/pty.ts +inline src/main/ipc/remote-workspace.ts +inline src/main/ipc/repos-remote.test.ts +inline src/main/ipc/repos.ts +inline src/main/ipc/runtime-environments.test.ts +inline src/main/ipc/ssh.test.ts +inline src/main/ipc/ssh.ts +inline src/main/ipc/worktree-remote.ts +inline src/main/ipc/worktrees.test.ts +inline src/main/ipc/worktrees.ts +inline src/main/jira/client.ts +inline src/main/jira/issues.ts +inline src/main/keybindings/keybinding-file.ts +inline src/main/linear/client.ts +inline src/main/linear/issues.ts +inline src/main/linear/projects.ts +inline src/main/memory/collector.ts +inline src/main/opencode-usage/scanner.ts +inline src/main/opencode-usage/store.ts +inline src/main/opencode/hook-service.ts +inline src/main/persistence.test.ts +inline src/main/persistence.ts +inline src/main/ports/advertised-url-watcher.ts +inline src/main/ports/local-workspace-port-scanner.ts +inline src/main/project-groups/nested-repo-discovery.ts +inline src/main/providers/local-pty-provider.test.ts +inline src/main/providers/local-pty-provider.ts +inline src/main/providers/local-pty-shell-ready.test.ts +inline src/main/providers/local-pty-shell-ready.ts +inline src/main/providers/ssh-git-provider.test.ts +inline src/main/providers/ssh-git-provider.ts +inline src/main/rate-limits/claude-fetcher.test.ts +inline src/main/rate-limits/claude-fetcher.ts +inline src/main/rate-limits/claude-pty.ts +inline src/main/rate-limits/codex-fetcher.ts +inline src/main/rate-limits/service.test.ts +inline src/main/rate-limits/service.ts +inline src/main/runtime/orca-runtime-browser.ts +inline src/main/runtime/orca-runtime-files.test.ts +inline src/main/runtime/orca-runtime-files.ts +inline src/main/runtime/orca-runtime-git.ts +inline src/main/runtime/orca-runtime.test.ts +inline src/main/runtime/orca-runtime.ts +inline src/main/runtime/orchestration/coordinator.ts +inline src/main/runtime/orchestration/db.ts +inline src/main/runtime/rpc/methods/files.ts +inline src/main/runtime/rpc/methods/git.ts +inline src/main/runtime/rpc/methods/github.ts +inline src/main/runtime/rpc/methods/orchestration.test.ts +inline src/main/runtime/rpc/methods/orchestration.ts +inline src/main/runtime/rpc/methods/terminal.ts +inline src/main/runtime/rpc/terminal-multiplex.test.ts +inline src/main/runtime/runtime-rpc.test.ts +inline src/main/runtime/runtime-rpc.ts +inline src/main/source-control/hosted-review-creation.ts +inline src/main/speech/model-manager.ts +inline src/main/speech/stt-service.ts +inline src/main/ssh/ssh-channel-multiplexer.ts +inline src/main/ssh/ssh-connection.test.ts +inline src/main/ssh/ssh-connection.ts +inline src/main/ssh/ssh-relay-deploy.ts +inline src/main/ssh/ssh-relay-session.ts +inline src/main/star-nag/service.test.ts +inline src/main/text-generation/commit-message-text-generation.test.ts +inline src/main/text-generation/commit-message-text-generation.ts +inline src/main/updater.test.ts +inline src/main/updater.ts +inline src/main/window/attach-main-window-services.ts +inline src/main/window/createMainWindow.test.ts +inline src/main/window/createMainWindow.ts +inline src/main/workspace-space-analysis.ts +inline src/preload/api-types.ts +inline src/preload/index.ts +inline src/relay/agent-hook-server.ts +inline src/relay/dispatcher.ts +inline src/relay/external-automations-handler.ts +inline src/relay/fs-handler.ts +inline src/relay/git-handler.test.ts +inline src/relay/git-handler.ts +inline src/relay/pty-handler.test.ts +inline src/relay/pty-handler.ts +inline src/relay/relay.ts +inline src/relay/workspace-space-scan.ts +inline src/renderer/src/App.tsx +inline src/renderer/src/components/GitHubItemDialog.tsx +inline src/renderer/src/components/GitLabItemDialog.tsx +inline src/renderer/src/components/JiraIssueWorkspace.tsx +inline src/renderer/src/components/LinearIssueWorkspace.tsx +inline src/renderer/src/components/LinearItemDrawer.tsx +inline src/renderer/src/components/NewWorkspaceComposerCard.tsx +inline src/renderer/src/components/PullRequestPage.tsx +inline src/renderer/src/components/TaskPage.tsx +inline src/renderer/src/components/Terminal.tsx +inline src/renderer/src/components/UpdateCard.tsx +inline src/renderer/src/components/WorktreeJumpPalette.tsx +inline src/renderer/src/components/activity/ActivityPrototypePage.test.ts +inline src/renderer/src/components/activity/ActivityPrototypePage.tsx +inline src/renderer/src/components/automations/AutomationsPage.tsx +inline src/renderer/src/components/browser-pane/BrowserPane.tsx +inline src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx +inline src/renderer/src/components/editor/CombinedDiffViewer.tsx +inline src/renderer/src/components/editor/EditorContent.tsx +inline src/renderer/src/components/editor/IpynbViewer.tsx +inline src/renderer/src/components/editor/MarkdownPreview.tsx +inline src/renderer/src/components/editor/MonacoEditor.tsx +inline src/renderer/src/components/editor/editor-autosave-controller.ts +inline src/renderer/src/components/editor/ipynb-parse.ts +inline src/renderer/src/components/editor/useEditorPanelContentState.ts +inline src/renderer/src/components/feature-wall/BrowserAnimatedVisual.tsx +inline src/renderer/src/components/feature-wall/EditorAnimatedVisual.tsx +inline src/renderer/src/components/feature-wall/WorkbenchAnimatedVisual.tsx +inline src/renderer/src/components/floating-terminal/FloatingTerminalPanel.test.tsx +inline src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx +inline src/renderer/src/components/github-project/ProjectCell.tsx +inline src/renderer/src/components/github-project/ProjectPicker.tsx +inline src/renderer/src/components/github-project/ProjectViewWrapper.tsx +inline src/renderer/src/components/linear-project-view-surfaces.tsx +inline src/renderer/src/components/new-workspace/SmartWorkspaceNameField.tsx +inline src/renderer/src/components/onboarding/use-onboarding-flow.ts +inline src/renderer/src/components/right-sidebar/ChecksPanel.tsx +inline src/renderer/src/components/right-sidebar/FileExplorer.test.tsx +inline src/renderer/src/components/right-sidebar/FileExplorer.tsx +inline src/renderer/src/components/right-sidebar/FileExplorerRow.tsx +inline src/renderer/src/components/right-sidebar/PortsPanel.tsx +inline src/renderer/src/components/right-sidebar/SourceControl.tsx +inline src/renderer/src/components/right-sidebar/checks-panel-content.tsx +inline src/renderer/src/components/right-sidebar/index.tsx +inline src/renderer/src/components/right-sidebar/source-control-dropdown-items.ts +inline src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts +inline src/renderer/src/components/right-sidebar/useFileExplorerDragDrop.ts +inline src/renderer/src/components/settings/AccountsPane.tsx +inline src/renderer/src/components/settings/AgentsPane.tsx +inline src/renderer/src/components/settings/RepositoryHooksSection.tsx +inline src/renderer/src/components/settings/RuntimeEnvironmentsPane.tsx +inline src/renderer/src/components/settings/Settings.tsx +inline src/renderer/src/components/settings/SettingsFormControls.tsx +inline src/renderer/src/components/sidebar/RemoteFileBrowser.tsx +inline src/renderer/src/components/sidebar/WorkspaceKanbanDrawer.tsx +inline src/renderer/src/components/sidebar/WorktreeCard.tsx +inline src/renderer/src/components/sidebar/WorktreeContextMenu.tsx +inline src/renderer/src/components/sidebar/WorktreeList.lineage-child-card.test.ts +inline src/renderer/src/components/sidebar/WorktreeList.tsx +inline src/renderer/src/components/sidebar/use-workspace-kanban-area-selection.ts +inline src/renderer/src/components/sidebar/worktree-list-groups.test.ts +inline src/renderer/src/components/sidebar/worktree-list-groups.ts +inline src/renderer/src/components/stats/usage-overview-model.ts +inline src/renderer/src/components/status-bar/ResourceUsageStatusSegment.tsx +inline src/renderer/src/components/status-bar/StatusBar.tsx +inline src/renderer/src/components/status-bar/WorkspaceSpaceManagerPanel.tsx +inline src/renderer/src/components/tab-bar/TabBar.tsx +inline src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts +inline src/renderer/src/components/tab-group/useTabDragSplit.ts +inline src/renderer/src/components/tab-group/useTabGroupWorkspaceModel.ts +inline src/renderer/src/components/task-page-cache-selectors.ts +inline src/renderer/src/components/terminal-pane/TerminalPane.tsx +inline src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts +inline src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts +inline src/renderer/src/components/terminal-pane/keyboard-handlers.ts +inline src/renderer/src/components/terminal-pane/pty-connection.test.ts +inline src/renderer/src/components/terminal-pane/pty-connection.ts +inline src/renderer/src/components/terminal-pane/pty-transport.test.ts +inline src/renderer/src/components/terminal-pane/pty-transport.ts +inline src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts +inline src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts +inline src/renderer/src/components/terminal-pane/terminal-link-handlers.test.ts +inline src/renderer/src/components/terminal-pane/use-terminal-pane-context-menu.ts +inline src/renderer/src/components/terminal-pane/use-terminal-pane-global-effects.test.ts +inline src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts +inline src/renderer/src/components/workspace-cleanup/WorkspaceCleanupDialog.tsx +inline src/renderer/src/hooks/useAutomationDispatchEvents.ts +inline src/renderer/src/hooks/useComposerState.ts +inline src/renderer/src/hooks/useEditorExternalWatch.ts +inline src/renderer/src/hooks/useIpcEvents.test.ts +inline src/renderer/src/hooks/useIpcEvents.ts +inline src/renderer/src/hooks/useIssueMetadata.ts +inline src/renderer/src/hooks/useSettingsNavigationMetadata.ts +inline src/renderer/src/lib/active-agent-note-send.test.ts +inline src/renderer/src/lib/file-type-icons.ts +inline src/renderer/src/lib/pane-manager/pane-manager.ts +inline src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.test.ts +inline src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts +inline src/renderer/src/lib/pane-manager/pane-tree-ops.ts +inline src/renderer/src/lib/terminal-links.ts +inline src/renderer/src/lib/worktree-activation.test.ts +inline src/renderer/src/lib/worktree-activation.ts +inline src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts +inline src/renderer/src/runtime/runtime-file-client.test.ts +inline src/renderer/src/runtime/runtime-file-client.ts +inline src/renderer/src/runtime/runtime-git-client.ts +inline src/renderer/src/runtime/runtime-linear-client.ts +inline src/renderer/src/runtime/sync-runtime-graph.test.ts +inline src/renderer/src/runtime/sync-runtime-graph.ts +inline src/renderer/src/runtime/web-runtime-session.test.ts +inline src/renderer/src/runtime/web-runtime-session.ts +inline src/renderer/src/runtime/web-session-tabs-sync.test.ts +inline src/renderer/src/runtime/web-session-tabs-sync.ts +inline src/renderer/src/store/slices/agent-status.test.ts +inline src/renderer/src/store/slices/agent-status.ts +inline src/renderer/src/store/slices/browser.test.ts +inline src/renderer/src/store/slices/browser.ts +inline src/renderer/src/store/slices/diffComments.ts +inline src/renderer/src/store/slices/editor.test.ts +inline src/renderer/src/store/slices/editor.ts +inline src/renderer/src/store/slices/github.test.ts +inline src/renderer/src/store/slices/github.ts +inline src/renderer/src/store/slices/hosted-review.ts +inline src/renderer/src/store/slices/jira.ts +inline src/renderer/src/store/slices/linear.test.ts +inline src/renderer/src/store/slices/linear.ts +inline src/renderer/src/store/slices/repos.ts +inline src/renderer/src/store/slices/store-cascades.test.ts +inline src/renderer/src/store/slices/store-session-cascades.test.ts +inline src/renderer/src/store/slices/tabs.test.ts +inline src/renderer/src/store/slices/tabs.ts +inline src/renderer/src/store/slices/terminals.ts +inline src/renderer/src/store/slices/ui.test.ts +inline src/renderer/src/store/slices/ui.ts +inline src/renderer/src/store/slices/workspace-cleanup.ts +inline src/renderer/src/store/slices/worktrees.test.ts +inline src/renderer/src/store/slices/worktrees.ts +inline src/renderer/src/web/web-preload-api.test.ts +inline src/renderer/src/web/web-preload-api.ts +inline src/renderer/src/web/web-runtime-client.ts +inline src/shared/agent-hook-listener.test.ts +inline src/shared/agent-hook-listener.ts +inline src/shared/automation-schedules.ts +inline src/shared/commit-message-agent-spec.ts +inline src/shared/constants.ts +inline src/shared/github-project-types.ts +inline src/shared/keybindings.test.ts +inline src/shared/keybindings.ts +inline src/shared/marine-creatures.ts +inline src/shared/remote-runtime-client.ts +inline src/shared/runtime-types.ts +inline src/shared/source-control-ai.ts +inline src/shared/telemetry-events.ts +inline src/shared/text-search.ts +inline src/shared/types.ts +inline tests/e2e/helpers/terminal.ts +inline tests/e2e/terminal-panes.spec.ts +mobile-config app/h/*/files/*.tsx +mobile-config app/h/*/index.tsx +mobile-config app/h/*/session/*.tsx +mobile-config app/h/*/source-control/*.tsx +mobile-config app/h/*/tasks.tsx +mobile-config app/index.tsx +mobile-config app/pair-scan.tsx +mobile-config app/terminal-settings.tsx +mobile-config app/troubleshoot.tsx +mobile-config scripts/mock-server.ts +mobile-config scripts/repro-terminal-colors.ts +mobile-config scripts/repro-worktree-startup-stream.ts +mobile-config src/browser/MobileBrowserPane.tsx +mobile-config src/components/CustomKeyModal.tsx +mobile-config src/components/NewWorktreeModal.tsx +mobile-config src/components/mobile-rich-markdown-editor-html.ts +mobile-config src/terminal/terminal-accessory-keys.ts +mobile-config src/terminal/terminal-webview-html.ts +mobile-config src/transport/rpc-client.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index bd90a3370..bdabd2a7b 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -458,6 +458,97 @@ ], "demotionRule": "Cannot promote while it only checks visual rendering." }, + { + "id": "terminal-scroll.intent-preservation", + "title": "Scrollbar drag intent survives tab and visibility resume", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-rendering", + "layer": "renderer-unit", + "surfaces": [ + "terminal lifecycle", + "hidden-to-visible resume", + "tab switching", + "xterm scrollbar DOM", + "scrollback" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon", + "ssh", + "wsl", + "remote-runtime" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [], + "coverageNotes": "Renderer-unit coverage proves the shared xterm DOM intent path. Live Electron evidence is PR validation evidence for local macOS only until the flow has stable automation; live SSH, WSL, Linux, and Windows paths remain unproved.", + "motivatingLinks": [ + "STA-1341" + ], + "invariant": "A user-driven xterm scrollbar thumb or track scroll updates the live terminal scroll intent before tab, visibility, or layout resume enforces intent, so resume preserves the latest dragged viewport instead of an older pinned line.", + "oracle": "Pointerdown on .xterm-scrollbar or .xterm-slider followed by xterm viewport movement records the new pinned viewport, and enforcing current intent restores that dragged line instead of stale top intent.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts" + ], + "testFiles": [ + "src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts" + ], + "assertionRefs": [ + { + "file": "src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts", + "assertions": [ + "pointer-driven .xterm-scrollbar and .xterm-slider scrolls update terminal scroll intent", + "a scrollbar-dragged viewport is restored instead of stale top intent", + "terminal body pointer activity is not treated as scrollbar intent" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-05", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts", + "result": "passed", + "durationSeconds": 0.3, + "summary": "1 test file(s) passed, 17 tests passed in this worktree." + } + ], + "runtimeBudget": { + "p95Seconds": 10, + "scope": "focused renderer unit test" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "New experimental gate; needs soak history before promotion." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "The new scrollbar DOM target assertions fail when only .xterm-viewport pointerdown is recognized. Needs saved CI/intentional-break artifact before blocking promotion." + }, + "performanceBudget": { + "required": true, + "evidence": "Runtime fix is limited to constant-time class/closest checks on pointerdown. It must not add polling, output parsing, PTY listing, hidden-pane wakeups, resize calls, or startup awaits." + }, + "promotionCriteria": [ + "Collect stable CI soak history for the renderer-unit gate.", + "Add stable live Electron automation for the scrollbar drag plus tab-switch repro.", + "Attach red/green evidence for stale intent restoring the wrong viewport." + ], + "knownGaps": [ + "Manifest command is deterministic renderer-unit coverage, not a live Electron scrollbar drag.", + "Live daemon, SSH, WSL, remote-runtime, Linux, and Windows validation is not covered by this gate.", + "Future xterm scrollbar DOM class changes are only caught if they break the currently modeled class contract." + ], + "demotionRule": "Demote or quarantine if the unit gate flakes without a product bug or harness bug filed to the owner." + }, { "id": "startup-upgrade.persisted-session-corpus", "title": "Current Orca preserves or recovers old production persisted sessions", diff --git a/config/scripts/check-max-lines-ratchet.mjs b/config/scripts/check-max-lines-ratchet.mjs new file mode 100644 index 000000000..d4e8b9fa0 --- /dev/null +++ b/config/scripts/check-max-lines-ratchet.mjs @@ -0,0 +1,254 @@ +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import path from 'node:path' +import process from 'node:process' +import { pathToFileURL } from 'node:url' + +// Ratchet gate for the oxlint `max-lines` rule. +// +// oxlint already fails any file that exceeds max-lines WITHOUT a suppression, so +// the only way a file grows past the budget is by adding an `eslint/oxlint-disable +// max-lines` comment or a per-file `max-lines` bump in mobile/.oxlintrc.json. This +// check freezes the set of files currently allowed to do that (the baseline) and +// fails CI when a NEW bypass appears — the existing over-limit files are +// grandfathered; new ones must split instead. The baseline may only shrink. + +const BASELINE_PATH = 'config/max-lines-baseline.txt' +const MOBILE_CONFIG_PATH = 'mobile/.oxlintrc.json' +// These two files legitimately contain the directive text as data (regex, fixtures), +// so scanning them would self-flag. The ratchet does not police itself. +const SELF_FILES = new Set([ + 'config/scripts/check-max-lines-ratchet.mjs', + 'config/scripts/check-max-lines-ratchet.test.mjs' +]) + +// Default max-lines budgets from .oxlintrc.json (counted lines). +export function defaultLimitForPath(p) { + if (/\.(test|spec)\.(ts|tsx)$/.test(p)) { + return 800 + } + if (p.endsWith('.tsx')) { + return 400 + } + if (p.endsWith('.mjs')) { + return 600 + } + return 300 +} + +// True if the source contains an eslint/oxlint disable directive listing `max-lines` +// (block or line, bare or compound, with or without a `-- Why:` reason). +export function hasMaxLinesDisable(sourceText) { + const re = /(?:eslint|oxlint)-disable(?:-next-line|-line)?\b([^\n]*)/g + let m + while ((m = re.exec(sourceText)) !== null) { + let rules = m[1] + rules = rules.split('--')[0] // strip the reason + const close = rules.indexOf('*/') + if (close !== -1) { + rules = rules.slice(0, close) // strip block-comment tail + } + if (/\bmax-lines\b/.test(rules)) { + return true + } + } + return false +} + +// Per-file `max-lines` bumps in mobile/.oxlintrc.json whose `max` exceeds the +// default for that glob (a lower `max` is stricter, not a bypass). +export function collectMobileBumps(configText) { + const cfg = JSON.parse(configText) + const bumps = [] + for (const override of cfg.overrides ?? []) { + const rule = override.rules?.['max-lines'] + if (!Array.isArray(rule) || typeof rule[1]?.max !== 'number') { + continue + } + for (const glob of override.files ?? []) { + if (rule[1].max > defaultLimitForPath(glob)) { + bumps.push(`mobile-config ${glob}`) + } + } + } + return bumps +} + +export function parseBaseline(text) { + return new Set( + text + .split('\n') + .map((l) => l.trim()) + .filter((l) => l && !l.startsWith('#')) + ) +} + +export function diffBaseline(current, baseline) { + const cur = new Set(current) + const base = baseline instanceof Set ? baseline : new Set(baseline) + const added = [...cur].filter((e) => !base.has(e)).sort() + const stale = [...base].filter((e) => !cur.has(e)).sort() + return { added, stale } +} + +// Collect every current suppression entry from the tracked tree. +export function collectCurrentSuppressions(root = process.cwd()) { + const tracked = execFileSync('git', ['ls-files', '*.ts', '*.tsx', '*.mjs'], { + cwd: root, + encoding: 'utf8', + maxBuffer: 64 * 1024 * 1024 + }) + .split('\n') + .filter(Boolean) + .filter((f) => !SELF_FILES.has(f)) + + const entries = [] + for (const rel of tracked) { + let src + try { + src = fs.readFileSync(path.join(root, rel), 'utf8') + } catch { + continue + } + if (hasMaxLinesDisable(src)) { + entries.push(`inline ${rel}`) + } + } + + const mobileCfgPath = path.join(root, MOBILE_CONFIG_PATH) + if (fs.existsSync(mobileCfgPath)) { + entries.push(...collectMobileBumps(fs.readFileSync(mobileCfgPath, 'utf8'))) + } + + return entries.sort() +} + +function printAddedFailure(added) { + for (const entry of added) { + console.error(`::error::New max-lines bypass not allowed: ${entry}`) + } + console.error('') + console.error('╭────────────────────────────────────────────────────────────────────────────╮') + console.error('│ ❌ max-lines ratchet failed — a NEW file is trying to exceed the line cap. │') + console.error('╰────────────────────────────────────────────────────────────────────────────╯') + console.error('') + console.error(` ${added.length} file(s)/glob(s) newly bypass the oxlint \`max-lines\` rule:`) + console.error('') + for (const entry of added) { + const [kind, ...rest] = entry.split(' ') + const target = rest.join(' ') + const how = + kind === 'inline' + ? 'added an eslint/oxlint-disable max-lines comment' + : 'added a per-file max-lines bump in mobile/.oxlintrc.json' + console.error(` • ${target}\n ↳ ${how}`) + } + console.error('') + console.error(' Orca caps file size (300 .ts / 400 .tsx / 600 .mjs / 800 test — non-blank,') + console.error( + ' non-comment lines). Existing oversized files are grandfathered; NEW ones are not.' + ) + console.error('') + console.error(' ✅ Fix it: SPLIT the file into focused modules — do NOT suppress the rule.') + console.error(' See AGENTS.md → "Lint Rules: Do Not Disable Max Lines".') + console.error('') + console.error(' (If you are intentionally, with reviewer sign-off, adding an unavoidable') + console.error(` exception, add the exact line(s) above to ${BASELINE_PATH}.)`) + console.error('') +} + +function printStaleFailure(stale) { + for (const entry of stale) { + console.error(`::error::Stale max-lines baseline entry (prune it): ${entry}`) + } + console.error('') + console.error('╭────────────────────────────────────────────────────────────────────────────╮') + console.error('│ ⚠️ max-lines baseline is out of date — nice work removing a bypass! │') + console.error('╰────────────────────────────────────────────────────────────────────────────╯') + console.error('') + console.error(` ${stale.length} baseline entr(y/ies) no longer have a max-lines suppression.`) + console.error( + ' The baseline may only shrink, so these must be removed to keep re-adding blocked:' + ) + console.error('') + for (const entry of stale) { + console.error(` • ${entry}`) + } + console.error('') + console.error(` ✅ Fix it (one command): pnpm check:max-lines-ratchet --prune`) + console.error('') +} + +export function main(root = process.cwd()) { + const baselineFile = path.join(root, BASELINE_PATH) + if (!fs.existsSync(baselineFile)) { + console.error( + `::error::Missing ${BASELINE_PATH}. Generate it with: node config/scripts/check-max-lines-ratchet.mjs --init` + ) + return 1 + } + const baseline = parseBaseline(fs.readFileSync(baselineFile, 'utf8')) + const current = collectCurrentSuppressions(root) + const { added, stale } = diffBaseline(current, baseline) + + if (added.length > 0) { + printAddedFailure(added) + if (stale.length > 0) { + console.error( + ` (Also: ${stale.length} stale baseline entr(y/ies) can be pruned — see below.)` + ) + printStaleFailure(stale) + } + return 1 + } + if (stale.length > 0) { + printStaleFailure(stale) + return 1 + } + console.log( + `max-lines ratchet OK — ${current.length} grandfathered suppression(s), no new bypasses.` + ) + return 0 +} + +function writeBaseline(root, entries) { + const header = [ + '# Files/globs currently allowed to exceed the oxlint `max-lines` budget.', + '# This is a RATCHET: the list may only SHRINK. Do NOT add entries to get CI green —', + '# split the oversized file instead (AGENTS.md → "Do Not Disable Max Lines").', + '# Regenerate/prune: pnpm check:max-lines-ratchet --prune (removes stale entries only)', + '' + ].join('\n') + fs.writeFileSync(path.join(root, BASELINE_PATH), `${header}${entries.join('\n')}\n`) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const root = process.cwd() + const arg = process.argv[2] + if (arg === '--init') { + // One-time bootstrap: capture the current suppression set as the baseline. + const entries = collectCurrentSuppressions(root) + writeBaseline(root, entries) + console.log(`Wrote ${BASELINE_PATH} with ${entries.length} entries.`) + process.exit(0) + } + if (arg === '--prune') { + // Remove baseline entries whose suppression is gone (shrink only; never adds). + const current = new Set(collectCurrentSuppressions(root)) + const baseline = parseBaseline(fs.readFileSync(path.join(root, BASELINE_PATH), 'utf8')) + const kept = [...baseline].filter((e) => current.has(e)).sort() + const newlyAdded = [...current].filter((e) => !baseline.has(e)) + writeBaseline(root, kept) + console.log( + `Pruned baseline to ${kept.length} entries (removed ${baseline.size - kept.length}).` + ) + if (newlyAdded.length > 0) { + console.error( + `::error::--prune does not add entries; ${newlyAdded.length} new bypass(es) remain — split those files.` + ) + process.exit(1) + } + process.exit(0) + } + process.exit(main(root)) +} diff --git a/config/scripts/check-max-lines-ratchet.test.mjs b/config/scripts/check-max-lines-ratchet.test.mjs new file mode 100644 index 000000000..f1eb41834 --- /dev/null +++ b/config/scripts/check-max-lines-ratchet.test.mjs @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest' + +import { + collectMobileBumps, + defaultLimitForPath, + diffBaseline, + hasMaxLinesDisable, + parseBaseline +} from './check-max-lines-ratchet.mjs' + +describe('hasMaxLinesDisable', () => { + it('detects a bare block disable', () => { + expect(hasMaxLinesDisable('/* eslint-disable max-lines */\nexport const a = 1\n')).toBe(true) + }) + + it('detects the oxlint spelling', () => { + expect(hasMaxLinesDisable('/* oxlint-disable max-lines */\n')).toBe(true) + }) + + it('detects a disable with a -- Why reason', () => { + expect(hasMaxLinesDisable('/* eslint-disable max-lines -- Why: one owner. */\n')).toBe(true) + }) + + it('detects a multi-line block where the reason wraps', () => { + const src = + '/* eslint-disable max-lines -- Why: this contract is\n * intentionally centralized. */\nimport x from "y"\n' + expect(hasMaxLinesDisable(src)).toBe(true) + }) + + it('detects max-lines inside a compound rule list', () => { + expect(hasMaxLinesDisable('/* eslint-disable no-control-regex, max-lines -- Why: x */\n')).toBe( + true + ) + expect(hasMaxLinesDisable('/* eslint-disable max-lines, no-control-regex */\n')).toBe(true) + }) + + it('detects a line-scoped disable', () => { + expect(hasMaxLinesDisable('const a = 1 // eslint-disable-line max-lines\n')).toBe(true) + }) + + it('ignores a disable for an unrelated rule', () => { + expect(hasMaxLinesDisable('/* eslint-disable no-console */\n')).toBe(false) + }) + + it('does not treat "max-lines" appearing only in the reason text as a suppression', () => { + // max-lines is after the `--`, so it is prose, not a suppressed rule. + expect( + hasMaxLinesDisable('/* eslint-disable no-console -- we could hit max-lines later */\n') + ).toBe(false) + }) + + it('returns false for ordinary source', () => { + expect(hasMaxLinesDisable('export function f() {\n return 42\n}\n')).toBe(false) + }) +}) + +describe('defaultLimitForPath', () => { + it('uses 800 for tests, 400 for tsx, 600 for mjs, 300 otherwise', () => { + expect(defaultLimitForPath('a/b.test.ts')).toBe(800) + expect(defaultLimitForPath('a/b.spec.tsx')).toBe(800) + expect(defaultLimitForPath('a/b.tsx')).toBe(400) + expect(defaultLimitForPath('a/b.mjs')).toBe(600) + expect(defaultLimitForPath('a/b.ts')).toBe(300) + }) +}) + +describe('collectMobileBumps', () => { + it('captures only overrides whose max exceeds the default for the glob', () => { + const cfg = JSON.stringify({ + overrides: [ + { files: ['app/h/*/tasks.tsx'], rules: { 'max-lines': ['error', { max: 14682 }] } }, // bump (>400) + { + files: ['src/terminal/TerminalWebView.tsx'], + rules: { 'max-lines': ['error', { max: 379 }] } + }, // stricter (<400), skip + { files: ['scripts/mock-server.ts'], rules: { 'max-lines': ['error', { max: 407 }] } } // bump (>300) + ] + }) + expect(collectMobileBumps(cfg)).toEqual([ + 'mobile-config app/h/*/tasks.tsx', + 'mobile-config scripts/mock-server.ts' + ]) + }) + + it('ignores overrides without a max-lines rule', () => { + const cfg = JSON.stringify({ + overrides: [{ files: ['a.tsx'], rules: { 'no-console': 'off' } }] + }) + expect(collectMobileBumps(cfg)).toEqual([]) + }) +}) + +describe('parseBaseline', () => { + it('drops comments and blank lines', () => { + const b = parseBaseline('# header\n\ninline a.ts\nmobile-config x/*.tsx\n') + expect(b).toEqual(new Set(['inline a.ts', 'mobile-config x/*.tsx'])) + }) +}) + +describe('diffBaseline', () => { + it('reports added and stale entries', () => { + const { added, stale } = diffBaseline( + ['inline b.ts', 'inline c.ts'], + new Set(['inline a.ts', 'inline b.ts']) + ) + expect(added).toEqual(['inline c.ts']) // new bypass + expect(stale).toEqual(['inline a.ts']) // suppression removed + }) + + it('is clean when current matches baseline', () => { + const { added, stale } = diffBaseline(['inline a.ts'], new Set(['inline a.ts'])) + expect(added).toEqual([]) + expect(stale).toEqual([]) + }) +}) diff --git a/docs/assets/readme-downloads.svg b/docs/assets/readme-downloads.svg index abc2d902e..3f124029e 100644 --- a/docs/assets/readme-downloads.svg +++ b/docs/assets/readme-downloads.svg @@ -1,5 +1,5 @@ - - downloads: 3.6m + + downloads: 3.7m @@ -15,7 +15,7 @@ downloads downloads - 3.6m - 3.6m + 3.7m + 3.7m diff --git a/docs/reference/ssh-typing-latency-under-relay-load.md b/docs/reference/ssh-typing-latency-under-relay-load.md new file mode 100644 index 000000000..f7ae8e0b3 --- /dev/null +++ b/docs/reference/ssh-typing-latency-under-relay-load.md @@ -0,0 +1,115 @@ +# SSH Typing Latency Under Relay Load + +Date: 2026-07-06 + +## Symptom + +Typing in an SSH-host terminal can become extremely slow (hundreds of ms to +seconds per echoed keystroke) while other SSH work is active — file previews, +source-control refresh, search. A quiet SSH shell stays snappy, which made the +reports look unreproducible. + +This is distinct from the local warm-switch lag documented in +`terminal-switch-typing-lag-investigation.md` (daemon `listSessions()` +snapshot cost — already fixed; `TerminalHost.listSessions()` is now +metadata-only via `getAppliedSize()`). + +## Root Cause + +The relay and the Electron client share ONE ordered SSH channel for all +JSON-RPC traffic: PTY input/output, file streams, git responses, search, port +scans. Two mechanisms turned bulk traffic into typing latency: + +1. **Relay-side head-of-line blocking (primary).** The `fs.readFileStream` + pump (`src/relay/fs-handler-file-read.ts`) wrote every 256KB chunk (~340KB + framed) into the relay's stdout as fast as local disk reads completed, + ignoring the `write() === false` backpressure signal. A 10MB preview + enqueued ~13.6MB into the pipe at once; a `pty.data` echo emitted + mid-stream queued behind ALL of it. At 2MB/s WAN that is multiple seconds + of echo delay per open file. The reproduced measurement: 4,195,592 bytes + (the entire remaining 3MB test file, framed) queued ahead of one echo + frame. + +2. **Client-side O(n²) frame buffering (secondary).** `FrameDecoder.feed()` + in both `src/main/ssh/relay-protocol.ts` and `src/relay/protocol.ts` did + `Buffer.concat([buffered, chunk])` per data event, re-copying the whole + backlog for every ~32KB TCP chunk — ~2MB of memcpy per 340KB frame, + ~80MB per 10MB file — on the Electron main thread, delaying `pty:write` + IPC dispatch and echo delivery to the renderer. + +## Fix + +- **Bulk lane with sink backpressure** (`RelayDispatcher.notifyBulk`): + `fs.streamChunk` frames are serialized per client and each send waits for + the sink's `drain` when `write()` returns `false`. Interactive frames + (`pty.data`) still use plain `notify()` and are admitted immediately — + because the bulk lane keeps the outbound buffer at ~1 frame, an echo jumps + ahead of every not-yet-admitted chunk. Sinks (`relay.ts` stdout + Unix + socket clients) surface `write()`'s boolean and a one-shot + `waitWriteDrain`; every death path (EPIPE, stdin end, detach, dispose) + flushes parked waiters so a pump can never hang on a dead pipe. + +- **Credit-based flow control** (`fs.streamAck`): the client requests + streams with `flowControl: 'ack'` and acks each processed chunk; the relay + caps unacked chunks at `STREAM_ACK_WINDOW_CHUNKS = 4` (~1MB raw). This + bounds in-flight bulk bytes even past the relay's own pipe (sshd/TCP + buffers) and paces the relay's base64/JSON encode loop so incoming + keystroke frames get event-loop turns. A parked pump wakes on ack, cancel, + release, client detach, and a 1s staleness recheck. + +- **Cross-version compatibility**: old client + new relay → no + `flowControl` param → legacy unpaced pump (still drain-bounded, which is + transparent). New client + old relay → `fs.streamAck` is an unknown + notification and is silently ignored. `STREAM_CHUNK_SIZE` (256KB) is + intentionally unchanged — both sides bake it into chunk offset math, so + changing it would corrupt cross-version streams. + +- **FrameDecoder rewrite** (both mirrored protocol files): chunk-list + buffering; each frame is assembled exactly once (one copy) instead of + re-concatenating the backlog per feed. + +## What Stays Fast / Unchanged + +- Relay PTY output batching (interactive echo fast path in + `src/relay/pty-handler.ts`) is untouched. +- No `listSessions()` / provider inventory was added anywhere near typing, + focus, switch, resume, resize, or render paths. +- Remote file streaming correctness: per-chunk length checks, chunk-count and + byte-count invariants, cancel paths, and the 12MB round-trip integration + test all pass unchanged. + +## Regression Coverage + +- `src/relay/fs-stream-pty-echo-backpressure.integration.test.ts` — real + mux ↔ dispatcher ↔ FsHandler over a congestible in-memory pipe; asserts + deterministic BYTE bounds (not wall-clock): echo queues behind < 2 framed + chunks when congested (pre-fix: whole file), ack window caps in-flight + chunks, legacy no-ack clients still get complete streams. +- `src/relay/fs-handler-stream.test.ts` — pump parks at the ack window, + resumes per ack, and releases its file handle when cancelled while parked. +- `src/relay/dispatcher.test.ts` — notifyBulk semantics: drain gating, + per-client targeting, dispose releases parked senders, interactive + notify() not gated behind a stalled bulk lane. +- `src/main/ssh/relay-protocol.test.ts` — decoder byte-at-a-time boundary + straddling, oversized-frame resync across odd chunk sizes, and a + no-`Buffer.concat`-during-feed guard that locks out the O(n²) shape. +- `tests/e2e/ssh-docker-relay-perf.spec.ts` — new "busy relay" scenario: + types while two 8MB remote file-read loops and a git.status loop run; + budgets median < 500ms, worst < 2000ms. (On loopback Docker the pre-fix + HOL is only tens of ms — the in-process byte-bound test is the + authoritative red/green; the e2e guards the end-to-end wiring.) + +## Residual Gaps + +- **Large single-frame responses**: `git.*` responses (stdout capped at + `MAX_GIT_BUFFER` = 10MB → ~13MB framed) and other request/response results + are one atomic frame on the wire; a huge diff can still delay an echo by + its own transfer time. Fixing this requires response chunking (a protocol + change); bounded by the 16MB `MAX_MESSAGE_SIZE`. +- **Outbound direction**: a large `fs.writeFile` request frame (client → + relay) can queue ahead of keystroke `pty.data` frames on `channel.stdin`. + Same shape, opposite direction, rarer trigger (saving a large remote file + while typing). +- `pty.ackData` flow control for PTY output remains unenforced + (`src/relay/pty-handler.ts` — "not yet enforced"); PTY output floods are + already paced by the relay's 8ms batch/16KB slice scheduler. diff --git a/mobile/app.json b/mobile/app.json index 27d3b7d88..b50147f04 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -2,7 +2,7 @@ "expo": { "name": "Orca", "slug": "orca-mobile", - "version": "0.0.22", + "version": "0.0.24", "orientation": "default", "icon": "./assets/icon.png", "userInterfaceStyle": "automatic", @@ -75,7 +75,7 @@ "allowBackup": false, "permissions": ["RECORD_AUDIO", "MODIFY_AUDIO_SETTINGS"], "package": "com.stably.orca.mobile", - "versionCode": 4 + "versionCode": 5 }, "plugins": [ "expo-router", diff --git a/mobile/scripts/mock-server-file-preview-data.ts b/mobile/scripts/mock-server-file-preview-data.ts index a64c76eda..9bf43471d 100644 --- a/mobile/scripts/mock-server-file-preview-data.ts +++ b/mobile/scripts/mock-server-file-preview-data.ts @@ -21,6 +21,31 @@ const MOCK_FILE_LIST = [ { relativePath: 'dist/archive.zip', basename: 'archive.zip', kind: 'binary' } ] +function readMockDirectory(relativePath: string): Array<{ name: string; isDirectory: boolean }> { + const prefix = relativePath ? `${relativePath}/` : '' + const children = new Map() + for (const file of MOCK_FILE_LIST) { + if (!file.relativePath.startsWith(prefix)) { + continue + } + const rest = file.relativePath.slice(prefix.length) + if (!rest) { + continue + } + const [name, ...descendants] = rest.split('/') + if (!name) { + continue + } + children.set(name, children.get(name) === true || descendants.length > 0) + } + return Array.from(children, ([name, isDirectory]) => ({ name, isDirectory })).sort((a, b) => { + if (a.isDirectory !== b.isDirectory) { + return a.isDirectory ? -1 : 1 + } + return a.name.localeCompare(b.name) + }) +} + export function handleMockFilePreviewRequest( request: RpcRequest, respond: Respond, @@ -40,6 +65,10 @@ export function handleMockFilePreviewRequest( ) return true + case 'files.readDir': + respond(success(request.id, readMockDirectory(String(request.params?.relativePath ?? '')))) + return true + case 'files.read': { const relativePath = String(request.params?.relativePath ?? '') const content = MOCK_FILE_CONTENT[relativePath] diff --git a/mobile/src/files/MobileFileExplorerPanel.test.ts b/mobile/src/files/MobileFileExplorerPanel.test.ts new file mode 100644 index 000000000..0d003e9f4 --- /dev/null +++ b/mobile/src/files/MobileFileExplorerPanel.test.ts @@ -0,0 +1,398 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { MobileFileExplorerPanel } from './MobileFileExplorerPanel' +import type { MobileDirEntry } from './file-tree' +import type { RpcResponse } from '../transport/types' + +type MockClient = { + sendRequest: ReturnType +} + +const mockTransport = vi.hoisted(() => ({ + client: null as MockClient | null, + connectionState: 'connected', + forceReconnect: vi.fn() +})) + +vi.mock('react-native', async () => { + const React = await import('react') + return { + ActivityIndicator: 'ActivityIndicator', + FlatList: (props: { + data: unknown[] + keyExtractor: (item: unknown, index: number) => string + renderItem: (info: { + item: unknown + index: number + separators: Record + }) => unknown + }) => + React.createElement( + 'FlatList', + props, + props.data.map((item, index) => + React.createElement( + 'FlatListItem', + { key: props.keyExtractor(item, index) }, + props.renderItem({ item, index, separators: {} }) + ) + ) + ), + Pressable: 'Pressable', + StyleSheet: { + create: (styles: unknown) => styles, + hairlineWidth: 1 + }, + Text: 'Text', + View: 'View' + } +}) + +vi.mock('react-native-safe-area-context', () => ({ + SafeAreaView: 'SafeAreaView' +})) + +vi.mock('expo-router', () => ({ + useRouter: () => ({ + back: vi.fn(), + push: vi.fn() + }) +})) + +vi.mock('lucide-react-native', () => ({ + ChevronDown: 'ChevronDown', + ChevronLeft: 'ChevronLeft', + ChevronRight: 'ChevronRight', + File: 'File', + FileText: 'FileText', + Folder: 'Folder', + Image: 'Image', + X: 'X' +})) + +vi.mock('../platform/haptics', () => ({ + triggerSelection: vi.fn() +})) + +vi.mock('../transport/client-context', () => ({ + useForceReconnect: () => mockTransport.forceReconnect, + useHostClient: () => ({ + client: mockTransport.client, + state: mockTransport.connectionState + }) +})) + +function suppressReactTestRendererDeprecationWarning(): () => void { + const originalConsoleError = console.error + const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation((...args) => { + const firstArg = args[0] + if (typeof firstArg === 'string' && firstArg.includes('react-test-renderer is deprecated')) { + return + } + originalConsoleError(...args) + }) + return () => consoleErrorSpy.mockRestore() +} + +function entry(name: string, isDirectory = false): MobileDirEntry { + return { name, isDirectory } +} + +function ok(result: MobileDirEntry[]): RpcResponse { + return { id: 'response-id', ok: true, result, _meta: { runtimeId: 'runtime-id' } } +} + +function createMockClient(entriesByPath: Record): MockClient { + return { + sendRequest: vi.fn(async (_method: string, params: { relativePath: string }) => { + return ok(entriesByPath[params.relativePath] ?? []) + }) + } +} + +async function renderExplorer(): Promise { + let renderer: ReactTestRenderer | null = null + const restoreConsoleError = suppressReactTestRendererDeprecationWarning() + try { + await act(async () => { + renderer = create( + createElement(MobileFileExplorerPanel, { + hostId: 'host-a', + worktreeId: 'worktree-a', + name: 'Example Worktree', + embedded: true + }) + ) + }) + } finally { + restoreConsoleError() + } + if (!renderer) { + throw new Error('MobileFileExplorerPanel did not render') + } + return renderer +} + +async function updateExplorer(renderer: ReactTestRenderer): Promise { + await act(async () => { + renderer.update( + createElement(MobileFileExplorerPanel, { + hostId: 'host-a', + worktreeId: 'worktree-a', + name: 'Example Worktree', + embedded: true + }) + ) + }) +} + +async function pressByLabel( + renderer: ReactTestRenderer, + accessibilityLabel: string +): Promise { + const pressable = renderer.root + .findAllByType('Pressable') + .find((node) => node.props.accessibilityLabel === accessibilityLabel) + if (!pressable) { + throw new Error(`Unable to find pressable: ${accessibilityLabel}`) + } + await act(async () => { + pressable.props.onPress() + }) +} + +function renderedText(renderer: ReactTestRenderer): string { + return renderer.root + .findAllByType('Text') + .flatMap((node) => node.props.children) + .join(' ') +} + +describe('MobileFileExplorerPanel', () => { + afterEach(() => { + vi.restoreAllMocks() + mockTransport.client = null + mockTransport.connectionState = 'connected' + mockTransport.forceReconnect = vi.fn() + }) + + it('loads directories lazily and reuses cached children when reopened', async () => { + const client = createMockClient({ + '': [entry('src', true), entry('README.md')], + src: [entry('app.ts'), entry('components', true)] + }) + mockTransport.client = client + + const renderer = await renderExplorer() + + expect(client.sendRequest).toHaveBeenCalledTimes(1) + expect(client.sendRequest).toHaveBeenLastCalledWith('files.readDir', { + worktree: 'id:worktree-a', + relativePath: '' + }) + + await pressByLabel(renderer, 'Open folder src') + await vi.waitFor(() => expect(client.sendRequest).toHaveBeenCalledTimes(2)) + expect(client.sendRequest).toHaveBeenLastCalledWith('files.readDir', { + worktree: 'id:worktree-a', + relativePath: 'src' + }) + expect(renderedText(renderer)).toContain('app.ts') + + await pressByLabel(renderer, 'Open folder src') + await pressByLabel(renderer, 'Open folder src') + + expect(client.sendRequest).toHaveBeenCalledTimes(2) + }) + + it('keeps the loaded tree visible during a transient disconnect', async () => { + const client = createMockClient({ + '': [entry('src', true), entry('README.md')] + }) + mockTransport.client = client + + const renderer = await renderExplorer() + expect(renderedText(renderer)).toContain('src') + + mockTransport.client = null + mockTransport.connectionState = 'disconnected' + await updateExplorer(renderer) + + expect(client.sendRequest).toHaveBeenCalledTimes(1) + expect(renderedText(renderer)).toContain('src') + expect(renderedText(renderer)).toContain('README.md') + expect(renderedText(renderer)).not.toContain('Waiting for desktop...') + }) + + it('refreshes the root in the background after reconnect without blanking the tree', async () => { + const client = createMockClient({ + '': [entry('src', true), entry('README.md')] + }) + mockTransport.client = client + + const renderer = await renderExplorer() + expect(renderedText(renderer)).toContain('README.md') + + mockTransport.client = null + mockTransport.connectionState = 'disconnected' + await updateExplorer(renderer) + + let resolveReload: ((response: RpcResponse) => void) | undefined + const reconnectedClient: MockClient = { + sendRequest: vi.fn( + () => + new Promise((resolve) => { + resolveReload = resolve + }) + ) + } + mockTransport.client = reconnectedClient + mockTransport.connectionState = 'connected' + await updateExplorer(renderer) + + expect(reconnectedClient.sendRequest).toHaveBeenCalledTimes(1) + expect(renderedText(renderer)).toContain('src') + expect(renderedText(renderer)).toContain('README.md') + + await act(async () => { + resolveReload?.(ok([entry('src', true), entry('README.md'), entry('CHANGELOG.md')])) + }) + expect(renderedText(renderer)).toContain('CHANGELOG.md') + }) + + it('keeps the cached tree when a post-reconnect root refresh fails', async () => { + const client = createMockClient({ + '': [entry('src', true), entry('README.md')] + }) + mockTransport.client = client + + const renderer = await renderExplorer() + expect(renderedText(renderer)).toContain('README.md') + + mockTransport.client = null + mockTransport.connectionState = 'disconnected' + await updateExplorer(renderer) + + const failingClient: MockClient = { + sendRequest: vi.fn(async () => { + throw new Error('refresh failed') + }) + } + mockTransport.client = failingClient + mockTransport.connectionState = 'connected' + await updateExplorer(renderer) + + expect(failingClient.sendRequest).toHaveBeenCalledTimes(1) + expect(renderedText(renderer)).toContain('src') + expect(renderedText(renderer)).toContain('README.md') + expect(renderedText(renderer)).not.toContain('refresh failed') + }) + + it('falls back to the capped files.list against desktops without files.readDir', async () => { + const legacyClient: MockClient = { + sendRequest: vi.fn(async (method: string): Promise => { + if (method === 'files.readDir') { + return { + id: 'response-id', + ok: false, + error: { + code: 'forbidden', + message: "Method 'files.readDir' is not available to mobile clients" + }, + _meta: { runtimeId: 'runtime-id' } + } + } + return { + id: 'response-id', + ok: true, + result: { + files: [ + { relativePath: 'src/app.ts', basename: 'app.ts', kind: 'text' }, + { relativePath: 'README.md', basename: 'README.md', kind: 'text' } + ], + totalCount: 2, + truncated: false + }, + _meta: { runtimeId: 'runtime-id' } + } + }) + } + mockTransport.client = legacyClient + + const renderer = await renderExplorer() + + expect(legacyClient.sendRequest).toHaveBeenCalledWith('files.list', { + worktree: 'id:worktree-a' + }) + expect(renderedText(renderer)).toContain('src') + expect(renderedText(renderer)).toContain('README.md') + + await pressByLabel(renderer, 'Open folder src') + expect(renderedText(renderer)).toContain('app.ts') + // Every directory comes from the synthesized cache: one readDir attempt + // plus one files.list call total, no per-directory RPCs afterwards. + expect(legacyClient.sendRequest).toHaveBeenCalledTimes(2) + }) + + it('surfaces the legacy cap note when the files.list fallback is truncated', async () => { + const legacyClient: MockClient = { + sendRequest: vi.fn(async (method: string): Promise => { + if (method === 'files.readDir') { + return { + id: 'response-id', + ok: false, + error: { code: 'method_not_found', message: 'Unknown method' }, + _meta: { runtimeId: 'runtime-id' } + } + } + return { + id: 'response-id', + ok: true, + result: { + files: [{ relativePath: 'README.md', basename: 'README.md', kind: 'text' }], + totalCount: 6000, + truncated: true + }, + _meta: { runtimeId: 'runtime-id' } + } + }) + } + mockTransport.client = legacyClient + + const renderer = await renderExplorer() + + expect(renderedText(renderer)).toContain('README.md') + expect(renderedText(renderer)).toContain('Showing first 5000') + }) + + it('reports the files.list failure when the fallback itself fails', async () => { + const legacyClient: MockClient = { + sendRequest: vi.fn(async (method: string): Promise => { + if (method === 'files.readDir') { + return { + id: 'response-id', + ok: false, + error: { + code: 'forbidden', + message: "Method 'files.readDir' is not available to mobile clients" + }, + _meta: { runtimeId: 'runtime-id' } + } + } + return { + id: 'response-id', + ok: false, + error: { code: 'internal', message: 'legacy list failed' }, + _meta: { runtimeId: 'runtime-id' } + } + }) + } + mockTransport.client = legacyClient + + const renderer = await renderExplorer() + + expect(renderedText(renderer)).toContain('legacy list failed') + expect(renderedText(renderer)).not.toContain('not available to mobile clients') + }) +}) diff --git a/mobile/src/files/MobileFileExplorerPanel.tsx b/mobile/src/files/MobileFileExplorerPanel.tsx index 8192eb900..7e67bf81b 100644 --- a/mobile/src/files/MobileFileExplorerPanel.tsx +++ b/mobile/src/files/MobileFileExplorerPanel.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ActivityIndicator, FlatList, @@ -9,34 +9,33 @@ import { } from 'react-native' import { SafeAreaView } from 'react-native-safe-area-context' import { useRouter } from 'expo-router' -import { - ChevronDown, - ChevronLeft, - ChevronRight, - File, - FileText, - Folder, - Image as ImageIcon, - X -} from 'lucide-react-native' +import { ChevronLeft, X } from 'lucide-react-native' import { useHostClient, useForceReconnect } from '../transport/client-context' import { getWorktreeLabel } from '../session/worktree-label' import { - buildTree, - flattenTree, - isMarkdownPath, - type FilesListResult, - type MobileFileEntry, - type TreeNode + flattenDirectoryCache, + getDirectoryCacheState, + type DirectoryCache, + type FileExplorerRow, + type MobileDirEntry } from './file-tree' import type { RpcSuccess } from '../transport/types' -import { triggerSelection } from '../platform/haptics' -import { colors, spacing } from '../theme/mobile-theme' -import { fileExplorerStyles as styles } from './mobile-file-explorer-styles' +import { colors } from '../theme/mobile-theme' import { - canPreviewMobileFileRow, - navigateToMobileFilePreview -} from './mobile-file-preview-navigation' + beginDirectoryLoad, + createDirectoryLoadRevisions, + isCurrentDirectoryLoad, + resetDirectoryLoadRevisions, + type DirectoryLoadRevisions +} from './directory-load-revisions' +import { + directoryCacheFromFileList, + isMobileMethodUnavailableError, + type LegacyFilesListResult +} from './file-list-fallback' +import { fileExplorerStyles as styles } from './mobile-file-explorer-styles' +import { MobileFileExplorerRow } from './mobile-file-explorer-row' +import { navigateToMobileFilePreview } from './mobile-file-preview-navigation' export function MobileFileExplorerPanel(props: { hostId: string @@ -49,58 +48,217 @@ export function MobileFileExplorerPanel(props: { const router = useRouter() const { client, state: connState } = useHostClient(hostId) const forceReconnect = useForceReconnect() - const [files, setFiles] = useState([]) + const scopeRef = useRef('') + const scope = `${hostId}:${worktreeId}` + scopeRef.current = scope + const directoryLoadRevisionsRef = useRef(createDirectoryLoadRevisions()) + const pendingDirectoryRetriesRef = useRef>(new Set()) + const directoryCacheRef = useRef({}) + const [directoryCache, setDirectoryCache] = useState({}) const [expanded, setExpanded] = useState>(() => new Set()) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) - const [truncated, setTruncated] = useState(false) + const [legacyListTruncated, setLegacyListTruncated] = useState(false) const worktreeLabel = getWorktreeLabel(name, worktreeId) - const loadFiles = useCallback(async () => { - if (!client || connState !== 'connected') { - setLoading(false) - setError(connState === 'connected' ? 'Connecting to desktop...' : 'Waiting for desktop...') - return - } - setLoading(true) - setError(null) - try { - const response = await client.sendRequest('files.list', { worktree: `id:${worktreeId}` }) - if (!response.ok) { - throw new Error(response.error?.message || 'Unable to load files') + const loadDirectory = useCallback( + async (relativePath: string) => { + const scope = scopeRef.current + const loadToken = beginDirectoryLoad(directoryLoadRevisionsRef.current, scope, relativePath) + const rootLoad = relativePath === '' + + if (!client || connState !== 'connected') { + const message = + connState === 'connected' ? 'Connecting to desktop...' : 'Waiting for desktop...' + if (rootLoad) { + const hasLoadedRoot = + (getDirectoryCacheState(directoryCacheRef.current, '')?.entries.length ?? 0) > 0 + setLoading(false) + // Why: transient reconnects should not blank an already browsable tree. + setError(hasLoadedRoot ? null : message) + } else { + setDirectoryCache((prev) => ({ + ...prev, + [relativePath]: { + entries: getDirectoryCacheState(prev, relativePath)?.entries ?? [], + error: message + } + })) + } + return } - const result = (response as RpcSuccess).result as FilesListResult - setFiles(result.files) - setTruncated(result.truncated) - } catch (err) { - setError(err instanceof Error ? err.message : 'Unable to load files') - } finally { - setLoading(false) - } - }, [client, connState, worktreeId]) + + const hadLoadedRoot = + rootLoad && (getDirectoryCacheState(directoryCacheRef.current, '')?.entries.length ?? 0) > 0 + if (rootLoad) { + // Why: a reconnect refresh must not blank an already browsable tree — + // the full-screen spinner unmounts the list and resets scroll. + if (!hadLoadedRoot) { + setLoading(true) + } + setError(null) + } + setDirectoryCache((prev) => ({ + ...prev, + [relativePath]: { + entries: getDirectoryCacheState(prev, relativePath)?.entries ?? [], + loading: true + } + })) + + try { + const response = await client.sendRequest('files.readDir', { + worktree: `id:${worktreeId}`, + relativePath + }) + if (!response.ok) { + // Why: desktops that predate the files.readDir mobile allowlist + // entry still serve the capped files.list; fall back so the Files + // tab keeps working until the desktop updates. + if ( + rootLoad && + isMobileMethodUnavailableError(response.error?.code, response.error?.message) + ) { + const legacy = await client.sendRequest('files.list', { + worktree: `id:${worktreeId}` + }) + if (legacy.ok) { + if ( + !isCurrentDirectoryLoad( + directoryLoadRevisionsRef.current, + scopeRef.current, + loadToken + ) + ) { + return + } + const legacyResult = (legacy as RpcSuccess).result as LegacyFilesListResult + setDirectoryCache(directoryCacheFromFileList(legacyResult.files)) + // Why: the capped list silently omits files past the cap — keep + // the legacy explorer's "Showing first 5000" note. + setLegacyListTruncated(legacyResult.truncated) + return + } + throw new Error( + legacy.error?.message || response.error?.message || 'Unable to load files' + ) + } + throw new Error(response.error?.message || 'Unable to load files') + } + if ( + !isCurrentDirectoryLoad(directoryLoadRevisionsRef.current, scopeRef.current, loadToken) + ) { + return + } + const entries = (response as RpcSuccess).result as MobileDirEntry[] + if (rootLoad) { + setLegacyListTruncated(false) + } + setDirectoryCache((prev) => ({ + ...prev, + [relativePath]: { entries } + })) + } catch (err) { + if ( + !isCurrentDirectoryLoad(directoryLoadRevisionsRef.current, scopeRef.current, loadToken) + ) { + return + } + const message = err instanceof Error ? err.message : 'Unable to load files' + if (rootLoad) { + // Why: a failed background refresh keeps the cached tree browsable; + // only a cold load surfaces the full-screen error. + setError(hadLoadedRoot ? null : message) + } else { + setDirectoryCache((prev) => ({ + ...prev, + [relativePath]: { + entries: getDirectoryCacheState(prev, relativePath)?.entries ?? [], + error: message + } + })) + } + } finally { + if ( + rootLoad && + isCurrentDirectoryLoad(directoryLoadRevisionsRef.current, scopeRef.current, loadToken) + ) { + setLoading(false) + } + } + }, + [client, connState, worktreeId] + ) useEffect(() => { - void loadFiles() - }, [loadFiles]) + scopeRef.current = scope + resetDirectoryLoadRevisions(directoryLoadRevisionsRef.current) + pendingDirectoryRetriesRef.current.clear() + directoryCacheRef.current = {} + setDirectoryCache({}) + setExpanded(new Set()) + setLoading(true) + setError(null) + setLegacyListTruncated(false) + }, [scope]) - const rows = useMemo(() => flattenTree(buildTree(files), expanded), [expanded, files]) + useEffect(() => { + directoryCacheRef.current = directoryCache + }, [directoryCache]) - const toggleDirectory = useCallback((relativePath: string) => { - triggerSelection() - setExpanded((prev) => { - const next = new Set(prev) - if (next.has(relativePath)) { - next.delete(relativePath) - } else { - next.add(relativePath) + useEffect(() => { + void loadDirectory('') + }, [hostId, loadDirectory]) + + useEffect(() => { + if (connState !== 'connected' || pendingDirectoryRetriesRef.current.size === 0) { + return + } + const pending = [...pendingDirectoryRetriesRef.current] + pendingDirectoryRetriesRef.current.clear() + for (const relativePath of pending) { + void loadDirectory(relativePath) + } + }, [connState, loadDirectory]) + + const rows = useMemo( + () => flattenDirectoryCache(directoryCache, expanded), + [directoryCache, expanded] + ) + + const toggleDirectory = useCallback( + (relativePath: string) => { + setExpanded((prev) => { + const next = new Set(prev) + if (next.has(relativePath)) { + next.delete(relativePath) + } else { + next.add(relativePath) + } + return next + }) + const state = getDirectoryCacheState(directoryCache, relativePath) + if (!expanded.has(relativePath) && !state?.loading && (!state?.entries || state.error)) { + void loadDirectory(relativePath) } - return next - }) - }, []) + }, + [directoryCache, expanded, loadDirectory] + ) + + const retryDirectory = useCallback( + (relativePath: string) => { + if (connState !== 'connected' && hostId) { + pendingDirectoryRetriesRef.current.add(relativePath) + void forceReconnect(hostId) + return + } + void loadDirectory(relativePath) + }, + [connState, forceReconnect, hostId, loadDirectory] + ) const previewFile = useCallback( (relativePath: string, displayName: string) => { - triggerSelection() navigateToMobileFilePreview( router, { @@ -116,66 +274,15 @@ export function MobileFileExplorerPanel(props: { [embedded, hostId, name, onRequestClose, router, worktreeId] ) - const renderItem: ListRenderItem = ({ item }) => { - const isDirectory = item.kind === 'directory' - const isExpanded = expanded.has(item.relativePath) - // Images render in the mobile viewer (via files.readPreview), so a binary - // image is openable; only non-previewable binaries are unavailable. - const previewable = - item.kind !== 'directory' && - canPreviewMobileFileRow({ kind: item.kind, relativePath: item.relativePath }) - const isImage = item.kind === 'binary' && previewable - const disabled = item.kind === 'binary' && !previewable - const markdown = item.kind === 'text' && isMarkdownPath(item.relativePath) + const renderItem: ListRenderItem = ({ item }) => { return ( - [ - styles.row, - { paddingLeft: spacing.lg + item.depth * 18 }, - pressed && !disabled && styles.rowPressed, - disabled && styles.rowDisabled - ]} - disabled={disabled} - onPress={() => { - if (isDirectory) { - toggleDirectory(item.relativePath) - } else if (!disabled) { - previewFile(item.relativePath, item.name) - } - }} - accessibilityLabel={ - isDirectory - ? `Open folder ${item.name}` - : disabled - ? `${item.name} unavailable on mobile` - : `Preview file ${item.name}` - } - > - {isDirectory ? ( - isExpanded ? ( - - ) : ( - - ) - ) : ( - - )} - {isDirectory ? ( - - ) : markdown ? ( - - ) : isImage ? ( - - ) : ( - - )} - - - {item.name} - - {disabled ? Unavailable on mobile : null} - - + ) } @@ -206,7 +313,7 @@ export function MobileFileExplorerPanel(props: { {worktreeLabel} - {truncated ? ' - Showing first 5000' : ''} + {legacyListTruncated ? ' - Showing first 5000' : ''} @@ -220,12 +327,12 @@ export function MobileFileExplorerPanel(props: { {error} {/* Why: while disconnected, re-sending the request is useless — revive - the parked transport instead (issue #5049); loadFiles re-runs via + the parked transport instead (issue #5049); loadDirectory re-runs via its effect once the new client connects. */} - connState !== 'connected' && hostId ? void forceReconnect(hostId) : void loadFiles() + connState !== 'connected' && hostId ? void forceReconnect(hostId) : void loadDirectory('') } > Retry diff --git a/mobile/src/files/directory-load-revisions.test.ts b/mobile/src/files/directory-load-revisions.test.ts new file mode 100644 index 000000000..86ebfc3c0 --- /dev/null +++ b/mobile/src/files/directory-load-revisions.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { + beginDirectoryLoad, + createDirectoryLoadRevisions, + isCurrentDirectoryLoad, + resetDirectoryLoadRevisions, + type DirectoryLoadRevisions +} from './directory-load-revisions' + +describe('directory-load-revisions', () => { + it('ignores stale duplicate loads for the same directory and scope', () => { + const revisions: DirectoryLoadRevisions = createDirectoryLoadRevisions() + const older = beginDirectoryLoad(revisions, 'host-a:worktree-a', 'src') + const newer = beginDirectoryLoad(revisions, 'host-a:worktree-a', 'src') + + expect(isCurrentDirectoryLoad(revisions, 'host-a:worktree-a', newer)).toBe(true) + expect(isCurrentDirectoryLoad(revisions, 'host-a:worktree-a', older)).toBe(false) + }) + + it('ignores loads from an old host/worktree scope', () => { + const revisions: DirectoryLoadRevisions = createDirectoryLoadRevisions() + const oldScopeLoad = beginDirectoryLoad(revisions, 'host-a:worktree-a', '') + + expect(isCurrentDirectoryLoad(revisions, 'host-b:worktree-b', oldScopeLoad)).toBe(false) + }) + + it('ignores loads from an old reset generation in the same scope', () => { + const revisions: DirectoryLoadRevisions = createDirectoryLoadRevisions() + const oldLoad = beginDirectoryLoad(revisions, 'host-a:worktree-a', '') + + resetDirectoryLoadRevisions(revisions) + const newLoad = beginDirectoryLoad(revisions, 'host-a:worktree-a', '') + + expect(isCurrentDirectoryLoad(revisions, 'host-a:worktree-a', newLoad)).toBe(true) + expect(isCurrentDirectoryLoad(revisions, 'host-a:worktree-a', oldLoad)).toBe(false) + }) + + it('tracks directory names that overlap object prototype keys', () => { + const revisions: DirectoryLoadRevisions = createDirectoryLoadRevisions() + const load = beginDirectoryLoad(revisions, 'host-a:worktree-a', '__proto__') + + expect(isCurrentDirectoryLoad(revisions, 'host-a:worktree-a', load)).toBe(true) + }) +}) diff --git a/mobile/src/files/directory-load-revisions.ts b/mobile/src/files/directory-load-revisions.ts new file mode 100644 index 000000000..04153092b --- /dev/null +++ b/mobile/src/files/directory-load-revisions.ts @@ -0,0 +1,42 @@ +export type DirectoryLoadRevisions = { + generation: number + revisionsByPath: Map +} + +export type DirectoryLoadToken = { + generation: number + relativePath: string + revision: number + scope: string +} + +export function createDirectoryLoadRevisions(): DirectoryLoadRevisions { + return { generation: 0, revisionsByPath: new Map() } +} + +export function resetDirectoryLoadRevisions(revisions: DirectoryLoadRevisions): void { + revisions.generation += 1 + revisions.revisionsByPath.clear() +} + +export function beginDirectoryLoad( + revisions: DirectoryLoadRevisions, + scope: string, + relativePath: string +): DirectoryLoadToken { + const revision = (revisions.revisionsByPath.get(relativePath) ?? 0) + 1 + revisions.revisionsByPath.set(relativePath, revision) + return { generation: revisions.generation, relativePath, revision, scope } +} + +export function isCurrentDirectoryLoad( + revisions: DirectoryLoadRevisions, + currentScope: string, + token: DirectoryLoadToken +): boolean { + return ( + currentScope === token.scope && + revisions.generation === token.generation && + revisions.revisionsByPath.get(token.relativePath) === token.revision + ) +} diff --git a/mobile/src/files/file-list-fallback.test.ts b/mobile/src/files/file-list-fallback.test.ts new file mode 100644 index 000000000..a69affc5f --- /dev/null +++ b/mobile/src/files/file-list-fallback.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest' +import { directoryCacheFromFileList, isMobileMethodUnavailableError } from './file-list-fallback' +import { getDirectoryCacheState } from './file-tree' + +describe('isMobileMethodUnavailableError', () => { + it('detects old-desktop allowlist and missing-method failures', () => { + expect(isMobileMethodUnavailableError('forbidden', undefined)).toBe(true) + expect(isMobileMethodUnavailableError('method_not_found', undefined)).toBe(true) + expect( + isMobileMethodUnavailableError( + 'some_code', + "Method 'files.readDir' is not available to mobile clients" + ) + ).toBe(true) + expect(isMobileMethodUnavailableError('internal', 'boom')).toBe(false) + expect(isMobileMethodUnavailableError(undefined, undefined)).toBe(false) + }) +}) + +describe('directoryCacheFromFileList', () => { + it('synthesizes every ancestor directory from flat paths', () => { + const cache = directoryCacheFromFileList([ + { relativePath: 'src/lib/util.ts', basename: 'util.ts', kind: 'text' }, + { relativePath: 'src/app.ts', basename: 'app.ts', kind: 'text' }, + { relativePath: 'README.md', basename: 'README.md', kind: 'text' } + ]) + expect(cache['']?.entries).toEqual( + expect.arrayContaining([ + { name: 'src', isDirectory: true }, + { name: 'README.md', isDirectory: false } + ]) + ) + expect(cache['src']?.entries).toEqual( + expect.arrayContaining([ + { name: 'lib', isDirectory: true }, + { name: 'app.ts', isDirectory: false } + ]) + ) + expect(cache['src/lib']?.entries).toEqual([{ name: 'util.ts', isDirectory: false }]) + }) + + it('keeps a name a directory when it appears as both file and dir prefix', () => { + const cache = directoryCacheFromFileList([ + { relativePath: 'src', basename: 'src', kind: 'text' }, + { relativePath: 'src/app.ts', basename: 'app.ts', kind: 'text' } + ]) + expect(cache['']?.entries).toEqual([{ name: 'src', isDirectory: true }]) + }) + + it('returns an empty root for an empty list', () => { + const cache = directoryCacheFromFileList([]) + expect(cache['']?.entries).toEqual([]) + }) + + it('stores a __proto__ directory as an own key instead of mutating the prototype', () => { + const cache = directoryCacheFromFileList([ + { relativePath: '__proto__/pollute.js', basename: 'pollute.js', kind: 'text' } + ]) + expect(Object.getPrototypeOf(cache)).toBe(Object.prototype) + expect(cache['']?.entries).toEqual([{ name: '__proto__', isDirectory: true }]) + expect(getDirectoryCacheState(cache, '__proto__')?.entries).toEqual([ + { name: 'pollute.js', isDirectory: false } + ]) + }) +}) diff --git a/mobile/src/files/file-list-fallback.ts b/mobile/src/files/file-list-fallback.ts new file mode 100644 index 000000000..ef3041029 --- /dev/null +++ b/mobile/src/files/file-list-fallback.ts @@ -0,0 +1,73 @@ +// Fallback for desktops that predate files.readDir in the mobile RPC +// allowlist: synthesize the lazy directory cache from the flat, capped +// files.list result so the Files tab stays browsable against old desktops. +import type { DirectoryCache, MobileDirEntry } from './file-tree' + +export type LegacyMobileFileEntry = { + relativePath: string + basename: string + kind: 'text' | 'binary' +} + +export type LegacyFilesListResult = { + files: LegacyMobileFileEntry[] + totalCount: number + truncated: boolean +} + +// Same detection shape as isMobileGitUnavailable in mobile-git-status.ts: +// 'forbidden' = method exists but is not mobile-allowlisted on the old +// desktop; 'method_not_found' = desktop predates the method entirely. +export function isMobileMethodUnavailableError( + code: string | undefined, + message: string | undefined +): boolean { + return ( + code === 'forbidden' || + code === 'method_not_found' || + message?.includes('not available to mobile clients') === true + ) +} + +export function directoryCacheFromFileList(files: LegacyMobileFileEntry[]): DirectoryCache { + const childrenByDir = new Map>() + const ensureDir = (path: string): Map => { + let children = childrenByDir.get(path) + if (!children) { + children = new Map() + childrenByDir.set(path, children) + } + return children + } + ensureDir('') + for (const file of files) { + const parts = file.relativePath.split('/').filter(Boolean) + let parentPath = '' + parts.forEach((name, index) => { + const isDirectory = index < parts.length - 1 + const children = ensureDir(parentPath) + children.set(name, children.get(name) === true || isDirectory) + parentPath = parentPath ? `${parentPath}/${name}` : name + if (isDirectory) { + ensureDir(parentPath) + } + }) + } + // Why: plain `cache[path] = ...` with a '__proto__' path segment mutates the + // object's prototype instead of storing the directory; fromEntries always + // creates own keys. + return Object.fromEntries( + Array.from(childrenByDir, ([path, children]) => [ + path, + { + entries: Array.from( + children, + ([name, isDirectory]): MobileDirEntry => ({ + name, + isDirectory + }) + ) + } + ]) + ) +} diff --git a/mobile/src/files/file-tree.test.ts b/mobile/src/files/file-tree.test.ts index c4777ca21..bdd9e9225 100644 --- a/mobile/src/files/file-tree.test.ts +++ b/mobile/src/files/file-tree.test.ts @@ -1,32 +1,109 @@ import { describe, expect, it } from 'vitest' -import { buildTree, flattenTree, isMarkdownPath, type MobileFileEntry } from './file-tree' +import { + flattenDirectoryCache, + getMobileFileKind, + isMarkdownPath, + shouldIncludeMobileFileExplorerEntry, + type DirectoryCache, + type MobileDirEntry +} from './file-tree' -function entry(relativePath: string, kind: 'text' | 'binary' = 'text'): MobileFileEntry { - return { relativePath, basename: relativePath.split('/').pop() ?? relativePath, kind } +function entry(name: string, isDirectory = false, isSymlink = false): MobileDirEntry { + return { name, isDirectory, isSymlink } } describe('file-tree', () => { - it('nests files under their directories', () => { - const root = buildTree([entry('src/app.ts'), entry('src/lib/util.ts'), entry('readme.md')]) - expect(root.files.map((f) => f.relativePath)).toEqual(['readme.md']) - expect(root.directories.get('src')?.directories.get('lib')?.files[0]?.relativePath).toBe( - 'src/lib/util.ts' - ) + it('flattens cached directories lazily with directories before files', () => { + const cache: DirectoryCache = { + '': { entries: [entry('zeta.txt'), entry('src', true), entry('readme.md')] }, + src: { entries: [entry('app.ts'), entry('lib', true)] }, + 'src/lib': { entries: [entry('util.ts')] } + } + + const collapsed = flattenDirectoryCache(cache, new Set()) + expect(collapsed.map((row) => row.id)).toEqual(['dir:src', 'file:readme.md', 'file:zeta.txt']) + + const expanded = flattenDirectoryCache(cache, new Set(['src', 'src/lib'])) + expect(expanded.map((row) => row.id)).toEqual([ + 'dir:src', + 'dir:src/lib', + 'file:src/lib/util.ts', + 'file:src/app.ts', + 'file:readme.md', + 'file:zeta.txt' + ]) }) - it('flattens with directories before files and only expands open dirs', () => { - const root = buildTree([entry('src/app.ts'), entry('zeta.txt')]) - const collapsed = flattenTree(root, new Set()) - expect(collapsed.map((r) => r.id)).toEqual(['dir:src', 'file:zeta.txt']) + it('mirrors desktop default browse exclusions while keeping dotfiles visible', () => { + const cache: DirectoryCache = { + '': { + entries: [ + entry('.git', true), + entry('.env'), + entry('node_modules', true), + entry('src', true) + ] + } + } - const expanded = flattenTree(root, new Set(['src'])) - expect(expanded.map((r) => r.id)).toEqual(['dir:src', 'file:src/app.ts', 'file:zeta.txt']) + expect(flattenDirectoryCache(cache, new Set()).map((row) => row.id)).toEqual([ + 'dir:src', + 'file:.env' + ]) + expect(shouldIncludeMobileFileExplorerEntry(entry('.config', true))).toBe(true) }) - it('preserves the binary kind on flattened rows', () => { - const root = buildTree([entry('assets/logo.png', 'binary')]) - const rows = flattenTree(root, new Set(['assets'])) - expect(rows.find((r) => r.id === 'file:assets/logo.png')?.kind).toBe('binary') + it('renders inline loading and error rows under expanded directories', () => { + const cache: DirectoryCache = { + '': { entries: [entry('loading-dir', true), entry('error-dir', true)] }, + 'loading-dir': { entries: [], loading: true }, + 'error-dir': { entries: [], error: 'permission denied' } + } + + const rows = flattenDirectoryCache(cache, new Set(['loading-dir', 'error-dir'])) + expect(rows.map((row) => row.id)).toEqual([ + 'dir:error-dir', + 'error:error-dir', + 'dir:loading-dir', + 'loading:loading-dir' + ]) + expect(rows.find((row) => row.id === 'error:error-dir')).toMatchObject({ + kind: 'error', + message: 'permission denied' + }) + }) + + it('preserves symlink metadata for user-initiated activation', () => { + const cache: DirectoryCache = { + '': { entries: [entry('linked-docs', false, true)] } + } + + expect(flattenDirectoryCache(cache, new Set())).toEqual([ + { + id: 'file:linked-docs', + name: 'linked-docs', + relativePath: 'linked-docs', + depth: 0, + kind: 'text', + isSymlink: true + } + ]) + }) + + it('does not treat inherited object keys as loaded directories', () => { + const cache: DirectoryCache = { + '': { entries: [entry('constructor', true), entry('__proto__', true)] }, + ['__proto__']: { entries: [entry('file.txt')] } + } + + expect( + flattenDirectoryCache(cache, new Set(['constructor', '__proto__'])).map((row) => row.id) + ).toEqual(['dir:__proto__', 'file:__proto__/file.txt', 'dir:constructor']) + }) + + it('classifies binary file paths for existing mobile preview behavior', () => { + expect(getMobileFileKind('assets/logo.png')).toBe('binary') + expect(getMobileFileKind('src/app.ts')).toBe('text') }) it('detects markdown paths', () => { diff --git a/mobile/src/files/file-tree.ts b/mobile/src/files/file-tree.ts index e453cc152..a9283cfa4 100644 --- a/mobile/src/files/file-tree.ts +++ b/mobile/src/files/file-tree.ts @@ -1,91 +1,152 @@ -// Pure tree model for the mobile file explorer: turns the flat files.list -// result into a nested directory structure and flattens it into renderable -// rows. Kept out of the screen component so the screen stays under its line cap. +// Pure tree projection for the mobile file explorer. Mobile mirrors desktop +// browse semantics by flattening cached files.readDir results as folders open. -export type MobileFileEntry = { - relativePath: string - basename: string - kind: 'text' | 'binary' +export type MobileDirEntry = { + name: string + isDirectory: boolean + isSymlink?: boolean } -export type FilesListResult = { - files: MobileFileEntry[] - totalCount: number - truncated: boolean -} +export type MobileFileKind = 'text' | 'binary' export type TreeNode = { id: string name: string relativePath: string depth: number - kind: 'directory' | 'text' | 'binary' + kind: 'directory' | MobileFileKind + isSymlink?: boolean } -export type DirectoryNode = { - name: string +export type DirectoryState = { + entries: MobileDirEntry[] + loading?: boolean + error?: string +} + +export type DirectoryCache = Record + +export type InlineStatusNode = { + id: string relativePath: string - directories: Map - files: MobileFileEntry[] + depth: number + kind: 'loading' | 'error' + message?: string } -function createDirectoryNode(name: string, relativePath: string): DirectoryNode { - return { name, relativePath, directories: new Map(), files: [] } -} +export type FileExplorerRow = TreeNode | InlineStatusNode -export function buildTree(files: MobileFileEntry[]): DirectoryNode { - const root = createDirectoryNode('', '') - for (const file of files) { - const parts = file.relativePath.split('/').filter(Boolean) - let current = root - for (let index = 0; index < parts.length - 1; index += 1) { - const name = parts[index]! - const relativePath = parts.slice(0, index + 1).join('/') - let child = current.directories.get(name) - if (!child) { - child = createDirectoryNode(name, relativePath) - current.directories.set(name, child) - } - current = child - } - current.files.push(file) - } - return root -} +const DESKTOP_EXCLUDED_NAMES = new Set(['.git', 'node_modules']) +const BINARY_EXTENSIONS = new Set([ + '.avif', + '.bmp', + '.gif', + '.heic', + '.ico', + '.jpeg', + '.jpg', + '.mov', + '.mp3', + '.mp4', + '.pdf', + '.png', + '.webp', + '.zip' +]) -export function flattenTree(root: DirectoryNode, expanded: ReadonlySet): TreeNode[] { - const rows: TreeNode[] = [] - const visit = (directory: DirectoryNode, depth: number): void => { - const dirs = Array.from(directory.directories.values()).sort((a, b) => - a.name.localeCompare(b.name) - ) - for (const child of dirs) { - rows.push({ - id: `dir:${child.relativePath}`, - name: child.name, - relativePath: child.relativePath, - depth, - kind: 'directory' - }) - if (expanded.has(child.relativePath)) { - visit(child, depth + 1) - } - } - const files = [...directory.files].sort((a, b) => a.basename.localeCompare(b.basename)) - for (const file of files) { - rows.push({ - id: `file:${file.relativePath}`, - name: file.basename, - relativePath: file.relativePath, - depth, - kind: file.kind - }) - } - } - visit(root, 0) +export function flattenDirectoryCache( + cache: DirectoryCache, + expanded: ReadonlySet +): FileExplorerRow[] { + const rows: FileExplorerRow[] = [] + visitDirectory('', 0, cache, expanded, rows) return rows } +function visitDirectory( + relativePath: string, + depth: number, + cache: DirectoryCache, + expanded: ReadonlySet, + rows: FileExplorerRow[] +): void { + const state = getDirectoryCacheState(cache, relativePath) + const entries = state?.entries ?? [] + const visibleEntries = entries + .filter(shouldIncludeMobileFileExplorerEntry) + .sort(compareDirectoryEntries) + + for (const entry of visibleEntries) { + const childPath = joinRelativePath(relativePath, entry.name) + rows.push(toTreeNode(entry, childPath, depth)) + if (entry.isDirectory && expanded.has(childPath)) { + const childState = getDirectoryCacheState(cache, childPath) + if (childState?.loading) { + rows.push({ + id: `loading:${childPath}`, + relativePath: childPath, + depth: depth + 1, + kind: 'loading' + }) + } else if (childState?.error) { + rows.push({ + id: `error:${childPath}`, + relativePath: childPath, + depth: depth + 1, + kind: 'error', + message: childState.error + }) + } else { + visitDirectory(childPath, depth + 1, cache, expanded, rows) + } + } + } +} + +function toTreeNode(entry: MobileDirEntry, relativePath: string, depth: number): TreeNode { + return { + id: `${entry.isDirectory ? 'dir' : 'file'}:${relativePath}`, + name: entry.name, + relativePath, + depth, + kind: entry.isDirectory ? 'directory' : getMobileFileKind(relativePath), + isSymlink: entry.isSymlink + } +} + +function compareDirectoryEntries(a: MobileDirEntry, b: MobileDirEntry): number { + if (a.isDirectory !== b.isDirectory) { + return a.isDirectory ? -1 : 1 + } + return a.name.localeCompare(b.name) +} + +export function shouldIncludeMobileFileExplorerEntry(entry: MobileDirEntry): boolean { + return !DESKTOP_EXCLUDED_NAMES.has(entry.name) +} + +export function getDirectoryCacheState( + cache: DirectoryCache, + relativePath: string +): DirectoryState | undefined { + // Why: repository paths are arbitrary object keys; inherited keys like + // "constructor" must not masquerade as loaded directory state. + return Object.prototype.hasOwnProperty.call(cache, relativePath) ? cache[relativePath] : undefined +} + +export function joinRelativePath(parentPath: string, name: string): string { + return parentPath ? `${parentPath}/${name}` : name +} + +export function getMobileFileKind(relativePath: string): MobileFileKind { + const basename = relativePath.split('/').pop() ?? relativePath + const dotIndex = basename.lastIndexOf('.') + if (dotIndex <= 0) { + return 'text' + } + return BINARY_EXTENSIONS.has(basename.slice(dotIndex).toLowerCase()) ? 'binary' : 'text' +} + export function isMarkdownPath(relativePath: string): boolean { return /\.(md|mdx|markdown)$/i.test(relativePath) } diff --git a/mobile/src/files/mobile-file-explorer-row.tsx b/mobile/src/files/mobile-file-explorer-row.tsx new file mode 100644 index 000000000..36f74ad3b --- /dev/null +++ b/mobile/src/files/mobile-file-explorer-row.tsx @@ -0,0 +1,145 @@ +import { ActivityIndicator, Pressable, Text, View } from 'react-native' +import { + ChevronDown, + ChevronRight, + File, + FileText, + Folder, + Image as ImageIcon +} from 'lucide-react-native' +import { triggerSelection } from '../platform/haptics' +import { colors, spacing } from '../theme/mobile-theme' +import { type FileExplorerRow, isMarkdownPath, type TreeNode } from './file-tree' +import { fileExplorerStyles as styles } from './mobile-file-explorer-styles' +import { canPreviewMobileFileRow } from './mobile-file-preview-navigation' + +type Props = { + item: FileExplorerRow + expanded: ReadonlySet + onPreviewFile: (relativePath: string, displayName: string) => void + onRetryDirectory: (relativePath: string) => void + onToggleDirectory: (relativePath: string) => void +} + +export function MobileFileExplorerRow(props: Props) { + const { item, expanded, onPreviewFile, onRetryDirectory, onToggleDirectory } = props + + if (item.kind === 'loading') { + return ( + + + + Loading... + + ) + } + + if (item.kind === 'error') { + return ( + + + + {item.message || 'Unable to load folder'} + + [styles.inlineRetryButton, pressed && styles.rowPressed]} + onPress={() => { + triggerSelection() + onRetryDirectory(item.relativePath) + }} + accessibilityLabel={`Retry loading ${item.relativePath}`} + > + Retry + + + ) + } + + if (isTreeNode(item)) { + return ( + + ) + } + + return null +} + +function isTreeNode(item: FileExplorerRow): item is TreeNode { + return item.kind === 'directory' || item.kind === 'text' || item.kind === 'binary' +} + +function TreeRow(props: { + item: TreeNode + expanded: ReadonlySet + onPreviewFile: (relativePath: string, displayName: string) => void + onToggleDirectory: (relativePath: string) => void +}) { + const { item, expanded, onPreviewFile, onToggleDirectory } = props + const isDirectory = item.kind === 'directory' + const isExpanded = expanded.has(item.relativePath) + // Images render in the mobile viewer (via files.readPreview), so a binary + // image is openable; only non-previewable binaries are unavailable. + const previewable = + item.kind !== 'directory' && + canPreviewMobileFileRow({ kind: item.kind, relativePath: item.relativePath }) + const isImage = item.kind === 'binary' && previewable + const disabled = item.kind === 'binary' && !previewable + const markdown = item.kind === 'text' && isMarkdownPath(item.relativePath) + + return ( + [ + styles.row, + { paddingLeft: spacing.lg + item.depth * 18 }, + pressed && !disabled && styles.rowPressed, + disabled && styles.rowDisabled + ]} + disabled={disabled} + onPress={() => { + triggerSelection() + if (isDirectory) { + onToggleDirectory(item.relativePath) + } else if (!disabled) { + onPreviewFile(item.relativePath, item.name) + } + }} + accessibilityLabel={ + isDirectory + ? `Open folder ${item.name}` + : disabled + ? `${item.name} unavailable on mobile` + : `Preview file ${item.name}` + } + > + {isDirectory ? ( + isExpanded ? ( + + ) : ( + + ) + ) : ( + + )} + {isDirectory ? ( + + ) : markdown ? ( + + ) : isImage ? ( + + ) : ( + + )} + + + {item.name} + + {disabled ? Unavailable on mobile : null} + + + ) +} diff --git a/mobile/src/files/mobile-file-explorer-styles.ts b/mobile/src/files/mobile-file-explorer-styles.ts index 339dd5519..5df9710be 100644 --- a/mobile/src/files/mobile-file-explorer-styles.ts +++ b/mobile/src/files/mobile-file-explorer-styles.ts @@ -78,6 +78,37 @@ export const fileExplorerStyles = StyleSheet.create({ color: colors.textMuted, fontSize: 11 }, + inlineStatusRow: { + minHeight: 36, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.sm, + paddingRight: spacing.md + }, + inlineStatusText: { + color: colors.textSecondary, + fontSize: typography.metaSize + }, + inlineErrorText: { + flex: 1, + minWidth: 0, + color: colors.statusRed, + fontSize: typography.metaSize + }, + inlineRetryButton: { + minHeight: 28, + alignItems: 'center', + justifyContent: 'center', + borderRadius: radii.button, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle, + paddingHorizontal: spacing.md + }, + inlineRetryText: { + color: colors.textPrimary, + fontSize: typography.metaSize, + fontWeight: '600' + }, state: { flex: 1, alignItems: 'center', diff --git a/mobile/src/hooks/use-mobile-dictation.ts b/mobile/src/hooks/use-mobile-dictation.ts index 5f43ffcf0..a1028cf92 100644 --- a/mobile/src/hooks/use-mobile-dictation.ts +++ b/mobile/src/hooks/use-mobile-dictation.ts @@ -1,6 +1,3 @@ -/* oxlint-disable max-lines -- Why: mobile dictation keeps permission, recording, - * chunk upload, completion, and cancellation in one hook so native audio state - * cannot drift from the runtime RPC lifecycle. */ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' // Why: import from 'buffer' (the npm polyfill), not 'node:buffer' — Metro // can't resolve Node's builtin in a React Native bundle. diff --git a/package.json b/package.json index d5ab3164f..2e48c135c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orca", - "version": "1.4.124-rc.9", + "version": "1.4.126", "description": "Next-gen IDE for parallel agentic development", "homepage": "https://github.com/stablyai/orca", "author": "stablyai", @@ -11,7 +11,7 @@ "main": "./out/main/index.js", "scripts": { "format": "oxfmt --write .", - "lint": "oxlint && pnpm run lint:switch-exhaustiveness && node config/scripts/check-styled-scrollbars.mjs && pnpm run check:reliability-gates && pnpm run verify:localization-catalog && pnpm run verify:localization-coverage", + "lint": "oxlint && pnpm run lint:switch-exhaustiveness && node config/scripts/check-styled-scrollbars.mjs && pnpm run check:reliability-gates && pnpm run check:max-lines-ratchet && pnpm run verify:localization-catalog && pnpm run verify:localization-coverage", "lint:react-doctor": "oxlint --config config/oxlint-react-doctor.json", "lint:react-doctor:changed": "node config/scripts/lint-react-doctor-changed.mjs", "lint:switch-exhaustiveness": "oxlint --type-aware --config config/oxlint-switch-exhaustiveness.json src/main src/preload src/shared src/relay src/cli src/renderer/src config tests --quiet", @@ -19,6 +19,7 @@ "test": "node config/scripts/ensure-native-runtime.mjs --runtime=node && vitest run --config config/vitest.config.ts", "check:styled-scrollbars": "node config/scripts/check-styled-scrollbars.mjs", "check:reliability-gates": "node config/scripts/check-reliability-gates.mjs", + "check:max-lines-ratchet": "node config/scripts/check-max-lines-ratchet.mjs", "check:feature-wall-assets": "node config/scripts/check-feature-wall-assets.mjs", "verify:macos-entitlements": "node config/scripts/verify-macos-entitlements.mjs", "vendor:feature-wall-assets": "node config/scripts/vendor-feature-wall-assets.mjs", @@ -87,6 +88,7 @@ "bench:idle-cpu": "pnpm run ensure:electron-runtime && node config/scripts/run-idle-cpu-benchmark.mjs", "bench:startup": "pnpm run ensure:electron-runtime && node tools/benchmarks/startup-time-bench.mjs", "bench:daemon-coldstart": "pnpm run ensure:electron-runtime && node tools/benchmarks/daemon-coldstart-bench.mjs", + "bench:main-thread-jank": "pnpm run ensure:electron-runtime && node tools/benchmarks/main-thread-jank-bench.mjs", "bench:compare": "node config/scripts/compare-benchmark-artifacts.mjs" }, "dependencies": { diff --git a/src/cli/browser.test.ts b/src/cli/browser.test.ts index 7ca2c509a..83ca43d48 100644 --- a/src/cli/browser.test.ts +++ b/src/cli/browser.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: this file groups every CLI browser-command test (page targeting, profiles, waits, viewport) so test-fixture imports and the runtime-client mock stay shared in one place. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() diff --git a/src/cli/handlers/file.test.ts b/src/cli/handlers/file.test.ts index fa03e286c..4e36ddbff 100644 --- a/src/cli/handlers/file.test.ts +++ b/src/cli/handlers/file.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: file CLI coverage shares one mocked runtime setup across command contracts. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const callMock = vi.fn() diff --git a/src/main/agent-hooks/remote-hook-service-installers.test.ts b/src/main/agent-hooks/remote-hook-service-installers.test.ts index 3cd61db55..8a85128cd 100644 --- a/src/main/agent-hooks/remote-hook-service-installers.test.ts +++ b/src/main/agent-hooks/remote-hook-service-installers.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: this fixture verifies the shared remote hook installer fake across every managed agent so SSH regressions are caught together. */ import { describe, expect, it, vi } from 'vitest' import type { SFTPWrapper } from 'ssh2' diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index 46ff181a7..91b0dc660 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -13,7 +13,12 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, agentHookServer, _internals } from './server' +import { + AgentHookServer, + agentHookServer, + CLOSED_AGENT_STATUS_TAB_IDS_MAX, + _internals +} from './server' import { AGENT_STATUS_MAX_FIELD_LENGTH, AGENT_STATUS_STALE_AFTER_MS, @@ -6848,3 +6853,23 @@ describe('AgentHookServer ingestTerminalStatus', () => { expect(server.getStatusSnapshot()).toEqual([]) }) }) + +describe('AgentHookServer closed-tab suppression bound', () => { + it('bounds closedAgentStatusTabIds with LRU eviction as tabs close', () => { + const server = new AgentHookServer() + const internals = server as unknown as { + markTabClosedForAgentStatus: (tabId: string) => void + closedAgentStatusTabIds: Set + } + + const total = CLOSED_AGENT_STATUS_TAB_IDS_MAX + 200 + for (let i = 0; i < total; i += 1) { + internals.markTabClosedForAgentStatus(`closed-tab-${i}`) + } + + // Set stays bounded; oldest ids are evicted, most-recent are retained. + expect(internals.closedAgentStatusTabIds.size).toBe(CLOSED_AGENT_STATUS_TAB_IDS_MAX) + expect(internals.closedAgentStatusTabIds.has('closed-tab-0')).toBe(false) + expect(internals.closedAgentStatusTabIds.has(`closed-tab-${total - 1}`)).toBe(true) + }) +}) diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index d4cc443d8..167331765 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -119,6 +119,12 @@ const AGENT_PROMPT_SENT_AGENT_KINDS = new Set(AGENT_KIND_VALUES) // not resurrect on hydrate. const HYDRATE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 +// Why: closed-tab suppression only needs to cover recently closed tabs — a +// status event for a long-closed tab cannot arrive once its process/hooks are +// gone. Bound the set so it can't grow one entry per tab close for the whole +// session (it is otherwise only cleared at app quit). +export const CLOSED_AGENT_STATUS_TAB_IDS_MAX = 1024 + type LastStatusFile = { version: number entries: Record @@ -596,7 +602,17 @@ export class AgentHookServer { } private markTabClosedForAgentStatus(tabId: string): void { + // Delete-then-add keeps recently closed tabs most-recent so eviction only + // sheds the oldest ids, which can no longer receive status events. + this.closedAgentStatusTabIds.delete(tabId) this.closedAgentStatusTabIds.add(tabId) + while (this.closedAgentStatusTabIds.size > CLOSED_AGENT_STATUS_TAB_IDS_MAX) { + const oldest = this.closedAgentStatusTabIds.keys().next().value + if (oldest === undefined) { + break + } + this.closedAgentStatusTabIds.delete(oldest) + } } private shouldSuppressClosedTabStatus(paneKey: string): boolean { diff --git a/src/main/ai-vault/remote-session-scanner-sources.ts b/src/main/ai-vault/remote-session-scanner-sources.ts index f232b0adf..e8d43ae1f 100644 --- a/src/main/ai-vault/remote-session-scanner-sources.ts +++ b/src/main/ai-vault/remote-session-scanner-sources.ts @@ -15,7 +15,7 @@ import { parseHermesSessionContent } from './session-scanner-secondary-parsers' import type { FileWithMtime } from './session-scanner-types' -import { normalizePiSessionsDir } from './session-scanner-values' +import { normalizeAgentSessionsDir } from './session-scanner-values' import { remoteCodexIndexTitles } from './remote-session-scanner-codex-index' import type { RemoteParserOptions, @@ -83,6 +83,7 @@ export function remoteSessionSources( parseDevinSessionContent ), jsonlSource('pi', remoteHome, hostPlatform, remotePiSessionsSegments(), piParser), + jsonlSource('omp', remoteHome, hostPlatform, remoteOmpSessionsSegments(), ompParser), jsonlSource( 'droid', remoteHome, @@ -203,6 +204,15 @@ function piParser( return parseMessageGraphSessionContent('pi', file, content, platform, options) } +function ompParser( + file: FileWithMtime, + content: string, + platform: NodeJS.Platform, + options: RemoteParserOptions +): Promise { + return parseMessageGraphSessionContent('omp', file, content, platform, options) +} + function openClawParser( file: FileWithMtime, content: string, @@ -217,5 +227,9 @@ function remotePathSegments(path: string): string[] { } function remotePiSessionsSegments(): string[] { - return normalizePiSessionsDir('/.pi/agent/sessions').split('/').filter(Boolean) + return normalizeAgentSessionsDir('/.pi/agent/sessions', '.pi').split('/').filter(Boolean) +} + +function remoteOmpSessionsSegments(): string[] { + return normalizeAgentSessionsDir('/.omp/agent/sessions', '.omp').split('/').filter(Boolean) } diff --git a/src/main/ai-vault/session-scanner-accumulator.ts b/src/main/ai-vault/session-scanner-accumulator.ts index 85b33a962..8e44e30c6 100644 --- a/src/main/ai-vault/session-scanner-accumulator.ts +++ b/src/main/ai-vault/session-scanner-accumulator.ts @@ -7,7 +7,11 @@ import { type AiVaultSessionPreviewMessage } from '../../shared/ai-vault-types' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host' -import type { FileWithMtime, SessionAccumulator } from './session-scanner-types' +import type { + FileWithMtime, + ResumableSessionParseState, + SessionAccumulator +} from './session-scanner-types' import { extractPreviewContentText, extractString, @@ -41,6 +45,31 @@ export function createAccumulator(args: { } } +export function cloneSessionAccumulator(accumulator: SessionAccumulator): SessionAccumulator { + return { ...accumulator, previewMessages: [...accumulator.previewMessages] } +} + +// Resumable fold for parsers whose only parse state is the accumulator itself +// (cursor, copilot, droid, openclaw/pi, gemini-jsonl). Parsers with extra +// closure state (claude, codex) build their own ResumableSessionParseState. +export function accumulatorFoldResumeState( + accumulator: SessionAccumulator, + consumeRecordLine: (accumulator: SessionAccumulator, line: string) => void +): ResumableSessionParseState { + return { + consumeLine: (line) => consumeRecordLine(accumulator, line), + clone: () => + accumulatorFoldResumeState(cloneSessionAccumulator(accumulator), consumeRecordLine), + touchFile: (file) => { + accumulator.modifiedAt = file.modifiedAt + }, + // Finalize a snapshot: the live accumulator (and its preview array) keeps + // accumulating appended lines after this session object is handed out. + finalize: (platform, options) => + finalizeSession(cloneSessionAccumulator(accumulator), platform, options) + } +} + export function finalizeSession( accumulator: SessionAccumulator, platform: NodeJS.Platform, @@ -84,6 +113,7 @@ export function finalizeSession( resumeCommand: buildAiVaultResumeCommand({ agent: accumulator.agent, sessionId, + resumeFilePath: accumulator.filePath, cwd: accumulator.cwd, platform, codexHome: options.codexHome diff --git a/src/main/ai-vault/session-scanner-agent-parser.ts b/src/main/ai-vault/session-scanner-agent-parser.ts index 1114c1b8b..5a81ff260 100644 --- a/src/main/ai-vault/session-scanner-agent-parser.ts +++ b/src/main/ai-vault/session-scanner-agent-parser.ts @@ -64,6 +64,8 @@ export async function parseAgentSessionFile( return parseMessageGraphSessionFile('openclaw', candidate.file, platform) case 'pi': return parseMessageGraphSessionFile('pi', candidate.file, platform) + case 'omp': + return parseMessageGraphSessionFile('omp', candidate.file, platform) case 'droid': return parseDroidSessionFile(candidate.file, platform) case 'devin': diff --git a/src/main/ai-vault/session-scanner-codex-fixtures.ts b/src/main/ai-vault/session-scanner-codex-fixtures.ts new file mode 100644 index 000000000..ffdab7f1d --- /dev/null +++ b/src/main/ai-vault/session-scanner-codex-fixtures.ts @@ -0,0 +1,92 @@ +import type { IncrementalAgentFixture } from './session-scanner-incremental-fixtures' + +// Codex fixture lines for the incremental-parse differential tests, split out +// of session-scanner-incremental-fixtures.ts to respect the max-lines budget. + +const CODEX_SESSION_ID = '019f0000-1111-7222-8333-444444444444' + +function codexLine(record: Record): string { + return JSON.stringify(record) +} + +export function codexFixture(): IncrementalAgentFixture { + return { + agent: 'codex', + fileName: `rollout-2026-05-01T10-00-00-${CODEX_SESSION_ID}.jsonl`, + seedLines: [ + codexLine({ + timestamp: '2026-05-01T10:00:00.000Z', + type: 'session_meta', + payload: { id: CODEX_SESSION_ID, cwd: '/repo/app', git: { branch: 'feature/vault' } } + }), + codexLine({ + timestamp: '2026-05-01T10:00:05.000Z', + type: 'response_item', + payload: { type: 'message', role: 'user', content: 'codex seed question' } + }), + codexLine({ + timestamp: '2026-05-01T10:00:10.000Z', + type: 'response_item', + payload: { type: 'message', role: 'assistant', content: 'codex seed answer' } + }), + codexLine({ + timestamp: '2026-05-01T10:00:11.000Z', + type: 'event_msg', + payload: { + type: 'token_count', + info: { total_token_usage: { input_tokens: 100, output_tokens: 40, total_tokens: 140 } }, + model: 'gpt-5.1-codex' + } + }) + ], + appendLines: [ + codexLine({ + timestamp: '2026-05-01T10:05:00.000Z', + type: 'event_msg', + payload: { type: 'user_message', message: 'codex follow-up' } + }), + codexLine({ + timestamp: '2026-05-01T10:05:20.000Z', + type: 'event_msg', + payload: { type: 'agent_message', message: 'codex incremental answer' } + }), + codexLine({ + timestamp: '2026-05-01T10:05:21.000Z', + type: 'event_msg', + payload: { + type: 'token_count', + info: { total_token_usage: { input_tokens: 220, output_tokens: 90, total_tokens: 310 } } + } + }) + ], + truncatedLines: [ + codexLine({ + timestamp: '2026-05-01T10:00:00.000Z', + type: 'session_meta', + payload: { id: CODEX_SESSION_ID, cwd: '/repo/app' } + }), + codexLine({ + timestamp: '2026-05-01T10:00:05.000Z', + type: 'event_msg', + payload: { type: 'user_message', message: 'rewritten only turn' } + }) + ] + } +} + +export function codexWorkerFixtureLines(): string[] { + return [ + codexLine({ + timestamp: '2026-05-01T10:00:00.000Z', + type: 'session_meta', + payload: { id: CODEX_SESSION_ID, cwd: '/repo/app', thread_source: 'subagent' } + }), + codexLine({ + timestamp: '2026-05-01T10:00:05.000Z', + type: 'event_msg', + payload: { type: 'user_message', message: 'worker turn' } + }) + ] +} + +export const CODEX_FIXTURE_SESSION_ID = CODEX_SESSION_ID diff --git a/src/main/ai-vault/session-scanner-codex-parser.ts b/src/main/ai-vault/session-scanner-codex-parser.ts index b18721a82..5127720b1 100644 --- a/src/main/ai-vault/session-scanner-codex-parser.ts +++ b/src/main/ai-vault/session-scanner-codex-parser.ts @@ -1,18 +1,25 @@ import { createReadStream } from 'node:fs' -import { stat } from 'node:fs/promises' -import { basename, dirname, join } from 'node:path' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' +import { readCodexSessionIndexTitle } from './session-scanner-codex-title-index' import type { ExecutionHostId } from '../../shared/execution-host' import { addPreviewContent, + cloneSessionAccumulator, createAccumulator, finalizeSession, sessionIdFromFileName, updateTimeline } from './session-scanner-accumulator' -import type { CodexUsageSnapshot, FileWithMtime } from './session-scanner-types' +import type { + CodexUsageSnapshot, + FileWithMtime, + ResumableParseFinalizeOptions, + ResumableSessionParseState, + SessionAccumulator +} from './session-scanner-types' import { + addCodexUsage, asRecord, extractContentText, extractGitBranch, @@ -24,15 +31,6 @@ import { subtractCodexUsage } from './session-scanner-values' -const CODEX_SESSION_INDEX_FILE = 'session_index.jsonl' - -type CodexSessionIndexTitleCacheEntry = { - signature: string - titles: Map -} - -const codexSessionIndexTitleCache = new Map>() - export async function parseCodexSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform, @@ -74,6 +72,213 @@ export async function parseCodexSessionContent(args: { }) } +type CodexSessionParseState = { + accumulator: SessionAccumulator + previousTotals: CodexUsageSnapshot | null + rejectedWorkerSession: boolean + sawSessionMeta: boolean + // Which source set the current title; an index-file title outranks the raw + // first user prompt, so finalize must know whether 'meta' already won. + titleSource: 'meta' | 'user' | null +} + +function createCodexParseState(file: FileWithMtime): CodexSessionParseState { + return { + accumulator: createAccumulator({ + agent: 'codex', + file, + sessionId: sessionIdFromFileName(file.path) + }), + previousTotals: null, + rejectedWorkerSession: false, + sawSessionMeta: false, + titleSource: null + } +} + +function cloneCodexParseState(state: CodexSessionParseState): CodexSessionParseState { + return { + // previousTotals snapshots are replaced, never mutated, so sharing is safe. + ...state, + accumulator: cloneSessionAccumulator(state.accumulator) + } +} + +function consumeCodexRecordLine(state: CodexSessionParseState, line: string): void { + if (state.rejectedWorkerSession) { + return + } + const record = parseJsonObject(line) + if (!record) { + return + } + const { accumulator } = state + + updateTimeline(accumulator, extractString(record.timestamp)) + + const payload = asRecord(record.payload) + if (record.type === 'session_meta' && payload) { + if (isCodexWorkerSession(payload)) { + // Why: Codex writes internal worker/sub-agent transcripts into the same + // history tree; AI Vault should show user-started sessions only. + state.rejectedWorkerSession = true + return + } + state.sawSessionMeta = true + const sessionId = extractString(payload.id) + if (sessionId) { + accumulator.sessionId = sessionId + } + const metadataTitle = extractCodexSessionMetadataTitle(payload) + if (metadataTitle) { + accumulator.title = metadataTitle + state.titleSource = 'meta' + } + const cwd = extractString(payload.cwd) + if (cwd) { + accumulator.cwd = cwd + } + accumulator.branch = extractGitBranch(payload.git) ?? accumulator.branch + return + } + + if (record.type === 'turn_context' && payload) { + const cwd = extractString(payload.cwd) + if (cwd) { + accumulator.cwd = cwd + } + const model = extractModel(payload) + if (model) { + accumulator.model = model + } + return + } + + if (!payload) { + return + } + + if (record.type === 'response_item' && payload.type === 'message') { + accumulator.messageCount++ + if (payload.role === 'user' && !accumulator.title) { + accumulator.title = extractContentText(payload.content) + state.titleSource = accumulator.title ? 'user' : state.titleSource + } + addPreviewContent( + accumulator, + payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : 'unknown', + payload.content, + record.timestamp + ) + return + } + + if (record.type !== 'event_msg') { + return + } + + if (payload.type === 'user_message') { + accumulator.messageCount++ + if (!accumulator.title) { + accumulator.title = extractContentText(payload.message) + state.titleSource = accumulator.title ? 'user' : state.titleSource + } + addPreviewContent(accumulator, 'user', payload.message, record.timestamp) + return + } + + if (payload.type === 'agent_message') { + accumulator.messageCount++ + addPreviewContent(accumulator, 'assistant', payload.message, record.timestamp) + return + } + + if (payload.type !== 'token_count') { + return + } + + const info = asRecord(payload.info) + if (!info) { + return + } + const totalUsage = normalizeCodexUsage(info.total_token_usage) + const lastUsage = normalizeCodexUsage(info.last_token_usage) + let delta: CodexUsageSnapshot | null = null + if (totalUsage) { + delta = subtractCodexUsage(totalUsage, state.previousTotals) + state.previousTotals = totalUsage + } else if (lastUsage) { + delta = lastUsage + state.previousTotals = state.previousTotals + ? addCodexUsage(state.previousTotals, lastUsage) + : lastUsage + } + if (delta) { + accumulator.totalTokens += delta.totalTokens + } + const model = extractModel(payload) + if (model) { + accumulator.model = model + } +} + +async function finalizeCodexParseState( + state: CodexSessionParseState, + platform: NodeJS.Platform, + args: { + codexHome: string | null + titleReader?: (sessionId: string) => Promise + executionHostId?: ExecutionHostId + executionHostPlatform?: NodeJS.Platform | null + } +): Promise { + if (state.rejectedWorkerSession) { + return null + } + // Finalize a snapshot: the live state keeps accumulating appended lines. + const snapshot = cloneCodexParseState(state) + // Why: Codex names threads lazily in session_index.jsonl, so the lookup runs + // per finalize (the index read is signature-cached) — a title that appears + // after the transcript was first parsed must still replace the raw prompt. + if (snapshot.sawSessionMeta && snapshot.titleSource !== 'meta') { + const indexedTitle = await args.titleReader?.(snapshot.accumulator.sessionId) + if (indexedTitle) { + snapshot.accumulator.title = indexedTitle + } + } + return finalizeSession(snapshot.accumulator, platform, { + codexHome: args.codexHome, + executionHostId: args.executionHostId, + executionHostPlatform: args.executionHostPlatform + }) +} + +export function createCodexSessionResumeState( + file: FileWithMtime, + codexHome: string | null +): ResumableSessionParseState { + return codexResumeStateFromParseState(createCodexParseState(file), codexHome, (sessionId) => + readCodexSessionIndexTitle(file.path, codexHome, sessionId) + ) +} + +function codexResumeStateFromParseState( + state: CodexSessionParseState, + codexHome: string | null, + titleReader: (sessionId: string) => Promise +): ResumableSessionParseState { + return { + consumeLine: (line) => consumeCodexRecordLine(state, line), + clone: () => + codexResumeStateFromParseState(cloneCodexParseState(state), codexHome, titleReader), + touchFile: (file) => { + state.accumulator.modifiedAt = file.modifiedAt + }, + finalize: (platform, options?: ResumableParseFinalizeOptions) => + finalizeCodexParseState(state, platform, { codexHome, titleReader, ...options }) + } +} + async function parseCodexSessionLines(args: { file: FileWithMtime lines: AsyncIterable | Iterable @@ -83,142 +288,22 @@ async function parseCodexSessionLines(args: { executionHostPlatform?: NodeJS.Platform | null titleReader?: (sessionId: string) => Promise }): Promise { - const accumulator = createAccumulator({ - agent: 'codex', - file: args.file, - sessionId: sessionIdFromFileName(args.file.path) - }) - let previousTotals: CodexUsageSnapshot | null = null - + const state = createCodexParseState(args.file) for await (const line of args.lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - - updateTimeline(accumulator, extractString(record.timestamp)) - - const payload = asRecord(record.payload) - if (record.type === 'session_meta' && payload) { - if (isCodexWorkerSession(payload)) { - // Why: Codex writes internal worker/sub-agent transcripts into the same - // history tree; AI Vault should show user-started sessions only. - return null - } - const sessionId = extractString(payload.id) - if (sessionId) { - accumulator.sessionId = sessionId - } - const indexedTitle = - extractCodexSessionMetadataTitle(payload) ?? - (await args.titleReader?.(accumulator.sessionId)) - if (indexedTitle) { - accumulator.title = indexedTitle - } - const cwd = extractString(payload.cwd) - if (cwd) { - accumulator.cwd = cwd - } - accumulator.branch = extractGitBranch(payload.git) ?? accumulator.branch - continue - } - - if (record.type === 'turn_context' && payload) { - const cwd = extractString(payload.cwd) - if (cwd) { - accumulator.cwd = cwd - } - const model = extractModel(payload) - if (model) { - accumulator.model = model - } - continue - } - - if (!payload) { - continue - } - - if (record.type === 'response_item' && payload.type === 'message') { - accumulator.messageCount++ - if (payload.role === 'user' && !accumulator.title) { - accumulator.title = extractContentText(payload.content) - } - addPreviewContent( - accumulator, - payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : 'unknown', - payload.content, - record.timestamp - ) - continue - } - - if (record.type !== 'event_msg') { - continue - } - - if (payload.type === 'user_message') { - accumulator.messageCount++ - if (!accumulator.title) { - accumulator.title = extractContentText(payload.message) - } - addPreviewContent(accumulator, 'user', payload.message, record.timestamp) - continue - } - - if (payload.type === 'agent_message') { - accumulator.messageCount++ - addPreviewContent(accumulator, 'assistant', payload.message, record.timestamp) - continue - } - - if (payload.type !== 'token_count') { - continue - } - - const info = asRecord(payload.info) - if (!info) { - continue - } - const totalUsage = normalizeCodexUsage(info.total_token_usage) - const lastUsage = normalizeCodexUsage(info.last_token_usage) - let delta: CodexUsageSnapshot | null = null - if (totalUsage) { - delta = subtractCodexUsage(totalUsage, previousTotals) - previousTotals = totalUsage - } else if (lastUsage) { - delta = lastUsage - previousTotals = previousTotals ? addCodexUsage(previousTotals, lastUsage) : lastUsage - } - if (delta) { - accumulator.totalTokens += delta.totalTokens - } - const model = extractModel(payload) - if (model) { - accumulator.model = model + consumeCodexRecordLine(state, line) + if (state.rejectedWorkerSession) { + // Worker transcripts are excluded outright; stop reading early. + return null } } - - return finalizeSession(accumulator, args.platform, { + return finalizeCodexParseState(state, args.platform, { codexHome: args.codexHome, + titleReader: args.titleReader, executionHostId: args.executionHostId, executionHostPlatform: args.executionHostPlatform }) } -function addCodexUsage( - base: CodexUsageSnapshot, - increment: CodexUsageSnapshot -): CodexUsageSnapshot { - return { - inputTokens: base.inputTokens + increment.inputTokens, - cachedInputTokens: base.cachedInputTokens + increment.cachedInputTokens, - outputTokens: base.outputTokens + increment.outputTokens, - reasoningOutputTokens: base.reasoningOutputTokens + increment.reasoningOutputTokens, - totalTokens: base.totalTokens + increment.totalTokens - } -} - function extractCodexThreadSource(payload: Record): string | null { return extractString(payload.thread_source) ?? extractString(payload.threadSource) } @@ -240,79 +325,3 @@ function extractCodexSessionMetadataTitle(payload: Record): str normalizeTitleText(extractString(payload.threadName) ?? '') ) } - -async function readCodexSessionIndexTitle( - sessionFilePath: string, - codexHome: string | null, - sessionId: string -): Promise { - const resolvedCodexHome = codexHome ?? codexHomeFromSessionFilePath(sessionFilePath) - if (!resolvedCodexHome) { - return null - } - const titleBySessionId = await readCodexSessionIndexTitles(resolvedCodexHome) - return titleBySessionId.get(sessionId) ?? null -} - -function codexHomeFromSessionFilePath(sessionFilePath: string): string | null { - let currentDir = dirname(sessionFilePath) - while (currentDir && dirname(currentDir) !== currentDir) { - if (basename(currentDir) === 'sessions') { - return dirname(currentDir) - } - currentDir = dirname(currentDir) - } - return null -} - -async function readCodexSessionIndexTitles(codexHome: string): Promise> { - const indexPath = join(codexHome, CODEX_SESSION_INDEX_FILE) - let signature: string - try { - const indexStat = await stat(indexPath) - signature = `${indexStat.size}:${indexStat.mtimeMs}` - } catch { - return new Map() - } - - const cached = codexSessionIndexTitleCache.get(codexHome) - if (cached) { - const entry = await cached - if (entry.signature === signature) { - return entry.titles - } - } - - const pending = readCodexSessionIndexTitlesFromDisk(indexPath).then((titles) => ({ - signature, - titles - })) - codexSessionIndexTitleCache.set(codexHome, pending) - return (await pending).titles -} - -async function readCodexSessionIndexTitlesFromDisk( - indexPath: string -): Promise> { - const titleBySessionId = new Map() - try { - const lines = createInterface({ - input: createReadStream(indexPath, { encoding: 'utf-8' }), - crlfDelay: Infinity - }) - for await (const line of lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - const sessionId = extractString(record.id) - const title = normalizeTitleText(extractString(record.thread_name) ?? '') - if (sessionId && title) { - titleBySessionId.set(sessionId, title) - } - } - } catch { - // Codex creates the index opportunistically; older homes may only have raw transcripts. - } - return titleBySessionId -} diff --git a/src/main/ai-vault/session-scanner-codex-title-index.ts b/src/main/ai-vault/session-scanner-codex-title-index.ts new file mode 100644 index 000000000..d22f964f5 --- /dev/null +++ b/src/main/ai-vault/session-scanner-codex-title-index.ts @@ -0,0 +1,93 @@ +import { createReadStream } from 'node:fs' +import { stat } from 'node:fs/promises' +import { basename, dirname, join } from 'node:path' +import { createInterface } from 'node:readline' +import { extractString, normalizeTitleText, parseJsonObject } from './session-scanner-values' + +// Codex names threads lazily in /session_index.jsonl; transcripts +// carry no title of their own, so parsers look the thread name up here. + +const CODEX_SESSION_INDEX_FILE = 'session_index.jsonl' + +type CodexSessionIndexTitleCacheEntry = { + signature: string + titles: Map +} + +const codexSessionIndexTitleCache = new Map>() + +export async function readCodexSessionIndexTitle( + sessionFilePath: string, + codexHome: string | null, + sessionId: string +): Promise { + const resolvedCodexHome = codexHome ?? codexHomeFromSessionFilePath(sessionFilePath) + if (!resolvedCodexHome) { + return null + } + const titleBySessionId = await readCodexSessionIndexTitles(resolvedCodexHome) + return titleBySessionId.get(sessionId) ?? null +} + +function codexHomeFromSessionFilePath(sessionFilePath: string): string | null { + let currentDir = dirname(sessionFilePath) + while (currentDir && dirname(currentDir) !== currentDir) { + if (basename(currentDir) === 'sessions') { + return dirname(currentDir) + } + currentDir = dirname(currentDir) + } + return null +} + +async function readCodexSessionIndexTitles(codexHome: string): Promise> { + const indexPath = join(codexHome, CODEX_SESSION_INDEX_FILE) + let signature: string + try { + const indexStat = await stat(indexPath) + signature = `${indexStat.size}:${indexStat.mtimeMs}` + } catch { + return new Map() + } + + const cached = codexSessionIndexTitleCache.get(codexHome) + if (cached) { + const entry = await cached + if (entry.signature === signature) { + return entry.titles + } + } + + const pending = readCodexSessionIndexTitlesFromDisk(indexPath).then((titles) => ({ + signature, + titles + })) + codexSessionIndexTitleCache.set(codexHome, pending) + return (await pending).titles +} + +async function readCodexSessionIndexTitlesFromDisk( + indexPath: string +): Promise> { + const titleBySessionId = new Map() + try { + const lines = createInterface({ + input: createReadStream(indexPath, { encoding: 'utf-8' }), + crlfDelay: Infinity + }) + for await (const line of lines) { + const record = parseJsonObject(line) + if (!record) { + continue + } + const sessionId = extractString(record.id) + const title = normalizeTitleText(extractString(record.thread_name) ?? '') + if (sessionId && title) { + titleBySessionId.set(sessionId, title) + } + } + } catch { + // Codex creates the index opportunistically; older homes may only have raw transcripts. + } + return titleBySessionId +} diff --git a/src/main/ai-vault/session-scanner-codex-workers.test.ts b/src/main/ai-vault/session-scanner-codex-workers.test.ts index 585e37b02..8a6fb183f 100644 --- a/src/main/ai-vault/session-scanner-codex-workers.test.ts +++ b/src/main/ai-vault/session-scanner-codex-workers.test.ts @@ -117,6 +117,7 @@ describe('scanAiVaultSessions Codex worker sessions', () => { openclawStateDir: join(root, 'openclaw-state'), openclawLegacyStateDir: join(root, 'openclaw-legacy-state'), piSessionsDir: join(root, 'pi-sessions'), + ompSessionsDir: join(root, 'omp-sessions'), droidSessionsDir: join(root, 'droid-sessions'), droidProjectsDir: join(root, 'droid-projects'), kimiSessionsDir: join(root, 'kimi-sessions'), diff --git a/src/main/ai-vault/session-scanner-discovery.ts b/src/main/ai-vault/session-scanner-discovery.ts index f5541ca39..9bfade6e6 100644 --- a/src/main/ai-vault/session-scanner-discovery.ts +++ b/src/main/ai-vault/session-scanner-discovery.ts @@ -25,7 +25,8 @@ export async function discoverFiles(args: { files.push({ path, mtimeMs: fileStat.mtimeMs, - modifiedAt: fileStat.mtime.toISOString() + modifiedAt: fileStat.mtime.toISOString(), + sizeBytes: fileStat.size }) } catch (err) { args.issues.push({ agent: args.agent, path, message: errorMessage(err) }) diff --git a/src/main/ai-vault/session-scanner-droid-parser.ts b/src/main/ai-vault/session-scanner-droid-parser.ts index d99795bbb..2abaa7b81 100644 --- a/src/main/ai-vault/session-scanner-droid-parser.ts +++ b/src/main/ai-vault/session-scanner-droid-parser.ts @@ -2,11 +2,15 @@ import { createReadStream } from 'node:fs' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' -import type { FileWithMtime, SessionAccumulator } from './session-scanner-types' +import type { + FileWithMtime, + ResumableSessionParseState, + SessionAccumulator +} from './session-scanner-types' import { + accumulatorFoldResumeState, addPreviewMessage, createAccumulator, - finalizeSession, sessionIdFromFileName, updateTimeline } from './session-scanner-accumulator' @@ -50,51 +54,57 @@ export async function parseDroidSessionContent( }) } +function consumeDroidRecordLine(accumulator: SessionAccumulator, line: string): void { + const record = parseJsonObject(line) + if (!record) { + return + } + updateTimeline(accumulator, record.timestamp) + if (record.type === 'session_start') { + accumulator.sessionId = extractString(record.id) ?? accumulator.sessionId + accumulator.title = normalizeTitleText(extractString(record.title) ?? '') + accumulator.cwd = extractString(record.cwd) ?? accumulator.cwd + return + } + if (record.type === 'system') { + accumulator.cwd = extractString(record.cwd) ?? accumulator.cwd + accumulator.model = extractString(record.model) ?? accumulator.model + } + const streamSessionId = extractString(record.session_id) ?? extractString(record.sessionId) + if (streamSessionId) { + accumulator.sessionId = streamSessionId + } + if (record.type === 'message') { + consumeDroidMessage(accumulator, record) + } else if (record.type === 'completion') { + accumulator.messageCount++ + accumulator.totalTokens += tokenTotal(record.usage) + addPreviewMessage(accumulator, { + role: 'assistant', + text: extractString(record.finalText), + timestamp: record.timestamp + }) + } +} + +export function createDroidSessionResumeState(file: FileWithMtime): ResumableSessionParseState { + return accumulatorFoldResumeState( + createAccumulator({ agent: 'droid', file, sessionId: sessionIdFromFileName(file.path) }), + consumeDroidRecordLine + ) +} + async function parseDroidSessionLines(args: { file: FileWithMtime lines: AsyncIterable | Iterable platform: NodeJS.Platform options?: ParserSessionOptions }): Promise { - const accumulator = createAccumulator({ - agent: 'droid', - file: args.file, - sessionId: sessionIdFromFileName(args.file.path) - }) - + const state = createDroidSessionResumeState(args.file) for await (const line of args.lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - updateTimeline(accumulator, record.timestamp) - if (record.type === 'session_start') { - accumulator.sessionId = extractString(record.id) ?? accumulator.sessionId - accumulator.title = normalizeTitleText(extractString(record.title) ?? '') - accumulator.cwd = extractString(record.cwd) ?? accumulator.cwd - continue - } - if (record.type === 'system') { - accumulator.cwd = extractString(record.cwd) ?? accumulator.cwd - accumulator.model = extractString(record.model) ?? accumulator.model - } - const streamSessionId = extractString(record.session_id) ?? extractString(record.sessionId) - if (streamSessionId) { - accumulator.sessionId = streamSessionId - } - if (record.type === 'message') { - consumeDroidMessage(accumulator, record) - } else if (record.type === 'completion') { - accumulator.messageCount++ - accumulator.totalTokens += tokenTotal(record.usage) - addPreviewMessage(accumulator, { - role: 'assistant', - text: extractString(record.finalText), - timestamp: record.timestamp - }) - } + state.consumeLine(line) } - return finalizeSession(accumulator, args.platform, args.options) + return state.finalize(args.platform, args.options) } function consumeDroidMessage( diff --git a/src/main/ai-vault/session-scanner-graph-parsers.ts b/src/main/ai-vault/session-scanner-graph-parsers.ts index a52c83b32..04601eacd 100644 --- a/src/main/ai-vault/session-scanner-graph-parsers.ts +++ b/src/main/ai-vault/session-scanner-graph-parsers.ts @@ -4,8 +4,13 @@ import { basename, dirname, join } from 'node:path' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' -import type { FileWithMtime, SessionAccumulator } from './session-scanner-types' +import type { + FileWithMtime, + ResumableSessionParseState, + SessionAccumulator +} from './session-scanner-types' import { + accumulatorFoldResumeState, addPreviewContent, addPreviewMessage, createAccumulator, @@ -158,8 +163,12 @@ export function rovoPartsText(parts: unknown[], role: 'user' | 'assistant'): str return extractContentText(textParts) } +// Agents whose transcripts are append-only message-graph JSONL (session + +// model_change + message records). OMP is a Pi fork and shares the format. +export type MessageGraphAgent = 'openclaw' | 'pi' | 'omp' + export async function parseMessageGraphSessionFile( - agent: 'openclaw' | 'pi', + agent: MessageGraphAgent, file: FileWithMtime, platform: NodeJS.Platform = process.platform ): Promise { @@ -171,7 +180,7 @@ export async function parseMessageGraphSessionFile( } export async function parseMessageGraphSessionContent( - agent: 'openclaw' | 'pi', + agent: MessageGraphAgent, file: FileWithMtime, content: string, platform: NodeJS.Platform = process.platform, @@ -186,53 +195,64 @@ export async function parseMessageGraphSessionContent( }) } +function consumeMessageGraphRecordLine(accumulator: SessionAccumulator, line: string): void { + const record = parseJsonObject(line) + if (!record) { + return + } + updateTimeline(accumulator, extractString(record.timestamp)) + if (record.type === 'session') { + const sessionId = extractString(record.id) + if (sessionId) { + accumulator.sessionId = sessionId + } + accumulator.cwd = extractString(record.cwd) ?? accumulator.cwd + return + } + if (record.type === 'model_change') { + // Pi writes `modelId`; OMP writes `model`. Prefer either so an in-progress + // session shows its model before the first assistant reply lands. + accumulator.model = + extractString(record.modelId) ?? extractString(record.model) ?? accumulator.model + return + } + if (record.type !== 'message') { + return + } + const message = asRecord(record.message) + const role = extractString(message?.role) + if (role === 'user' || role === 'assistant') { + accumulator.messageCount++ + if (role === 'user') { + accumulator.title ??= extractMessageText(message) + } else { + accumulator.model = extractString(message?.model) ?? accumulator.model + accumulator.totalTokens += tokenTotal(message?.usage) + } + addPreviewContent(accumulator, role, message?.content, record.timestamp) + } +} + +export function createMessageGraphSessionResumeState( + agent: MessageGraphAgent, + file: FileWithMtime +): ResumableSessionParseState { + return accumulatorFoldResumeState( + createAccumulator({ agent, file, sessionId: sessionIdFromFileName(file.path) }), + consumeMessageGraphRecordLine + ) +} + async function parseMessageGraphSessionLines(args: { - agent: 'openclaw' | 'pi' + agent: MessageGraphAgent file: FileWithMtime lines: AsyncIterable | Iterable platform: NodeJS.Platform options?: ParserSessionOptions }): Promise { - const accumulator = createAccumulator({ - agent: args.agent, - file: args.file, - sessionId: sessionIdFromFileName(args.file.path) - }) - + const state = createMessageGraphSessionResumeState(args.agent, args.file) for await (const line of args.lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - updateTimeline(accumulator, extractString(record.timestamp)) - if (record.type === 'session') { - const sessionId = extractString(record.id) - if (sessionId) { - accumulator.sessionId = sessionId - } - accumulator.cwd = extractString(record.cwd) ?? accumulator.cwd - continue - } - if (record.type === 'model_change') { - accumulator.model = extractString(record.modelId) ?? accumulator.model - continue - } - if (record.type !== 'message') { - continue - } - const message = asRecord(record.message) - const role = extractString(message?.role) - if (role === 'user' || role === 'assistant') { - accumulator.messageCount++ - if (role === 'user') { - accumulator.title ??= extractMessageText(message) - } else { - accumulator.model = extractString(message?.model) ?? accumulator.model - accumulator.totalTokens += tokenTotal(message?.usage) - } - addPreviewContent(accumulator, role, message?.content, record.timestamp) - } + state.consumeLine(line) } - - return finalizeSession(accumulator, args.platform, args.options) + return state.finalize(args.platform, args.options) } diff --git a/src/main/ai-vault/session-scanner-incremental-fixtures.ts b/src/main/ai-vault/session-scanner-incremental-fixtures.ts new file mode 100644 index 000000000..1945193e6 --- /dev/null +++ b/src/main/ai-vault/session-scanner-incremental-fixtures.ts @@ -0,0 +1,291 @@ +import type { AiVaultAgent } from '../../shared/ai-vault-types' + +import { codexFixture } from './session-scanner-codex-fixtures' + +// Line builders for the incremental-parse differential tests: each agent gets +// a seed transcript, an appended continuation, and a truncated rewrite, all in +// that agent's real on-disk JSONL record shapes. + +export type IncrementalAgentFixture = { + agent: AiVaultAgent + fileName: string + seedLines: string[] + appendLines: string[] + truncatedLines: string[] +} + +export function cursorFixture(): IncrementalAgentFixture { + const line = (role: string, text: string, at: string) => + JSON.stringify({ role, message: { content: text }, timestamp: at }) + return { + agent: 'cursor', + fileName: 'agent-transcripts-aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl', + seedLines: [ + line('user', 'cursor seed question', '2026-05-01T10:00:00.000Z'), + line('assistant', 'cursor seed answer', '2026-05-01T10:01:00.000Z') + ], + appendLines: [ + line('user', 'cursor follow-up', '2026-05-01T10:02:00.000Z'), + line('assistant', 'cursor incremental answer', '2026-05-01T10:03:00.000Z') + ], + truncatedLines: [line('user', 'cursor rewritten', '2026-05-01T10:00:00.000Z')] + } +} + +export function copilotFixture(): IncrementalAgentFixture { + const line = (type: string, data: Record, at: string) => + JSON.stringify({ type, data, timestamp: at }) + return { + agent: 'copilot', + fileName: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl', + seedLines: [ + line( + 'session.start', + { sessionId: 'copilot-session-1', startTime: '2026-05-01T10:00:00.000Z' }, + '2026-05-01T10:00:00.000Z' + ), + line('user.message', { content: 'copilot seed question' }, '2026-05-01T10:00:05.000Z'), + line('assistant.message', { content: 'copilot seed answer' }, '2026-05-01T10:00:30.000Z') + ], + appendLines: [ + line('user.message', { content: 'copilot follow-up' }, '2026-05-01T10:05:00.000Z'), + line( + 'assistant.message', + { content: 'copilot incremental answer' }, + '2026-05-01T10:05:30.000Z' + ), + line( + 'session.shutdown', + { currentModel: 'gpt-5.1', currentTokens: 340 }, + '2026-05-01T10:06:00.000Z' + ) + ], + truncatedLines: [ + line( + 'session.start', + { sessionId: 'copilot-session-1', startTime: '2026-05-01T10:00:00.000Z' }, + '2026-05-01T10:00:00.000Z' + ) + ] + } +} + +export function droidFixture(): IncrementalAgentFixture { + return { + agent: 'droid', + fileName: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl', + seedLines: [ + JSON.stringify({ + type: 'session_start', + id: 'droid-session-1', + title: 'Droid seed task', + cwd: '/repo/app', + timestamp: '2026-05-01T10:00:00.000Z' + }), + JSON.stringify({ + type: 'message', + role: 'user', + text: 'droid seed question', + timestamp: '2026-05-01T10:00:05.000Z' + }) + ], + appendLines: [ + JSON.stringify({ + type: 'completion', + finalText: 'droid incremental answer', + usage: { input_tokens: 50, output_tokens: 25 }, + timestamp: '2026-05-01T10:01:00.000Z' + }) + ], + truncatedLines: [ + JSON.stringify({ + type: 'session_start', + id: 'droid-session-1', + title: 'Droid rewritten', + timestamp: '2026-05-01T10:00:00.000Z' + }) + ] + } +} + +export function openclawFixture(): IncrementalAgentFixture { + return { + agent: 'openclaw', + fileName: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl', + seedLines: [ + JSON.stringify({ + type: 'session', + id: 'openclaw-session-1', + cwd: '/repo/app', + timestamp: '2026-05-01T10:00:00.000Z' + }), + JSON.stringify({ + type: 'message', + message: { role: 'user', content: 'openclaw seed question' }, + timestamp: '2026-05-01T10:00:05.000Z' + }) + ], + appendLines: [ + JSON.stringify({ + type: 'message', + message: { + role: 'assistant', + content: 'openclaw incremental answer', + model: 'claw-1', + usage: { input_tokens: 40, output_tokens: 20 } + }, + timestamp: '2026-05-01T10:01:00.000Z' + }) + ], + truncatedLines: [ + JSON.stringify({ + type: 'session', + id: 'openclaw-session-1', + timestamp: '2026-05-01T10:00:00.000Z' + }) + ] + } +} + +// Pi shares OpenClaw's message-graph format and factory, but gets its own +// fixture so the registry's 'pi' branch is exercised explicitly. +export function piFixture(): IncrementalAgentFixture { + return { + agent: 'pi', + fileName: 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff.jsonl', + seedLines: [ + JSON.stringify({ + type: 'session', + id: 'pi-session-1', + cwd: '/repo/app', + timestamp: '2026-05-01T10:00:00.000Z' + }), + JSON.stringify({ + type: 'message', + message: { role: 'user', content: 'pi seed question' }, + timestamp: '2026-05-01T10:00:05.000Z' + }) + ], + appendLines: [ + JSON.stringify({ + type: 'model_change', + modelId: 'pi-2', + timestamp: '2026-05-01T10:00:30.000Z' + }), + JSON.stringify({ + type: 'message', + message: { + role: 'assistant', + content: 'pi incremental answer', + usage: { input_tokens: 30, output_tokens: 10 } + }, + timestamp: '2026-05-01T10:01:00.000Z' + }) + ], + truncatedLines: [ + JSON.stringify({ type: 'session', id: 'pi-session-1', timestamp: '2026-05-01T10:00:00.000Z' }) + ] + } +} + +// OMP is a Pi fork sharing the message-graph format, but keys the model on +// `model` (not Pi's `modelId`); its own fixture exercises the registry's 'omp' +// branch and that model-key difference. (The session `title` is included for +// realism only — the parser derives the title from the first user message.) +export function ompFixture(): IncrementalAgentFixture { + return { + agent: 'omp', + fileName: '2026-05-01T10-00-00-000Z_cccccccc-dddd-4eee-8fff-000000000000.jsonl', + seedLines: [ + JSON.stringify({ + type: 'session', + version: 3, + id: 'cccccccc-dddd-4eee-8fff-000000000000', + cwd: '/repo/app', + title: 'OMP session title', + timestamp: '2026-05-01T10:00:00.000Z' + }), + JSON.stringify({ + type: 'model_change', + model: 'gpt-5.4-mini', + timestamp: '2026-05-01T10:00:01.000Z' + }), + JSON.stringify({ + type: 'message', + message: { role: 'user', content: [{ type: 'text', text: 'omp seed question' }] }, + timestamp: '2026-05-01T10:00:05.000Z' + }) + ], + appendLines: [ + JSON.stringify({ + type: 'message', + message: { + role: 'assistant', + content: [{ type: 'text', text: 'omp incremental answer' }], + model: 'gpt-5.4-mini', + usage: { input: 40, output: 20, totalTokens: 60 } + }, + timestamp: '2026-05-01T10:01:00.000Z' + }) + ], + truncatedLines: [ + JSON.stringify({ + type: 'session', + id: 'cccccccc-dddd-4eee-8fff-000000000000', + timestamp: '2026-05-01T10:00:00.000Z' + }) + ] + } +} + +export function geminiJsonlFixture(): IncrementalAgentFixture { + return { + agent: 'gemini', + fileName: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl', + seedLines: [ + JSON.stringify({ + sessionId: 'gemini-session-1', + startTime: '2026-05-01T10:00:00.000Z', + type: 'user', + content: 'gemini seed question', + timestamp: '2026-05-01T10:00:00.000Z' + }), + JSON.stringify({ + type: 'gemini', + content: 'gemini seed answer', + model: 'gemini-3-pro', + tokens: { input: 80, output: 30 }, + timestamp: '2026-05-01T10:00:30.000Z' + }) + ], + appendLines: [ + JSON.stringify({ + type: 'user', + content: 'gemini follow-up', + timestamp: '2026-05-01T10:01:00.000Z' + }), + JSON.stringify({ $set: { lastUpdated: '2026-05-01T10:01:05.000Z' } }) + ], + truncatedLines: [ + JSON.stringify({ + sessionId: 'gemini-session-1', + type: 'user', + content: 'gemini rewritten', + timestamp: '2026-05-01T10:00:00.000Z' + }) + ] + } +} + +export function allIncrementalAgentFixtures(): IncrementalAgentFixture[] { + return [ + codexFixture(), + cursorFixture(), + copilotFixture(), + droidFixture(), + openclawFixture(), + piFixture(), + ompFixture(), + geminiJsonlFixture() + ] +} diff --git a/src/main/ai-vault/session-scanner-opencode-sqlite-coexistence.test.ts b/src/main/ai-vault/session-scanner-opencode-sqlite-coexistence.test.ts index d0eaa6498..2fb3df216 100644 --- a/src/main/ai-vault/session-scanner-opencode-sqlite-coexistence.test.ts +++ b/src/main/ai-vault/session-scanner-opencode-sqlite-coexistence.test.ts @@ -36,7 +36,8 @@ function isolatedScanRoots(root: string) { piSessionsDir: join(root, 'pi-sessions'), droidSessionsDir: join(root, 'droid-sessions'), droidProjectsDir: join(root, 'droid-projects'), - kimiSessionsDir: join(root, 'kimi-sessions') + kimiSessionsDir: join(root, 'kimi-sessions'), + ompSessionsDir: join(root, 'omp-sessions') } } diff --git a/src/main/ai-vault/session-scanner-parse-cache-agents.test.ts b/src/main/ai-vault/session-scanner-parse-cache-agents.test.ts new file mode 100644 index 000000000..61348ad7c --- /dev/null +++ b/src/main/ai-vault/session-scanner-parse-cache-agents.test.ts @@ -0,0 +1,250 @@ +import { appendFile, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { parseAgentSessionFile } from './session-scanner-agent-parser' +import { + CODEX_FIXTURE_SESSION_ID, + codexFixture, + codexWorkerFixtureLines +} from './session-scanner-codex-fixtures' +import { allIncrementalAgentFixtures } from './session-scanner-incremental-fixtures' +import { + createSessionParseStats, + parseAgentSessionFileCached, + resetSessionParseCacheForTests +} from './session-scanner-parse-cache' +import type { SessionFileCandidate } from './session-scanner-types' + +let tempRoots: string[] = [] + +beforeEach(() => { + resetSessionParseCacheForTests() +}) + +afterEach(async () => { + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +async function makeTempDir(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-parse-cache-agents-')) + tempRoots.push(root) + return root +} + +async function candidateFor( + agent: SessionFileCandidate['agent'], + path: string, + codexHome: string | null = null +): Promise { + const fileStat = await stat(path) + return { + agent, + file: { + path, + mtimeMs: fileStat.mtimeMs, + modifiedAt: fileStat.mtime.toISOString(), + sizeBytes: fileStat.size + }, + codexHome + } +} + +describe.each(allIncrementalAgentFixtures())('incremental parse parity: $agent', (fixture) => { + it('reuses unchanged files, resumes appends, and matches cold parses exactly', async () => { + const root = await makeTempDir() + const path = join(root, fixture.fileName) + await writeFile(path, `${fixture.seedLines.join('\n')}\n`) + + const stats = createSessionParseStats() + const seedCandidate = await candidateFor(fixture.agent, path) + const seeded = await parseAgentSessionFileCached(seedCandidate, process.platform, stats) + expect(stats.fullParses).toBe(1) + expect(seeded).toEqual(await parseAgentSessionFile(seedCandidate, process.platform)) + + // Unchanged rescan returns the identical cached object. + const reused = await parseAgentSessionFileCached(seedCandidate, process.platform, stats) + expect(reused).toBe(seeded) + expect(stats.reused).toBe(1) + + // Appended lines resume from the stored byte offset and must equal a + // cold parse of the grown file. + await appendFile(path, `${fixture.appendLines.join('\n')}\n`) + const grownCandidate = await candidateFor(fixture.agent, path) + const incremental = await parseAgentSessionFileCached(grownCandidate, process.platform, stats) + expect(stats.incremental).toBe(1) + expect(incremental).toEqual(await parseAgentSessionFile(grownCandidate, process.platform)) + + // A truncated rewrite falls back to a full parse. + await writeFile(path, `${fixture.truncatedLines.join('\n')}\n`) + const truncatedCandidate = await candidateFor(fixture.agent, path) + const reparsed = await parseAgentSessionFileCached(truncatedCandidate, process.platform, stats) + expect(stats.fullParses).toBe(2) + expect(reparsed).toEqual(await parseAgentSessionFile(truncatedCandidate, process.platform)) + }) + + it('includes a trailing unterminated line without double-counting it later', async () => { + const root = await makeTempDir() + const path = join(root, fixture.fileName) + const lastSeedLine = fixture.seedLines.at(-1) + const headLines = fixture.seedLines.slice(0, -1) + await writeFile(path, `${[...headLines, ''].join('\n')}${lastSeedLine}`) + + const partialCandidate = await candidateFor(fixture.agent, path) + const shown = await parseAgentSessionFileCached(partialCandidate, process.platform) + expect(shown).toEqual(await parseAgentSessionFile(partialCandidate, process.platform)) + + await appendFile(path, `\n${fixture.appendLines.join('\n')}\n`) + const grownCandidate = await candidateFor(fixture.agent, path) + const stats = createSessionParseStats() + const completed = await parseAgentSessionFileCached(grownCandidate, process.platform, stats) + expect(stats.incremental).toBe(1) + expect(completed).toEqual(await parseAgentSessionFile(grownCandidate, process.platform)) + }) + + it('tolerates a mid-write truncated trailing line and never double-counts it', async () => { + const root = await makeTempDir() + const path = join(root, fixture.fileName) + // A writer caught mid-record: the trailing line is invalid JSON. + await writeFile(path, `${fixture.seedLines.join('\n')}\n{"type":"user","mess`) + + const shown = await parseAgentSessionFileCached( + await candidateFor(fixture.agent, path), + process.platform + ) + expect(shown).toEqual( + await parseAgentSessionFile(await candidateFor(fixture.agent, path), process.platform) + ) + + // The writer "finishes" the interrupted record as unparseable junk (both + // the fold and a cold parse must skip it identically) and appends more. + await appendFile(path, `age": }\n${fixture.appendLines.join('\n')}\n`) + const stats = createSessionParseStats() + const completed = await parseAgentSessionFileCached( + await candidateFor(fixture.agent, path), + process.platform, + stats + ) + expect(stats.incremental).toBe(1) + expect(completed).toEqual( + await parseAgentSessionFile(await candidateFor(fixture.agent, path), process.platform) + ) + }) +}) + +describe('codex-specific resume behavior', () => { + it('keeps rejecting worker sessions across incremental appends', async () => { + const root = await makeTempDir() + const path = join(root, codexFixture().fileName) + await writeFile(path, `${codexWorkerFixtureLines().join('\n')}\n`) + + const stats = createSessionParseStats() + const seeded = await parseAgentSessionFileCached( + await candidateFor('codex', path), + process.platform, + stats + ) + expect(seeded).toBeNull() + + await appendFile( + path, + `${JSON.stringify({ + timestamp: '2026-05-01T10:10:00.000Z', + type: 'event_msg', + payload: { type: 'agent_message', message: 'worker keeps writing' } + })}\n` + ) + const grown = await parseAgentSessionFileCached( + await candidateFor('codex', path), + process.platform, + stats + ) + expect(stats.incremental).toBe(1) + expect(grown).toBeNull() + }) + + it('picks up a session_index title that appears after the transcript was cached', async () => { + const root = await makeTempDir() + const codexHome = join(root, 'codex-home') + const sessionsDir = join(codexHome, 'sessions', '2026', '05', '01') + await mkdir(sessionsDir, { recursive: true }) + const fixture = codexFixture() + const path = join(sessionsDir, fixture.fileName) + await writeFile(path, `${fixture.seedLines.join('\n')}\n`) + + // No index yet: the title falls back to the first user prompt. + const seeded = await parseAgentSessionFileCached( + await candidateFor('codex', path, codexHome), + process.platform + ) + expect(seeded?.title).toBe('codex seed question') + + // Codex names the thread lazily; the next (incremental) parse must adopt it. + await writeFile( + join(codexHome, 'session_index.jsonl'), + `${JSON.stringify({ id: CODEX_FIXTURE_SESSION_ID, thread_name: 'Indexed thread title' })}\n` + ) + await appendFile(path, `${fixture.appendLines.join('\n')}\n`) + const stats = createSessionParseStats() + const renamed = await parseAgentSessionFileCached( + await candidateFor('codex', path, codexHome), + process.platform, + stats + ) + expect(stats.incremental).toBe(1) + expect(renamed?.title).toBe('Indexed thread title') + expect(renamed).toEqual( + await parseAgentSessionFile(await candidateFor('codex', path, codexHome), process.platform) + ) + }) +}) + +describe('non-resumable formats keep reuse-only caching', () => { + it('re-parses a changed grok summary fully and reuses it when unchanged', async () => { + const root = await makeTempDir() + const sessionDir = join(root, 'session-1') + await mkdir(sessionDir, { recursive: true }) + const path = join(sessionDir, 'summary.json') + await writeFile( + path, + JSON.stringify({ + session_id: 'grok-1', + title: 'Grok seed', + updated_at: '2026-05-01T10:00:00Z' + }) + ) + + const stats = createSessionParseStats() + const seeded = await parseAgentSessionFileCached( + await candidateFor('grok', path), + process.platform, + stats + ) + const reused = await parseAgentSessionFileCached( + await candidateFor('grok', path), + process.platform, + stats + ) + expect(reused).toBe(seeded) + expect(stats).toMatchObject({ fullParses: 1, reused: 1, incremental: 0 }) + + await writeFile( + path, + JSON.stringify({ + session_id: 'grok-1', + title: 'Grok rewritten with a longer title', + updated_at: '2026-05-01T11:00:00Z' + }) + ) + const rewritten = await parseAgentSessionFileCached( + await candidateFor('grok', path), + process.platform, + stats + ) + expect(stats).toMatchObject({ fullParses: 2, incremental: 0 }) + expect(rewritten).toEqual( + await parseAgentSessionFile(await candidateFor('grok', path), process.platform) + ) + }) +}) diff --git a/src/main/ai-vault/session-scanner-parse-cache.test.ts b/src/main/ai-vault/session-scanner-parse-cache.test.ts new file mode 100644 index 000000000..6ba5e3266 --- /dev/null +++ b/src/main/ai-vault/session-scanner-parse-cache.test.ts @@ -0,0 +1,249 @@ +import { appendFile, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + parseAgentSessionFileCached, + resetSessionParseCacheForTests, + createSessionParseStats +} from './session-scanner-parse-cache' +import { parseClaudeSessionFile } from './session-scanner-primary-parsers' +import type { FileWithMtime, SessionFileCandidate } from './session-scanner-types' + +let tempRoots: string[] = [] + +beforeEach(() => { + resetSessionParseCacheForTests() +}) + +afterEach(async () => { + await Promise.all(tempRoots.map((root) => rm(root, { recursive: true, force: true }))) + tempRoots = [] +}) + +async function makeTempDir(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-parse-cache-')) + tempRoots.push(root) + return root +} + +async function claudeCandidate(path: string): Promise { + const fileStat = await stat(path) + const file: FileWithMtime = { + path, + mtimeMs: fileStat.mtimeMs, + modifiedAt: fileStat.mtime.toISOString(), + sizeBytes: fileStat.size + } + return { agent: 'claude', file, codexHome: null } +} + +function userRecord(index: number, text: string): string { + return JSON.stringify({ + type: 'user', + sessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + timestamp: new Date(1740000000000 + index * 60_000).toISOString(), + cwd: '/repo/app', + gitBranch: 'main', + message: { role: 'user', content: text } + }) +} + +function assistantRecord(index: number, text: string): string { + return JSON.stringify({ + type: 'assistant', + sessionId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + timestamp: new Date(1740000000000 + index * 60_000).toISOString(), + message: { + role: 'assistant', + model: 'claude-fable-5', + content: [{ type: 'text', text }], + usage: { input_tokens: 100, output_tokens: 40 } + } + }) +} + +// Ground truth: what a cold one-shot parse of the current file contents yields. +async function freshParse(path: string) { + const candidate = await claudeCandidate(path) + return parseClaudeSessionFile(candidate.file) +} + +async function cachedParse(path: string) { + const candidate = await claudeCandidate(path) + return parseAgentSessionFileCached(candidate, process.platform) +} + +describe('parseAgentSessionFileCached', () => { + it('returns the identical cached session for an unchanged file', async () => { + const root = await makeTempDir() + const path = join(root, 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl') + await writeFile(path, `${userRecord(0, 'first question')}\n${assistantRecord(1, 'answer')}\n`) + + const stats = createSessionParseStats() + const candidate = await claudeCandidate(path) + const first = await parseAgentSessionFileCached(candidate, process.platform, stats) + const second = await parseAgentSessionFileCached(candidate, process.platform, stats) + + expect(first).not.toBeNull() + expect(second).toBe(first) + expect(stats.fullParses).toBe(1) + expect(stats.reused).toBe(1) + expect(stats.incremental).toBe(0) + }) + + it('incrementally parses appended lines and matches a cold parse exactly', async () => { + const root = await makeTempDir() + const path = join(root, 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl') + await writeFile( + path, + `${[ + userRecord(0, 'first question'), + assistantRecord(1, 'first answer'), + JSON.stringify({ type: 'ai-title', aiTitle: 'Original title' }) + ].join('\n')}\n` + ) + const stats = createSessionParseStats() + await parseAgentSessionFileCached(await claudeCandidate(path), process.platform, stats) + + await appendFile( + path, + `${[ + userRecord(2, 'second question'), + assistantRecord(3, 'second answer'), + JSON.stringify({ type: 'ai-title', aiTitle: 'Revised title' }), + assistantRecord(4, 'third answer') + ].join('\n')}\n` + ) + + const incremental = await parseAgentSessionFileCached( + await claudeCandidate(path), + process.platform, + stats + ) + expect(stats.incremental).toBe(1) + expect(incremental).toEqual(await freshParse(path)) + expect(incremental?.messageCount).toBe(5) + expect(incremental?.title).toBe('Revised title') + expect(incremental?.totalTokens).toBe(420) + }) + + it('shows a trailing unterminated line without double-counting it later', async () => { + const root = await makeTempDir() + const path = join(root, 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl') + // Final record has no trailing newline (mid-write file). + await writeFile(path, `${userRecord(0, 'question')}\n${assistantRecord(1, 'partial answer')}`) + + const first = await cachedParse(path) + expect(first?.messageCount).toBe(2) + expect(first).toEqual(await freshParse(path)) + + // The writer finishes the line and appends one more record. + await appendFile(path, `\n${userRecord(2, 'follow-up')}\n`) + const second = await cachedParse(path) + expect(second?.messageCount).toBe(3) + expect(second).toEqual(await freshParse(path)) + }) + + it('falls back to a full parse when the file is truncated', async () => { + const root = await makeTempDir() + const path = join(root, 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl') + await writeFile( + path, + `${[userRecord(0, 'one'), assistantRecord(1, 'two'), userRecord(2, 'three')].join('\n')}\n` + ) + await cachedParse(path) + + await writeFile(path, `${userRecord(0, 'rewritten only line')}\n`) + const stats = createSessionParseStats() + const reparsed = await parseAgentSessionFileCached( + await claudeCandidate(path), + process.platform, + stats + ) + expect(stats.fullParses).toBe(1) + expect(stats.incremental).toBe(0) + expect(reparsed).toEqual(await freshParse(path)) + expect(reparsed?.messageCount).toBe(1) + }) + + it('detects a grown rewrite via the resume-point newline guard', async () => { + const root = await makeTempDir() + const path = join(root, 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl') + const original = `${userRecord(0, 'aa')}\n` + await writeFile(path, original) + await cachedParse(path) + + // Larger file whose byte at the old resume point is mid-line, not '\n'. + const rewritten = `${userRecord(0, 'a much longer rewritten question than before')}\n${assistantRecord(1, 'answer')}\n` + expect(rewritten.length).toBeGreaterThan(original.length) + expect(rewritten[original.length - 1]).not.toBe('\n') + await writeFile(path, rewritten) + + const stats = createSessionParseStats() + const reparsed = await parseAgentSessionFileCached( + await claudeCandidate(path), + process.platform, + stats + ) + expect(stats.fullParses).toBe(1) + expect(stats.incremental).toBe(0) + expect(reparsed).toEqual(await freshParse(path)) + expect(reparsed?.messageCount).toBe(2) + }) + + it('parses CRLF transcripts identically to the streaming parser', async () => { + const root = await makeTempDir() + const path = join(root, 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee.jsonl') + await writeFile( + path, + `${userRecord(0, 'windows question')}\r\n${assistantRecord(1, 'answer')}\r\n` + ) + + const first = await cachedParse(path) + expect(first).toEqual(await freshParse(path)) + expect(first?.messageCount).toBe(2) + + await appendFile(path, `${userRecord(2, 'more')}\r\n`) + const second = await cachedParse(path) + expect(second?.messageCount).toBe(3) + expect(second).toEqual(await freshParse(path)) + }) + + it('caches non-Claude sessions by mtime and size', async () => { + const root = await makeTempDir() + await mkdir(join(root, '2026', '05', '01'), { recursive: true }) + const path = join( + root, + '2026', + '05', + '01', + 'rollout-2026-05-01T10-00-00-019f0000-1111-7222-8333-444444444444.jsonl' + ) + await writeFile( + path, + `${JSON.stringify({ + timestamp: '2026-05-01T11:00:00.000Z', + type: 'session_meta', + payload: { id: '019f0000-1111-7222-8333-444444444444', cwd: '/repo/app' } + })}\n` + ) + const fileStat = await stat(path) + const candidate: SessionFileCandidate = { + agent: 'codex', + file: { + path, + mtimeMs: fileStat.mtimeMs, + modifiedAt: fileStat.mtime.toISOString(), + sizeBytes: fileStat.size + }, + codexHome: null + } + const stats = createSessionParseStats() + const first = await parseAgentSessionFileCached(candidate, process.platform, stats) + const second = await parseAgentSessionFileCached(candidate, process.platform, stats) + expect(second).toBe(first) + expect(stats.fullParses).toBe(1) + expect(stats.reused).toBe(1) + }) +}) diff --git a/src/main/ai-vault/session-scanner-parse-cache.ts b/src/main/ai-vault/session-scanner-parse-cache.ts new file mode 100644 index 000000000..20650f105 --- /dev/null +++ b/src/main/ai-vault/session-scanner-parse-cache.ts @@ -0,0 +1,283 @@ +import { createReadStream } from 'node:fs' +import { open } from 'node:fs/promises' +import type { AiVaultSession } from '../../shared/ai-vault-types' +import { parseAgentSessionFile } from './session-scanner-agent-parser' +import { createCodexSessionResumeState } from './session-scanner-codex-parser' +import { createDroidSessionResumeState } from './session-scanner-droid-parser' +import { createMessageGraphSessionResumeState } from './session-scanner-graph-parsers' +import { + createClaudeSessionResumeState, + createGeminiJsonlSessionResumeState +} from './session-scanner-primary-parsers' +import { + createCopilotSessionResumeState, + createCursorSessionResumeState +} from './session-scanner-secondary-parsers' +import type { ResumableSessionParseState, SessionFileCandidate } from './session-scanner-types' + +// Sized past the default recency cap (1000) plus the in-scope cap (2000) so a +// full steady-state result set stays resident between forced rescans. +const MAX_CACHE_ENTRIES = 4096 + +const NEWLINE_BYTE = 0x0a +const CARRIAGE_RETURN_BYTE = 0x0d + +type ResumePoint = { + state: ResumableSessionParseState + // Byte offset just past the last complete ('\n'-terminated) line consumed; + // a trailing unterminated line is deliberately left before this point. + byteOffset: number +} + +type SessionParseCacheEntry = { + mtimeMs: number + sizeBytes: number | null + platform: NodeJS.Platform + session: AiVaultSession | null + resume: ResumePoint | null +} + +// Incremental append-parsing applies only to transcripts that are append-only +// JSONL line-folds. Whole-JSON documents (grok/rovo/devin/hermes/gemini-json) +// are rewritten in place, Kimi reads a state doc plus a sibling wire file, and +// OpenCode reads SQLite rows or a doc plus a message dir — those formats keep +// unchanged-file reuse only and re-parse whole when they change. +// Returns a factory (not a state) so steady-state resumes, which clone the +// cached state instead, never pay for a throwaway accumulator. +function resumableStateFactoryFor( + candidate: SessionFileCandidate +): (() => ResumableSessionParseState) | null { + switch (candidate.agent) { + case 'claude': + return () => createClaudeSessionResumeState(candidate.file) + case 'codex': + return () => createCodexSessionResumeState(candidate.file, candidate.codexHome) + case 'cursor': + return () => createCursorSessionResumeState(candidate.file) + case 'copilot': + return () => createCopilotSessionResumeState(candidate.file) + case 'droid': + return () => createDroidSessionResumeState(candidate.file) + case 'openclaw': + case 'pi': + case 'omp': { + const agent = candidate.agent + return () => createMessageGraphSessionResumeState(agent, candidate.file) + } + case 'gemini': + return candidate.file.path.endsWith('.jsonl') + ? () => createGeminiJsonlSessionResumeState(candidate.file) + : null + case 'devin': + case 'grok': + case 'hermes': + case 'kimi': + case 'opencode': + case 'rovo': + return null + } +} + +export type SessionParseStats = { + reused: number + incremental: number + fullParses: number + bytesRead: number +} + +export function createSessionParseStats(): SessionParseStats { + return { reused: 0, incremental: 0, fullParses: 0, bytesRead: 0 } +} + +const cache = new Map() + +export function resetSessionParseCacheForTests(): void { + cache.clear() +} + +function storeEntry(path: string, entry: SessionParseCacheEntry): void { + cache.delete(path) + cache.set(path, entry) + if (cache.size > MAX_CACHE_ENTRIES) { + const oldest = cache.keys().next() + if (!oldest.done) { + cache.delete(oldest.value) + } + } +} + +/** + * Parse a session file, reusing prior work where the file is provably + * unchanged (mtime+size) and, for append-only JSONL transcripts (Claude, + * Codex, Cursor, Copilot, Droid, OpenClaw/Pi/OMP, Gemini-JSONL), resuming the + * parse from the last consumed byte when the file only grew. This is what + * keeps the renderer's ~5s forced rescans from re-reading gigabytes of + * transcripts (STA-1278/STA-1417: main process pegging one core during + * multi-agent workloads). + */ +export async function parseAgentSessionFileCached( + candidate: SessionFileCandidate, + platform: NodeJS.Platform, + stats?: SessionParseStats +): Promise { + const { file } = candidate + const entry = cache.get(file.path) + + const unchanged = + entry !== undefined && + entry.platform === platform && + entry.mtimeMs === file.mtimeMs && + (entry.sizeBytes === null || file.sizeBytes === undefined || entry.sizeBytes === file.sizeBytes) + if (unchanged) { + if (stats) { + stats.reused++ + } + storeEntry(file.path, entry) + return entry.session + } + + const stateFactory = resumableStateFactoryFor(candidate) + if (stateFactory) { + const parsed = await parseResumableCandidate({ + candidate, + platform, + entry, + stats, + stateFactory + }) + storeEntry(file.path, parsed) + return parsed.session + } + + if (stats) { + stats.fullParses++ + stats.bytesRead += file.sizeBytes ?? 0 + } + const session = await parseAgentSessionFile(candidate, platform) + storeEntry(file.path, { + mtimeMs: file.mtimeMs, + sizeBytes: file.sizeBytes ?? null, + platform, + session, + resume: null + }) + return session +} + +async function parseResumableCandidate(args: { + candidate: SessionFileCandidate + platform: NodeJS.Platform + entry: SessionParseCacheEntry | undefined + stats?: SessionParseStats + stateFactory: () => ResumableSessionParseState +}): Promise { + const { file } = args.candidate + const resume = args.entry?.platform === args.platform ? args.entry.resume : null + const canResume = + resume !== null && + resume !== undefined && + typeof file.sizeBytes === 'number' && + file.sizeBytes >= resume.byteOffset && + (resume.byteOffset === 0 || (await endsWithNewlineAt(file.path, resume.byteOffset))) + + // Clone before consuming: a failed read must not corrupt the cached state, + // or the next resume would double-count the lines applied before the error. + const state = canResume ? resume.state.clone() : args.stateFactory() + const startOffset = canResume ? resume.byteOffset : 0 + if (args.stats) { + if (canResume) { + args.stats.incremental++ + } else { + args.stats.fullParses++ + } + } + + const readResult = await consumeCompleteJsonlLines({ + path: file.path, + start: startOffset, + onLine: (line) => state.consumeLine(line) + }) + if (args.stats) { + args.stats.bytesRead += readResult.bytesRead + } + + // The stat this scan displays is current even when nothing new was consumed. + state.touchFile(file) + + // Keep parity with the one-shot parser: a final unterminated line is shown, + // but stays out of the resumable state so the (possibly still-growing) line + // is re-read once complete instead of being half-counted. + let displayState = state + if (readResult.trailingPartialLine !== null) { + displayState = state.clone() + displayState.consumeLine(readResult.trailingPartialLine) + } + + return { + mtimeMs: file.mtimeMs, + sizeBytes: file.sizeBytes ?? null, + platform: args.platform, + session: await displayState.finalize(args.platform), + resume: { state, byteOffset: readResult.consumedThrough } + } +} + +// A resume point is only valid if it still sits just past a line break; +// anything else means the file was rewritten, not appended. Heuristic: a +// grown rewrite keeping '\n' at exactly this byte would slip through, but +// agent transcripts are append-only so that trade is accepted (worst case is +// a stale vault row until the file is next truncated or the app restarts). +async function endsWithNewlineAt(path: string, offset: number): Promise { + const handle = await open(path, 'r') + try { + const { bytesRead, buffer } = await handle.read(Buffer.alloc(1), 0, 1, offset - 1) + return bytesRead === 1 && buffer[0] === NEWLINE_BYTE + } finally { + await handle.close() + } +} + +type JsonlReadResult = { + consumedThrough: number + trailingPartialLine: string | null + bytesRead: number +} + +// Byte-accurate replacement for readline: offsets must count bytes (not +// UTF-8-decoded characters) so a resumed read starts exactly where the last +// complete line ended. +async function consumeCompleteJsonlLines(args: { + path: string + start: number + onLine: (line: string) => void +}): Promise { + let consumedThrough = args.start + let bytesRead = 0 + let remainder: Buffer | null = null + + const stream = createReadStream(args.path, { start: args.start }) + for await (const chunk of stream as AsyncIterable) { + bytesRead += chunk.length + const data = remainder ? Buffer.concat([remainder, chunk]) : chunk + let lineStart = 0 + let newlineIndex = data.indexOf(NEWLINE_BYTE, lineStart) + while (newlineIndex !== -1) { + let lineEnd = newlineIndex + if (lineEnd > lineStart && data[lineEnd - 1] === CARRIAGE_RETURN_BYTE) { + lineEnd-- + } + args.onLine(data.toString('utf-8', lineStart, lineEnd)) + lineStart = newlineIndex + 1 + newlineIndex = data.indexOf(NEWLINE_BYTE, lineStart) + } + consumedThrough += lineStart + // Copy the tail so retaining it doesn't pin the whole chunk buffer. + remainder = lineStart < data.length ? Buffer.from(data.subarray(lineStart)) : null + } + + return { + consumedThrough, + trailingPartialLine: remainder && remainder.length > 0 ? remainder.toString('utf-8') : null, + bytesRead + } +} diff --git a/src/main/ai-vault/session-scanner-primary-parsers.ts b/src/main/ai-vault/session-scanner-primary-parsers.ts index b574cd312..e07329a30 100644 --- a/src/main/ai-vault/session-scanner-primary-parsers.ts +++ b/src/main/ai-vault/session-scanner-primary-parsers.ts @@ -3,8 +3,13 @@ import { readFile } from 'node:fs/promises' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' -import type { FileWithMtime, SessionAccumulator } from './session-scanner-types' +import type { + FileWithMtime, + ResumableSessionParseState, + SessionAccumulator +} from './session-scanner-types' import { + accumulatorFoldResumeState, addPreviewContent, createAccumulator, finalizeSession, @@ -29,6 +34,133 @@ type ParserSessionOptions = { executionHostPlatform?: NodeJS.Platform | null } +// Parse state kept resumable so the scan cache can append newly written +// transcript lines without re-reading the whole (potentially huge) file. +export type ClaudeSessionParseState = { + accumulator: SessionAccumulator + metaTitle: string | null + generatedTitle: string | null + firstUserTitle: string | null +} + +export function createClaudeSessionParseState(file: FileWithMtime): ClaudeSessionParseState { + return { + accumulator: createAccumulator({ + agent: 'claude', + file, + sessionId: sessionIdFromFileName(file.path) + }), + metaTitle: null, + generatedTitle: null, + firstUserTitle: null + } +} + +export function cloneClaudeSessionParseState( + state: ClaudeSessionParseState +): ClaudeSessionParseState { + return { + accumulator: { + ...state.accumulator, + previewMessages: [...state.accumulator.previewMessages] + }, + metaTitle: state.metaTitle, + generatedTitle: state.generatedTitle, + firstUserTitle: state.firstUserTitle + } +} + +export function consumeClaudeSessionLine(state: ClaudeSessionParseState, line: string): void { + const { accumulator } = state + const record = parseJsonObject(line) + if (!record) { + return + } + + if (typeof record.sessionId === 'string' && record.sessionId.trim()) { + accumulator.sessionId = record.sessionId.trim() + } + updateTimeline(accumulator, extractString(record.timestamp)) + updateLatestLocation(accumulator, record) + + if (record.type === 'custom-title') { + accumulator.title = normalizeTitleText(extractString(record.customTitle) ?? '') + return + } + + if (record.type === 'ai-title') { + const title = normalizeTitleText(extractString(record.aiTitle) ?? '') + if (title) { + // Claude can revise generated names; AI Vault should mirror the current one. + state.generatedTitle = title + } + return + } + + if (record.type === 'agent-name' && !state.generatedTitle) { + state.metaTitle ??= normalizeTitleText(extractString(record.agentName) ?? '') + return + } + + if (record.type === 'user') { + accumulator.messageCount++ + const title = extractMessageText(record.message) + addPreviewContent(accumulator, 'user', asRecord(record.message)?.content, record.timestamp) + if (title) { + // Meta prompts (injected context) only seed the last-resort title. + if (record.isMeta === true) { + state.metaTitle ??= title + } else { + state.firstUserTitle ??= title + } + } + return + } + + if (record.type === 'assistant') { + accumulator.messageCount++ + const message = asRecord(record.message) + addPreviewContent(accumulator, 'assistant', message?.content, record.timestamp) + const model = extractString(message?.model) + if (model) { + accumulator.model = model + } + accumulator.totalTokens += claudeUsageTotal(message?.usage) + } +} + +export function finalizeClaudeSessionParseState( + state: ClaudeSessionParseState, + platform: NodeJS.Platform, + options: ParserSessionOptions = {} +): AiVaultSession | null { + // Finalize a snapshot: the live state (and its preview array) may keep + // accumulating appended lines after this session object is handed out. + const snapshot = cloneClaudeSessionParseState(state) + // Why: a user-set custom-title (accumulator.title) wins, but Claude's generated + // session name (ai-title) should outrank the raw first prompt when present. + snapshot.accumulator.fallbackTitle = + snapshot.generatedTitle ?? snapshot.firstUserTitle ?? snapshot.metaTitle + return finalizeSession(snapshot.accumulator, platform, options) +} + +export function createClaudeSessionResumeState(file: FileWithMtime): ResumableSessionParseState { + return claudeResumeStateFromParseState(createClaudeSessionParseState(file)) +} + +function claudeResumeStateFromParseState( + state: ClaudeSessionParseState +): ResumableSessionParseState { + return { + consumeLine: (line) => consumeClaudeSessionLine(state, line), + clone: () => claudeResumeStateFromParseState(cloneClaudeSessionParseState(state)), + touchFile: (file) => { + state.accumulator.modifiedAt = file.modifiedAt + }, + finalize: (platform, options) => finalizeClaudeSessionParseState(state, platform, options) + } +} + export async function parseClaudeSessionFile( file: FileWithMtime, platform: NodeJS.Platform = process.platform @@ -60,77 +192,11 @@ async function parseClaudeSessionLines(args: { platform: NodeJS.Platform options?: ParserSessionOptions }): Promise { - const accumulator = createAccumulator({ - agent: 'claude', - file: args.file, - sessionId: sessionIdFromFileName(args.file.path) - }) - let metaTitle: string | null = null - let generatedTitle: string | null = null - let firstUserTitle: string | null = null - + const state = createClaudeSessionParseState(args.file) for await (const line of args.lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - - if (typeof record.sessionId === 'string' && record.sessionId.trim()) { - accumulator.sessionId = record.sessionId.trim() - } - updateTimeline(accumulator, extractString(record.timestamp)) - updateLatestLocation(accumulator, record) - - if (record.type === 'custom-title') { - accumulator.title = normalizeTitleText(extractString(record.customTitle) ?? '') - continue - } - - if (record.type === 'ai-title') { - const title = normalizeTitleText(extractString(record.aiTitle) ?? '') - if (title) { - // Claude can revise generated names; AI Vault should mirror the current one. - generatedTitle = title - } - continue - } - - if (record.type === 'agent-name' && !generatedTitle) { - metaTitle ??= normalizeTitleText(extractString(record.agentName) ?? '') - continue - } - - if (record.type === 'user') { - accumulator.messageCount++ - const title = extractMessageText(record.message) - addPreviewContent(accumulator, 'user', asRecord(record.message)?.content, record.timestamp) - if (title) { - // Meta prompts (injected context) only seed the last-resort title. - if (record.isMeta === true) { - metaTitle ??= title - } else { - firstUserTitle ??= title - } - } - continue - } - - if (record.type === 'assistant') { - accumulator.messageCount++ - const message = asRecord(record.message) - addPreviewContent(accumulator, 'assistant', message?.content, record.timestamp) - const model = extractString(message?.model) - if (model) { - accumulator.model = model - } - accumulator.totalTokens += claudeUsageTotal(message?.usage) - } + consumeClaudeSessionLine(state, line) } - - // Why: a user-set custom-title (accumulator.title) wins, but Claude's generated - // session name (ai-title) should outrank the raw first prompt when present. - accumulator.fallbackTitle = generatedTitle ?? firstUserTitle ?? metaTitle - return finalizeSession(accumulator, args.platform, args.options) + return finalizeClaudeSessionParseState(state, args.platform, args.options) } export async function parseGeminiSessionFile( @@ -195,38 +261,47 @@ export async function parseGeminiJsonlSessionFile( return parseGeminiJsonlSessionLines({ file, lines, platform }) } +function consumeGeminiJsonlRecordLine(accumulator: SessionAccumulator, line: string): void { + const record = parseJsonObject(line) + if (!record) { + return + } + const setRecord = asRecord(record.$set) + if (setRecord) { + updateTimeline(accumulator, extractString(setRecord.lastUpdated)) + return + } + const sessionId = extractString(record.sessionId) + if (sessionId) { + accumulator.sessionId = sessionId + } + updateTimeline(accumulator, extractString(record.startTime)) + updateTimeline(accumulator, extractString(record.lastUpdated)) + consumeGeminiMessage(accumulator, record) +} + +// Resumable only for the JSONL log format; Gemini's legacy single-JSON +// session documents are rewritten in place and must be re-read whole. +export function createGeminiJsonlSessionResumeState( + file: FileWithMtime +): ResumableSessionParseState { + return accumulatorFoldResumeState( + createAccumulator({ agent: 'gemini', file, sessionId: sessionIdFromFileName(file.path) }), + consumeGeminiJsonlRecordLine + ) +} + async function parseGeminiJsonlSessionLines(args: { file: FileWithMtime lines: AsyncIterable | Iterable platform: NodeJS.Platform options?: ParserSessionOptions }): Promise { - const accumulator = createAccumulator({ - agent: 'gemini', - file: args.file, - sessionId: sessionIdFromFileName(args.file.path) - }) - + const state = createGeminiJsonlSessionResumeState(args.file) for await (const line of args.lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - const setRecord = asRecord(record.$set) - if (setRecord) { - updateTimeline(accumulator, extractString(setRecord.lastUpdated)) - continue - } - const sessionId = extractString(record.sessionId) - if (sessionId) { - accumulator.sessionId = sessionId - } - updateTimeline(accumulator, extractString(record.startTime)) - updateTimeline(accumulator, extractString(record.lastUpdated)) - consumeGeminiMessage(accumulator, record) + state.consumeLine(line) } - - return finalizeSession(accumulator, args.platform, args.options) + return state.finalize(args.platform, args.options) } export function consumeGeminiMessage( diff --git a/src/main/ai-vault/session-scanner-scope-discovery.ts b/src/main/ai-vault/session-scanner-scope-discovery.ts index 4900e3e23..41aac5f27 100644 --- a/src/main/ai-vault/session-scanner-scope-discovery.ts +++ b/src/main/ai-vault/session-scanner-scope-discovery.ts @@ -17,6 +17,36 @@ const REPRESENTATIVE_CWD_LINE_LIMIT = 200 const REPRESENTATIVE_FILE_LIMIT = 3 const CLAUDE_EXTENSIONS = new Set(['.jsonl']) +// A Claude project dir encodes exactly one cwd, so a resolved cwd never +// changes; caching it spares each rescan the transcript-head reads. +const PROJECT_DIR_CWD_CACHE_MAX = 2048 +const projectDirCwdCache = new Map() + +export function resetProjectDirCwdCacheForTests(): void { + projectDirCwdCache.clear() +} + +async function cachedProjectDirCwd(projectDir: string): Promise { + const cached = projectDirCwdCache.get(projectDir) + if (cached !== undefined) { + // Refresh recency so hot in-scope dirs outlive one-off ones at the cap. + projectDirCwdCache.delete(projectDir) + projectDirCwdCache.set(projectDir, cached) + return cached + } + const cwd = await readProjectDirCwd(projectDir) + if (cwd) { + if (projectDirCwdCache.size >= PROJECT_DIR_CWD_CACHE_MAX) { + const oldest = projectDirCwdCache.keys().next() + if (!oldest.done) { + projectDirCwdCache.delete(oldest.value) + } + } + projectDirCwdCache.set(projectDir, cwd) + } + return cwd +} + /** * Fully include the transcripts of Claude project directories whose cwd falls * inside the active workspace/project paths. @@ -41,7 +71,7 @@ export async function discoverInScopeClaudeFiles(args: { const collected = new Map() for (const rootDir of args.rootDirs) { for (const projectDir of await listProjectDirs(rootDir, scopeProjectPrefixes)) { - const cwd = await readProjectDirCwd(projectDir) + const cwd = await cachedProjectDirCwd(projectDir) if (!cwd || !args.scopePaths.some((scopePath) => isCwdInsideScopePath(scopePath, cwd))) { continue } @@ -205,7 +235,8 @@ async function collectClaudeFiles(args: { addBoundedFile(args.collected, args.limit, { path, mtimeMs: fileStat.mtimeMs, - modifiedAt: fileStat.mtime.toISOString() + modifiedAt: fileStat.mtime.toISOString(), + sizeBytes: fileStat.size }) } catch (err) { args.issues.push({ agent: 'claude', path, message: errorMessage(err) }) diff --git a/src/main/ai-vault/session-scanner-secondary-parsers.ts b/src/main/ai-vault/session-scanner-secondary-parsers.ts index 1edcf6292..364c25b5d 100644 --- a/src/main/ai-vault/session-scanner-secondary-parsers.ts +++ b/src/main/ai-vault/session-scanner-secondary-parsers.ts @@ -4,8 +4,13 @@ import { join } from 'node:path' import { createInterface } from 'node:readline' import type { AiVaultSession } from '../../shared/ai-vault-types' import type { ExecutionHostId } from '../../shared/execution-host' -import type { FileWithMtime, SessionAccumulator } from './session-scanner-types' +import type { + FileWithMtime, + ResumableSessionParseState, + SessionAccumulator +} from './session-scanner-types' import { + accumulatorFoldResumeState, addPreviewContent, addPreviewMessage, createAccumulator, @@ -60,70 +65,75 @@ export async function parseCopilotSessionContent( }) } +function consumeCopilotRecordLine(accumulator: SessionAccumulator, line: string): void { + const record = parseJsonObject(line) + if (!record) { + return + } + updateTimeline(accumulator, extractString(record.timestamp)) + const data = asRecord(record.data) + if (record.type === 'session.start' && data) { + const sessionId = extractString(data.sessionId) + if (sessionId) { + accumulator.sessionId = sessionId + } + updateTimeline(accumulator, extractString(data.startTime)) + return + } + if (record.type === 'session.model_change' && data) { + accumulator.model = extractString(data.newModel) ?? accumulator.model + return + } + if (record.type === 'session.info' && data) { + accumulator.cwd = extractTrustedFolder(data.message) ?? accumulator.cwd + return + } + if (record.type === 'user.message' && data) { + accumulator.messageCount++ + accumulator.title ??= normalizeTitleText( + extractString(data.transformedContent) ?? extractString(data.content) ?? '' + ) + addPreviewMessage(accumulator, { + role: 'user', + text: extractString(data.transformedContent) ?? extractString(data.content), + timestamp: record.timestamp + }) + return + } + if (record.type === 'assistant.message' && data) { + accumulator.messageCount++ + addPreviewMessage(accumulator, { + role: 'assistant', + text: extractString(data.content), + timestamp: record.timestamp + }) + return + } + if (record.type === 'session.shutdown' && data) { + accumulator.model = extractString(data.currentModel) ?? accumulator.model + accumulator.totalTokens += numberValue(data.currentTokens) + accumulator.totalTokens += copilotModelMetricsTotal(data.modelMetrics) + } +} + +export function createCopilotSessionResumeState(file: FileWithMtime): ResumableSessionParseState { + return accumulatorFoldResumeState( + createAccumulator({ agent: 'copilot', file, sessionId: sessionIdFromFileName(file.path) }), + consumeCopilotRecordLine + ) +} + async function parseCopilotSessionLines(args: { file: FileWithMtime lines: AsyncIterable | Iterable platform: NodeJS.Platform options?: ParserSessionOptions }): Promise { - const accumulator = createAccumulator({ - agent: 'copilot', - file: args.file, - sessionId: sessionIdFromFileName(args.file.path) - }) - + const state = createCopilotSessionResumeState(args.file) for await (const line of args.lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - updateTimeline(accumulator, extractString(record.timestamp)) - const data = asRecord(record.data) - if (record.type === 'session.start' && data) { - const sessionId = extractString(data.sessionId) - if (sessionId) { - accumulator.sessionId = sessionId - } - updateTimeline(accumulator, extractString(data.startTime)) - continue - } - if (record.type === 'session.model_change' && data) { - accumulator.model = extractString(data.newModel) ?? accumulator.model - continue - } - if (record.type === 'session.info' && data) { - accumulator.cwd = extractTrustedFolder(data.message) ?? accumulator.cwd - continue - } - if (record.type === 'user.message' && data) { - accumulator.messageCount++ - accumulator.title ??= normalizeTitleText( - extractString(data.transformedContent) ?? extractString(data.content) ?? '' - ) - addPreviewMessage(accumulator, { - role: 'user', - text: extractString(data.transformedContent) ?? extractString(data.content), - timestamp: record.timestamp - }) - continue - } - if (record.type === 'assistant.message' && data) { - accumulator.messageCount++ - addPreviewMessage(accumulator, { - role: 'assistant', - text: extractString(data.content), - timestamp: record.timestamp - }) - continue - } - if (record.type === 'session.shutdown' && data) { - accumulator.model = extractString(data.currentModel) ?? accumulator.model - accumulator.totalTokens += numberValue(data.currentTokens) - accumulator.totalTokens += copilotModelMetricsTotal(data.modelMetrics) - } + state.consumeLine(line) } - - return finalizeSession(accumulator, args.platform, args.options) + return state.finalize(args.platform, args.options) } export async function parseCursorSessionFile( @@ -151,40 +161,45 @@ export async function parseCursorSessionContent( }) } +function consumeCursorRecordLine(accumulator: SessionAccumulator, line: string): void { + const record = parseJsonObject(line) + if (!record) { + return + } + updateTimeline(accumulator, extractString(record.timestamp)) + const role = extractString(record.role) + if (role === 'user' || role === 'assistant') { + accumulator.messageCount++ + if (role === 'user') { + accumulator.title ??= extractMessageText(record.message) ?? extractContentText(record.content) + } + addPreviewContent( + accumulator, + role, + asRecord(record.message)?.content ?? record.content, + record.timestamp + ) + } +} + +export function createCursorSessionResumeState(file: FileWithMtime): ResumableSessionParseState { + return accumulatorFoldResumeState( + createAccumulator({ agent: 'cursor', file, sessionId: sessionIdFromFileName(file.path) }), + consumeCursorRecordLine + ) +} + async function parseCursorSessionLines(args: { file: FileWithMtime lines: AsyncIterable | Iterable platform: NodeJS.Platform options?: ParserSessionOptions }): Promise { - const accumulator = createAccumulator({ - agent: 'cursor', - file: args.file, - sessionId: sessionIdFromFileName(args.file.path) - }) - + const state = createCursorSessionResumeState(args.file) for await (const line of args.lines) { - const record = parseJsonObject(line) - if (!record) { - continue - } - updateTimeline(accumulator, extractString(record.timestamp)) - const role = extractString(record.role) - if (role === 'user' || role === 'assistant') { - accumulator.messageCount++ - if (role === 'user') { - accumulator.title ??= - extractMessageText(record.message) ?? extractContentText(record.content) - } - addPreviewContent( - accumulator, - role, - asRecord(record.message)?.content ?? record.content, - record.timestamp - ) - } + state.consumeLine(line) } - return finalizeSession(accumulator, args.platform, args.options) + return state.finalize(args.platform, args.options) } export async function parseOpenCodeSessionFile( diff --git a/src/main/ai-vault/session-scanner-source-discovery.ts b/src/main/ai-vault/session-scanner-source-discovery.ts index 12acdeab1..8c03ec72e 100644 --- a/src/main/ai-vault/session-scanner-source-discovery.ts +++ b/src/main/ai-vault/session-scanner-source-discovery.ts @@ -6,7 +6,7 @@ import { discoverFiles, discoverOpenClawFiles } from './session-scanner-discover import { droidDiscoveries, kimiDiscoveries } from './session-scanner-droid-kimi-sources' import { opencodeDiscoveries } from './session-scanner-opencode-sources' import type { AiVaultScanOptions, SessionFileDiscovery } from './session-scanner-types' -import { normalizePiSessionsDir } from './session-scanner-values' +import { normalizeAgentSessionsDir } from './session-scanner-values' const CLAUDE_PROJECTS_DIR = join(homedir(), '.claude', 'projects') export const DEFAULT_CODEX_HOME_DIR = join(homedir(), '.codex') @@ -25,8 +25,13 @@ const GROK_SESSIONS_DIR = join( const HERMES_SESSIONS_DIR = join(homedir(), '.hermes', 'sessions') const ROVO_SESSIONS_DIR = join(homedir(), '.rovodev', 'sessions') const OPENCLAW_STATE_DIR = process.env.OPENCLAW_STATE_DIR?.trim() || join(homedir(), '.openclaw') -const PI_SESSIONS_DIR = normalizePiSessionsDir( - process.env.PI_CODING_AGENT_DIR?.trim() || join(homedir(), '.pi', 'agent', 'sessions') +const PI_SESSIONS_DIR = normalizeAgentSessionsDir( + process.env.PI_CODING_AGENT_DIR?.trim() || join(homedir(), '.pi', 'agent', 'sessions'), + '.pi' +) +const OMP_SESSIONS_DIR = normalizeAgentSessionsDir( + process.env.OMP_CODING_AGENT_DIR?.trim() || join(homedir(), '.omp', 'agent', 'sessions'), + '.omp' ) // Why: Devin ATIF transcripts are stored under /transcripts. const DEVIN_TRANSCRIPTS_DIR = join( @@ -124,7 +129,8 @@ function standardDiscoveries( ...devinDiscoveries(options, wslHomeDirs, limit, issues), ...hermesDiscoveries(options, wslHomeDirs, limit, issues), ...rovoDiscoveries(options, wslHomeDirs, limit, issues), - ...piDiscoveries(options, wslHomeDirs, limit, issues) + ...piDiscoveries(options, wslHomeDirs, limit, issues), + ...ompDiscoveries(options, wslHomeDirs, limit, issues) ] } @@ -244,6 +250,21 @@ function piDiscoveries( ) } +function ompDiscoveries( + options: AiVaultScanOptions, + wslHomeDirs: readonly string[], + limit: number, + issues: AiVaultScanIssue[] +): Promise[] { + return sessionRootDirs(options.ompSessionsDir ?? OMP_SESSIONS_DIR, wslHomeDirs, [ + '.omp', + 'agent', + 'sessions' + ]).map((rootDir) => + discoverFiles({ rootDir, limit, agent: 'omp', issues, extensions: ['.jsonl'] }) + ) +} + function openClawDiscovery( options: AiVaultScanOptions, wslHomeDirs: readonly string[], diff --git a/src/main/ai-vault/session-scanner-test-fixtures.ts b/src/main/ai-vault/session-scanner-test-fixtures.ts index b7c4dfd05..0a3b6c7c1 100644 --- a/src/main/ai-vault/session-scanner-test-fixtures.ts +++ b/src/main/ai-vault/session-scanner-test-fixtures.ts @@ -19,6 +19,7 @@ export function isolatedScanRoots(root: string) { openclawStateDir: join(root, 'openclaw-state'), openclawLegacyStateDir: join(root, 'openclaw-legacy-state'), piSessionsDir: join(root, 'pi-sessions'), + ompSessionsDir: join(root, 'omp-sessions'), droidSessionsDir: join(root, 'droid-sessions'), droidProjectsDir: join(root, 'droid-projects'), kimiSessionsDir: join(root, 'kimi-sessions') diff --git a/src/main/ai-vault/session-scanner-token-values.ts b/src/main/ai-vault/session-scanner-token-values.ts index 83b288140..e2621b9f4 100644 --- a/src/main/ai-vault/session-scanner-token-values.ts +++ b/src/main/ai-vault/session-scanner-token-values.ts @@ -104,3 +104,16 @@ export function subtractCodexUsage( export function numberValue(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) ? value : 0 } + +export function addCodexUsage( + base: CodexUsageSnapshot, + increment: CodexUsageSnapshot +): CodexUsageSnapshot { + return { + inputTokens: base.inputTokens + increment.inputTokens, + cachedInputTokens: base.cachedInputTokens + increment.cachedInputTokens, + outputTokens: base.outputTokens + increment.outputTokens, + reasoningOutputTokens: base.reasoningOutputTokens + increment.reasoningOutputTokens, + totalTokens: base.totalTokens + increment.totalTokens + } +} diff --git a/src/main/ai-vault/session-scanner-types.ts b/src/main/ai-vault/session-scanner-types.ts index 5d2208b7b..5364e29e2 100644 --- a/src/main/ai-vault/session-scanner-types.ts +++ b/src/main/ai-vault/session-scanner-types.ts @@ -25,6 +25,7 @@ export type AiVaultScanOptions = { openclawStateDir?: string openclawLegacyStateDir?: string piSessionsDir?: string + ompSessionsDir?: string droidSessionsDir?: string droidProjectsDir?: string kimiSessionsDir?: string @@ -41,6 +42,10 @@ export type FileWithMtime = { path: string mtimeMs: number modifiedAt: string + // Present when discovery statted the file; lets the parse cache detect + // unchanged/truncated files without a second stat. Synthetic candidates + // (OpenCode SQLite rows, remote files) omit it. + sizeBytes?: number } export type SessionFileCandidate = { @@ -60,6 +65,26 @@ export type SessionParseResult = { issue: AiVaultScanIssue | null } +export type ResumableParseFinalizeOptions = { + executionHostId?: ExecutionHostId + executionHostPlatform?: NodeJS.Platform | null +} + +// One in-progress parse of an append-only transcript, resumable across scans. +// The parse cache stores a state per file and feeds it only newly appended +// lines; `clone` must deep-copy anything `consumeLine` mutates so a failed +// read or a display-only trailing line can never corrupt the cached fold. +export type ResumableSessionParseState = { + consumeLine(line: string): void + clone(): ResumableSessionParseState + // Refresh per-scan file metadata (mtime display string) without re-parsing. + touchFile(file: FileWithMtime): void + finalize( + platform: NodeJS.Platform, + options?: ResumableParseFinalizeOptions + ): Promise | AiVaultSession | null +} + export type SessionAccumulator = { agent: AiVaultAgent sessionId: string diff --git a/src/main/ai-vault/session-scanner-values.test.ts b/src/main/ai-vault/session-scanner-values.test.ts index 9c1de341d..a9954ae8d 100644 --- a/src/main/ai-vault/session-scanner-values.test.ts +++ b/src/main/ai-vault/session-scanner-values.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { extractPreviewContentText, + normalizeAgentSessionsDir, normalizePreviewText, normalizeTitleText } from './session-scanner-values' @@ -51,4 +52,20 @@ describe('AI Vault session scanner text values', () => { expect(result).toBe(`${'a'.repeat(216)}...`) }) + + it('expands Pi and OMP agent homes to their session directories', () => { + expect(normalizeAgentSessionsDir('/agents/.pi', '.pi')).toBe('/agents/.pi/agent/sessions') + expect(normalizeAgentSessionsDir('/agents/.pi/agent', '.pi')).toBe('/agents/.pi/agent/sessions') + expect(normalizeAgentSessionsDir('/agents/.pi/agent/sessions', '.pi')).toBe( + '/agents/.pi/agent/sessions' + ) + + expect(normalizeAgentSessionsDir('/agents/.omp', '.omp')).toBe('/agents/.omp/agent/sessions') + expect(normalizeAgentSessionsDir('/agents/.omp/agent', '.omp')).toBe( + '/agents/.omp/agent/sessions' + ) + expect(normalizeAgentSessionsDir('/agents/.omp/agent/sessions', '.omp')).toBe( + '/agents/.omp/agent/sessions' + ) + }) }) diff --git a/src/main/ai-vault/session-scanner-values.ts b/src/main/ai-vault/session-scanner-values.ts index 8a5a76306..39006bd68 100644 --- a/src/main/ai-vault/session-scanner-values.ts +++ b/src/main/ai-vault/session-scanner-values.ts @@ -126,10 +126,15 @@ export function findOpenCodeStorageRoot(filePath: string): string | null { return dirname(sessionRoot) } -export function normalizePiSessionsDir(rawValue: string): string { +// Pi and OMP (a Pi fork) both store transcripts under +// //agent/sessions; accept any prefix of that path. +export function normalizeAgentSessionsDir( + rawValue: string, + agentHomeDirName: '.pi' | '.omp' +): string { const trimmed = rawValue.trim() if (!trimmed) { - return join(homedir(), '.pi', 'agent', 'sessions') + return join(homedir(), agentHomeDirName, 'agent', 'sessions') } const normalized = trimmed.replace(/[\\/]+$/, '') const leaf = basename(normalized) @@ -139,7 +144,7 @@ export function normalizePiSessionsDir(rawValue: string): string { if (leaf === 'agent') { return join(normalized, 'sessions') } - if (leaf === '.pi') { + if (leaf === agentHomeDirName) { return join(normalized, 'agent', 'sessions') } return normalized @@ -154,6 +159,7 @@ export function errorMessage(err: unknown): string { } export { + addCodexUsage, claudeUsageTotal, copilotModelMetricsTotal, normalizeCodexUsage, diff --git a/src/main/ai-vault/session-scanner.test.ts b/src/main/ai-vault/session-scanner.test.ts index 41b1b2b05..d4404341f 100644 --- a/src/main/ai-vault/session-scanner.test.ts +++ b/src/main/ai-vault/session-scanner.test.ts @@ -2,7 +2,7 @@ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AI_VAULT_AGENTS, buildAiVaultResumeCommand } from '../../shared/ai-vault-types' +import { AI_VAULT_AGENTS } from '../../shared/ai-vault-types' import { scanAiVaultSessions } from './session-scanner' import { isolatedScanRoots, jsonLines } from './session-scanner-test-fixtures' @@ -584,6 +584,44 @@ describe('scanAiVaultSessions', () => { ]) ) + const ompSessionFile = join(roots.ompSessionsDir, 'omp-session.jsonl') + await mkdir(roots.ompSessionsDir, { recursive: true }) + await writeFile( + ompSessionFile, + jsonLines([ + { + type: 'session', + version: 3, + id: 'omp-session', + title: 'OMP session title', + timestamp: '2026-05-01T10:08:30.000Z', + cwd: '/tmp/omp' + }, + { + type: 'model_change', + model: 'gpt-5.4-mini', + timestamp: '2026-05-01T10:08:30.500Z' + }, + { + type: 'message', + timestamp: '2026-05-01T10:08:31.000Z', + message: { role: 'user', content: [{ type: 'text', text: 'OMP title' }] } + }, + { + type: 'message', + timestamp: '2026-05-01T10:08:32.000Z', + message: { + role: 'assistant', + content: [{ type: 'text', text: 'OMP answer' }], + model: 'gpt-5.4-mini', + // totalTokens deliberately != input+output so the assertion proves + // the explicit-total field is read, not an input/output sum. + usage: { input: 10, output: 5, totalTokens: 160 } + } + } + ]) + ) + await mkdir(roots.devinTranscriptsDir, { recursive: true }) await writeFile( join(roots.devinTranscriptsDir, 'devin-session.json'), @@ -719,11 +757,48 @@ describe('scanAiVaultSessions', () => { "cd '/tmp/openclaw' && openclaw --resume 'openclaw-session'" ) expect(commandByAgent.get('pi')).toBe("cd '/tmp/pi' && pi --session 'pi-session'") + // OMP resumes by absolute transcript path, not by internal session id. + expect(commandByAgent.get('omp')).toBe(`cd '/tmp/omp' && omp --resume '${ompSessionFile}'`) expect(commandByAgent.get('devin')).toBe("cd '/tmp/devin' && devin --resume 'devin-session'") expect(commandByAgent.get('droid')).toBe("cd '/tmp/droid' && droid --resume 'droid-session'") expect(commandByAgent.get('kimi')).toBe( "cd '/tmp/kimi' && kimi --session 'session_kimi-session'" ) + + const ompSession = result.sessions.find((session) => session.agent === 'omp') + expect(ompSession?.model).toBe('gpt-5.4-mini') + expect(ompSession?.totalTokens).toBe(160) + }) + + it('captures an in-progress OMP model from model_change before any assistant reply', async () => { + // OMP writes the model on `model_change.model` (not Pi's `modelId`). With no + // assistant message yet, the model must still come through — proving the + // model_change fallback rather than assistant-message capture. + const root = await mkdtemp(join(tmpdir(), 'orca-ai-vault-omp-mc-')) + tempRoots.push(root) + const roots = isolatedScanRoots(root) + await mkdir(roots.ompSessionsDir, { recursive: true }) + await writeFile( + join(roots.ompSessionsDir, 'omp-in-progress.jsonl'), + jsonLines([ + { + type: 'session', + id: 'omp-in-progress', + timestamp: '2026-05-01T10:00:00.000Z', + cwd: '/tmp/omp' + }, + { type: 'model_change', model: 'omp-mc-only-model', timestamp: '2026-05-01T10:00:01.000Z' }, + { + type: 'message', + timestamp: '2026-05-01T10:00:02.000Z', + message: { role: 'user', content: [{ type: 'text', text: 'first prompt' }] } + } + ]) + ) + + const result = await scanAiVaultSessions({ ...roots, platform: 'darwin', limit: 5 }) + const session = result.sessions.find((s) => s.agent === 'omp') + expect(session?.model).toBe('omp-mc-only-model') }) it('strips newline-heavy Grok user_query envelopes without regex matching', async () => { @@ -769,42 +844,3 @@ describe('scanAiVaultSessions', () => { expect(usedGrokWrapperMatch).toBe(false) }) }) - -describe('buildAiVaultResumeCommand', () => { - it('wraps Windows cwd changes in cmd so PowerShell and cmd launch the same resume command', () => { - expect( - buildAiVaultResumeCommand({ - agent: 'codex', - sessionId: 'session-1', - cwd: 'C:\\Users\\Ada Lovelace\\repo', - platform: 'win32' - }) - ).toBe('cmd /d /s /c "cd /d ""C:\\Users\\Ada Lovelace\\repo"" && codex resume ""session-1"""') - }) - - it('carries non-default Codex homes in copied resume commands', () => { - expect( - buildAiVaultResumeCommand({ - agent: 'codex', - sessionId: 'session-1', - cwd: '/repo/app', - platform: 'darwin', - codexHome: '/Users/ada/Library/Application Support/Orca/codex-runtime-home/home' - }) - ).toBe( - "cd '/repo/app' && CODEX_HOME='/Users/ada/Library/Application Support/Orca/codex-runtime-home/home' codex resume 'session-1'" - ) - - expect( - buildAiVaultResumeCommand({ - agent: 'codex', - sessionId: 'session-1', - cwd: 'C:\\Users\\Ada Lovelace\\repo', - platform: 'win32', - codexHome: 'C:\\Users\\Ada\\AppData\\Roaming\\Orca\\codex-runtime-home\\home' - }) - ).toBe( - 'cmd /d /s /c "cd /d ""C:\\Users\\Ada Lovelace\\repo"" && set ""CODEX_HOME=C:\\Users\\Ada\\AppData\\Roaming\\Orca\\codex-runtime-home\\home"" && codex resume ""session-1"""' - ) - }) -}) diff --git a/src/main/ai-vault/session-scanner.ts b/src/main/ai-vault/session-scanner.ts index 59f92dafc..5ba2a95d5 100644 --- a/src/main/ai-vault/session-scanner.ts +++ b/src/main/ai-vault/session-scanner.ts @@ -4,9 +4,14 @@ import type { AiVaultSession } from '../../shared/ai-vault-types' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../shared/execution-host' +import { withSpan } from '../observability/tracer' import { sessionSortTime } from './session-scanner-accumulator' -import { parseAgentSessionFile } from './session-scanner-agent-parser' import { codexHomeForSessionsDir } from './session-scanner-codex-paths' +import { + createSessionParseStats, + parseAgentSessionFileCached, + type SessionParseStats +} from './session-scanner-parse-cache' import { discoverInScopeClaudeFiles } from './session-scanner-scope-discovery' import { DEFAULT_CODEX_HOME_DIR, @@ -39,54 +44,69 @@ const SCOPE_PARSE_LIMIT = 2000 export async function scanAiVaultSessions( options: AiVaultScanOptions = {} ): Promise { - const limit = clampPositiveInteger(options.limit, DEFAULT_LIMIT) - const limitPerAgent = clampPositiveInteger(options.limitPerAgent, DEFAULT_SCAN_LIMIT_PER_AGENT) - const platform = options.platform ?? process.platform - const executionHostId = options.executionHostId ?? LOCAL_EXECUTION_HOST_ID - const issues: AiVaultScanIssue[] = [] - const discoveries = await discoverAiVaultSessionSources({ options, limitPerAgent, issues }) + // The span makes scan cost visible in the local trace file: STA-1278-style + // "one core pegged" reports need to show whether transcript scanning is the + // subsystem burning CPU, and how much of each scan the cache absorbed. + return withSpan('aiVault.scan', async (span) => { + const limit = clampPositiveInteger(options.limit, DEFAULT_LIMIT) + const limitPerAgent = clampPositiveInteger(options.limitPerAgent, DEFAULT_SCAN_LIMIT_PER_AGENT) + const platform = options.platform ?? process.platform + const executionHostId = options.executionHostId ?? LOCAL_EXECUTION_HOST_ID + const issues: AiVaultScanIssue[] = [] + const parseStats = createSessionParseStats() + const discoveries = await discoverAiVaultSessionSources({ options, limitPerAgent, issues }) - const candidates = discoveries - .flatMap((discovery) => - discovery.files.map( - (file): SessionFileCandidate => ({ - agent: discovery.agent, - file, - codexHome: - discovery.agent === 'codex' - ? codexHomeForSessionsDir(discovery.rootDir, DEFAULT_CODEX_HOME_DIR) - : null - }) + const candidates = discoveries + .flatMap((discovery) => + discovery.files.map( + (file): SessionFileCandidate => ({ + agent: discovery.agent, + file, + codexHome: + discovery.agent === 'codex' + ? codexHomeForSessionsDir(discovery.rootDir, DEFAULT_CODEX_HOME_DIR) + : null + }) + ) ) - ) - .sort((left, right) => right.file.mtimeMs - left.file.mtimeMs) + .sort((left, right) => right.file.mtimeMs - left.file.mtimeMs) - const parsedSessions = await parseSessionCandidates({ - candidates, - limit, - platform, - executionHostId, - issues + const parsedSessions = await parseSessionCandidates({ + candidates, + limit, + platform, + executionHostId, + issues, + parseStats + }) + + const cappedSessions = parsedSessions + .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) + .slice(0, limit) + + const scopeSessions = await scanInScopeSessions({ + discoveries, + scopePaths: options.scopePaths ?? [], + alreadyParsedFilePaths: new Set(cappedSessions.map((session) => session.filePath)), + platform, + executionHostId, + issues, + parseStats + }) + + span.setAttribute('candidates', candidates.length) + span.setAttribute('reused', parseStats.reused) + span.setAttribute('incremental', parseStats.incremental) + span.setAttribute('fullParses', parseStats.fullParses) + span.setAttribute('bytesRead', parseStats.bytesRead) + span.setAttribute('issues', issues.length) + + return { + sessions: mergeSessions(cappedSessions, scopeSessions), + issues: issues.map((issue) => ({ executionHostId, ...issue })), + scannedAt: new Date().toISOString() + } }) - - const cappedSessions = parsedSessions - .sort((left, right) => sessionSortTime(right) - sessionSortTime(left)) - .slice(0, limit) - - const scopeSessions = await scanInScopeSessions({ - discoveries, - scopePaths: options.scopePaths ?? [], - alreadyParsedFilePaths: new Set(cappedSessions.map((session) => session.filePath)), - platform, - executionHostId, - issues - }) - - return { - sessions: mergeSessions(cappedSessions, scopeSessions), - issues: issues.map((issue) => ({ executionHostId, ...issue })), - scannedAt: new Date().toISOString() - } } // In-scope sessions are guaranteed regardless of the recency cap, so the global @@ -116,6 +136,7 @@ async function scanInScopeSessions(args: { platform: NodeJS.Platform executionHostId: ExecutionHostId issues: AiVaultScanIssue[] + parseStats: SessionParseStats }): Promise { if (args.scopePaths.length === 0) { return [] @@ -142,7 +163,8 @@ async function scanInScopeSessions(args: { limit: candidates.length, platform: args.platform, executionHostId: args.executionHostId, - issues: args.issues + issues: args.issues, + parseStats: args.parseStats }) } @@ -152,6 +174,7 @@ async function parseSessionCandidates(args: { platform: NodeJS.Platform executionHostId: ExecutionHostId issues: AiVaultScanIssue[] + parseStats: SessionParseStats }): Promise { const sessions: AiVaultSession[] = [] let index = 0 @@ -167,7 +190,7 @@ async function parseSessionCandidates(args: { const batch = args.candidates.slice(index, index + batchSize) const results = await Promise.all( batch.map((candidate) => - parseSessionCandidate(candidate, args.platform, args.executionHostId) + parseSessionCandidate(candidate, args.platform, args.executionHostId, args.parseStats) ) ) @@ -189,10 +212,11 @@ async function parseSessionCandidates(args: { async function parseSessionCandidate( candidate: SessionFileCandidate, platform: NodeJS.Platform, - executionHostId: ExecutionHostId + executionHostId: ExecutionHostId, + parseStats: SessionParseStats ): Promise { try { - const session = await parseAgentSessionFile(candidate, platform) + const session = await parseAgentSessionFileCached(candidate, platform, parseStats) return { session: session ? withSessionExecutionHost(session, executionHostId) : null, issue: null diff --git a/src/main/attribution/terminal-attribution.test.ts b/src/main/attribution/terminal-attribution.test.ts index a051d04ca..86096168f 100644 --- a/src/main/attribution/terminal-attribution.test.ts +++ b/src/main/attribution/terminal-attribution.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: these tests exercise generated shell wrapper -scripts end-to-end, and keeping the regression fixtures adjacent makes the -attribution safety cases easier to audit. */ import { execFileSync } from 'node:child_process' import { chmodSync, diff --git a/src/main/automations/external-manager.test.ts b/src/main/automations/external-manager.test.ts index a44ad186f..dc96b9b96 100644 --- a/src/main/automations/external-manager.test.ts +++ b/src/main/automations/external-manager.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: external automation mapping and lifecycle IPC share fixtures. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createExternalAutomation, diff --git a/src/main/browser/browser-cookie-import.test.ts b/src/main/browser/browser-cookie-import.test.ts index 767f35931..c2965e7f1 100644 --- a/src/main/browser/browser-cookie-import.test.ts +++ b/src/main/browser/browser-cookie-import.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: cookie import tests share import-time Electron mocks plus - browser-specific cookie fixtures; splitting would duplicate brittle setup. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { sessionFromPartitionMock, dialogShowOpenDialogMock } = vi.hoisted(() => ({ diff --git a/src/main/browser/browser-screencast-stream.test.ts b/src/main/browser/browser-screencast-stream.test.ts index 6c6be1cbc..d1fc83880 100644 --- a/src/main/browser/browser-screencast-stream.test.ts +++ b/src/main/browser/browser-screencast-stream.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: one fixture-backed file covers screencast frame, viewport, dialog, and cleanup behavior together. */ import { Buffer } from 'node:buffer' import { EventEmitter } from 'node:events' import { describe, expect, it, vi } from 'vitest' diff --git a/src/main/browser/cdp-bridge-integration.test.ts b/src/main/browser/cdp-bridge-integration.test.ts index e1992fe23..daaae6054 100644 --- a/src/main/browser/cdp-bridge-integration.test.ts +++ b/src/main/browser/cdp-bridge-integration.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: integration test covering the full browser automation pipeline end-to-end. */ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/claude-accounts/live-pty-gate.test.ts b/src/main/claude-accounts/live-pty-gate.test.ts index 1812299c4..8ffe4bf8b 100644 --- a/src/main/claude-accounts/live-pty-gate.test.ts +++ b/src/main/claude-accounts/live-pty-gate.test.ts @@ -1,15 +1,23 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { + attachClaudeLivePtyPersistence, beginClaudeAuthSwitch, + confirmSeededClaudeLivePtys, endClaudeAuthSwitch, + hasLiveClaudePtys, isClaudeAuthSwitchInProgress, markClaudePtyExited, - markClaudePtySpawned + markClaudePtySpawned, + seedLiveClaudePtysFromPersistence } from './live-pty-gate' describe('Claude live PTY gate', () => { afterEach(() => { markClaudePtyExited('live-claude-pty') + markClaudePtyExited('seeded-pty-1') + markClaudePtyExited('seeded-pty-2') + confirmSeededClaudeLivePtys([]) + attachClaudeLivePtyPersistence(null) endClaudeAuthSwitch() }) @@ -26,4 +34,61 @@ describe('Claude live PTY gate', () => { expect(() => beginClaudeAuthSwitch()).toThrow('already in progress') }) + + it('counts seeded session ids as live until confirmed dead', () => { + seedLiveClaudePtysFromPersistence(['seeded-pty-1', 'seeded-pty-2']) + + expect(hasLiveClaudePtys()).toBe(true) + + confirmSeededClaudeLivePtys(['seeded-pty-1']) + + expect(hasLiveClaudePtys()).toBe(true) + + confirmSeededClaudeLivePtys([]) + + expect(hasLiveClaudePtys()).toBe(true) + + markClaudePtyExited('seeded-pty-1') + + expect(hasLiveClaudePtys()).toBe(false) + }) + + it('releases seeded ids the daemon no longer knows', () => { + const removeClaudeLivePtySessionId = vi.fn() + attachClaudeLivePtyPersistence({ + addClaudeLivePtySessionId: vi.fn(), + removeClaudeLivePtySessionId + }) + seedLiveClaudePtysFromPersistence(['seeded-pty-1', 'seeded-pty-2']) + + confirmSeededClaudeLivePtys(['seeded-pty-2']) + + expect(hasLiveClaudePtys()).toBe(true) + expect(removeClaudeLivePtySessionId).toHaveBeenCalledWith('seeded-pty-1') + expect(removeClaudeLivePtySessionId).not.toHaveBeenCalledWith('seeded-pty-2') + }) + + it('keeps a seeded id confirmed by a real spawn out of later pruning', () => { + seedLiveClaudePtysFromPersistence(['seeded-pty-1']) + markClaudePtySpawned('seeded-pty-1') + + confirmSeededClaudeLivePtys([]) + + expect(hasLiveClaudePtys()).toBe(true) + }) + + it('persists spawns and exits when persistence is attached', () => { + const addClaudeLivePtySessionId = vi.fn() + const removeClaudeLivePtySessionId = vi.fn() + attachClaudeLivePtyPersistence({ + addClaudeLivePtySessionId, + removeClaudeLivePtySessionId + }) + + markClaudePtySpawned('live-claude-pty') + expect(addClaudeLivePtySessionId).toHaveBeenCalledWith('live-claude-pty') + + markClaudePtyExited('live-claude-pty') + expect(removeClaudeLivePtySessionId).toHaveBeenCalledWith('live-claude-pty') + }) }) diff --git a/src/main/claude-accounts/live-pty-gate.ts b/src/main/claude-accounts/live-pty-gate.ts index 028fbc29e..7c469d6bc 100644 --- a/src/main/claude-accounts/live-pty-gate.ts +++ b/src/main/claude-accounts/live-pty-gate.ts @@ -1,12 +1,60 @@ const liveClaudePtyIds = new Set() +// Why: ids restored from persistence at startup, not yet confirmed against the +// daemon. They keep the OAuth refresh gate closed so an early managed refresh +// cannot rotate the single-use refresh token out from under a Claude CLI that +// survived the app restart inside the daemon. +const seededUnconfirmedPtyIds = new Set() let switchInProgress = false +export type ClaudeLivePtyPersistence = { + addClaudeLivePtySessionId(sessionId: string): void + removeClaudeLivePtySessionId(sessionId: string): void +} + +let persistence: ClaudeLivePtyPersistence | null = null + +export function attachClaudeLivePtyPersistence(target: ClaudeLivePtyPersistence | null): void { + persistence = target +} + +export function seedLiveClaudePtysFromPersistence(sessionIds: readonly string[]): void { + for (const sessionId of sessionIds) { + liveClaudePtyIds.add(sessionId) + seededUnconfirmedPtyIds.add(sessionId) + } +} + +export function hasSeededUnconfirmedClaudePtys(): boolean { + return seededUnconfirmedPtyIds.size > 0 +} + +/** + * Reconcile seeded ids against the daemon's live session list. Seeded ids the + * daemon no longer knows are dead — release them so they cannot defer OAuth + * refresh forever. Seeded ids that are still alive stay in the gate even if + * their pane never reattaches: that daemon process still owns the credentials. + */ +export function confirmSeededClaudeLivePtys(aliveSessionIds: readonly string[]): void { + const alive = new Set(aliveSessionIds) + for (const sessionId of seededUnconfirmedPtyIds) { + if (!alive.has(sessionId)) { + liveClaudePtyIds.delete(sessionId) + persistence?.removeClaudeLivePtySessionId(sessionId) + } + } + seededUnconfirmedPtyIds.clear() +} + export function markClaudePtySpawned(ptyId: string): void { liveClaudePtyIds.add(ptyId) + seededUnconfirmedPtyIds.delete(ptyId) + persistence?.addClaudeLivePtySessionId(ptyId) } export function markClaudePtyExited(ptyId: string): void { liveClaudePtyIds.delete(ptyId) + seededUnconfirmedPtyIds.delete(ptyId) + persistence?.removeClaudeLivePtySessionId(ptyId) } export function hasLiveClaudePtys(): boolean { diff --git a/src/main/claude-accounts/runtime-auth-service.test.ts b/src/main/claude-accounts/runtime-auth-service.test.ts index 1df59c0dc..c6c2043de 100644 --- a/src/main/claude-accounts/runtime-auth-service.test.ts +++ b/src/main/claude-accounts/runtime-auth-service.test.ts @@ -1081,6 +1081,53 @@ describe('ClaudeRuntimeAuthService', () => { } }) + it('rematerializes managed credentials over a wiped runtime blob while a Claude terminal is live', async () => { + setPlatform('win32') + const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json') + const originalCredentials = createClaudeCredentialsJson('user@example.com', 'original', 'org-a') + // Why: Claude CLI wipes tokens in place (keeps identity fields) after an + // invalid_grant refresh — the exact blob shape this regression guards. + const parsedOriginal = JSON.parse(originalCredentials) as { + claudeAiOauth: Record + } + const wipedCredentials = `${JSON.stringify({ + claudeAiOauth: { + ...parsedOriginal.claudeAiOauth, + accessToken: '', + refreshToken: '', + expiresAt: 0 + } + })}\n` + const managedAuthPath = createManagedClaudeAuth( + testState.userDataDir, + 'account-1', + originalCredentials + ) + const settings = createSettings({ + claudeManagedAccounts: [ + createClaudeAccount('account-1', managedAuthPath, { organizationUuid: 'org-a' }) + ], + activeClaudeManagedAccountId: 'account-1' + }) + const store = createStore(settings) + + const { ClaudeRuntimeAuthService } = await import('./runtime-auth-service') + const { markClaudePtyExited, markClaudePtySpawned } = await import('./live-pty-gate') + const service = new ClaudeRuntimeAuthService(store as never) + await service.syncForCurrentSelection() + + markClaudePtySpawned('live-claude-pty') + try { + writeFileSync(runtimeCredentialsPath, wipedCredentials, 'utf-8') + await service.syncForCurrentSelection() + + expect(readManagedCredentialsForTest('account-1', managedAuthPath)).toBe(originalCredentials) + expect(readFileSync(runtimeCredentialsPath, 'utf-8')).toBe(originalCredentials) + } finally { + markClaudePtyExited('live-claude-pty') + } + }) + it('rejects unverifiable refreshed runtime credentials', async () => { const runtimeCredentialsPath = join(testState.fakeHomeDir, '.claude', '.credentials.json') const originalCredentials = createClaudeCredentialsWithoutEmail('original') diff --git a/src/main/claude-accounts/runtime-auth-service.ts b/src/main/claude-accounts/runtime-auth-service.ts index 90d430835..72a29cfa6 100644 --- a/src/main/claude-accounts/runtime-auth-service.ts +++ b/src/main/claude-accounts/runtime-auth-service.ts @@ -67,7 +67,12 @@ type ClaudeAuthIdentity = { type ClaudeReadBackResult = | { status: 'unchanged' | 'persisted' } - | { status: 'rejected'; runtimeCredentialsChanged: boolean; runtimeCredentialsJson?: string } + | { + status: 'rejected' + runtimeCredentialsChanged: boolean + hasValidChangedRuntimeCredentials: boolean + runtimeCredentialsJson?: string + } type ClaudeReadBackMatch = | { kind: 'matched'; account: ClaudeManagedAccount; managedCredentialsJson: string } | { kind: 'none' | 'ambiguous' } @@ -378,6 +383,10 @@ export class ClaudeRuntimeAuthService { } else if ( readBackResult.status === 'rejected' && readBackResult.runtimeCredentialsChanged && + // Why: a live Claude that lost a refresh-token race wipes its runtime + // blob (empty tokens). Preserving that wreckage would leave every new + // session logged out — rematerialize managed credentials instead. + readBackResult.hasValidChangedRuntimeCredentials && hasLiveClaudePtys() ) { if ( @@ -499,10 +508,12 @@ export class ClaudeRuntimeAuthService { }[] = [] const ambiguousCandidates: string[] = [] let sawAmbiguousCandidate = false + let sawValidChangedCandidate = false for (const runtimeContents of changedCandidates) { if (!this.isValidCredentialsJsonObject(runtimeContents.credentialsJson)) { continue } + sawValidChangedCandidate = true const match = await this.findManagedAccountForRuntimeCredentials( runtimeContents.credentialsJson, runtimeContents.runtimeOauthAccount @@ -557,6 +568,7 @@ export class ClaudeRuntimeAuthService { return { status: 'rejected', runtimeCredentialsChanged: true, + hasValidChangedRuntimeCredentials: sawValidChangedCandidate, runtimeCredentialsJson: ambiguousCandidates.length === 1 ? ambiguousCandidates[0] : undefined } @@ -582,7 +594,10 @@ export class ClaudeRuntimeAuthService { return { status: 'rejected', runtimeCredentialsChanged: - this.runtimeCredentialsChangedSinceLastWrite(baselineCredentialsJson) + this.runtimeCredentialsChangedSinceLastWrite(baselineCredentialsJson), + // Why: an fs error hides whether a live session's refresh is present, + // so err toward preserving runtime state like before. + hasValidChangedRuntimeCredentials: true } } } diff --git a/src/main/claude-usage/store.test.ts b/src/main/claude-usage/store.test.ts index 1bd4502d2..08a76e469 100644 --- a/src/main/claude-usage/store.test.ts +++ b/src/main/claude-usage/store.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: scan gating, pricing, and automation -usage attribution share one stateful Claude usage store fixture. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { ClaudeUsagePersistedState } from './types' diff --git a/src/main/cli/wsl-cli-installer.test.ts b/src/main/cli/wsl-cli-installer.test.ts index 4698281ec..b9228fcb6 100644 --- a/src/main/cli/wsl-cli-installer.test.ts +++ b/src/main/cli/wsl-cli-installer.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- WSL CLI tests cover one installer state machine with shared - runner fixtures; splitting would duplicate the fake WSL filesystem setup. */ import type { CliInstallStatus } from '../../shared/cli-install-types' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index 0f6d968cc..9a6b8566f 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -484,6 +484,134 @@ describe('CodexRuntimeHomeService', () => { } }) + it('starts WSL session bridging after materializing the WSL launch home', async () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + const startWslCodexSessionBridgeInBackground = vi.fn(() => Promise.resolve()) + vi.doMock('../codex/wsl-codex-session-bridge', () => ({ + startWslCodexSessionBridgeInBackground + })) + const wslHome = join(testState.userDataDir, 'wsl-home') + vi.doMock('../wsl', () => ({ + getDefaultWslDistro: () => 'Ubuntu', + getWslHome: () => wslHome + })) + const store = createStore( + createSettings({ + activeCodexManagedAccountId: null, + activeCodexManagedAccountIdsByRuntime: { host: null, wsl: { Ubuntu: null } } + }) + ) + + try { + const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + const wslRuntimeHomePath = join( + wslHome, + '.local', + 'share', + 'orca', + 'codex-runtime-home', + 'home' + ) + + expect(service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: 'Ubuntu' })).toBe( + wslRuntimeHomePath + ) + expect(startWslCodexSessionBridgeInBackground).toHaveBeenCalledTimes(1) + expect(startWslCodexSessionBridgeInBackground).toHaveBeenCalledWith({ + distro: 'Ubuntu', + systemCodexHomePath: join(wslHome, '.codex'), + managedCodexHomePath: wslRuntimeHomePath + }) + } finally { + vi.doUnmock('../codex/wsl-codex-session-bridge') + vi.doUnmock('../wsl') + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + } + }) + + it('starts WSL session bridging for the distro used by the materialized runtime home', async () => { + const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + const startWslCodexSessionBridgeInBackground = vi.fn(() => Promise.resolve()) + vi.doMock('../codex/wsl-codex-session-bridge', () => ({ + startWslCodexSessionBridgeInBackground + })) + const wslHome = join(testState.userDataDir, 'debian-wsl-home') + const wslRuntimeHomePath = join( + wslHome, + '.local', + 'share', + 'orca', + 'codex-runtime-home', + 'home' + ) + vi.doMock('../wsl', () => ({ + getDefaultWslDistro: () => null, + getWslHome: (distro: string) => (distro === 'Debian' ? wslHome : null) + })) + vi.doMock('../../shared/wsl-paths', () => ({ + parseWslUncPath: (candidate: string) => + candidate === wslRuntimeHomePath + ? { + distro: 'Debian', + linuxPath: '/home/alice/.local/share/orca/codex-runtime-home/home' + } + : null + })) + const managedHomePath = createManagedAuth( + testState.userDataDir, + 'debian-account', + '{"account":"debian"}\n' + ) + const store = createStore( + createSettings({ + codexManagedAccounts: [ + { + id: 'debian-account', + email: 'debian@example.com', + managedHomePath, + managedHomeRuntime: 'wsl', + wslDistro: 'Debian', + wslLinuxHomePath: '/home/alice/.local/share/orca/codex-accounts/debian/home', + providerAccountId: null, + workspaceLabel: null, + workspaceAccountId: null, + createdAt: 1, + updatedAt: 1, + lastAuthenticatedAt: 1 + } + ], + activeCodexManagedAccountId: null, + activeCodexManagedAccountIdsByRuntime: { host: null, wsl: { Debian: 'debian-account' } } + }) + ) + + try { + const { CodexRuntimeHomeService } = await import('./runtime-home-service') + const service = new CodexRuntimeHomeService(store as never) + + expect(service.prepareForCodexLaunch({ runtime: 'wsl', wslDistro: null })).toBe( + wslRuntimeHomePath + ) + expect(startWslCodexSessionBridgeInBackground).toHaveBeenCalledWith({ + distro: 'Debian', + systemCodexHomePath: join(wslHome, '.codex'), + managedCodexHomePath: wslRuntimeHomePath + }) + } finally { + vi.doUnmock('../codex/wsl-codex-session-bridge') + vi.doUnmock('../wsl') + vi.doUnmock('../../shared/wsl-paths') + if (originalPlatform) { + Object.defineProperty(process, 'platform', originalPlatform) + } + } + }) + it('restores the system-default snapshot when no managed account is selected', async () => { const runtimeAuthPath = getRuntimeCodexAuthPath() writeFileSync(getSystemCodexAuthPath(), '{"account":"system"}\n', 'utf-8') diff --git a/src/main/codex-accounts/runtime-home-service.ts b/src/main/codex-accounts/runtime-home-service.ts index 4d5d8e4c6..3d2b06703 100644 --- a/src/main/codex-accounts/runtime-home-service.ts +++ b/src/main/codex-accounts/runtime-home-service.ts @@ -40,6 +40,7 @@ import { syncSystemCodexResourcesIntoManagedHome } from '../codex/codex-home-paths' import { startSystemCodexSessionBridgeInBackground } from '../codex/codex-session-bridge' +import { startWslCodexSessionBridgeInBackground } from '../codex/wsl-codex-session-bridge' import { prepareSystemConfigForFreshRuntimeMirror, syncSystemConfigIntoManagedCodexHome @@ -134,10 +135,11 @@ export class CodexRuntimeHomeService { prepareForCodexLaunch(target?: CodexAccountSelectionTarget): string | null { if (target?.runtime === 'wsl') { const wslTarget = this.resolveWslDefaultTarget(target) - return ( + const runtimeHomePath = this.syncWslRuntimeForCurrentSelection(wslTarget) ?? this.getWslSystemCodexHomePath(wslTarget) - ) + this.startWslSessionBridgeForLaunch(wslTarget, runtimeHomePath) + return runtimeHomePath } this.syncForCurrentSelection() syncSystemCodexResourcesIntoManagedHome() @@ -148,6 +150,34 @@ export class CodexRuntimeHomeService { return this.getRuntimeHomePath() } + private startWslSessionBridgeForLaunch( + target: CodexAccountSelectionTarget, + runtimeHomePath: string | null + ): void { + if (process.platform !== 'win32' || !runtimeHomePath) { + return + } + const runtimeHomeWsl = parseWslUncPath(runtimeHomePath) + const distro = target.wslDistro?.trim() || runtimeHomeWsl?.distro || getDefaultWslDistro() + if (!distro) { + return + } + const systemCodexHomePath = this.getWslSystemCodexHomePath({ + runtime: 'wsl', + wslDistro: distro + }) + if (!systemCodexHomePath || systemCodexHomePath === runtimeHomePath) { + return + } + // Why: WSL history must be hardlinked inside the distro; host-side links + // cannot bridge Windows and WSL filesystems in a resume-visible way. + void startWslCodexSessionBridgeInBackground({ + distro, + systemCodexHomePath, + managedCodexHomePath: runtimeHomePath + }) + } + getHostRuntimeHomePath(): string { return this.getRuntimeHomePath() } diff --git a/src/main/codex-usage/scanner-paths.test.ts b/src/main/codex-usage/scanner-paths.test.ts index 3f3eec442..46c10be0c 100644 --- a/src/main/codex-usage/scanner-paths.test.ts +++ b/src/main/codex-usage/scanner-paths.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: path discovery and legacy bridge scan preference cases need shared mocked homes to keep filesystem behavior realistic. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { linkSync, lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' diff --git a/src/main/codex/wsl-codex-session-bridge.test.ts b/src/main/codex/wsl-codex-session-bridge.test.ts new file mode 100644 index 000000000..c4218913a --- /dev/null +++ b/src/main/codex/wsl-codex-session-bridge.test.ts @@ -0,0 +1,168 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { ChildProcess } from 'node:child_process' + +const { execFileMock } = vi.hoisted(() => ({ + execFileMock: vi.fn() +})) + +vi.mock('node:child_process', () => ({ + execFile: execFileMock +})) + +import { + buildWslCodexSessionBridgeShellCommand, + resolveWslCodexSessionBridgeLinuxPaths, + startWslCodexSessionBridgeInBackground, + syncWslCodexSessionsIntoManagedHome +} from './wsl-codex-session-bridge' + +function mockExecFileSuccess(stdout = '{"scannedFiles":2,"linkedFiles":1}\n'): void { + execFileMock.mockImplementation( + ( + _command: string, + _args: string[], + _options: unknown, + callback: (error: Error | null, stdout: string, stderr: string) => void + ): ChildProcess => { + callback(null, stdout, '') + return {} as ChildProcess + } + ) +} + +beforeEach(() => { + execFileMock.mockReset() +}) + +describe('syncWslCodexSessionsIntoManagedHome', () => { + it('runs a WSL hardlink bridge from the WSL system sessions into the managed home', async () => { + mockExecFileSuccess() + + const summary = await syncWslCodexSessionsIntoManagedHome({ + distro: 'Ubuntu', + systemCodexHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex', + managedCodexHomePath: + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.local\\share\\orca\\codex-runtime-home\\home' + }) + + expect(summary).toEqual({ scannedFiles: 2, linkedFiles: 1 }) + expect(execFileMock).toHaveBeenCalledTimes(1) + const firstCall = execFileMock.mock.calls[0] + expect(firstCall).toBeDefined() + const [command, args, options] = firstCall as [ + string, + string[], + { timeout?: number; windowsHide?: boolean } + ] + expect(command).toBe('wsl.exe') + expect(args.slice(0, 5)).toEqual(['-d', 'Ubuntu', '--', 'bash', '-lc']) + expect(args).toHaveLength(6) + expect(options.timeout).toBe(30_000) + expect(options.windowsHide).toBe(true) + + const shellCommand = args[5] + expect(shellCommand).toContain("source_sessions_root='/home/alice/.codex/sessions'") + expect(shellCommand).toContain( + "managed_sessions_root='/home/alice/.local/share/orca/codex-runtime-home/home/sessions'" + ) + expect(shellCommand).toContain(`find "\\$source_sessions_root" -type f -name '*.jsonl' -print0`) + expect(shellCommand).toContain('ln -- "\\$source_file" "\\$target_file"') + expect(shellCommand).toContain('if [ -e "\\$target_file" ] || [ -L "\\$target_file" ]; then') + expect(shellCommand).not.toContain('ln -s') + expect(shellCommand).not.toContain('cp ') + expect(shellCommand).not.toContain('sqlite') + }) + + it('does not invoke WSL when paths are not resolvable inside the distro', async () => { + const summary = await syncWslCodexSessionsIntoManagedHome({ + distro: 'Ubuntu', + systemCodexHomePath: 'C:\\Users\\alice\\.codex', + managedCodexHomePath: 'C:\\Users\\alice\\AppData\\Roaming\\orca\\codex-runtime-home\\home' + }) + + expect(summary).toEqual({ scannedFiles: 0, linkedFiles: 0 }) + expect(execFileMock).not.toHaveBeenCalled() + }) + + it('parses the summary after WSL profile stdout', async () => { + mockExecFileSuccess('Welcome to Ubuntu\nprofile output\n{"scannedFiles":4,"linkedFiles":3}\n') + + const summary = await syncWslCodexSessionsIntoManagedHome({ + distro: 'Ubuntu', + systemCodexHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex', + managedCodexHomePath: + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.local\\share\\orca\\codex-runtime-home\\home' + }) + + expect(summary).toEqual({ scannedFiles: 4, linkedFiles: 3 }) + }) + + it('coalesces duplicate background bridges for the same WSL target', async () => { + mockExecFileSuccess() + const target = { + distro: 'Ubuntu', + systemCodexHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex', + managedCodexHomePath: + '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.local\\share\\orca\\codex-runtime-home\\home' + } + + const firstTask = startWslCodexSessionBridgeInBackground(target) + const secondTask = startWslCodexSessionBridgeInBackground(target) + + expect(firstTask).toBe(secondTask) + await firstTask + expect(execFileMock).toHaveBeenCalledTimes(1) + }) +}) + +describe('resolveWslCodexSessionBridgeLinuxPaths', () => { + it('requires both homes to belong to the requested distro', () => { + expect( + resolveWslCodexSessionBridgeLinuxPaths({ + distro: 'Ubuntu', + systemCodexHomePath: '\\\\wsl.localhost\\Ubuntu\\home\\alice\\.codex', + managedCodexHomePath: + '\\\\wsl.localhost\\Debian\\home\\alice\\.local\\share\\orca\\codex-runtime-home\\home' + }) + ).toBeNull() + }) + + it('accepts Linux paths for direct script construction tests', () => { + expect( + resolveWslCodexSessionBridgeLinuxPaths({ + distro: 'Ubuntu', + systemCodexHomePath: '/home/alice/.codex', + managedCodexHomePath: '/home/alice/.local/share/orca/codex-runtime-home/home' + }) + ).toEqual({ + systemSessionsRoot: '/home/alice/.codex/sessions', + managedSessionsRoot: '/home/alice/.local/share/orca/codex-runtime-home/home/sessions' + }) + }) +}) + +describe('buildWslCodexSessionBridgeShellCommand', () => { + it('only targets JSONL session files under sessions', () => { + const shellCommand = buildWslCodexSessionBridgeShellCommand({ + systemSessionsRoot: "/home/alice/.codex/sessions with 'quote'", + managedSessionsRoot: '/home/alice/.local/share/orca/codex-runtime-home/home/sessions' + }) + + expect(shellCommand).toContain( + `source_sessions_root='/home/alice/.codex/sessions with '\\''quote'\\'''` + ) + expect(shellCommand).toContain(`-name '*.jsonl'`) + expect(shellCommand).not.toContain('.sqlite') + }) + + it('escapes Linux-side shell variable expansion for wsl.exe argv', () => { + const shellCommand = buildWslCodexSessionBridgeShellCommand({ + systemSessionsRoot: '/home/alice/.codex/sessions', + managedSessionsRoot: '/home/alice/.local/share/orca/codex-runtime-home/home/sessions' + }) + + expect(shellCommand).toContain('\\$source_sessions_root') + expect(shellCommand).toContain('\\$source_file') + expect(shellCommand).toContain('\\$((scanned_files + 1))') + }) +}) diff --git a/src/main/codex/wsl-codex-session-bridge.ts b/src/main/codex/wsl-codex-session-bridge.ts new file mode 100644 index 000000000..e83abfadd --- /dev/null +++ b/src/main/codex/wsl-codex-session-bridge.ts @@ -0,0 +1,185 @@ +import { execFile } from 'node:child_process' +import { posix as pathPosix } from 'node:path' +import { escapeWslShCommandForWindows } from '../../shared/wsl-login-shell-command' +import { parseWslUncPath } from '../../shared/wsl-paths' + +export type WslCodexSessionBridgeTarget = { + distro: string + systemCodexHomePath: string + managedCodexHomePath: string +} + +export type WslCodexSessionBridgeLinuxPaths = { + systemSessionsRoot: string + managedSessionsRoot: string +} + +export type WslCodexSessionBridgeSummary = { + scannedFiles: number + linkedFiles: number +} + +const emptySummary: WslCodexSessionBridgeSummary = { scannedFiles: 0, linkedFiles: 0 } +const backgroundWslSessionBridgeTasks = new Map>() +const WSL_SESSION_BRIDGE_TIMEOUT_MS = 30_000 + +export function startWslCodexSessionBridgeInBackground( + target: WslCodexSessionBridgeTarget +): Promise { + const taskKey = getWslSessionBridgeTaskKey(target) + const existingTask = backgroundWslSessionBridgeTasks.get(taskKey) + if (existingTask) { + return existingTask + } + + const task = syncWslCodexSessionsIntoManagedHome(target) + .catch((error: unknown) => { + console.warn('[codex-session-bridge] Background WSL session bridge failed:', error) + }) + .then(() => undefined) + backgroundWslSessionBridgeTasks.set(taskKey, task) + void task.finally(() => { + if (backgroundWslSessionBridgeTasks.get(taskKey) === task) { + backgroundWslSessionBridgeTasks.delete(taskKey) + } + }) + return task +} + +export async function syncWslCodexSessionsIntoManagedHome( + target: WslCodexSessionBridgeTarget +): Promise { + const paths = resolveWslCodexSessionBridgeLinuxPaths(target) + if (!paths) { + return emptySummary + } + + const stdout = await execFileUtf8('wsl.exe', [ + '-d', + target.distro, + '--', + 'bash', + '-lc', + buildWslCodexSessionBridgeShellCommand(paths) + ]) + return parseWslSessionBridgeSummary(stdout) +} + +export function resolveWslCodexSessionBridgeLinuxPaths( + target: WslCodexSessionBridgeTarget +): WslCodexSessionBridgeLinuxPaths | null { + const systemHomePath = getLinuxPathForWslDistro(target.systemCodexHomePath, target.distro) + const managedHomePath = getLinuxPathForWslDistro(target.managedCodexHomePath, target.distro) + if (!systemHomePath || !managedHomePath) { + return null + } + + return { + systemSessionsRoot: joinLinuxPath(systemHomePath, 'sessions'), + managedSessionsRoot: joinLinuxPath(managedHomePath, 'sessions') + } +} + +export function buildWslCodexSessionBridgeShellCommand( + paths: WslCodexSessionBridgeLinuxPaths +): string { + const shellCommand = [ + 'set -u', + `source_sessions_root=${quoteBashString(paths.systemSessionsRoot)}`, + `managed_sessions_root=${quoteBashString(paths.managedSessionsRoot)}`, + 'scanned_files=0', + 'linked_files=0', + 'if [ ! -d "$source_sessions_root" ]; then', + ` printf '{"scannedFiles":0,"linkedFiles":0}\\n'`, + ' exit 0', + 'fi', + "while IFS= read -r -d '' source_file; do", + ' scanned_files=$((scanned_files + 1))', + ' relative_path=${source_file#"$source_sessions_root"/}', + ' target_file="$managed_sessions_root/$relative_path"', + ' if [ -e "$target_file" ] || [ -L "$target_file" ]; then', + ' continue', + ' fi', + ' target_dir=${target_file%/*}', + ' mkdir -p -- "$target_dir" || continue', + // Why: Codex resume ignores symlinked JSONL, so WSL links must be + // Linux hardlinks created inside the distro filesystem. + ' if ln -- "$source_file" "$target_file"; then', + ' linked_files=$((linked_files + 1))', + ' fi', + `done < <(find "$source_sessions_root" -type f -name '*.jsonl' -print0 2>/dev/null)`, + `printf '{"scannedFiles":%s,"linkedFiles":%s}\\n' "$scanned_files" "$linked_files"` + ].join('\n') + return escapeWslShCommandForWindows(shellCommand) +} + +function getWslSessionBridgeTaskKey(target: WslCodexSessionBridgeTarget): string { + return [target.distro, target.systemCodexHomePath, target.managedCodexHomePath].join('\0') +} + +function getLinuxPathForWslDistro(path: string, distro: string): string | null { + const wslPath = parseWslUncPath(path) + if (wslPath) { + return wslDistroNamesMatch(wslPath.distro, distro) ? wslPath.linuxPath : null + } + return path.startsWith('/') ? path : null +} + +function wslDistroNamesMatch(left: string, right: string): boolean { + return left.toLowerCase() === right.toLowerCase() +} + +function joinLinuxPath(basePath: string, ...segments: string[]): string { + return pathPosix.join(basePath, ...segments) +} + +function quoteBashString(value: string): string { + return `'${value.replace(/'/g, `'\\''`)}'` +} + +function execFileUtf8(command: string, args: string[]): Promise { + return new Promise((resolve, reject) => { + execFile( + command, + args, + { + encoding: 'utf-8', + maxBuffer: 1024 * 1024, + timeout: WSL_SESSION_BRIDGE_TIMEOUT_MS, + windowsHide: true + }, + (error, stdout) => { + if (error) { + reject(error) + return + } + resolve(stdout) + } + ) + }) +} + +function parseWslSessionBridgeSummary(stdout: string): WslCodexSessionBridgeSummary { + try { + // Why: login/profile scripts may write stdout before the bridge summary. + const summaryLine = + stdout + .split(/\r?\n/) + .findLast((line) => line.trim().length > 0) + ?.trim() ?? '' + const parsed: unknown = JSON.parse(summaryLine) + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + return emptySummary + } + const summary = parsed as Record + if (typeof summary.scannedFiles !== 'number' || typeof summary.linkedFiles !== 'number') { + return emptySummary + } + return { + scannedFiles: summary.scannedFiles, + linkedFiles: summary.linkedFiles + } + } catch { + return emptySummary + } +} diff --git a/src/main/daemon/client.test.ts b/src/main/daemon/client.test.ts index 7d2bea915..25aaebe16 100644 --- a/src/main/daemon/client.test.ts +++ b/src/main/daemon/client.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: daemon connection, RPC, event, and disconnect behavior share one socket test harness. */ import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createServer, type Server, type Socket } from 'node:net' diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts index 273d30ac0..bb2f1f4b7 100644 --- a/src/main/daemon/daemon-init.test.ts +++ b/src/main/daemon/daemon-init.test.ts @@ -38,6 +38,7 @@ const { spawnerInstances, ensureRunningOverrides, adapterInstances, + defaultListSessionsSessions, getLocalPtyProviderMock, localFallbackProvider, setLocalPtyProviderMock, @@ -103,6 +104,9 @@ const { // Same for DaemonPtyAdapter. The test asserts the replacement adapter is a // fresh instance whose respawn closure targets the *original* spawner. const adapterInstances: MockAdapter[] = [] + // Why: adapters are constructed inside initDaemonPtyProvider, so tests that + // need listSessions to report live sessions set this before calling init. + const defaultListSessionsSessions: { sessionId: string }[] = [] const localFallbackProvider = { routesFreshSpawnsToLocalProvider: undefined, @@ -154,6 +158,7 @@ const { spawnerInstances, ensureRunningOverrides, adapterInstances, + defaultListSessionsSessions, getLocalPtyProviderMock, localFallbackProvider, setLocalPtyProviderMock, @@ -303,7 +308,7 @@ vi.mock('./daemon-pty-adapter', () => ({ this.callOrder.push('fanoutSyntheticExits') }) this.listProcesses = vi.fn(async () => []) - this.listSessions = vi.fn(async () => []) + this.listSessions = vi.fn(async () => [...defaultListSessionsSessions]) this.shutdown = vi.fn(async () => {}) this.dispose = vi.fn() this.disconnectOnly = vi.fn(async () => {}) @@ -326,6 +331,7 @@ async function importFresh() { spawnerInstances.length = 0 ensureRunningOverrides.length = 0 adapterInstances.length = 0 + defaultListSessionsSessions.length = 0 getLocalPtyProviderMock.mockClear() localFallbackProvider.spawn.mockClear() localFallbackProvider.write.mockClear() @@ -397,6 +403,28 @@ describe('daemon-init: runRestartDaemon (7-step sequence)', () => { ) }) + it('prunes seeded Claude live-PTY ids against daemon sessions after init', async () => { + const mod = await importFresh() + // Why: live-pty-gate is intentionally unmocked — import from the same fresh + // module registry so the module-level gate state matches daemon-init's. + const gate = await import('../claude-accounts/live-pty-gate') + defaultListSessionsSessions.push({ sessionId: 'claude-alive' }) + gate.seedLiveClaudePtysFromPersistence(['claude-alive', 'claude-dead']) + try { + await mod.initDaemonPtyProvider() + + expect(gate.hasLiveClaudePtys()).toBe(true) + + gate.markClaudePtyExited('claude-alive') + // Why: proves 'claude-dead' was released by the daemon reconcile — the + // surviving session was the only id still holding the gate. + expect(gate.hasLiveClaudePtys()).toBe(false) + } finally { + gate.markClaudePtyExited('claude-alive') + gate.markClaudePtyExited('claude-dead') + } + }) + it('does not install a late daemon provider after startup fallback aborts the init attempt', async () => { const mod = await importFresh() let resolveEnsureRunning!: (value: { socketPath: string; tokenPath: string }) => void diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index 6b4551fe8..b7fa28903 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -50,6 +50,10 @@ import { } from '../ipc/pty' import { isStartupDiagnosticsEnabled, logStartupDiagnostic } from '../startup/startup-diagnostics' import { getDaemonLogFilePath } from '../observability/logs-directory' +import { + confirmSeededClaudeLivePtys, + hasSeededUnconfirmedClaudePtys +} from '../claude-accounts/live-pty-gate' // Why: daemon init runs concurrently with window load, so harness-side stderr // arrival times are useless — in-process `t` lets the startup benchmark derive @@ -489,6 +493,38 @@ export async function initDaemonPtyProvider(signal?: AbortSignal): Promise // data/exit events through the renderer and runtime listeners. rebindLocalProviderListeners() logDaemonMilestone('daemon-init-done', { legacyAdapters: legacyAdapters.length }) + await reconcileSeededClaudeLivePtys(routedAdapter) +} + +// Why: the Claude live-PTY gate is seeded pessimistically from persistence at +// store load. Once the daemon is up we know which of those sessions actually +// survived — release dead ids so they cannot defer OAuth refresh forever. +// Listing failures keep the seeds: over-holding the gate only delays a usage +// refresh, while releasing it early can rotate a live CLI's refresh token. +async function reconcileSeededClaudeLivePtys(provider: DaemonProvider): Promise { + if (!hasSeededUnconfirmedClaudePtys()) { + return + } + try { + const adapters = + provider instanceof DaemonPtyRouter || provider instanceof DegradedDaemonPtyProvider + ? provider.getAllAdapters() + : [provider] + const results = await Promise.allSettled(adapters.map((entry) => entry.listSessions())) + if (results.some((result) => result.status === 'rejected')) { + console.warn('[daemon] Keeping seeded Claude live-PTY gate — session listing failed') + return + } + confirmSeededClaudeLivePtys( + results.flatMap((result) => + result.status === 'fulfilled' ? result.value.map((session) => session.sessionId) : [] + ) + ) + } catch (error) { + // Why: gate bookkeeping must never fail daemon init; stale seeds only + // defer a usage refresh until the next restart. + console.warn('[daemon] Failed to reconcile seeded Claude live-PTY gate:', error) + } } // Why: the Manage Sessions IPC handlers need read access to the current diff --git a/src/main/daemon/daemon-server.test.ts b/src/main/daemon/daemon-server.test.ts index ab3486677..ae017e0ef 100644 --- a/src/main/daemon/daemon-server.test.ts +++ b/src/main/daemon/daemon-server.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: daemon server RPC, auth, stream batching, and shutdown behavior share one socket/client harness; splitting would duplicate setup. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { connect, type Server, type Socket } from 'node:net' import { tmpdir } from 'node:os' diff --git a/src/main/daemon/reattach-snapshot.test.ts b/src/main/daemon/reattach-snapshot.test.ts index 8735b76be..a8bdf2524 100644 --- a/src/main/daemon/reattach-snapshot.test.ts +++ b/src/main/daemon/reattach-snapshot.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines */ import { afterEach, describe, expect, it, vi } from 'vitest' import { TerminalHost } from './terminal-host' import { HeadlessEmulator } from './headless-emulator' diff --git a/src/main/daemon/shell-ready.test.ts b/src/main/daemon/shell-ready.test.ts index af3ced5ad..b741ef057 100644 --- a/src/main/daemon/shell-ready.test.ts +++ b/src/main/daemon/shell-ready.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: shell-ready wrapper coverage keeps zsh, - bash, marker scanning, and env restoration cases in one suite so the - generated wrapper contract is reviewed as a unit. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { spawnSync } from 'node:child_process' import { tmpdir } from 'node:os' diff --git a/src/main/daemon/terminal-host.test.ts b/src/main/daemon/terminal-host.test.ts index ecc9fd116..4f92d4c1e 100644 --- a/src/main/daemon/terminal-host.test.ts +++ b/src/main/daemon/terminal-host.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Session, type SubprocessHandle } from './session' import { TerminalHost } from './terminal-host' diff --git a/src/main/diagnostics/main-thread-churn-probe.test.ts b/src/main/diagnostics/main-thread-churn-probe.test.ts new file mode 100644 index 000000000..cfc159fc1 --- /dev/null +++ b/src/main/diagnostics/main-thread-churn-probe.test.ts @@ -0,0 +1,74 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + MAIN_THREAD_DIAGNOSTICS_ENV, + classifySubprocessCommand, + drainSubprocessSpawnStats, + isMainThreadDiagnosticsEnabled, + recordSubprocessSpawn +} from './main-thread-churn-probe' + +afterEach(() => { + vi.unstubAllEnvs() + drainSubprocessSpawnStats() +}) + +describe('classifySubprocessCommand', () => { + it('uses the git subcommand, skipping global value flags', () => { + expect(classifySubprocessCommand('git', ['-C', '/repo', 'status', '--porcelain=v2'])).toBe( + 'git status' + ) + expect( + classifySubprocessCommand('git', ['-c', 'core.quotepath=off', 'rev-list', '--count']) + ).toBe('git rev-list') + expect(classifySubprocessCommand('git', ['--git-dir=/repo/.git', 'log', '--oneline'])).toBe( + 'git log' + ) + }) + + it('normalizes absolute paths and .exe suffixes', () => { + expect(classifySubprocessCommand('/usr/bin/git', ['status'])).toBe('git status') + expect(classifySubprocessCommand('C:\\Program Files\\Git\\git.exe', ['fetch'])).toBe( + 'git fetch' + ) + expect(classifySubprocessCommand('gh', ['api', 'rate_limit'])).toBe('gh api') + }) + + it('unwraps wsl.exe-routed commands', () => { + expect( + classifySubprocessCommand('wsl.exe', ['-d', 'Ubuntu', '--', 'git', 'status', '--porcelain']) + ).toBe('git status') + expect(classifySubprocessCommand('wsl.exe', ['-d', 'Ubuntu'])).toBe('wsl') + }) + + it('falls back to the binary name when no subcommand exists', () => { + expect(classifySubprocessCommand('rg', ['--files'])).toBe('rg') + }) + + it('never treats positionals or git-flag values as subcommands for non-subcommand CLIs', () => { + // rg's -C takes a number; it must not be consumed as a git-style flag + // value, and "3"/"pattern" must not become fake subcommand buckets. + expect(classifySubprocessCommand('rg', ['-C', '3', 'pattern'])).toBe('rg') + expect(classifySubprocessCommand('node', ['script.js'])).toBe('node') + }) +}) + +describe('recordSubprocessSpawn', () => { + it('is a no-op when the diagnostics env var is unset', () => { + vi.stubEnv(MAIN_THREAD_DIAGNOSTICS_ENV, '') + expect(isMainThreadDiagnosticsEnabled()).toBe(false) + recordSubprocessSpawn('git', ['status'], 1) + expect(drainSubprocessSpawnStats()).toEqual({}) + }) + + it('aggregates count and block time per command, and drain resets', () => { + vi.stubEnv(MAIN_THREAD_DIAGNOSTICS_ENV, '1') + recordSubprocessSpawn('git', ['-C', '/repo', 'status'], 2) + recordSubprocessSpawn('/usr/bin/git', ['status', '--porcelain=v2'], 4) + recordSubprocessSpawn('git', ['rev-list', '--count'], 1.5) + expect(drainSubprocessSpawnStats()).toEqual({ + 'git status': { count: 2, blockMsTotal: 6, blockMsMax: 4 }, + 'git rev-list': { count: 1, blockMsTotal: 1.5, blockMsMax: 1.5 } + }) + expect(drainSubprocessSpawnStats()).toEqual({}) + }) +}) diff --git a/src/main/diagnostics/main-thread-churn-probe.ts b/src/main/diagnostics/main-thread-churn-probe.ts new file mode 100644 index 000000000..f4fe900cf --- /dev/null +++ b/src/main/diagnostics/main-thread-churn-probe.ts @@ -0,0 +1,185 @@ +import { writeStartupDiagnosticLine } from '../startup/startup-diagnostics' + +export const MAIN_THREAD_DIAGNOSTICS_ENV = 'ORCA_MAIN_THREAD_DIAGNOSTICS' + +// Why: 25ms mirrors event-loop-stall-probe — a timer that fires late by N ms +// proves the main thread was blocked for N ms, which is the direct in-process +// measurement of the macOS "Performance Diagnostics" main-thread warnings +// reported in issue #7576. +const TICK_MS = 25 +const REPORT_EVERY_MS = 5_000 + +export function isMainThreadDiagnosticsEnabled(env: NodeJS.ProcessEnv = process.env): boolean { + return env[MAIN_THREAD_DIAGNOSTICS_ENV] === '1' +} + +// Git global options that precede the subcommand. Value-taking flags must be +// skipped together with their value to find the real subcommand. +const GIT_VALUE_FLAGS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--exec-path']) + +// Why: only subcommand-style CLIs get a " " bucket; for +// anything else (rg, node, …) the first positional is an operand, not a +// subcommand, and would fragment the aggregation. +const SUBCOMMAND_BINARIES = new Set(['git', 'gh', 'glab']) + +/** + * Reduce a resolved spawn to a stable aggregation key like "git status" or + * "gh api". Handles WSL wrapping (`wsl.exe -d -- git …`), absolute + * binary paths, `.exe` suffixes, and git global flags before the subcommand. + */ +// Split on both separators so Windows-style paths classify correctly even +// when the classifier itself runs in a posix test environment. +function binaryName(command: string): string { + const leaf = command.split(/[\\/]/).pop() ?? command + return leaf.replace(/\.exe$/i, '').toLowerCase() +} + +export function classifySubprocessCommand(command: string, args: readonly string[]): string { + let binary = binaryName(command) + const rest = [...args] + if (binary === 'wsl') { + while (rest.length > 0) { + const arg = rest.shift() + if (arg === '--') { + break + } + } + const unwrapped = rest.shift() + if (!unwrapped) { + return 'wsl' + } + binary = binaryName(unwrapped) + } + if (!SUBCOMMAND_BINARIES.has(binary)) { + return binary + } + let subcommand: string | null = null + for (let i = 0; i < rest.length; i++) { + const arg = rest[i] + if (!arg.startsWith('-')) { + subcommand = arg + break + } + // Why: only git's global flags take a separate value; e.g. rg's -C takes + // a number that must not be consumed as if it were a flag value. + if (binary === 'git' && GIT_VALUE_FLAGS.has(arg)) { + i++ + } + } + if (!subcommand) { + return binary + } + return `${binary} ${subcommand.slice(0, 40)}` +} + +export type SubprocessSpawnStats = { + count: number + // Cumulative and worst synchronous cost of initiating the spawn (the + // uv_spawn → posix_spawn call runs on the main thread before returning). + blockMsTotal: number + blockMsMax: number +} + +const spawnStatsByCommand = new Map() + +/** + * Record one subprocess spawn from the main process. `blockMs` is how long + * the synchronous spawn/execFile initiation call held the main thread. + * No-op unless ORCA_MAIN_THREAD_DIAGNOSTICS=1. + */ +export function recordSubprocessSpawn( + command: string, + args: readonly string[], + blockMs: number +): void { + if (!isMainThreadDiagnosticsEnabled()) { + return + } + const key = classifySubprocessCommand(command, args) + const stats = spawnStatsByCommand.get(key) + if (stats) { + stats.count++ + stats.blockMsTotal += blockMs + stats.blockMsMax = Math.max(stats.blockMsMax, blockMs) + } else { + spawnStatsByCommand.set(key, { count: 1, blockMsTotal: blockMs, blockMsMax: blockMs }) + } +} + +export function drainSubprocessSpawnStats(): Record { + const drained: Record = {} + for (const [key, stats] of spawnStatsByCommand) { + drained[key] = { + count: stats.count, + blockMsTotal: Math.round(stats.blockMsTotal * 100) / 100, + blockMsMax: Math.round(stats.blockMsMax * 100) / 100 + } + } + spawnStatsByCommand.clear() + return drained +} + +/** + * Timestamped marker line for correlating a specific main-process activity + * (e.g. an updater check) with the probe's stall windows and with macOS + * Performance Diagnostics log entries in field captures. No-op unless + * ORCA_MAIN_THREAD_DIAGNOSTICS=1. + */ +export function writeMainThreadDiagnosticMarker(marker: string): void { + if (!isMainThreadDiagnosticsEnabled()) { + return + } + writeStartupDiagnosticLine( + `[main-thread] ${JSON.stringify({ marker, t: Math.round(performance.now()) })}` + ) +} + +/** + * Long-running main-process jank probe for benchmarks and field diagnosis of + * issue #7576. Every 5s emits one `[main-thread] {json}` stderr line with the + * window's worst event-loop stall, stall counts over 50/250ms, and drained + * subprocess spawn stats. Unlike the startup stall probe this never stops: + * the churn it measures (git status polling, updater retries) is steady-state. + */ +export function startMainThreadChurnProbe(): void { + if (!isMainThreadDiagnosticsEnabled()) { + return + } + let last = performance.now() + let lastReport = last + let windowMaxGapMs = 0 + let gapsOver50Ms = 0 + let gapsOver250Ms = 0 + const timer = setInterval(() => { + const now = performance.now() + const gap = now - last - TICK_MS + last = now + if (gap > windowMaxGapMs) { + windowMaxGapMs = gap + } + if (gap > 50) { + gapsOver50Ms++ + } + if (gap > 250) { + gapsOver250Ms++ + } + if (now - lastReport < REPORT_EVERY_MS) { + return + } + lastReport = now + const spawns = drainSubprocessSpawnStats() + const report = { + t: Math.round(now), + maxGapMs: Math.max(0, Math.round(windowMaxGapMs)), + gapsOver50Ms, + gapsOver250Ms, + spawnCount: Object.values(spawns).reduce((sum, s) => sum + s.count, 0), + spawns + } + windowMaxGapMs = 0 + gapsOver50Ms = 0 + gapsOver250Ms = 0 + writeStartupDiagnosticLine(`[main-thread] ${JSON.stringify(report)}`) + }, TICK_MS) + timer.unref?.() +} diff --git a/src/main/git/gh-rate-limit-breaker.test.ts b/src/main/git/gh-rate-limit-breaker.test.ts new file mode 100644 index 000000000..0975dd325 --- /dev/null +++ b/src/main/git/gh-rate-limit-breaker.test.ts @@ -0,0 +1,93 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + _resetGhRateLimitBreaker, + classifyGhRateLimitBucket, + createGhRateLimitBlockedError, + getGhRateLimitBlockedUntilMs, + isGhPrimaryRateLimitStderr, + isGhRateLimitProbe, + notifyGhPrimaryRateLimit, + recordGhPrimaryRateLimit, + registerGhRateLimitResetProbe +} from './gh-rate-limit-breaker' + +afterEach(() => { + _resetGhRateLimitBreaker() +}) + +describe('classifyGhRateLimitBucket', () => { + it('classifies search API endpoints, skipping flag values', () => { + expect( + classifyGhRateLimitBucket([ + 'api', + '--cache', + '120s', + 'search/issues?q=repo:a/b is:issue is:open&per_page=1', + '--jq', + '.total_count' + ]) + ).toBe('search') + expect(classifyGhRateLimitBucket(['search', 'prs', '--author', 'x'])).toBe('search') + }) + + it('classifies graphql and defaults everything else to core', () => { + expect(classifyGhRateLimitBucket(['api', 'graphql', '-f', 'query=…'])).toBe('graphql') + expect(classifyGhRateLimitBucket(['api', 'repos/a/b/pulls?per_page=36'])).toBe('core') + expect(classifyGhRateLimitBucket(['pr', 'list', '--limit', '36'])).toBe('core') + }) +}) + +describe('isGhRateLimitProbe', () => { + it('recognizes the exempt rate_limit endpoint only', () => { + expect(isGhRateLimitProbe(['api', 'rate_limit'])).toBe(true) + expect(isGhRateLimitProbe(['api', '/rate_limit'])).toBe(true) + expect(isGhRateLimitProbe(['api', 'search/issues?q=x'])).toBe(false) + expect(isGhRateLimitProbe(['pr', 'list'])).toBe(false) + }) +}) + +describe('isGhPrimaryRateLimitStderr', () => { + it('matches primary rate-limit 403s but not secondary limits', () => { + expect( + isGhPrimaryRateLimitStderr( + 'gh: API rate limit exceeded for user ID 1775218. If you reach out to GitHub Support… (HTTP 403)' + ) + ).toBe(true) + expect(isGhPrimaryRateLimitStderr('You have exceeded a secondary rate limit.')).toBe(false) + expect(isGhPrimaryRateLimitStderr('gh: Not Found (HTTP 404)')).toBe(false) + }) +}) + +describe('breaker state', () => { + it('blocks until the recorded time, then expires', () => { + const now = 1_000_000 + recordGhPrimaryRateLimit('search', now + 5_000) + expect(getGhRateLimitBlockedUntilMs('search', now)).toBe(now + 5_000) + expect(getGhRateLimitBlockedUntilMs('core', now)).toBeNull() + expect(getGhRateLimitBlockedUntilMs('search', now + 5_001)).toBeNull() + // Expiry is sticky — the entry was removed on the expired read. + expect(getGhRateLimitBlockedUntilMs('search', now)).toBeNull() + }) + + it('keeps the later of two recorded reset times', () => { + const now = 1_000_000 + recordGhPrimaryRateLimit('core', now + 60_000) + recordGhPrimaryRateLimit('core', now + 10_000) + expect(getGhRateLimitBlockedUntilMs('core', now)).toBe(now + 60_000) + }) + + it('notifyGhPrimaryRateLimit applies a fallback block and fires the reset probe', () => { + const probe = vi.fn() + registerGhRateLimitResetProbe(probe) + notifyGhPrimaryRateLimit('search') + expect(probe).toHaveBeenCalledWith('search') + expect(getGhRateLimitBlockedUntilMs('search')).toBeGreaterThan(Date.now()) + }) + + it('creates an error that classifies as rate_limited, not permission_denied', () => { + const error = createGhRateLimitBlockedError('search', Date.now() + 30_000) + expect(error.stderr.toLowerCase()).toContain('rate limit') + expect(error.stderr.toLowerCase()).not.toContain('403') + expect(error.ghRateLimitBlocked).toBe(true) + }) +}) diff --git a/src/main/git/gh-rate-limit-breaker.ts b/src/main/git/gh-rate-limit-breaker.ts new file mode 100644 index 000000000..94bef46ff --- /dev/null +++ b/src/main/git/gh-rate-limit-breaker.ts @@ -0,0 +1,166 @@ +/** + * Global circuit breaker for gh CLI primary rate limits. + * + * Why: a primary rate-limit 403 means every further request in that bucket + * will fail until GitHub's reset time. Without shared state, a 90-repo + * Tasks-page fan-out keeps spawning gh subprocesses that each take a fresh + * 403 — burning main-thread spawn time and log noise while returning nothing + * (the Discord "countWorkItems failed ×90" storm). This module holds + * blocked-until state consulted by the runner before every gh spawn. + * + * Lives under git/ (not github/) with zero imports so both the runner and + * the github rate-limit prober can use it without an import cycle. + */ + +export type GhRateLimitBucket = 'core' | 'search' | 'graphql' + +// Why: a primary 403 does not carry the reset time. The search window resets +// every minute; core/graphql reset hourly but blocking a full hour on a guess +// would be too punishing, so pick a modest re-probe interval. The registered +// reset probe (gh api rate_limit — exempt from limits) refines these to the +// real reset time right after the breaker trips. +const FALLBACK_BLOCK_MS: Record = { + search: 70_000, + core: 5 * 60_000, + graphql: 5 * 60_000 +} + +const blockedUntilMsByBucket = new Map() +let resetProbe: ((bucket: GhRateLimitBucket) => void) | null = null + +// gh api flags that take a separate value, so the endpoint arg can be found. +const GH_API_VALUE_FLAGS = new Set([ + '--cache', + '--jq', + '-q', + '--method', + '-X', + '--field', + '-F', + '--raw-field', + '-f', + '--header', + '-H', + '--hostname', + '--input', + '--template', + '-t', + '--preview', + '-p' +]) + +function findGhApiEndpoint(args: readonly string[]): string | null { + for (let i = 1; i < args.length; i++) { + const arg = args[i] + if (!arg.startsWith('-')) { + return arg + } + if (GH_API_VALUE_FLAGS.has(arg)) { + i++ + } + } + return null +} + +export function classifyGhRateLimitBucket(args: readonly string[]): GhRateLimitBucket { + const command = args[0] + if (command === 'search') { + return 'search' + } + if (command !== 'api') { + return 'core' + } + const endpoint = findGhApiEndpoint(args) + if (!endpoint) { + return 'core' + } + const path = endpoint.replace(/^\//, '') + if (path.startsWith('search/')) { + return 'search' + } + if (path === 'graphql' || path.startsWith('graphql?')) { + return 'graphql' + } + return 'core' +} + +/** `gh api rate_limit` is exempt from rate limits and must never be blocked — + * it is the probe that refines the breaker's reset time. */ +export function isGhRateLimitProbe(args: readonly string[]): boolean { + if (args[0] !== 'api') { + return false + } + const endpoint = findGhApiEndpoint(args) + return endpoint === 'rate_limit' || endpoint === '/rate_limit' +} + +/** + * Primary rate-limit detection. Secondary limits ("secondary rate limit") + * carry Retry-After and are handled by the runner's transient retry logic. + */ +export function isGhPrimaryRateLimitStderr(stderr: string): boolean { + const s = stderr.toLowerCase() + return s.includes('api rate limit exceeded') && !s.includes('secondary rate limit') +} + +export function recordGhPrimaryRateLimit(bucket: GhRateLimitBucket, blockedUntilMs: number): void { + const existing = blockedUntilMsByBucket.get(bucket) ?? 0 + blockedUntilMsByBucket.set(bucket, Math.max(existing, blockedUntilMs)) +} + +export function clearGhRateLimitBlock(bucket: GhRateLimitBucket): void { + blockedUntilMsByBucket.delete(bucket) +} + +export function getGhRateLimitBlockedUntilMs( + bucket: GhRateLimitBucket, + nowMs: number = Date.now() +): number | null { + const blockedUntil = blockedUntilMsByBucket.get(bucket) + if (blockedUntil === undefined) { + return null + } + if (blockedUntil <= nowMs) { + blockedUntilMsByBucket.delete(bucket) + return null + } + return blockedUntil +} + +/** Register the (single) callback that refreshes precise reset times after a + * breaker trip. Registered by the github rate-limit prober at module load. */ +export function registerGhRateLimitResetProbe( + probe: ((bucket: GhRateLimitBucket) => void) | null +): void { + resetProbe = probe +} + +/** Called by the runner when a gh spawn came back with a primary 403. */ +export function notifyGhPrimaryRateLimit(bucket: GhRateLimitBucket): void { + recordGhPrimaryRateLimit(bucket, Date.now() + FALLBACK_BLOCK_MS[bucket]) + try { + resetProbe?.(bucket) + } catch { + // best-effort refinement; the fallback block stands + } +} + +export function createGhRateLimitBlockedError( + bucket: GhRateLimitBucket, + blockedUntilMs: number +): Error & { stderr: string; ghRateLimitBlocked: true } { + const resetsIn = Math.max(1, Math.ceil((blockedUntilMs - Date.now()) / 1000)) + // Why: "rate limit" (and no "HTTP 403") so classifyGhError maps this to + // rate_limited instead of permission_denied, matching a real gh failure. + const message = `GitHub API rate limit exceeded (${bucket}); retrying in ~${resetsIn}s without spawning gh.` + return Object.assign(new Error(message), { + stderr: message, + ghRateLimitBlocked: true as const + }) +} + +/** @internal — test-only */ +export function _resetGhRateLimitBreaker(): void { + blockedUntilMsByBucket.clear() + resetProbe = null +} diff --git a/src/main/git/runner-gh-rate-limit-breaker.test.ts b/src/main/git/runner-gh-rate-limit-breaker.test.ts new file mode 100644 index 000000000..dc22bb54f --- /dev/null +++ b/src/main/git/runner-gh-rate-limit-breaker.test.ts @@ -0,0 +1,95 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { execFileMock, execFileSyncMock, spawnMock } = vi.hoisted(() => ({ + execFileMock: vi.fn(), + execFileSyncMock: vi.fn(), + spawnMock: vi.fn() +})) + +vi.mock('child_process', () => ({ + execFile: execFileMock, + execFileSync: execFileSyncMock, + spawn: spawnMock +})) + +import { ghExecFileAsync } from './runner' +import { _resetGhRateLimitBreaker } from './gh-rate-limit-breaker' + +const PRIMARY_RATE_LIMIT_STDERR = + 'gh: API rate limit exceeded for user ID 1775218. Please wait. (HTTP 403)' + +function mockGhFailure(stderr: string): void { + execFileMock.mockImplementation((_binary, _args, options, callback) => { + const done = typeof options === 'function' ? options : callback + queueMicrotask(() => + done(Object.assign(new Error(`Command failed: gh\n${stderr}`), { stderr }), '', stderr) + ) + return { once: vi.fn() } + }) +} + +function mockGhSuccess(stdout: string): void { + execFileMock.mockImplementation((_binary, _args, options, callback) => { + const done = typeof options === 'function' ? options : callback + queueMicrotask(() => done(null, stdout, '')) + return { once: vi.fn() } + }) +} + +beforeEach(() => { + execFileMock.mockReset() +}) + +afterEach(() => { + _resetGhRateLimitBreaker() +}) + +describe('ghExecFileAsync rate-limit breaker', () => { + it('spawns once for a primary 403, then short-circuits same-bucket calls', async () => { + mockGhFailure(PRIMARY_RATE_LIMIT_STDERR) + await expect( + ghExecFileAsync(['api', '--cache', '120s', 'search/issues?q=repo:a/b&per_page=1']) + ).rejects.toThrow('rate limit') + expect(execFileMock).toHaveBeenCalledTimes(1) + + // The 90-repo storm case: every further search-bucket call must fail fast + // without a subprocess. + await expect( + ghExecFileAsync(['api', '--cache', '120s', 'search/issues?q=repo:c/d&per_page=1']) + ).rejects.toMatchObject({ ghRateLimitBlocked: true }) + expect(execFileMock).toHaveBeenCalledTimes(1) + }) + + it('keeps other buckets working while one bucket is blocked', async () => { + mockGhFailure(PRIMARY_RATE_LIMIT_STDERR) + await expect(ghExecFileAsync(['api', 'search/issues?q=x'])).rejects.toThrow() + mockGhSuccess('[]') + await expect(ghExecFileAsync(['pr', 'list', '--limit', '36'])).resolves.toEqual({ + stdout: '[]', + stderr: '' + }) + expect(execFileMock).toHaveBeenCalledTimes(2) + }) + + it('never blocks the exempt rate_limit probe', async () => { + mockGhFailure(PRIMARY_RATE_LIMIT_STDERR) + await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).rejects.toThrow() + mockGhSuccess('{"resources":{}}') + await expect(ghExecFileAsync(['api', 'rate_limit'])).resolves.toMatchObject({ + stdout: '{"resources":{}}' + }) + expect(execFileMock).toHaveBeenCalledTimes(2) + }) + + it('does not trip the breaker on secondary rate limits', async () => { + mockGhFailure('gh: You have exceeded a secondary rate limit. (HTTP 403)') + await expect( + ghExecFileAsync(['api', 'repos/a/b/pulls'], { idempotent: false }) + ).rejects.toThrow() + mockGhSuccess('[]') + await expect(ghExecFileAsync(['api', 'repos/a/b/pulls'])).resolves.toEqual({ + stdout: '[]', + stderr: '' + }) + }) +}) diff --git a/src/main/git/runner-wsl-gh-fallback.test.ts b/src/main/git/runner-wsl-gh-fallback.test.ts index 4bafa9f19..3aae18243 100644 --- a/src/main/git/runner-wsl-gh-fallback.test.ts +++ b/src/main/git/runner-wsl-gh-fallback.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: WSL fallback, retry safety, and glab parity share mocks. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type * as WslModule from '../wsl' diff --git a/src/main/git/runner.ts b/src/main/git/runner.ts index ec0d1d7b8..c90098453 100644 --- a/src/main/git/runner.ts +++ b/src/main/git/runner.ts @@ -19,6 +19,15 @@ import { } from 'node:child_process' import { StringDecoder } from 'node:string_decoder' import { withGitSpan } from '../observability/instrumentation' +import { recordSubprocessSpawn } from '../diagnostics/main-thread-churn-probe' +import { + classifyGhRateLimitBucket, + createGhRateLimitBlockedError, + getGhRateLimitBlockedUntilMs, + isGhPrimaryRateLimitStderr, + isGhRateLimitProbe, + notifyGhPrimaryRateLimit +} from './gh-rate-limit-breaker' import { getDefaultWslDistro, parseWslPath, toWindowsWslPath, type WslPathInfo } from '../wsl' import { getSpawnArgsForWindows, isWindowsBatchScript, resolveWindowsCommand } from '../win32-utils' import { @@ -381,6 +390,7 @@ function execFileCapture( } try { + const spawnStartedAt = performance.now() child = execFile( command, args, @@ -399,6 +409,7 @@ function execFileCapture( finish(error, stdout, stderr) } ) + recordSubprocessSpawn(command, args, performance.now() - spawnStartedAt) } catch (error) { finish(error instanceof Error ? error : new Error(String(error))) return @@ -441,12 +452,14 @@ async function spawnCommandCapture( let stderr = '' let stdoutBytes = 0 let stderrBytes = 0 + const spawnStartedAt = performance.now() const child = spawn(spawnCmd, spawnArgs, { cwd: options.cwd, env: options.env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) + recordSubprocessSpawn(spawnCmd, spawnArgs, performance.now() - spawnStartedAt) let timer: NodeJS.Timeout | null = null const onAbort = (): void => { killSpawnedCommandTree(child) @@ -1033,12 +1046,19 @@ export function gitExecFileSync( } ): string { const resolved = resolveCommand('git', args, options.cwd) - return execFileSync(resolved.binary, resolved.args, { - cwd: resolved.cwd, - encoding: options.encoding ?? 'utf-8', - stdio: options.stdio ?? ['pipe', 'pipe', 'pipe'], - timeout: options.timeout ?? GIT_EXEC_SYNC_TIMEOUT_MS - }) as string + const spawnStartedAt = performance.now() + try { + return execFileSync(resolved.binary, resolved.args, { + cwd: resolved.cwd, + encoding: options.encoding ?? 'utf-8', + stdio: options.stdio ?? ['pipe', 'pipe', 'pipe'], + timeout: options.timeout ?? GIT_EXEC_SYNC_TIMEOUT_MS + }) as string + } finally { + // Sync exec holds the main thread for its whole duration, so the entire + // call is main-thread block time — the cost issue #7576 flags. + recordSubprocessSpawn(resolved.binary, resolved.args, performance.now() - spawnStartedAt) + } } /** @@ -1053,10 +1073,13 @@ export function gitSpawn( const resolved = resolveCommand('git', args, options.cwd, wslDistro, { useWslLoginShell: Boolean(wslDistro) }) - return spawn(resolved.binary, resolved.args, { + const spawnStartedAt = performance.now() + const child = spawn(resolved.binary, resolved.args, { ...spawnOptions, cwd: resolved.cwd }) + recordSubprocessSpawn(resolved.binary, resolved.args, performance.now() - spawnStartedAt) + return child } // ─── gh CLI runners ───────────────────────────────────────────────── @@ -1356,6 +1379,16 @@ export async function ghExecFileAsync( args: string[], options: GhExecOptions = {} ): Promise<{ stdout: string; stderr: string }> { + // Why: while a bucket's primary rate limit is exhausted, every spawn would + // return the same 403 — fail fast without paying the subprocess cost. The + // rate_limit probe itself is exempt so the breaker can learn the reset time. + const rateLimitBucket = classifyGhRateLimitBucket(args) + if (!isGhRateLimitProbe(args)) { + const blockedUntilMs = getGhRateLimitBlockedUntilMs(rateLimitBucket) + if (blockedUntilMs !== null) { + throw createGhRateLimitBlockedError(rateLimitBucket, blockedUntilMs) + } + } let resolved = resolveCommand('gh', args, options.cwd, options.wslDistro) let lastError: unknown let attemptedHostFallback = false @@ -1375,6 +1408,9 @@ export async function ghExecFileAsync( } catch (err) { lastError = err const { stderr } = extractExecError(err) + if (isGhPrimaryRateLimitStderr(stderr)) { + notifyGhPrimaryRateLimit(rateLimitBucket) + } if ( process.platform === 'win32' && !attemptedDefaultWslFallback && @@ -1554,10 +1590,13 @@ export function wslAwareSpawn( const resolved = resolveCommand(command, args, options.cwd, wslDistro, { useWslLoginShell }) - return spawn(resolved.binary, resolved.args, { + const spawnStartedAt = performance.now() + const child = spawn(resolved.binary, resolved.args, { ...spawnOptions, cwd: resolved.cwd }) + recordSubprocessSpawn(resolved.binary, resolved.args, performance.now() - spawnStartedAt) + return child } // ─── Path translation helpers ─────────────────────────────────────── diff --git a/src/main/git/status-upstream-probe-churn.test.ts b/src/main/git/status-upstream-probe-churn.test.ts index f5e8f06c3..49f6913e0 100644 --- a/src/main/git/status-upstream-probe-churn.test.ts +++ b/src/main/git/status-upstream-probe-churn.test.ts @@ -186,6 +186,90 @@ describe('getStatus missing-upstream polling churn', () => { expect(sameNameOriginProbeCalls).toHaveLength(1) }) + // The pushed-but-untracked branch shape (issue #7576): the effective + // upstream resolves to the same-name origin ref, and before the resolved-name + // cache each 3s poll re-ran the whole resolution chain (~5 spawns/tick). + function mockResolvedSameNameOrigin(revList: { failOnCall?: number } = {}): void { + let revListCalls = 0 + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args.includes('status')) { + return { + stdout: '# branch.oid abcdef1234567890\n# branch.head bench/feature\n' + } + } + if (args[0] === 'symbolic-ref' && args.includes('HEAD')) { + return { stdout: 'bench/feature\n' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + throw new Error("fatal: no upstream configured for branch 'bench/feature'") + } + if (isConfigListSnapshotCommand(args)) { + return emptyGitConfigSnapshot() + } + if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/bench/feature')) { + return { stdout: 'abcdef1234567890\n' } + } + if (args[0] === 'rev-list') { + revListCalls++ + if (revList.failOnCall === revListCalls) { + throw new Error('fatal: bad revision') + } + return { stdout: '1\t0\n' } + } + throw new Error(`unexpected git command: ${args.join(' ')}`) + }) + } + + function countCalls(predicate: (args: string[]) => boolean): number { + return gitExecFileAsyncMock.mock.calls.filter((call) => predicate(getGitArgs(call))).length + } + + it('revalidates a resolved same-name upstream with a single rev-list per poll', async () => { + mockResolvedSameNameOrigin() + + await getStatus('/repo') + await getStatus('/repo') + await getStatus('/repo') + + // Resolution chain ran once; the two later polls paid one rev-list each. + expect(countCalls((args) => args[0] === 'symbolic-ref')).toBe(1) + expect(countCalls((args) => args[0] === 'rev-parse' && args.includes('HEAD@{u}'))).toBe(1) + expect(countCalls(isConfigListSnapshotCommand)).toBe(1) + expect( + countCalls( + (args) => args[0] === 'rev-parse' && args.includes('refs/remotes/origin/bench/feature') + ) + ).toBe(1) + expect(countCalls((args) => args[0] === 'rev-list')).toBe(3) + }) + + it('re-resolves the upstream after the resolved-name cache TTL lapses', async () => { + vi.useFakeTimers() + vi.setSystemTime(0) + mockResolvedSameNameOrigin() + + await getStatus('/repo') + vi.setSystemTime(61_000) + await getStatus('/repo') + + expect(countCalls((args) => args[0] === 'symbolic-ref')).toBe(2) + expect(countCalls((args) => args[0] === 'rev-list')).toBe(2) + }) + + it('falls back to a full re-resolve when the cached upstream rev-list fails', async () => { + // Second rev-list (the first revalidation attempt) fails, e.g. deleted ref. + mockResolvedSameNameOrigin({ failOnCall: 2 }) + + await getStatus('/repo') + const status = await getStatus('/repo') + + // Full chain ran twice: initial resolve + the fallback after the failure. + expect(countCalls((args) => args[0] === 'symbolic-ref')).toBe(2) + // rev-list: initial + failed revalidate + fallback's own rev-list. + expect(countCalls((args) => args[0] === 'rev-list')).toBe(3) + expect(status.upstreamStatus?.hasUpstream).toBe(true) + }) + it('does not cache a positive configured push target signal', async () => { gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { if (args.includes('status')) { diff --git a/src/main/git/status.ts b/src/main/git/status.ts index e7b0d95b2..862c8c9b7 100644 --- a/src/main/git/status.ts +++ b/src/main/git/status.ts @@ -19,6 +19,7 @@ import type { import type { CommitMessageDraftContext } from '../../shared/commit-message-generation' import { getEffectiveGitUpstreamStatus, + getGitUpstreamStatusForUpstreamName, splitRemoteBranchName } from '../../shared/git-effective-upstream' import { createGitConfigSnapshotRunner } from '../../shared/git-config-snapshot-runner' @@ -66,6 +67,21 @@ const SUBMODULE_PATHS_CACHE_TTL_MS = 5_000 type SubmodulePathsCacheEntry = { paths: string[]; expiresAt: number } const submodulePathsCache = new Map() +// Why: the effective-upstream resolution chain (symbolic-ref + rev-parse ×2-3 +// + config snapshot) costs 4-5 subprocess spawns and only changes when branch +// or git config changes. Ahead/behind is a pure function of the two rev-list +// endpoints, so a recently-resolved name can be revalidated with one rev-list +// spawn per poll tick; a failed rev-list (deleted ref) falls back to a full +// re-resolve. Issue #7576: this path dominated idle main-process spawn churn. +const RESOLVED_UPSTREAM_NAME_CACHE_TTL_MS = 60_000 + +type ResolvedUpstreamNameCacheEntry = { + upstreamName: string + expiresAt: number +} + +const resolvedUpstreamNameCache = new Map() + const effectiveUpstreamStatusCache = new Map() const effectiveUpstreamStatusInFlight = new Map>() const retiredEffectiveUpstreamStatusInFlight = new Map>() @@ -80,6 +96,7 @@ function clearGitReadInvalidationState(): void { gitDiffReadDedupe.clear() statusReadsInFlight.clear() submodulePathsCache.clear() + resolvedUpstreamNameCache.clear() } export function clearSubmodulePathsCacheForTests(): void { @@ -508,6 +525,7 @@ export function clearEffectiveUpstreamNegativeStatusCache(identity: { retireEffectiveUpstreamStatusProbe(cacheKey) effectiveUpstreamStatusCache.delete(cacheKey) effectiveUpstreamStatusInFlight.delete(cacheKey) + resolvedUpstreamNameCache.delete(cacheKey) effectiveUpstreamStatusWriteGeneration.set( cacheKey, (effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? 0) + 1 @@ -626,7 +644,13 @@ async function readOrProbeEffectiveUpstreamStatus( // Why: source-control mount and root git refresh can overlap during startup. // Coalesce the richer upstream probe so a stable missing ref fails once. const writeGeneration = effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? 0 - const probe = probeEffectiveUpstreamStatus(worktreePath, branchName, options).then((result) => { + const probe = probeOrRevalidateEffectiveUpstreamStatus( + cacheKey, + worktreePath, + branchName, + options, + bypassCache + ).then((result) => { rememberEffectiveUpstreamStatus( cacheKey, result.status, @@ -649,6 +673,46 @@ async function readOrProbeEffectiveUpstreamStatus( } } +async function probeOrRevalidateEffectiveUpstreamStatus( + cacheKey: string, + worktreePath: string, + branchName: string, + options: GitRuntimeOptions = {}, + bypassCache = false +): Promise<{ status: GitUpstreamStatus; probedSameNameOriginRef: boolean }> { + const now = Date.now() + const cached = resolvedUpstreamNameCache.get(cacheKey) + if (cached && (bypassCache || cached.expiresAt <= now)) { + resolvedUpstreamNameCache.delete(cacheKey) + } else if (cached) { + try { + const status = await getGitUpstreamStatusForUpstreamName( + (args) => gitExecFileAsync(args, gitOptionsForWorktree(worktreePath, options)), + cached.upstreamName + ) + return { status, probedSameNameOriginRef: false } + } catch { + // Ref deleted or repo state changed — fall through to a full re-resolve. + resolvedUpstreamNameCache.delete(cacheKey) + } + } + const result = await probeEffectiveUpstreamStatus(worktreePath, branchName, options) + if (result.status.hasUpstream && result.status.upstreamName) { + resolvedUpstreamNameCache.set(cacheKey, { + upstreamName: result.status.upstreamName, + expiresAt: Date.now() + RESOLVED_UPSTREAM_NAME_CACHE_TTL_MS + }) + while (resolvedUpstreamNameCache.size > MAX_EFFECTIVE_UPSTREAM_NEGATIVE_CACHE_ENTRIES) { + const oldest = resolvedUpstreamNameCache.keys().next() + if (oldest.done) { + break + } + resolvedUpstreamNameCache.delete(oldest.value) + } + } + return result +} + async function probeEffectiveUpstreamStatus( worktreePath: string, branchName: string, diff --git a/src/main/github/client-create-pr.test.ts b/src/main/github/client-create-pr.test.ts index d46f461b9..6c64e4b80 100644 --- a/src/main/github/client-create-pr.test.ts +++ b/src/main/github/client-create-pr.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: create-PR tests share gh/SSH mocks across - template, CLI, and error-path cases; keeping them together prevents drift. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { readFile } from 'node:fs/promises' diff --git a/src/main/github/client-issue-source.test.ts b/src/main/github/client-issue-source.test.ts index 2b4a039b3..531234322 100644 --- a/src/main/github/client-issue-source.test.ts +++ b/src/main/github/client-issue-source.test.ts @@ -1,7 +1,3 @@ -/* eslint-disable max-lines -- Why: the issue-source test suite covers the -heuristic split (#1076), the partial-failure envelope (feature 1), and the -three-state preference matrix (feature 2) as one surface so a regression in -any of them blocks the same merge gate. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as GhUtils from './gh-utils' @@ -47,7 +43,8 @@ vi.mock('./gh-utils', async () => { vi.mock('./rate-limit', () => ({ rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: noteRateLimitSpendMock + noteRateLimitSpend: noteRateLimitSpendMock, + getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })) })) import { countWorkItems, getWorkItem, listWorkItems, _resetOwnerRepoCache } from './client' diff --git a/src/main/github/client-work-items.test.ts b/src/main/github/client-work-items.test.ts index e6ce6005c..66e728908 100644 --- a/src/main/github/client-work-items.test.ts +++ b/src/main/github/client-work-items.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: work-items coverage stays in one file so -the fan-out mock plumbing (issue + PR gh calls, allSettled handling) does -not drift across split files. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { @@ -66,7 +63,8 @@ vi.mock('../git/runner', () => ({ vi.mock('./rate-limit', () => ({ rateLimitGuard: rateLimitGuardMock, - noteRateLimitSpend: noteRateLimitSpendMock + noteRateLimitSpend: noteRateLimitSpendMock, + getRateLimit: vi.fn(async () => ({ ok: false, error: 'not probed in tests' })) })) import { @@ -75,6 +73,7 @@ import { _resetMergeQueueCacheForTests, _resetOwnerRepoCache } from './client' +import { _resetGhCwdRepoNegativeCache } from './gh-cwd-repo-negative-cache' import { GITHUB_WORK_ITEMS_QUERY_MAX_BYTES } from '../../shared/github-work-items-query-bounds' describe('listWorkItems', () => { @@ -102,6 +101,25 @@ describe('listWorkItems', () => { getOwnerRepoForRemoteMock.mockResolvedValue(null) _resetOwnerRepoCache() _resetMergeQueueCacheForTests() + _resetGhCwdRepoNegativeCache() + }) + + it('stops re-spawning gh for a repo whose cwd resolution already failed with no remotes', async () => { + getIssueOwnerRepoMock.mockResolvedValue(null) + getOwnerRepoMock.mockResolvedValue(null) + ghExecFileAsyncMock.mockRejectedValue( + Object.assign(new Error('Command failed: gh pr list\nno git remotes found'), { + stderr: 'no git remotes found' + }) + ) + + await expect(listWorkItems('/no-remote-repo', 36)).rejects.toThrow('no git remotes found') + // The first refresh pays the two cwd-fallback spawns (issue + pr list). + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) + + await expect(listWorkItems('/no-remote-repo', 36)).rejects.toThrow('no git remotes found') + // The second refresh is served from the negative cache — zero new spawns. + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(2) }) it('runs both issue and PR GitHub searches for a mixed query and merges the results by recency', async () => { @@ -540,6 +558,22 @@ describe('listWorkItems', () => { expect(apiPath).not.toContain('-is:merged') }) + it('returns zero without spawning gh when the search bucket is rate-limit blocked', async () => { + getIssueOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + rateLimitGuardMock.mockReturnValue({ + blocked: true, + remaining: 0, + limit: 30, + resetAt: Math.floor(Date.now() / 1000) + 60 + } as unknown as { blocked: boolean }) + + await expect(countWorkItems('/repo-root', 'is:issue is:open')).resolves.toBe(0) + + expect(rateLimitGuardMock).toHaveBeenCalledWith('search') + expect(ghExecFileAsyncMock).not.toHaveBeenCalled() + }) + it('returns zero for oversized count queries before resolving repo sources', async () => { const secret = 'main-github-work-items-secret' const oversizedQuery = secret + 'x'.repeat(GITHUB_WORK_ITEMS_QUERY_MAX_BYTES) diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index eb7943257..2138ba0aa 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -801,7 +801,7 @@ describe('getPRForBranch', () => { expect(ghExecFileAsyncMock).toHaveBeenNthCalledWith( 3, - ['api', 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100'], + ['api', 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1'], expect.anything() ) expect(pr).toMatchObject({ @@ -929,6 +929,209 @@ describe('getPRForBranch', () => { }) }) + function mockMergedLinkedPRLookup(prNumber = 7447) { + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ + candidates: [{ owner: 'acme', repo: 'widgets' }], + headRepo: { owner: 'acme', repo: 'widgets' } + }) + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: prNumber, + title: 'Merged linked PR', + state: 'MERGED', + url: `https://github.com/acme/widgets/pull/${prNumber}`, + statusCheckRollup: [], + updatedAt: '2026-07-03T21:27:36Z', + isDraft: false, + mergeable: 'MERGEABLE', + baseRefName: 'main', + headRefName: 'old-linked-branch', + baseRefOid: 'base-oid', + headRefOid: 'aaaa1111aaaa1111' + }) + }) + } + + it('stamps confirmedContainedHeadOid for a linked merged PR when HEAD is its commit', async () => { + mockMergedLinkedPRLookup() + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify([{ number: 7447 }]) + }) + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ + kind: 'found', + pr: { + number: 7447, + state: 'merged', + confirmedContainedHeadOid: 'bbbb2222bbbb2222' + } + }) + expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe( + undefined + ) + }) + + it('stamps headDivergedFromMergedPRAtOid for a linked merged PR with a definite miss', async () => { + mockMergedLinkedPRLookup() + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify([{ number: 42 }]) + }) + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ + kind: 'found', + pr: { + number: 7447, + state: 'merged', + headDivergedFromMergedPRAtOid: 'bbbb2222bbbb2222' + } + }) + }) + + it('stamps linked merged divergence when a later membership page proves absence', async () => { + mockMergedLinkedPRLookup() + // Page 1 is full and omits the linked PR (truncated), but page 2 is short and + // still omits it — that pair definitively proves the head is not contained. + const fullPage = Array.from({ length: 100 }, (_, index) => ({ number: 1000 + index })) + ghExecFileAsyncMock + .mockResolvedValueOnce({ stdout: JSON.stringify(fullPage) }) + .mockResolvedValueOnce({ stdout: JSON.stringify([{ number: 2000 }]) }) + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ + kind: 'found', + pr: { number: 7447, state: 'merged', headDivergedFromMergedPRAtOid: 'bbbb2222bbbb2222' } + }) + }) + + it('leaves linked merged divergence unset when membership pages stay full to the cap', async () => { + mockMergedLinkedPRLookup() + // Every page up to the cap is full and omits the linked PR, so absence can + // never be proven — the probe must stay unknown rather than clear the link. + const fullPage = Array.from({ length: 100 }, (_, index) => ({ number: 1000 + index })) + for (let page = 0; page < 5; page += 1) { + ghExecFileAsyncMock.mockResolvedValueOnce({ stdout: JSON.stringify(fullPage) }) + } + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } }) + expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe( + undefined + ) + }) + + it('stamps linked merged divergence via the PR url when no repo candidates resolve', async () => { + // Fallback path: no resolved candidates, so `gh pr view` returns the PR with + // dataRepo=null. The membership probe must still run against the repo derived + // from the PR's own URL so a diverged merged linked PR can clear. + resolvePRRepositoryCandidatesMock.mockResolvedValueOnce({ candidates: [], headRepo: null }) + ghExecFileAsyncMock + .mockResolvedValueOnce({ + stdout: JSON.stringify({ + number: 7447, + title: 'Merged linked PR', + state: 'MERGED', + url: 'https://github.com/acme/widgets/pull/7447', + statusCheckRollup: [], + updatedAt: '2026-07-03T21:27:36Z', + isDraft: false, + mergeable: 'MERGEABLE', + baseRefName: 'main', + headRefName: 'old-linked-branch', + baseRefOid: 'base-oid', + headRefOid: 'aaaa1111aaaa1111' + }) + }) + .mockResolvedValueOnce({ stdout: JSON.stringify([{ number: 2000 }]) }) + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ + kind: 'found', + pr: { number: 7447, state: 'merged', headDivergedFromMergedPRAtOid: 'bbbb2222bbbb2222' } + }) + expect(ghExecFileAsyncMock).toHaveBeenCalledWith( + ['api', 'repos/acme/widgets/commits/bbbb2222bbbb2222/pulls?per_page=100&page=1'], + expect.anything() + ) + }) + + it('leaves linked merged divergence unset when the membership probe is rate-limited', async () => { + mockMergedLinkedPRLookup() + rateLimitGuardMock.mockImplementation((bucket?: string) => + bucket === 'core' + ? { blocked: true, remaining: 0, limit: 5000, resetAt: 0 } + : { blocked: false } + ) + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } }) + expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe( + undefined + ) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) + + it('leaves linked merged divergence unset when the membership probe throws', async () => { + mockMergedLinkedPRLookup() + ghExecFileAsyncMock.mockRejectedValueOnce(new Error('HTTP 422: No commit found')) + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } }) + expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe( + undefined + ) + }) + + it('leaves linked merged divergence unset when the membership probe returns a non-array payload', async () => { + mockMergedLinkedPRLookup() + ghExecFileAsyncMock.mockResolvedValueOnce({ + stdout: JSON.stringify({ message: 'Server Error' }) + }) + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null, { + currentHeadOid: 'bbbb2222bbbb2222' + }) + + expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } }) + expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe( + undefined + ) + }) + + it('leaves linked merged divergence unset without a current head oid', async () => { + mockMergedLinkedPRLookup() + + const outcome = await getPRForBranchOutcome('/repo-root', 'new-work', 7447, null, null) + + expect(outcome).toMatchObject({ kind: 'found', pr: { number: 7447, state: 'merged' } }) + expect(outcome.kind === 'found' ? outcome.pr.headDivergedFromMergedPRAtOid : undefined).toBe( + undefined + ) + expect(ghExecFileAsyncMock).toHaveBeenCalledTimes(1) + }) + it('prefers branch lookup over a fallback PR number', async () => { getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) ghExecFileAsyncMock diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 0c86d547e..3a308a3ad 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -62,7 +62,10 @@ import { type LocalGitExecOptions, type OwnerRepo } from './gh-utils' -import { isCommitPartOfMergedPR } from './merged-pr-commit-membership' +import { + isCommitPartOfMergedPR, + type MergedPRCommitMembership +} from './merged-pr-commit-membership' import { getSshGitProvider } from '../providers/ssh-git-dispatch' import { hasHostedReviewLocalGitOptions, @@ -70,6 +73,12 @@ import { type HostedReviewExecutionOptions } from '../source-control/hosted-review-git-options' import { readLocalGitConfigSignature } from './local-git-config-signature' +import { + getRememberedGhCwdResolutionFailure, + isGhCwdRepoResolutionFailure, + rememberGhCwdResolutionFailure +} from './gh-cwd-repo-negative-cache' +import type { GitHubRepoContext } from './github-repository-identity' export { _resetOwnerRepoCache } from './gh-utils' export { getIssue, @@ -1002,6 +1011,32 @@ async function resolvePrWorkItemSource( return { source, originCandidate, upstreamCandidate } } +/** + * gh exec for calls that rely on gh's own cwd→repo resolution (no explicit + * owner/repo). Serves a remembered deterministic resolution failure without + * spawning, so a remote-less repo costs one gh spawn per config change/TTL + * instead of two per Tasks refresh. + */ +async function ghCwdResolvedExec( + context: GitHubRepoContext, + args: string[], + ghOptions: GhExecOptions +): Promise<{ stdout: string; stderr: string }> { + const remembered = await getRememberedGhCwdResolutionFailure(context) + if (remembered !== null) { + throw new Error(remembered) + } + try { + return await ghExecFileAsync(args, ghOptions) + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + if (isGhCwdRepoResolutionFailure(message)) { + await rememberGhCwdResolutionFailure(context, message) + } + throw err + } +} + async function listRecentWorkItems( repoPath: string, issueOwnerRepo: OwnerRepo | null, @@ -1011,7 +1046,8 @@ async function listRecentWorkItems( noCache?: boolean, localGitOptions: LocalGitExecOptions = {} ): Promise { - const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)) + const repoContext = githubRepoContext(repoPath, connectionId, localGitOptions) + const ghOptions = ghRepoExecOptions(repoContext) const requiresExplicitRepo = Boolean(connectionId) const restCacheArgs = noCache ? [] : ['--cache', '120s'] assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo }) @@ -1031,7 +1067,8 @@ async function listRecentWorkItems( ) : requiresExplicitRepo ? Promise.resolve({ stdout: '[]' }) - : ghExecFileAsync( + : ghCwdResolvedExec( + repoContext, [ 'issue', 'list', @@ -1055,7 +1092,8 @@ async function listRecentWorkItems( ) : requiresExplicitRepo ? Promise.resolve({ stdout: '[]' }) - : ghExecFileAsync( + : ghCwdResolvedExec( + repoContext, [ 'pr', 'list', @@ -1127,7 +1165,8 @@ async function listRecentWorkItems( // effectively unusable for the feature — reject-all matches reality. If // non-GitHub remotes ever grow source metadata, revisit this symmetry. const [issuesResult, prsResult] = await Promise.all([ - ghExecFileAsync( + ghCwdResolvedExec( + repoContext, [ 'issue', 'list', @@ -1140,7 +1179,8 @@ async function listRecentWorkItems( ], ghOptions ), - ghExecFileAsync( + ghCwdResolvedExec( + repoContext, [ 'pr', 'list', @@ -1177,7 +1217,8 @@ async function listQueriedWorkItems( connectionId?: string | null, localGitOptions: LocalGitExecOptions = {} ): Promise { - const ghOptions = ghRepoExecOptions(githubRepoContext(repoPath, connectionId, localGitOptions)) + const repoContext = githubRepoContext(repoPath, connectionId, localGitOptions) + const ghOptions = ghRepoExecOptions(repoContext) const requiresExplicitRepo = Boolean(connectionId) assertSshRepoHasResolvedGitHubSource({ connectionId, issueOwnerRepo, prOwnerRepo }) const hasPrOnlyFilter = @@ -1206,7 +1247,9 @@ async function listQueriedWorkItems( before }) try { - const { stdout } = await ghExecFileAsync(args, ghOptions) + const { stdout } = issueOwnerRepo + ? await ghExecFileAsync(args, ghOptions) + : await ghCwdResolvedExec(repoContext, args, ghOptions) return { items: (JSON.parse(stdout) as Record[]).map(mapIssueWorkItem) } @@ -1231,7 +1274,9 @@ async function listQueriedWorkItems( before }) try { - const { stdout } = await ghExecFileAsync(args, ghOptions) + const { stdout } = prOwnerRepo + ? await ghExecFileAsync(args, ghOptions) + : await ghCwdResolvedExec(repoContext, args, ghOptions) const mapped = (JSON.parse(stdout) as Record[]).map((item) => mapPullRequestWorkItem(item, prOwnerRepo) ) @@ -1395,6 +1440,9 @@ async function countWorkItemsForQuery( ], ghOptions ) + // Why: over-counts gh cache hits, which is the safe direction — the search + // bucket is only 30/min and the next probe corrects the estimate. + noteRateLimitSpend('search') return Number.parseInt(stdout.trim(), 10) || 0 } @@ -1450,6 +1498,15 @@ export async function countWorkItems( const parsedQuery = trimmedQuery ? parseTaskQuery(trimmedQuery) : null const effectiveQuery = parsedQuery ?? defaultOpenWorkItemQuery() + // Why: counts are decorative (pagination totals). The search bucket is only + // 30/min, so a multi-repo Tasks page must stop counting when the budget is + // gone instead of converting the remaining repos into 403 spawns. getRateLimit + // is 30s-cached and single-flight, so priming here is one spawn per window. + await getRateLimit() + if (rateLimitGuard('search').blocked) { + return 0 + } + await acquire() try { if (sameOwnerRepo(issueOwnerRepo, prOwnerRepo)) { @@ -2771,6 +2828,15 @@ export async function getPRForBranch( return outcome.kind === 'found' ? outcome.pr : null } +// Why: the exact-linked fallback (`gh pr view` with no resolved repo candidates) +// returns dataRepo=null, which would leave the merged-PR membership probe unable +// to run. Derive the PR's own repo from its web URL so a diverged merged linked +// PR can still be confirmed and cleared. Host-agnostic to cover GitHub Enterprise. +function ownerRepoFromPullRequestUrl(url: string): OwnerRepo | null { + const match = url.match(/^https?:\/\/[^/\s]+\/([^/\s]+)\/([^/\s]+)\/pull\/\d+/) + return match ? { owner: match[1], repo: match[2] } : null +} + export async function getPRForBranchOutcome( repoPath: string, branch: string, @@ -2810,24 +2876,49 @@ export async function getPRForBranchOutcome( ? options.currentHeadOid.trim() : null let confirmedContainedHeadOid: string | null = null + let headDivergedFromMergedPRAtOid: string | null = null const mergedPRContainsHead = async ( candidate: PullRequestLookupData, candidateRepo: OwnerRepo | null, headOid: string | null - ): Promise => { + ): Promise => { if (!candidateRepo || !headOid) { - return false + return 'unknown' } - const contained = await isCommitPartOfMergedPR({ + const membership = await isCommitPartOfMergedPR({ ownerRepo: candidateRepo, prNumber: candidate.number, commitOid: headOid, ghOptions }) - if (contained) { + if (membership === 'contained') { confirmedContainedHeadOid = headOid } - return contained + return membership + } + const recordLinkedMergedPRDivergence = async ( + candidate: PullRequestLookupData | null, + candidateRepo: OwnerRepo | null + ): Promise => { + if ( + typeof linkedPRNumber !== 'number' || + !candidate || + mapPRState(candidate.state, candidate.isDraft) !== 'merged' || + explicitCurrentHeadOid === null || + candidate.headRefOid === explicitCurrentHeadOid + ) { + return + } + const membership = await mergedPRContainsHead( + candidate, + candidateRepo ?? ownerRepoFromPullRequestUrl(candidate.url), + explicitCurrentHeadOid + ) + if (membership === 'not-contained') { + // explicitCurrentHeadOid is non-null here (guarded above); record the + // exact head so consumers only clear the worktree that actually diverged. + headDivergedFromMergedPRAtOid = explicitCurrentHeadOid + } } const hideMergedImplicitPR = async ( candidate: PullRequestLookupData | null, @@ -2850,11 +2941,10 @@ export async function getPRForBranchOutcome( // merges, web-committed suggestions). A head that is one of the PR's own // commits is the same line of work, not a reused branch name — keep the // merged PR visible instead of offering "create a pull request". - return !(await mergedPRContainsHead( - candidate, - candidateRepo, - currentHeadOidForMergedImplicit - )) + return ( + (await mergedPRContainsHead(candidate, candidateRepo, currentHeadOidForMergedImplicit)) !== + 'contained' + ) } if (typeof linkedPRNumber === 'number') { @@ -2942,6 +3032,7 @@ export async function getPRForBranchOutcome( } return { kind: 'no-pr', fetchedAt: Date.now() } } + await recordLinkedMergedPRDivergence(data, dataRepo) const fallbackConfirmedMergedBranch = typeof fallbackPRNumber === 'number' && mergedBranchLookupNumber === fallbackPRNumber && @@ -2949,7 +3040,7 @@ export async function getPRForBranchOutcome( const explicitHeadHidesMergedImplicitPR = explicitCurrentHeadOid !== null && shouldHideMergedImplicitPR(data, linkedPRNumber, explicitCurrentHeadOid) && - !(await mergedPRContainsHead(data, dataRepo, explicitCurrentHeadOid)) + (await mergedPRContainsHead(data, dataRepo, explicitCurrentHeadOid)) !== 'contained' // Why no lazy-HEAD re-check on preservation: fallback numbers come from // callers that already gated them on head equality or confirmed // containment; re-hiding against the main-repo HEAD would blank @@ -3003,6 +3094,7 @@ export async function getPRForBranchOutcome( ...(data.mergeStateStatus !== undefined ? { mergeStateStatus: data.mergeStateStatus } : {}), headSha: data.headRefOid, ...(confirmedContainedHeadOid ? { confirmedContainedHeadOid } : {}), + ...(headDivergedFromMergedPRAtOid ? { headDivergedFromMergedPRAtOid } : {}), ...(data.baseRefName ? { baseRefName: data.baseRefName } : {}), prRepo: dataRepo ?? undefined, headRepo: dataHeadRepo ?? undefined, diff --git a/src/main/github/gh-cwd-repo-negative-cache.test.ts b/src/main/github/gh-cwd-repo-negative-cache.test.ts new file mode 100644 index 000000000..240711143 --- /dev/null +++ b/src/main/github/gh-cwd-repo-negative-cache.test.ts @@ -0,0 +1,65 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' + +const { readLocalGitConfigSignatureMock } = vi.hoisted(() => ({ + readLocalGitConfigSignatureMock: vi.fn() +})) + +vi.mock('./local-git-config-signature', () => ({ + readLocalGitConfigSignature: readLocalGitConfigSignatureMock +})) + +import { + _resetGhCwdRepoNegativeCache, + getRememberedGhCwdResolutionFailure, + isGhCwdRepoResolutionFailure, + rememberGhCwdResolutionFailure +} from './gh-cwd-repo-negative-cache' + +const context = { repoPath: '/repo', connectionId: null } + +afterEach(() => { + _resetGhCwdRepoNegativeCache() + readLocalGitConfigSignatureMock.mockReset() +}) + +describe('isGhCwdRepoResolutionFailure', () => { + it('matches gh cwd-resolution failures only', () => { + expect(isGhCwdRepoResolutionFailure('Command failed: gh\nno git remotes found')).toBe(true) + expect( + isGhCwdRepoResolutionFailure( + 'none of the git remotes configured for this repository point to a known GitHub host' + ) + ).toBe(true) + expect(isGhCwdRepoResolutionFailure('gh: API rate limit exceeded (HTTP 403)')).toBe(false) + expect(isGhCwdRepoResolutionFailure('gh: Not Found (HTTP 404)')).toBe(false) + }) +}) + +describe('remembered failures', () => { + it('serves the remembered failure while the config signature is unchanged', async () => { + readLocalGitConfigSignatureMock.mockResolvedValue('sig-1') + await rememberGhCwdResolutionFailure(context, 'no git remotes found') + await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBe('no git remotes found') + }) + + it('invalidates when the git config signature changes (remote added)', async () => { + readLocalGitConfigSignatureMock.mockResolvedValueOnce('sig-1') + await rememberGhCwdResolutionFailure(context, 'no git remotes found') + readLocalGitConfigSignatureMock.mockResolvedValue('sig-2') + await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBeNull() + // The stale entry is gone, not just skipped. + readLocalGitConfigSignatureMock.mockResolvedValue('sig-1') + await expect(getRememberedGhCwdResolutionFailure(context)).resolves.toBeNull() + }) + + it('separates repos and runtimes by cache key', async () => { + readLocalGitConfigSignatureMock.mockResolvedValue('sig') + await rememberGhCwdResolutionFailure(context, 'no git remotes found') + await expect( + getRememberedGhCwdResolutionFailure({ repoPath: '/other-repo', connectionId: null }) + ).resolves.toBeNull() + await expect( + getRememberedGhCwdResolutionFailure({ repoPath: '/repo', connectionId: 'ssh-1' }) + ).resolves.toBeNull() + }) +}) diff --git a/src/main/github/gh-cwd-repo-negative-cache.ts b/src/main/github/gh-cwd-repo-negative-cache.ts new file mode 100644 index 000000000..97a810f5e --- /dev/null +++ b/src/main/github/gh-cwd-repo-negative-cache.ts @@ -0,0 +1,83 @@ +import { readLocalGitConfigSignature } from './local-git-config-signature' +import type { GitHubRepoContext } from './github-repository-identity' + +/** + * Negative cache for repos where gh's cwd-based repo resolution fails + * ("no git remotes found" etc). Orca only falls back to cwd resolution when + * it could not resolve an owner/repo itself, so for a remote-less repo the + * failure is deterministic — yet the Tasks page re-spawned gh for every such + * repo on every refresh (×90 repos in the reported storm). Remember the + * failure and re-throw it without a subprocess until the repo's git config + * changes (signature check) or the TTL lapses. + */ +const NEGATIVE_CACHE_TTL_MS = 5 * 60_000 +const MAX_ENTRIES = 512 + +type NegativeCacheEntry = { + message: string + configSignature: string | undefined + expiresAt: number +} + +const entries = new Map() + +function negativeCacheKey(context: GitHubRepoContext): string { + const runtimeKey = context.connectionId ?? `local:${context.wslDistro ?? 'host'}` + return `${runtimeKey}\0${context.repoPath}` +} + +export function isGhCwdRepoResolutionFailure(text: string): boolean { + const s = text.toLowerCase() + return ( + s.includes('no git remotes found') || + s.includes('not a git repository') || + s.includes('unable to determine base repository') || + s.includes('none of the git remotes configured') + ) +} + +export async function getRememberedGhCwdResolutionFailure( + context: GitHubRepoContext +): Promise { + const key = negativeCacheKey(context) + const entry = entries.get(key) + if (!entry) { + return null + } + if (entry.expiresAt <= Date.now()) { + entries.delete(key) + return null + } + // Why: adding a remote is the way out of this failure; the config signature + // (mtime/size of the repo's git config chain) changes when that happens. + const signature = await readLocalGitConfigSignature(context) + if (signature !== entry.configSignature) { + entries.delete(key) + return null + } + return entry.message +} + +export async function rememberGhCwdResolutionFailure( + context: GitHubRepoContext, + message: string +): Promise { + const configSignature = await readLocalGitConfigSignature(context) + entries.set(negativeCacheKey(context), { + message, + configSignature, + expiresAt: Date.now() + NEGATIVE_CACHE_TTL_MS + }) + while (entries.size > MAX_ENTRIES) { + const oldest = entries.keys().next() + if (oldest.done) { + break + } + entries.delete(oldest.value) + } +} + +/** @internal — test-only */ +export function _resetGhCwdRepoNegativeCache(): void { + entries.clear() +} diff --git a/src/main/github/gh-error-classification.ts b/src/main/github/gh-error-classification.ts index b7064ef0f..2de37919d 100644 --- a/src/main/github/gh-error-classification.ts +++ b/src/main/github/gh-error-classification.ts @@ -4,6 +4,14 @@ import type { ClassifiedError } from '../../shared/types' // patterns to typed errors so callers can show user-friendly messages. export function classifyGhError(stderr: string): ClassifiedError { const s = stderr.toLowerCase() + // Why: primary rate-limit errors also carry "HTTP 403" — check rate limit + // first so they don't misclassify as a token-scope problem. + if (s.includes('rate limit')) { + return { + type: 'rate_limited', + message: 'GitHub rate limit hit. Try again in a few minutes.' + } + } if (s.includes('http 403') || s.includes('resource not accessible')) { return { type: 'permission_denied', @@ -19,12 +27,6 @@ export function classifyGhError(stderr: string): ClassifiedError { if (s.includes('http 422') || s.includes('validation failed')) { return { type: 'validation_error', message: `Invalid update — ${stderr.trim()}` } } - if (s.includes('rate limit')) { - return { - type: 'rate_limited', - message: 'GitHub rate limit hit. Try again in a few minutes.' - } - } if ( s.includes('timeout') || s.includes('no such host') || diff --git a/src/main/github/merged-pr-commit-membership.ts b/src/main/github/merged-pr-commit-membership.ts index a09f43ef0..0bb390f64 100644 --- a/src/main/github/merged-pr-commit-membership.ts +++ b/src/main/github/merged-pr-commit-membership.ts @@ -11,8 +11,15 @@ type GhExecOptions = Parameters[1] const MEMBERSHIP_CACHE_MAX_ENTRIES = 200 const MEMBERSHIP_DEFINITIVE_TTL_MS = 6 * 60 * 60 * 1000 const MEMBERSHIP_ERROR_TTL_MS = 5 * 60 * 1000 +const COMMIT_PULLS_PAGE_SIZE = 100 +// Why: a worktree HEAD is associated with ~1 PR, so page 1 is short in practice +// and this cap is never reached; it only bounds the pathological case of a commit +// linked to hundreds of PRs, where staying 'unknown' is the safe answer. +const COMMIT_PULLS_MAX_PAGES = 5 -const membershipCache = new Map() +export type MergedPRCommitMembership = 'contained' | 'not-contained' | 'unknown' + +const membershipCache = new Map() function pruneMergedPRCommitMembershipCache(now = Date.now()): void { for (const [cacheKey, cached] of membershipCache) { @@ -38,17 +45,17 @@ export function resetMergedPRCommitMembershipCacheForTest(): void { * commit belongs to that PR's history rather than merely sharing a branch name. * A worktree sitting on such a commit is on the PR's own line of work (for * example behind web-committed suggestions or an update-branch merge), not a - * reused branch name. Conservative on any failure: returns false. + * reused branch name. Conservative on any failure: returns unknown. */ export async function isCommitPartOfMergedPR(args: { ownerRepo: OwnerRepo prNumber: number commitOid: string ghOptions: GhExecOptions -}): Promise { +}): Promise { const oid = args.commitOid.trim().toLowerCase() if (!/^[0-9a-f]{4,64}$/.test(oid) || !Number.isInteger(args.prNumber)) { - return false + return 'unknown' } const owner = args.ownerRepo.owner const repo = args.ownerRepo.repo @@ -59,38 +66,78 @@ export async function isCommitPartOfMergedPR(args: { if (cached && cached.expiresAt > now) { return cached.value } - // Why blocked → uncached false: keep the merged PR hidden without burning - // budget; the next poll re-asks once the rate-limit window recovers. + // Why blocked stays unknown: hiding a transient branch match is safe, but + // callers must not clear a durable linked PR when the probe never ran. if (rateLimitGuard('core').blocked) { - return false + return 'unknown' } try { - noteRateLimitSpend('core') - const { stdout } = await ghExecFileAsync( - ['api', `repos/${owner}/${repo}/commits/${oid}/pulls?per_page=100`], - args.ghOptions - ) - const parsed = JSON.parse(stdout) as unknown - const value = - Array.isArray(parsed) && - parsed.some( + // Why paginate: a full page that omits the target PR may just be truncated (a + // commit can belong to many PRs). Reading only page 1 and calling it + // 'not-contained' would wrongly clear a durable link; calling it 'unknown' + // would never clear one that genuinely diverged. Walk pages until the PR is + // found (contained) or a short page proves absence (not-contained); only the + // pathological all-full case up to the cap stays 'unknown'. + for (let page = 1; page <= COMMIT_PULLS_MAX_PAGES; page += 1) { + if (page > 1 && rateLimitGuard('core').blocked) { + membershipCache.set(cacheKey, { + value: 'unknown', + expiresAt: now + MEMBERSHIP_ERROR_TTL_MS + }) + return 'unknown' + } + noteRateLimitSpend('core') + const { stdout } = await ghExecFileAsync( + [ + 'api', + `repos/${owner}/${repo}/commits/${oid}/pulls?per_page=${COMMIT_PULLS_PAGE_SIZE}&page=${page}` + ], + args.ghOptions + ) + const parsed = JSON.parse(stdout) as unknown + // Why: a non-array success payload is a shape mismatch, not an empty page; + // caching it as definitive not-contained could wrongly clear a durable link. + if (!Array.isArray(parsed)) { + membershipCache.set(cacheKey, { + value: 'unknown', + expiresAt: now + MEMBERSHIP_ERROR_TTL_MS + }) + return 'unknown' + } + const entries = parsed + const contained = entries.some( (entry) => typeof entry === 'object' && entry !== null && (entry as { number?: unknown }).number === args.prNumber ) + if (contained) { + membershipCache.set(cacheKey, { + value: 'contained', + expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS + }) + return 'contained' + } + if (entries.length < COMMIT_PULLS_PAGE_SIZE) { + membershipCache.set(cacheKey, { + value: 'not-contained', + expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS + }) + return 'not-contained' + } + } membershipCache.set(cacheKey, { - value, - expiresAt: now + MEMBERSHIP_DEFINITIVE_TTL_MS - }) - return value - } catch { - // Why: the common failure is 422 for a commit never pushed to GitHub — - // definitive "new local work" today, but a push can change it; retry later. - membershipCache.set(cacheKey, { - value: false, + value: 'unknown', expiresAt: now + MEMBERSHIP_ERROR_TTL_MS }) - return false + return 'unknown' + } catch { + // Why: 422 often means "new local work" today, but a later push can make + // the answer knowable; preserve durable links until a probe succeeds. + membershipCache.set(cacheKey, { + value: 'unknown', + expiresAt: now + MEMBERSHIP_ERROR_TTL_MS + }) + return 'unknown' } } diff --git a/src/main/github/pr-refresh-coordinator.test.ts b/src/main/github/pr-refresh-coordinator.test.ts index 766a734f2..76bd24603 100644 --- a/src/main/github/pr-refresh-coordinator.test.ts +++ b/src/main/github/pr-refresh-coordinator.test.ts @@ -116,6 +116,25 @@ describe('pr-refresh-coordinator', () => { ) }) + it('copies the candidate worktree head onto broadcast aliases', async () => { + const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ state: 'merged' }), + fetchedAt: Date.now() + }) + + reportVisiblePRRefreshCandidates([makeCandidate({ currentHeadOid: 'worktree-head-oid' })], 1, 1) + await vi.runOnlyPendingTimersAsync() + + // Why: the renderer clear of a diverged merged linked PR is head-scoped, so + // the broadcast alias must carry the request-time head it was probed against. + const outcomeEvent = sendMock.mock.calls + .map(([, event]) => event) + .find((event) => event.outcome) + expect(outcomeEvent?.aliases[0]?.currentHeadOid).toBe('worktree-head-oid') + }) + it('does not show visible background refreshes as queued', async () => { const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') getPRForBranchOutcomeMock.mockResolvedValueOnce({ @@ -633,6 +652,103 @@ describe('pr-refresh-coordinator', () => { expect(getPRForBranchOutcomeMock).toHaveBeenCalledTimes(2) }) + it('probes with the survivor head after the representative alias is invalidated', async () => { + const { enqueuePRRefresh } = await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'found', + pr: makePR({ state: 'merged' }), + fetchedAt: Date.now() + }) + + const survivor = makeCandidate({ + cacheKey: '/repo::feature/b', + branch: 'feature/b', + linkedPRNumber: 12, + worktreeId: 'wt-b', + currentHeadOid: 'head-b' + }) + const representative = makeCandidate({ + cacheKey: '/repo::feature/a', + branch: 'feature/a', + linkedPRNumber: 12, + worktreeId: 'wt-a', + currentHeadOid: 'head-a' + }) + + // Enqueue the survivor first, then the representative (active coalescing + // promotes the latter to representative), then invalidate the representative + // so the still-queued entry rebinds to the survivor before draining. + enqueuePRRefresh(survivor, 'active', 80, 1) + enqueuePRRefresh(representative, 'active', 80, 1) + enqueuePRRefresh({ ...representative, isArchived: true }, 'active', 80, 1) + await vi.runOnlyPendingTimersAsync() + + const probedHeads = getPRForBranchOutcomeMock.mock.calls.map((call) => call[5]?.currentHeadOid) + expect(probedHeads).toContain('head-b') + expect(probedHeads).not.toContain('head-a') + }) + + it('probes with the survivor head after the representative worktree is pruned', async () => { + const { enqueuePRRefresh, pruneWorktreePRRefreshAliases } = + await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'found', + pr: makePR({ state: 'merged' }), + fetchedAt: Date.now() + }) + + const survivor = makeCandidate({ + cacheKey: '/repo::feature/b', + branch: 'feature/b', + linkedPRNumber: 12, + worktreeId: 'wt-b', + currentHeadOid: 'head-b' + }) + const representative = makeCandidate({ + cacheKey: '/repo::feature/a', + branch: 'feature/a', + linkedPRNumber: 12, + worktreeId: 'wt-a', + currentHeadOid: 'head-a' + }) + + enqueuePRRefresh(survivor, 'active', 80, 1) + enqueuePRRefresh(representative, 'active', 80, 1) + pruneWorktreePRRefreshAliases('wt-a') + await vi.runOnlyPendingTimersAsync() + + const probedHeads = getPRForBranchOutcomeMock.mock.calls.map((call) => call[5]?.currentHeadOid) + expect(probedHeads).toContain('head-b') + expect(probedHeads).not.toContain('head-a') + }) + + it('refreshes the representative head when the same worktree re-reports a moved head', async () => { + const { reportVisiblePRRefreshCandidates } = await import('./pr-refresh-coordinator') + getPRForBranchOutcomeMock.mockResolvedValue({ + kind: 'found', + pr: makePR({ state: 'merged' }), + fetchedAt: Date.now() + }) + + // Same worktree/branch, moved head, coalescing visible→visible (no promote): + // the representative head must track the newest report before the drain. + reportVisiblePRRefreshCandidates( + [makeCandidate({ linkedPRNumber: 12, worktreeId: 'wt-a', currentHeadOid: 'head-a' })], + 1, + 1 + ) + reportVisiblePRRefreshCandidates( + [makeCandidate({ linkedPRNumber: 12, worktreeId: 'wt-a', currentHeadOid: 'head-b' })], + 2, + 1 + ) + await vi.runOnlyPendingTimersAsync() + + const probedHeads = getPRForBranchOutcomeMock.mock.calls.map((call) => call[5]?.currentHeadOid) + expect(probedHeads).toContain('head-b') + expect(probedHeads).not.toContain('head-a') + }) + it('includes request start time on manual refresh events', async () => { const { refreshPRNow } = await import('./pr-refresh-coordinator') getPRForBranchOutcomeMock.mockResolvedValueOnce({ diff --git a/src/main/github/pr-refresh-coordinator.ts b/src/main/github/pr-refresh-coordinator.ts index 5bb70a970..a2576e480 100644 --- a/src/main/github/pr-refresh-coordinator.ts +++ b/src/main/github/pr-refresh-coordinator.ts @@ -188,7 +188,11 @@ export function pruneWorktreePRRefreshAliases(worktreeId: string): void { ...entry.candidate, cacheKey: replacementAlias.cacheKey, branch: replacementAlias.branch, - worktreeId: replacementAlias.worktreeId + worktreeId: replacementAlias.worktreeId, + // Why: the probe now represents the replacement worktree, so it must + // use that worktree's head — otherwise divergence is stamped for the + // removed worktree's head and the survivor's link is never cleared. + currentHeadOid: replacementAlias.currentHeadOid ?? null } } } @@ -321,6 +325,7 @@ function aliasFromCandidate(candidate: GitHubPRRefreshCandidate): GitHubPRRefres branch: candidate.branch, worktreeId: candidate.worktreeId, connectionId: candidate.connectionId ?? null, + currentHeadOid: candidate.currentHeadOid ?? null, linkedPRNumber: candidate.linkedPRNumber ?? null, fallbackPRNumber: candidate.linkedPRNumber == null ? (candidate.fallbackPRNumber ?? null) : null, @@ -393,6 +398,10 @@ function removeQueuedAliasForInvalidCandidate(key: string, alias: GitHubPRRefres cacheKey: replacementAlias.cacheKey, branch: replacementAlias.branch, worktreeId: replacementAlias.worktreeId, + // Why: the probe now represents the replacement worktree, so it must use + // that worktree's head — otherwise divergence is stamped for the pruned + // candidate's head and the survivor's link is never cleared. + currentHeadOid: replacementAlias.currentHeadOid ?? null, isArchived: false, isBare: false } @@ -809,6 +818,18 @@ export function enqueuePRRefresh( existing.activeDelayNotified = false existing.candidate = candidate existing.windowId = windowId ?? existing.windowId + } else if (existing.candidate.worktreeId === candidate.worktreeId) { + // Why: a non-promoting coalesce (e.g. visible→visible) keeps the existing + // representative, but the representative drives the probe head. If its own + // worktree moved head/branch, refresh those probe inputs so divergence is + // stamped for the current head — otherwise the head-scoped clear never + // matches and a merged linked PR lingers after a branch switch. + existing.candidate = { + ...existing.candidate, + cacheKey: candidate.cacheKey, + branch: candidate.branch, + currentHeadOid: candidate.currentHeadOid ?? null + } } } else { diagnosticsCounters.enqueued += 1 diff --git a/src/main/github/project-view/internals.ts b/src/main/github/project-view/internals.ts index 52509c306..586bbaa6e 100644 --- a/src/main/github/project-view/internals.ts +++ b/src/main/github/project-view/internals.ts @@ -1,7 +1,3 @@ -/* eslint-disable max-lines -- Why: shared infrastructure for project-view — -slug validation, error classification, runGraphql/runRest, and rate-limit -synthesis. Co-located so the read and write paths observe identical -classification semantics. */ // Why: `ghExecFileAsync` (WSL-aware, retry-enabled) is the single spawn site // for gh calls. The legacy plain `execFileAsync` is NOT used here — routing // every gh call through the runner gives us transient-5xx retry, WSL path diff --git a/src/main/github/rate-limit.ts b/src/main/github/rate-limit.ts index 1108b6bd2..ad1404224 100644 --- a/src/main/github/rate-limit.ts +++ b/src/main/github/rate-limit.ts @@ -20,6 +20,13 @@ import type { } from '../../shared/types' import { acquire, release } from './gh-utils' import { ghExecFileAsync } from '../git/runner' +import { + clearGhRateLimitBlock, + getGhRateLimitBlockedUntilMs, + recordGhPrimaryRateLimit, + registerGhRateLimitResetProbe, + type GhRateLimitBucket +} from '../git/gh-rate-limit-breaker' // Why: GitHub explicitly states `GET /rate_limit` does NOT count against // any bucket, so the only reason to cache is to avoid spawning a `gh` @@ -93,6 +100,18 @@ export function rateLimitGuard(bucket: RateLimitBucketKind): limit: number resetAt: number } { + // Why: the runner-level breaker learns about exhaustion from actual 403s, + // which can happen long before (or without) a snapshot probe — e.g. quota + // burned by another tool on the same account. + const breakerBlockedUntilMs = getGhRateLimitBlockedUntilMs(bucket) + if (breakerBlockedUntilMs !== null) { + return { + blocked: true, + remaining: 0, + limit: cached?.[bucket].limit ?? 0, + resetAt: Math.ceil(breakerBlockedUntilMs / 1000) + } + } if (!cached) { return { blocked: false } } @@ -103,6 +122,11 @@ export function rateLimitGuard(bucket: RateLimitBucketKind): : bucket === 'graphql' ? MIN_REMAINING_GRAPHQL : MIN_REMAINING_SEARCH + // Why: a snapshot from before the bucket's reset time describes a window + // that has already ended — fail open rather than blocking on stale data. + if (b.resetAt * 1000 <= Date.now()) { + return { blocked: false } + } // Why: only block when we have a positive limit (limit:0 means "unknown" per // parseBucket fallback — don't block on missing data, that would brick the // app on a single bad rate_limit response). @@ -130,10 +154,63 @@ export function noteRateLimitSpend(bucket: RateLimitBucketKind, cost = 1): void } } +// Why: when the runner's breaker trips it only knows "blocked", not for how +// long. `gh api rate_limit` is exempt from limits, so one forced probe turns +// the fallback block into the bucket's real reset time (or clears a block +// that a stale fallback would otherwise keep alive). Single-flight: a 90-repo +// 403 burst must refine once, not 90 times. +let resetRefinementInFlight: Promise | null = null + +function refineBreakerFromSnapshot(): void { + if (resetRefinementInFlight) { + return + } + resetRefinementInFlight = (async () => { + try { + const result = await getRateLimit({ force: true }) + if (!result.ok) { + return + } + for (const bucket of ['core', 'search', 'graphql'] as GhRateLimitBucket[]) { + const b = result.snapshot[bucket] + if (b.limit > 0 && b.remaining <= 0) { + recordGhPrimaryRateLimit(bucket, b.resetAt * 1000) + } else if (b.limit > 0) { + clearGhRateLimitBlock(bucket) + } + } + } finally { + resetRefinementInFlight = null + } + })() +} + +registerGhRateLimitResetProbe(() => refineBreakerFromSnapshot()) + +// Why: a 90-repo fan-out that primes the guard concurrently must resolve to +// one `gh api rate_limit` spawn, not one per repo — the TTL cache alone can't +// dedupe calls that all start before the first probe lands. +let probeInFlight: Promise | null = null + export async function getRateLimit(options?: { force?: boolean }): Promise { if (!options?.force && cached && Date.now() - cached.fetchedAt < RATE_LIMIT_CACHE_TTL_MS) { return { ok: true, snapshot: cached } } + if (!options?.force && probeInFlight) { + return probeInFlight + } + const probe = fetchRateLimitSnapshot() + probeInFlight = probe + try { + return await probe + } finally { + if (probeInFlight === probe) { + probeInFlight = null + } + } +} + +async function fetchRateLimitSnapshot(): Promise { await acquire() try { const { stdout } = await ghExecFileAsync(['api', 'rate_limit'], { encoding: 'utf-8' }) diff --git a/src/main/gitlab/issues.test.ts b/src/main/gitlab/issues.test.ts index f567936d9..edc6d2457 100644 --- a/src/main/gitlab/issues.test.ts +++ b/src/main/gitlab/issues.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: GitLab issue mutation/list coverage shares glab mocks across related endpoint cases. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as GlUtils from './gl-utils' diff --git a/src/main/gitlab/merge-request-creation.test.ts b/src/main/gitlab/merge-request-creation.test.ts index cd1b5de98..b7ead7c98 100644 --- a/src/main/gitlab/merge-request-creation.test.ts +++ b/src/main/gitlab/merge-request-creation.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: MR creation tests share glab and SSH filesystem mocks across CLI, template, and duplicate-detection paths. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { diff --git a/src/main/index.ts b/src/main/index.ts index 902a01a8d..251ea69e6 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -62,6 +62,7 @@ import { patchPackagedProcessPath, shouldInstallManagedHooks } from './startup/configure-process' +import { enableRendererHeapHeadroom } from './startup/renderer-heap-headroom' import { ensureVirtualDisplayForHeadlessServe } from './startup/ensure-virtual-display' import { readActiveGpuFallbackMarker, @@ -91,6 +92,7 @@ import { shouldBypassSingleInstanceLock } from './startup/single-instance-lock' import { startEventLoopStallProbe } from './startup/event-loop-stall-probe' +import { startMainThreadChurnProbe } from './diagnostics/main-thread-churn-probe' import { isStartupDiagnosticsEnabled, logStartupDiagnostic, @@ -119,6 +121,10 @@ import { normalizeClaudeRuntimeSelection } from './claude-accounts/runtime-selec import { codexHookService } from './codex/hook-service' import { ClaudeAccountService } from './claude-accounts/service' import { ClaudeRuntimeAuthService } from './claude-accounts/runtime-auth-service' +import { + attachClaudeLivePtyPersistence, + seedLiveClaudePtysFromPersistence +} from './claude-accounts/live-pty-gate' import { StarNagService } from './star-nag/service' import { agentHookServer } from './agent-hooks/server' import { maybeAutoRenameBranchOnFirstWork } from './agent-hooks/first-work-branch-rename' @@ -427,6 +433,9 @@ if (startupDiagnosticsEnabled) { }) startEventLoopStallProbe() } +// Self-gated on ORCA_MAIN_THREAD_DIAGNOSTICS; unlike the startup probe it +// runs for the whole session to catch steady-state churn (issue #7576). +startMainThreadChurnProbe() function focusExistingWindow(): void { focusExistingMainWindow({ @@ -581,6 +590,7 @@ if (hasSingleInstanceLock) { platform: process.platform }) configureElectronNetworkCompatibility() + enableRendererHeapHeadroom() maybeApplyGpuFallbackForThisLaunch() if (!gpuFallbackActiveThisLaunch) { enableMainProcessGpuFeatures() @@ -1616,6 +1626,18 @@ app.whenReady().then(async () => { store = new Store() logStartupMilestone('store-loaded') + // Why: must run before ClaudeRuntimeAuthService's constructor sync — a Claude + // CLI that survived the restart inside the daemon still holds the current + // single-use refresh token, and an unguarded early refresh would rotate it + // out from under that process (it then shows "Not logged in" mid-session). + attachClaudeLivePtyPersistence(store) + const persistedClaudePtyIds = store.getClaudeLivePtySessionIds() + seedLiveClaudePtysFromPersistence(persistedClaudePtyIds) + if (persistedClaudePtyIds.length > 0) { + console.log( + `[claude-live-pty] Seeded ${persistedClaudePtyIds.length} persisted Claude session id(s) into the refresh gate` + ) + } selfHealRuntimeEnvironmentFocus({ store, userDataPath: app.getPath('userData') }) applyAppIcon(store.getSettings().appIcon) if (shouldSuppressDevEducation({ isDev: is.dev })) { diff --git a/src/main/ipc/browser.test.ts b/src/main/ipc/browser.test.ts index 98fab06f4..042140cd3 100644 --- a/src/main/ipc/browser.test.ts +++ b/src/main/ipc/browser.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: browser IPC tests share one mocked trust-boundary handler registry plus registration waiters; splitting would duplicate setup and weaken coverage. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { diff --git a/src/main/ipc/crash-reporting.test.ts b/src/main/ipc/crash-reporting.test.ts index 1c2059bb7..04432899a 100644 --- a/src/main/ipc/crash-reporting.test.ts +++ b/src/main/ipc/crash-reporting.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: crash-reporting IPC tests share mocked Electron/observability handler setup; splitting would duplicate brittle IPC wiring. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { CrashReportRecord } from '../../shared/crash-reporting' diff --git a/src/main/ipc/diagnostics.test.ts b/src/main/ipc/diagnostics.test.ts index b30d013f6..2868fdec1 100644 --- a/src/main/ipc/diagnostics.test.ts +++ b/src/main/ipc/diagnostics.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: diagnostics IPC tests share mocked Electron handler setup; splitting would duplicate brittle IPC wiring. */ import { readFileSync, writeFileSync } from 'node:fs' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { CollectedBundle } from '../observability/bundle' diff --git a/src/main/ipc/filesystem-auth.test.ts b/src/main/ipc/filesystem-auth.test.ts index 979d6b561..c6fa78b12 100644 --- a/src/main/ipc/filesystem-auth.test.ts +++ b/src/main/ipc/filesystem-auth.test.ts @@ -8,8 +8,11 @@ import type * as RepoWorktrees from '../repo-worktrees' import { listRepoWorktrees } from '../repo-worktrees' import type { FolderWorkspace, GitWorktreeInfo, ProjectGroup, Repo } from '../../shared/types' import { + AUTHORIZED_EXTERNAL_PATHS_MAX, + authorizeExternalPath, invalidateAuthorizedRootsCache, isDescendantOrEqual, + isPathAllowed, rebuildAuthorizedRootsCache, resolveAuthorizedPath, resolveRegisteredWorktreePath, @@ -336,3 +339,42 @@ describe('filesystem-auth path containment', () => { } }) }) + +describe('filesystem-auth authorized external path bound', () => { + // Empty allow-list store, so a path is allowed only if it (or an ancestor) is + // in the session-authorized external-path set. + const emptyStore = makeStore([]) + const flood = (n: number): string => + resolve(`/leak-audit-ext/flood-${String(n).padStart(6, '0')}`) + + it('bounds the authorized external path set with LRU eviction', () => { + const keep = resolve('/leak-audit-ext/keep') + authorizeExternalPath(keep) + + // Flood past the cap with distinct external paths, re-authorizing `keep` + // periodically so LRU keeps it hot. + const total = AUTHORIZED_EXTERNAL_PATHS_MAX + 200 + for (let i = 0; i < total; i += 1) { + authorizeExternalPath(flood(i)) + if (i % 250 === 0) { + authorizeExternalPath(keep) + } + } + + // The oldest never-re-touched entries fell out of the bounded set... + expect(isPathAllowed(flood(0), emptyStore)).toBe(false) + // ...while the periodically re-authorized path and the most recent survive. + expect(isPathAllowed(keep, emptyStore)).toBe(true) + expect(isPathAllowed(flood(total - 1), emptyStore)).toBe(true) + }) + + it('re-authorizes an evicted path on next use (self-healing)', () => { + const path = resolve('/leak-audit-ext/evicted-then-reused') + for (let i = 0; i < AUTHORIZED_EXTERNAL_PATHS_MAX + 50; i += 1) { + authorizeExternalPath(flood(100_000 + i)) + } + expect(isPathAllowed(path, emptyStore)).toBe(false) + authorizeExternalPath(path) + expect(isPathAllowed(path, emptyStore)).toBe(true) + }) +}) diff --git a/src/main/ipc/filesystem-auth.ts b/src/main/ipc/filesystem-auth.ts index f931ebe11..7fee4ca19 100644 --- a/src/main/ipc/filesystem-auth.ts +++ b/src/main/ipc/filesystem-auth.ts @@ -13,6 +13,14 @@ import type { FolderWorkspace, ProjectGroup, Repo } from '../../shared/types' export const PATH_ACCESS_DENIED_MESSAGE = 'Access denied: path resolves outside allowed directories. If this blocks a legitimate workflow, please file a GitHub issue.' +// Why: authorized external paths accumulate for the whole session (file drops, +// terminal link opens, editor/composer/notebook opens). Bound the set with LRU +// eviction — mirrors rememberUnwatchableRoot in filesystem-watcher.ts — so a long +// session touching many distinct external files cannot grow it (or the O(n) auth +// scan in isPathAllowed) without limit. Every caller re-authorizes a path right +// before operating on it, so evicting a stale entry is self-healing and does not +// weaken the security boundary. +export const AUTHORIZED_EXTERNAL_PATHS_MAX = 4096 const authorizedExternalPaths = new Set() const registeredWorktreeRoots = new Set() const registeredWorktreeRootsByRepo = new Map>() @@ -23,12 +31,26 @@ const AUTHORIZED_ROOTS_REBUILD_CONCURRENCY = 8 type FolderScopeStore = Pick & Partial> +function rememberAuthorizedExternalPath(path: string): void { + // Delete-then-add keeps re-authorized (actively used) paths most-recent so + // eviction only sheds the oldest never-re-touched entries. + authorizedExternalPaths.delete(path) + authorizedExternalPaths.add(path) + while (authorizedExternalPaths.size > AUTHORIZED_EXTERNAL_PATHS_MAX) { + const oldest = authorizedExternalPaths.keys().next().value + if (oldest === undefined) { + break + } + authorizedExternalPaths.delete(oldest) + } +} + export function authorizeExternalPath(targetPath: string): void { const resolvedTarget = resolve(targetPath) - authorizedExternalPaths.add(resolvedTarget) + rememberAuthorizedExternalPath(resolvedTarget) try { // Why: macOS canonicalizes /tmp to /private/tmp during read authorization. - authorizedExternalPaths.add(realpathSync(resolvedTarget)) + rememberAuthorizedExternalPath(realpathSync(resolvedTarget)) } catch {} } diff --git a/src/main/ipc/filesystem-import.test.ts b/src/main/ipc/filesystem-import.test.ts index 01b28e1c3..fcd004dcd 100644 --- a/src/main/ipc/filesystem-import.test.ts +++ b/src/main/ipc/filesystem-import.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: import tests cover local copy, SSH routing, -symlink safety, and runtime-upload staging against one shared IPC fixture. */ import path from 'node:path' import { constants } from 'node:fs' import { Readable, Writable } from 'node:stream' diff --git a/src/main/ipc/filesystem-list-files.test.ts b/src/main/ipc/filesystem-list-files.test.ts index 9a04660ec..638775a48 100644 --- a/src/main/ipc/filesystem-list-files.test.ts +++ b/src/main/ipc/filesystem-list-files.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: one Quick Open file-list suite covers both rg and git fallback process lifecycles. */ import { describe, expect, it, vi, beforeEach } from 'vitest' const { diff --git a/src/main/ipc/filesystem-watcher.test.ts b/src/main/ipc/filesystem-watcher.test.ts index b1af20fd1..0b3b07ca0 100644 --- a/src/main/ipc/filesystem-watcher.test.ts +++ b/src/main/ipc/filesystem-watcher.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: filesystem watcher tests share module-level -state across local, WSL, and SSH lifecycle paths; keeping them together makes -closeAllWatchers cleanup regressions visible in one suite. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { handleMock, getSshFilesystemProviderMock } = vi.hoisted(() => ({ diff --git a/src/main/ipc/pty-management.test.ts b/src/main/ipc/pty-management.test.ts index c644d885d..443b356ba 100644 --- a/src/main/ipc/pty-management.test.ts +++ b/src/main/ipc/pty-management.test.ts @@ -1,7 +1,3 @@ -/* eslint-disable max-lines -- Why: covers every pty:management IPC channel -against shared mocks (electron, fs, daemon-init, DaemonPtyRouter). Splitting -across files would duplicate the vi.hoisted setup and the shared helpers, -with no meaningful ownership seam. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { DaemonSessionInfo } from '../daemon/types' diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 088f0d1d1..7ceb75516 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -1435,13 +1435,24 @@ export function registerPtyHandlers( } function recordPtyRendererDeliveryPressure(): void { - const current = readCurrentPtyRendererDeliveryDebugSnapshot() - peakPendingChars = Math.max(peakPendingChars, current.pendingChars) - peakMaxPendingCharsByPty = Math.max(peakMaxPendingCharsByPty, current.maxPendingCharsByPty) - peakRendererInFlightChars = Math.max(peakRendererInFlightChars, current.rendererInFlightChars) + // Why: this fires on every PTY delivery event (per send, per flush, per + // onData append). Update the four diagnostic peaks directly instead of + // allocating a full 13-field debug snapshot object per call — that object + // is only needed when the debug getter is actually read. Peak values are + // computed identically to readCurrentPtyRendererDeliveryDebugSnapshot. + let pendingChars = 0 + let maxPendingCharsByPty = 0 + for (const pending of pendingData.values()) { + const chars = pending.data.length + pendingChars += chars + maxPendingCharsByPty = Math.max(maxPendingCharsByPty, chars) + } + peakPendingChars = Math.max(peakPendingChars, pendingChars) + peakMaxPendingCharsByPty = Math.max(peakMaxPendingCharsByPty, maxPendingCharsByPty) + peakRendererInFlightChars = Math.max(peakRendererInFlightChars, rendererInFlightTotalChars) peakMaxRendererInFlightCharsByPty = Math.max( peakMaxRendererInFlightCharsByPty, - current.maxRendererInFlightCharsByPty + getMaxMapValue(rendererInFlightCharsByPty.values()) ) } diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index 5ce6342c3..0b7c4e071 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: this test mirrors the complete core IPC handler registry so - duplicate-registration coverage stays tied to the one production entry point. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { diff --git a/src/main/ipc/remote-workspace-patch-queue.test.ts b/src/main/ipc/remote-workspace-patch-queue.test.ts index 6de465626..1c97ad6b7 100644 --- a/src/main/ipc/remote-workspace-patch-queue.test.ts +++ b/src/main/ipc/remote-workspace-patch-queue.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: queue/cache regression cases share one mocked IPC harness so stale revision sequencing stays visible. */ import { ipcMain } from 'electron' import { beforeEach, describe, expect, it, vi } from 'vitest' import type { Store } from '../persistence' diff --git a/src/main/ipc/shell.test.ts b/src/main/ipc/shell.test.ts index 24ac41e2d..2e1b84290 100644 --- a/src/main/ipc/shell.test.ts +++ b/src/main/ipc/shell.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: shell IPC path validation, OS opener fallbacks, and launcher lifecycle tests share one mocked Electron/child_process boundary. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { normalize, resolve } from 'node:path' import { pathToFileURL } from 'node:url' diff --git a/src/main/ipc/ssh.ts b/src/main/ipc/ssh.ts index ff6761122..0ac0c5e0d 100644 --- a/src/main/ipc/ssh.ts +++ b/src/main/ipc/ssh.ts @@ -714,8 +714,8 @@ export function registerSshHandlers( await removeRegisteredSshTarget(args.id) }) - ipcMain.handle('ssh:importConfig', () => { - return sshStore!.importFromSshConfig() + ipcMain.handle('ssh:importConfig', (_event, args?: { reAdopt?: boolean }) => { + return sshStore!.importFromSshConfig(args) }) // ── Connection lifecycle ─────────────────────────────────────────── diff --git a/src/main/ipc/telemetry.test.ts b/src/main/ipc/telemetry.test.ts index 27c7d0cd1..40679160f 100644 --- a/src/main/ipc/telemetry.test.ts +++ b/src/main/ipc/telemetry.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: a single test file pins the IPC boundary behavior for all four telemetry handlers plus the cohort-injection invariants; splitting would fragment the threat-model coverage. */ // IPC boundary behavior for the telemetry surface. Strict type narrows must // drop obviously-malformed calls before they reach the validator (the // renderer is in the threat model). Pins the consent-mutation rate limit: diff --git a/src/main/ipc/workspace-cleanup.test.ts b/src/main/ipc/workspace-cleanup.test.ts index 6fe5320b1..af084713a 100644 --- a/src/main/ipc/workspace-cleanup.test.ts +++ b/src/main/ipc/workspace-cleanup.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: scan and IPC process-liveness tests share - hoisted Electron/git provider mocks; splitting would duplicate brittle setup. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { ipcMain } from 'electron' import type { Store } from '../persistence' diff --git a/src/main/ipc/worktree-logic.test.ts b/src/main/ipc/worktree-logic.test.ts index 7ba2350c8..219235ac9 100644 --- a/src/main/ipc/worktree-logic.test.ts +++ b/src/main/ipc/worktree-logic.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: these worktree path/name tests share a -single setup-free pure-logic module, and splitting them would make the related -edge cases harder to audit together. */ import { posix, resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index c7ff8f45c..8b966e2b5 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -103,6 +103,7 @@ type CreateWorktreeArgsWithSystemProvenance = CreateWorktreeArgs & { } import { classifyWorkspaceCreateError } from './workspace-create-error-classifier' import { advertisedUrlWatcher } from '../ports/advertised-url-watcher' +import { localhostWorktreeLabelProxy } from '../localhost-worktree-label-proxy' import { assertWorktreeDoesNotContainRegisteredWorktree, canCleanupUnregisteredOrcaLeftoverDirectory, @@ -161,6 +162,9 @@ function removeWorktreeMetadataAndTransientState(store: Store, worktreeId: strin // drop process-local caches before the same ID can point at a new workspace. store.removeWorktreeMeta(worktreeId) advertisedUrlWatcher.forgetWorktree(worktreeId) + // Why: drop this worktree's localhost label routes so they don't accumulate + // in the proxy's route maps for the rest of the session. + localhostWorktreeLabelProxy.unregisterWorktree(worktreeId) deleteWorktreeHistoryDir(worktreeId) // Why: release the removed worktree's PR-refresh aliases so coalesced queue // entries do not retain it for the rest of the session (memory creep). diff --git a/src/main/localhost-worktree-label-proxy.test.ts b/src/main/localhost-worktree-label-proxy.test.ts index 49a5e866e..7d4992098 100644 --- a/src/main/localhost-worktree-label-proxy.test.ts +++ b/src/main/localhost-worktree-label-proxy.test.ts @@ -124,4 +124,33 @@ describe('localhost worktree label proxy', () => { expect(result.status).toBe(404) }) + + it('drops a worktree label routes on unregisterWorktree, leaving others intact', async () => { + const port = await startUpstream((_request, response) => { + response.writeHead(200, { 'content-type': 'text/plain' }) + response.end('ok') + }) + const proxy = new LocalhostWorktreeLabelProxy() + const a = await proxy.registerRoute({ + targetUrl: `http://localhost:${port}/`, + projectName: 'Snap Studio', + worktreeName: 'feature-a', + worktreeId: 'wt-a' + }) + const b = await proxy.registerRoute({ + targetUrl: `http://localhost:${port}/`, + projectName: 'Snap Studio', + worktreeName: 'feature-b', + worktreeId: 'wt-b' + }) + + expect((await fetchThroughProxy(a.url)).status).toBe(200) + expect((await fetchThroughProxy(b.url)).status).toBe(200) + + proxy.unregisterWorktree('wt-a') + + // The removed worktree's label no longer routes; the other worktree is unaffected. + expect((await fetchThroughProxy(a.url)).status).toBe(404) + expect((await fetchThroughProxy(b.url)).status).toBe(200) + }) }) diff --git a/src/main/localhost-worktree-label-proxy.ts b/src/main/localhost-worktree-label-proxy.ts index b2f815270..acc1164d1 100644 --- a/src/main/localhost-worktree-label-proxy.ts +++ b/src/main/localhost-worktree-label-proxy.ts @@ -49,6 +49,18 @@ export class LocalhostWorktreeLabelProxy { } } + // Why: routes are added per (worktreeId, targetUrl) but were never removed, so + // labels for deleted worktrees accumulated in both maps for the whole session. + // Drop them when the worktree is torn down. The shared http.Server stays up. + unregisterWorktree(worktreeId: string): void { + for (const [label, route] of this.routes) { + if (route.worktreeId === worktreeId) { + this.routes.delete(label) + this.routeKeys.delete(route.routeKey) + } + } + } + private async ensureServer(): Promise { if (this.server && this.listenPort !== null) { return diff --git a/src/main/observability/bundle.test.ts b/src/main/observability/bundle.test.ts index 83ae2ac67..347e10258 100644 --- a/src/main/observability/bundle.test.ts +++ b/src/main/observability/bundle.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: diagnostics bundle fixtures cover collection, preview deletion, upload URL hardening, and byte caps as one contract surface. Splitting would duplicate the temp-file/server harness and make edge-case coverage harder to audit. */ // Bundle collection + upload tests. Upload helpers live outside bundle.ts, but // this suite keeps the diagnostic bundle contract in one place. diff --git a/src/main/observability/redactor.test.ts b/src/main/observability/redactor.test.ts index 4ad470bc7..8de266151 100644 --- a/src/main/observability/redactor.test.ts +++ b/src/main/observability/redactor.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: the redactor has intentionally broad fixture coverage across every secret location and key-shape rule; keeping it together makes gaps visible. */ // Fixture-based test suite for the redactor. Each provider-key shape is // exercised in three locations (attribute value, span event message, // exit-status `cause`) — that's the contract telemetry-error-tracking.md diff --git a/src/main/opencode-usage/scanner.test.ts b/src/main/opencode-usage/scanner.test.ts index 6efec7beb..c4bd46aae 100644 --- a/src/main/opencode-usage/scanner.test.ts +++ b/src/main/opencode-usage/scanner.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: OpenCode scanner tests cover multiple DB schema generations and attribution boundaries together so parser regressions stay auditable. */ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/opencode/hook-service.test.ts b/src/main/opencode/hook-service.test.ts index 9d71a25d8..2ad00cf5b 100644 --- a/src/main/opencode/hook-service.test.ts +++ b/src/main/opencode/hook-service.test.ts @@ -1,8 +1,3 @@ -/* eslint-disable max-lines -- Why: this suite covers four orthogonal regimes - (plugin source, id guards, legacy per-PTY round-trip, and overlay mode for - user-set OPENCODE_CONFIG_DIR). Splitting them across files would scatter - tightly coupled fixtures (userData mock, hooks/overlay roots) and obscure - the docs/opencode-config-dir-collision.md regression matrix. */ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { existsSync, diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index 307fb3d88..d4862d9dc 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -8446,6 +8446,69 @@ describe('Store', () => { expect(store.getWorkspaceLineage(unrelatedLineage.childWorkspaceKey)).toEqual(unrelatedLineage) }) + // ── Live Claude PTY session ids (STA-1246) ───────────────────────── + + describe('claudeLivePtySessionIds', () => { + it('persists added ids across reloads and removes them durably', async () => { + const store = await createStore() + + store.addClaudeLivePtySessionId('claude-session-1') + store.addClaudeLivePtySessionId('claude-session-2') + store.addClaudeLivePtySessionId('claude-session-1') + + expect(store.getClaudeLivePtySessionIds()).toEqual(['claude-session-1', 'claude-session-2']) + + const reloaded = await createStore() + expect(reloaded.getClaudeLivePtySessionIds()).toEqual([ + 'claude-session-1', + 'claude-session-2' + ]) + + reloaded.removeClaudeLivePtySessionId('claude-session-1') + reloaded.flush() + + const reloadedAgain = await createStore() + expect(reloadedAgain.getClaudeLivePtySessionIds()).toEqual(['claude-session-2']) + }) + + it('drops malformed persisted entries on load', async () => { + writeDataFile({ + schemaVersion: 1, + claudeLivePtySessionIds: ['valid-id', '', 42, null, 'valid-id', 'x'.repeat(513)] + }) + + const store = await createStore() + + expect(store.getClaudeLivePtySessionIds()).toEqual(['valid-id']) + }) + + it('keeps the newest ids when an oversized persisted list is loaded', async () => { + writeDataFile({ + schemaVersion: 1, + claudeLivePtySessionIds: Array.from({ length: 205 }, (_, index) => `claude-${index}`) + }) + + const store = await createStore() + + const ids = store.getClaudeLivePtySessionIds() + expect(ids).toHaveLength(200) + expect(ids[0]).toBe('claude-5') + expect(ids[199]).toBe('claude-204') + }) + + it('caps the persisted id list', async () => { + const store = await createStore() + for (let index = 0; index < 205; index += 1) { + store.addClaudeLivePtySessionId(`claude-session-${index}`) + } + + const ids = store.getClaudeLivePtySessionIds() + expect(ids).toHaveLength(200) + expect(ids[0]).toBe('claude-session-5') + expect(ids[199]).toBe('claude-session-204') + }) + }) + // ── Rolling backups (issue #1158) ────────────────────────────────── describe('rolling backups', () => { diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 7645a8af6..5bad9510e 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2177,6 +2177,33 @@ function remapAcknowledgedAgentPaneKeys( return { acknowledgements: next, changed } } +// Why: bounds a corrupt/bloated persisted list — the gate only ever needs the +// handful of Claude sessions a daemon can realistically keep alive. +const MAX_CLAUDE_LIVE_PTY_SESSION_IDS = 200 + +function normalizeClaudeLivePtySessionIds(value: unknown): string[] { + if (!Array.isArray(value)) { + return [] + } + // Why: scan newest-first so the cap keeps the most recent ids, matching + // addClaudeLivePtySessionId's eviction policy while bounding the work done + // on an oversized/corrupt list. + const ids: string[] = [] + for (let index = value.length - 1; index >= 0; index -= 1) { + const entry = value[index] + if (typeof entry !== 'string' || entry.length === 0 || entry.length > 512) { + continue + } + if (!ids.includes(entry)) { + ids.push(entry) + } + if (ids.length >= MAX_CLAUDE_LIVE_PTY_SESSION_IDS) { + break + } + } + return ids.toReversed() +} + function normalizeMigrationUnsupportedPtyEntries(value: unknown): MigrationUnsupportedPtyEntry[] { if (!Array.isArray(value)) { return [] @@ -3312,9 +3339,15 @@ export class Store { defaults.workspaceSession ), sshTargets: (parsed.sshTargets ?? []).map(normalizeSshTarget), + deletedSshConfigAliases: Array.isArray(parsed.deletedSshConfigAliases) + ? parsed.deletedSshConfigAliases.filter( + (alias): alias is string => typeof alias === 'string' + ) + : [], sshRemotePtyLeases: (parsed.sshRemotePtyLeases ?? []) .map(normalizeSshRemotePtyLease) .filter((lease): lease is SshRemotePtyLease => lease !== null), + claudeLivePtySessionIds: normalizeClaudeLivePtySessionIds(parsed.claudeLivePtySessionIds), migrationUnsupportedPtyEntries: normalizeMigrationUnsupportedPtyEntries( parsed.migrationUnsupportedPtyEntries ), @@ -5914,6 +5947,65 @@ export class Store { this.scheduleSave() } + // ── Live Claude PTY sessions ─────────────────────────────────────── + + getClaudeLivePtySessionIds(): string[] { + return [...(this.state.claudeLivePtySessionIds ?? [])] + } + + addClaudeLivePtySessionId(sessionId: string): void { + if (sessionId.length === 0 || sessionId.length > 512) { + return + } + const ids = this.state.claudeLivePtySessionIds ?? [] + if (ids.includes(sessionId)) { + return + } + // Why: drop the oldest entry at the cap — stale ids are pruned against the + // daemon at startup anyway, so recency is the only thing worth keeping. + this.state.claudeLivePtySessionIds = [...ids, sessionId].slice(-MAX_CLAUDE_LIVE_PTY_SESSION_IDS) + // Why: flush synchronously — a force-quit right after a Claude spawn must + // still seed the live-PTY gate on the next launch. + this.flush() + } + + removeClaudeLivePtySessionId(sessionId: string): void { + const ids = this.state.claudeLivePtySessionIds ?? [] + if (!ids.includes(sessionId)) { + return + } + this.state.claudeLivePtySessionIds = ids.filter((id) => id !== sessionId) + this.scheduleSave() + } + + getDeletedSshConfigAliases(): string[] { + return [...(this.state.deletedSshConfigAliases ?? [])] + } + + addDeletedSshConfigAlias(alias: string): void { + this.state.deletedSshConfigAliases ??= [] + if (!this.state.deletedSshConfigAliases.includes(alias)) { + this.state.deletedSshConfigAliases.push(alias) + this.scheduleSave() + } + } + + removeDeletedSshConfigAlias(alias: string): void { + const current = this.state.deletedSshConfigAliases + if (!current || !current.includes(alias)) { + return + } + this.state.deletedSshConfigAliases = current.filter((entry) => entry !== alias) + this.scheduleSave() + } + + clearDeletedSshConfigAliases(): void { + if (this.state.deletedSshConfigAliases && this.state.deletedSshConfigAliases.length > 0) { + this.state.deletedSshConfigAliases = [] + this.scheduleSave() + } + } + // ── SSH Remote PTY Leases ────────────────────────────────────────── getSshRemotePtyLeases(targetId?: string): SshRemotePtyLease[] { diff --git a/src/main/project-groups/nested-repo-discovery.test.ts b/src/main/project-groups/nested-repo-discovery.test.ts index 0d016cf1c..f38e29ea5 100644 --- a/src/main/project-groups/nested-repo-discovery.test.ts +++ b/src/main/project-groups/nested-repo-discovery.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: nested scan behavior is intentionally covered in one -suite so traversal order, ignore rules, cancellation, and filesystem fixtures stay aligned. */ import { mkdtemp, mkdir, writeFile, rm, symlink } from 'node:fs/promises' import { join } from 'node:path' import { tmpdir } from 'node:os' diff --git a/src/main/providers/ssh-filesystem-provider-stream.test.ts b/src/main/providers/ssh-filesystem-provider-stream.test.ts index 29daf5af5..b66b56335 100644 --- a/src/main/providers/ssh-filesystem-provider-stream.test.ts +++ b/src/main/providers/ssh-filesystem-provider-stream.test.ts @@ -80,7 +80,8 @@ describe('SshFilesystemProvider readFile streaming', () => { const result = await provider.readFile('/home/user/file.txt') expect(mux.request).toHaveBeenCalledWith('fs.readFileStream', { - filePath: '/home/user/file.txt' + filePath: '/home/user/file.txt', + flowControl: 'ack' }) expect(result).toEqual({ content: text, isBinary: false }) }) diff --git a/src/main/providers/ssh-filesystem-provider.test.ts b/src/main/providers/ssh-filesystem-provider.test.ts index f008c380d..6d4170209 100644 --- a/src/main/providers/ssh-filesystem-provider.test.ts +++ b/src/main/providers/ssh-filesystem-provider.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: SSH filesystem provider coverage keeps relay fallback, -SFTP binary writes, watch fan-out, and provider lifecycle tests together so -transport parity regressions are visible in one suite. */ import { describe, expect, it, vi, beforeEach } from 'vitest' import { SshFilesystemProvider } from './ssh-filesystem-provider' import { JsonRpcErrorCode } from '../ssh/relay-protocol' diff --git a/src/main/runtime/mobile-subscribe-integration.test.ts b/src/main/runtime/mobile-subscribe-integration.test.ts index f2cf2587d..3d36716dd 100644 --- a/src/main/runtime/mobile-subscribe-integration.test.ts +++ b/src/main/runtime/mobile-subscribe-integration.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: integration tests cover the full mobile subscribe lifecycle across many scenarios; splitting would scatter related assertions. */ /** * Integration tests for the server-authoritative mobile subscribe lifecycle. * Tests handleMobileSubscribe, handleMobileUnsubscribe, applyMobileDisplayMode, diff --git a/src/main/runtime/orca-runtime-browser.test.ts b/src/main/runtime/orca-runtime-browser.test.ts index b3edc6cdb..7c55f7532 100644 --- a/src/main/runtime/orca-runtime-browser.test.ts +++ b/src/main/runtime/orca-runtime-browser.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: browser runtime command tests share one -mocked BrowserManager/agent-browser bridge so page wake and registration -ordering regressions stay in one boundary-focused suite. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { AgentBrowserBridge } from '../browser/agent-browser-bridge' import type { RuntimeBrowserCommandHost } from './orca-runtime-browser' diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index 48892c2d2..d2655b3d3 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -856,6 +856,8 @@ function antigravityPromptBeforeModelReadyScreen(model = 'Gemini 3.5 Flash (High class InMemoryOrchestrationMessages { private sequence = 0 + private activeCoordinatorRun: { coordinator_handle: string } | null = null + private messages: MessageRow[] = [] insertMessage(msg: { @@ -903,6 +905,14 @@ class InMemoryOrchestrationMessages { return this.getUnreadMessages(toHandle, types).filter((message) => !message.delivered_at) } + setActiveCoordinatorRun(run: { coordinator_handle: string } | null): void { + this.activeCoordinatorRun = run + } + + getActiveCoordinatorRun(): { coordinator_handle: string } | null { + return this.activeCoordinatorRun + } + markAsDelivered(ids: string[]): void { const deliveredIds = new Set(ids) for (const message of this.messages) { @@ -10880,6 +10890,7 @@ describe('OrcaRuntimeService', () => { const [terminal] = (await runtime.listTerminals()).terminals runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) + db.setActiveCoordinatorRun({ coordinator_handle: 'term_other' }) db.insertMessage({ from: 'term_sender', to: terminal.handle, subject: 'hello' }) runtime.deliverPendingMessagesForHandle(terminal.handle) @@ -10905,6 +10916,52 @@ describe('OrcaRuntimeService', () => { } }) + it('injects pending orchestration messages into the active coordinator without auto-submitting', async () => { + vi.useFakeTimers() + try { + const runtime = new OrcaRuntimeService(store) + const db = new InMemoryOrchestrationMessages() + const write = vi.fn().mockReturnValue(true) + setInMemoryOrchestrationMessages(runtime, db) + runtime.setPtyController({ + write, + kill: vi.fn(), + getForegroundProcess: async () => null + }) + syncSinglePty(runtime) + + const [terminal] = (await runtime.listTerminals()).terminals + runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 100) + runtime.onPtyData('pty-1', '\x1b]0;Codex done\x07', 101) + db.setActiveCoordinatorRun({ coordinator_handle: terminal.handle }) + db.insertMessage({ + from: 'term_sender', + to: terminal.handle, + subject: 'hello coordinator' + }) + + runtime.deliverPendingMessagesForHandle(terminal.handle) + + expect(write).toHaveBeenCalledWith( + 'pty-1', + expect.stringContaining('Subject: hello coordinator') + ) + await vi.advanceTimersByTimeAsync(500) + const submitWrites = write.mock.calls.filter( + ([ptyId, text]) => ptyId === 'pty-1' && text === '\r' + ) + expect(submitWrites).toHaveLength(0) + + const unread = db.getUnreadMessages(terminal.handle) + expect(unread).toHaveLength(1) + expect(unread[0].read).toBe(0) + expect(unread[0].delivered_at).not.toBeNull() + db.close() + } finally { + vi.useRealTimers() + } + }) + it('injects pending orchestration messages into Cursor Agent without auto-submitting', async () => { vi.useFakeTimers() try { diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 2e87e28e6..e6a5bcbfa 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -19936,6 +19936,12 @@ export class OrcaRuntimeService { return } + // The active coordinator prompt is user-owned input, so push-on-idle must not synthesize Enter. + if (this._orchestrationDb.getActiveCoordinatorRun()?.coordinator_handle === handle) { + this._orchestrationDb.markAsDelivered(unread.map((m) => m.id)) + return + } + const tabTitle = this.tabs.get(leaf.tabId)?.title if (isCursorAgentOrchestrationTarget(leaf, tabTitle)) { // Why: Cursor Agent treats injected PTY text as editable prompt input. diff --git a/src/main/runtime/orchestration/coordinator.test.ts b/src/main/runtime/orchestration/coordinator.test.ts index 5ec2b914a..a10c4ea20 100644 --- a/src/main/runtime/orchestration/coordinator.test.ts +++ b/src/main/runtime/orchestration/coordinator.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: coordinator tests cover dispatch, DAG ordering, escalation, decision gates, concurrency, and stop — splitting by category would scatter shared setup without improving clarity. */ import { afterEach, describe, expect, it } from 'vitest' import { OrchestrationDb } from './db' import { reconcileLifecycleMessage } from './lifecycle-reconciliation' diff --git a/src/main/runtime/orchestration/db.test.ts b/src/main/runtime/orchestration/db.test.ts index 3f2c12ef2..8f43298a9 100644 --- a/src/main/runtime/orchestration/db.test.ts +++ b/src/main/runtime/orchestration/db.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: DB tests cover messages, tasks, dispatch contexts, decision gates, coordinator runs, and lifecycle in one suite to share the createDb() helper and afterEach cleanup. */ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/runtime/rpc/methods/files.test.ts b/src/main/runtime/rpc/methods/files.test.ts index 7aea0b7c7..7282489c7 100644 --- a/src/main/runtime/rpc/methods/files.test.ts +++ b/src/main/runtime/rpc/methods/files.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: file RPC routing coverage stays together so -the dispatcher contract for read, write, mutation, and watch methods is easy to audit. */ import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' import type { RpcRequest } from '../core' diff --git a/src/main/runtime/rpc/methods/git.test.ts b/src/main/runtime/rpc/methods/git.test.ts index 850276906..bb69dfc59 100644 --- a/src/main/runtime/rpc/methods/git.test.ts +++ b/src/main/runtime/rpc/methods/git.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: git RPC methods share one dispatcher fixture, and keeping the contract cases together makes method coverage easy to audit. */ import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' import type { RpcRequest } from '../core' diff --git a/src/main/runtime/rpc/methods/github.test.ts b/src/main/runtime/rpc/methods/github.test.ts index 8330a1d0b..2135507c3 100644 --- a/src/main/runtime/rpc/methods/github.test.ts +++ b/src/main/runtime/rpc/methods/github.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: runtime GitHub RPC methods share one dispatcher suite so repo-scoped and Project-scoped contract coverage cannot drift. */ import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' import type { RpcRequest } from '../core' diff --git a/src/main/runtime/rpc/methods/gitlab.test.ts b/src/main/runtime/rpc/methods/gitlab.test.ts index cb88fbff7..ca429f3d4 100644 --- a/src/main/runtime/rpc/methods/gitlab.test.ts +++ b/src/main/runtime/rpc/methods/gitlab.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: one routing test exercises the full GitLab RPC surface so provider parity regressions show up in a single contract fixture. */ import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from '../dispatcher' import type { RpcRequest } from '../core' diff --git a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts b/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts index dfd185b33..adad88dde 100644 --- a/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts +++ b/src/main/runtime/rpc/terminal-subscribe-buffer.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: terminal subscribe buffering tests share a live dispatcher harness; splitting would duplicate stream setup and weaken lifecycle coverage. */ import { describe, expect, it, vi } from 'vitest' import { RpcDispatcher } from './dispatcher' import type { RpcRequest } from './core' diff --git a/src/main/runtime/rpc/ws-transport.test.ts b/src/main/runtime/rpc/ws-transport.test.ts index 775050fe8..b9f4c94dd 100644 --- a/src/main/runtime/rpc/ws-transport.test.ts +++ b/src/main/runtime/rpc/ws-transport.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: these tests exercise one stateful transport - boundary across connection lifecycle, heartbeat, pre-auth timeout, and - shutdown behavior; splitting the setup would obscure the shared invariants. */ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/main/runtime/rpc/ws-transport.ts b/src/main/runtime/rpc/ws-transport.ts index 53a776f39..37f6094b5 100644 --- a/src/main/runtime/rpc/ws-transport.ts +++ b/src/main/runtime/rpc/ws-transport.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: the WebSocket transport owns connection - admission, heartbeat, pre-auth timeout, and client-id cleanup together; those - invariants are easier to audit in one transport boundary. */ // Why: the WebSocket transport enables mobile clients to connect to the Orca // runtime over the local network. When TLS cert/key are provided it uses wss:// // to prevent passive sniffing; otherwise it falls back to plain ws://. Per-device diff --git a/src/main/runtime/runtime-rpc.ts b/src/main/runtime/runtime-rpc.ts index 59efa6abf..a5418500c 100644 --- a/src/main/runtime/runtime-rpc.ts +++ b/src/main/runtime/runtime-rpc.ts @@ -153,6 +153,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([ 'files.openDiff', 'files.read', 'files.readChunk', + 'files.readDir', 'files.readPreview', 'files.readTerminalArtifact', 'files.readTerminalArtifactPreview', diff --git a/src/main/source-control/hosted-review-creation.test.ts b/src/main/source-control/hosted-review-creation.test.ts index e50731c85..c03447d40 100644 --- a/src/main/source-control/hosted-review-creation.test.ts +++ b/src/main/source-control/hosted-review-creation.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: hosted review creation permutations share large mocks; splitting would hide branch-specific expectations. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { diff --git a/src/main/ssh/relay-protocol.test.ts b/src/main/ssh/relay-protocol.test.ts index 8369c3c02..c4e9f0897 100644 --- a/src/main/ssh/relay-protocol.test.ts +++ b/src/main/ssh/relay-protocol.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { HEADER_LENGTH, MessageType, @@ -160,6 +160,74 @@ describe('FrameDecoder', () => { expect(frames).toHaveLength(1) expect(frames[0].id).toBe(2) }) + + it('decodes frames fed one byte at a time (worst-case boundary straddling)', () => { + const frames: DecodedFrame[] = [] + const decoder = new FrameDecoder((f) => frames.push(f)) + + const frame1 = encodeFrame(MessageType.Regular, 1, 0, Buffer.from('first payload')) + const frame2 = encodeFrame(MessageType.Regular, 2, 1, Buffer.from('second')) + const combined = Buffer.concat([frame1, frame2]) + + for (let i = 0; i < combined.length; i += 1) { + decoder.feed(combined.subarray(i, i + 1)) + } + + expect(frames).toHaveLength(2) + expect(frames[0].payload.toString()).toBe('first payload') + expect(frames[1].id).toBe(2) + expect(frames[1].payload.toString()).toBe('second') + }) + + it('skips an oversized frame fed in odd-sized chunks and resynchronizes', () => { + const errors: Error[] = [] + const frames: DecodedFrame[] = [] + const decoder = new FrameDecoder( + (f) => frames.push(f), + (err) => errors.push(err) + ) + + const oversizedLength = 17 * 1024 * 1024 + const header = Buffer.alloc(HEADER_LENGTH) + header[0] = MessageType.Regular + header.writeUInt32BE(1, 1) + header.writeUInt32BE(0, 5) + header.writeUInt32BE(oversizedLength, 9) + const oversized = Buffer.concat([header, Buffer.alloc(oversizedLength)]) + const valid = encodeFrame(MessageType.Regular, 2, 0, Buffer.from('after')) + const combined = Buffer.concat([oversized, valid]) + + const chunkSize = 1024 * 1024 - 7 + for (let i = 0; i < combined.length; i += chunkSize) { + decoder.feed(combined.subarray(i, i + chunkSize)) + } + + expect(errors).toHaveLength(1) + expect(frames).toHaveLength(1) + expect(frames[0].payload.toString()).toBe('after') + }) + + it('never rebuilds the buffered stream per feed while assembling a large frame', () => { + // Regression: feed() used Buffer.concat([buffered, chunk]) per data event, + // re-copying the whole backlog for every TCP chunk — O(n²) memcpy on the + // Electron main thread while fs.streamChunk frames arrive (SSH typing lag). + const frames: DecodedFrame[] = [] + const decoder = new FrameDecoder((f) => frames.push(f)) + const frame = encodeFrame(MessageType.Regular, 1, 0, Buffer.alloc(512 * 1024, 0x61)) + + const concatSpy = vi.spyOn(Buffer, 'concat') + try { + for (let i = 0; i < frame.length; i += 32 * 1024) { + decoder.feed(frame.subarray(i, i + 32 * 1024)) + } + } finally { + concatSpy.mockRestore() + } + + expect(frames).toHaveLength(1) + expect(frames[0].payload.length).toBe(512 * 1024) + expect(concatSpy).not.toHaveBeenCalled() + }) }) describe('parseJsonRpcMessage', () => { diff --git a/src/main/ssh/relay-protocol.ts b/src/main/ssh/relay-protocol.ts index 3b8b63af1..db57c4d19 100644 --- a/src/main/ssh/relay-protocol.ts +++ b/src/main/ssh/relay-protocol.ts @@ -127,7 +127,13 @@ export type DecodedFrame = { * Incremental frame parser. Feed it chunks of data; it emits complete frames. */ export class FrameDecoder { - private buffer = Buffer.alloc(0) + // Why: feed() runs on the Electron main thread for every SSH channel data + // event. Rebuilding one contiguous buffer per feed (Buffer.concat) re-copies + // every already-buffered byte for each incoming ~32KB TCP chunk — O(n²) per + // large frame (a 340KB fs.streamChunk frame cost ~2MB of memcpy). A chunk + // list assembles each frame exactly once instead. + private chunks: Buffer[] = [] + private bufferedLength = 0 private onFrame: (frame: DecodedFrame) => void private onError: ((err: Error) => void) | null @@ -137,21 +143,31 @@ export class FrameDecoder { } feed(chunk: Buffer | Uint8Array): void { - this.buffer = Buffer.concat([this.buffer, chunk]) + const buf = Buffer.isBuffer(chunk) + ? chunk + : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + if (buf.length > 0) { + this.chunks.push(buf) + this.bufferedLength += buf.length + } - while (this.buffer.length >= HEADER_LENGTH) { - const length = this.buffer.readUInt32BE(9) + while (this.bufferedLength >= HEADER_LENGTH) { + const header = this.peekBytes(HEADER_LENGTH) + const length = header.readUInt32BE(9) const totalLength = HEADER_LENGTH + length + if (this.bufferedLength < totalLength) { + // Not fully received yet (also holds oversized frames until they can + // be skipped whole, keeping the decoder synchronized). + break + } + // Why: throwing here would leave the buffer in a partially consumed // state — subsequent feed() calls would try to parse leftover payload // bytes as a new header, corrupting every future frame. Instead we // skip the entire oversized frame so the decoder stays synchronized. if (length > MAX_MESSAGE_SIZE) { - if (this.buffer.length < totalLength) { - break - } - this.buffer = this.buffer.subarray(totalLength) + this.discardBytes(totalLength) const err = new Error(`Frame payload too large: ${length} bytes — discarded`) if (this.onError) { this.onError(err) @@ -159,24 +175,83 @@ export class FrameDecoder { continue } - if (this.buffer.length < totalLength) { - break - } - + const framed = this.takeBytes(totalLength) const frame: DecodedFrame = { - type: this.buffer[0], - id: this.buffer.readUInt32BE(1), - ack: this.buffer.readUInt32BE(5), - payload: this.buffer.subarray(HEADER_LENGTH, totalLength) + type: framed[0], + id: framed.readUInt32BE(1), + ack: framed.readUInt32BE(5), + payload: framed.subarray(HEADER_LENGTH, totalLength) } - - this.buffer = this.buffer.subarray(totalLength) this.onFrame(frame) } } reset(): void { - this.buffer = Buffer.alloc(0) + this.chunks = [] + this.bufferedLength = 0 + } + + /** View of the first `count` buffered bytes without consuming them. */ + private peekBytes(count: number): Buffer { + const first = this.chunks[0] + if (first.length >= count) { + return first + } + const out = Buffer.allocUnsafe(count) + let copied = 0 + for (const part of this.chunks) { + copied += part.copy(out, copied, 0, Math.min(part.length, count - copied)) + if (copied >= count) { + break + } + } + return out + } + + /** Consume and return the first `count` buffered bytes (single copy). */ + private takeBytes(count: number): Buffer { + const first = this.chunks[0] + if (first.length === count) { + this.chunks.shift() + this.bufferedLength -= count + return first + } + if (first.length > count) { + this.chunks[0] = first.subarray(count) + this.bufferedLength -= count + return first.subarray(0, count) + } + const out = Buffer.allocUnsafe(count) + let copied = 0 + while (copied < count) { + const part = this.chunks[0] + const take = Math.min(part.length, count - copied) + part.copy(out, copied, 0, take) + copied += take + if (take === part.length) { + this.chunks.shift() + } else { + this.chunks[0] = part.subarray(take) + } + } + this.bufferedLength -= count + return out + } + + /** Consume the first `count` buffered bytes without assembling them. */ + private discardBytes(count: number): void { + let remaining = count + while (remaining > 0) { + const part = this.chunks[0] + if (part.length <= remaining) { + this.chunks.shift() + remaining -= part.length + } else { + this.chunks[0] = part.subarray(remaining) + remaining = 0 + } + } + this.bufferedLength -= count } } diff --git a/src/main/ssh/ssh-channel-multiplexer.test.ts b/src/main/ssh/ssh-channel-multiplexer.test.ts index f0576a65f..8c56ae145 100644 --- a/src/main/ssh/ssh-channel-multiplexer.test.ts +++ b/src/main/ssh/ssh-channel-multiplexer.test.ts @@ -1,5 +1,3 @@ -/* oxlint-disable max-lines -- Why: keeps the mux protocol lifecycle harness - together across request, notification, keepalive, and disposal cases. */ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { SshChannelMultiplexer, type MultiplexerTransport } from './ssh-channel-multiplexer' import { encodeFrame, MessageType, HEADER_LENGTH, encodeKeepAliveFrame } from './relay-protocol' diff --git a/src/main/ssh/ssh-config-parser.test.ts b/src/main/ssh/ssh-config-parser.test.ts index 5999c1c96..f550c833a 100644 --- a/src/main/ssh/ssh-config-parser.test.ts +++ b/src/main/ssh/ssh-config-parser.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: SSH config parsing fixtures cover OpenSSH file parsing and ssh -G output together so import and connection resolution stay aligned. */ import { describe, expect, it, vi } from 'vitest' import { join } from 'node:path' import { parseSshConfig, sshConfigHostsToTargets, parseSshGOutput } from './ssh-config-parser' diff --git a/src/main/ssh/ssh-connection-store.test.ts b/src/main/ssh/ssh-connection-store.test.ts index 8e3e347d7..f1bf80d17 100644 --- a/src/main/ssh/ssh-connection-store.test.ts +++ b/src/main/ssh/ssh-connection-store.test.ts @@ -14,6 +14,7 @@ vi.mock('./ssh-config-parser', () => ({ function createMockStore() { const targets: SshTarget[] = [] + let deletedAliases: string[] = [] return { getSshTargets: vi.fn(() => [...targets]), @@ -32,6 +33,18 @@ function createMockStore() { if (idx !== -1) { targets.splice(idx, 1) } + }), + getDeletedSshConfigAliases: vi.fn(() => [...deletedAliases]), + addDeletedSshConfigAlias: vi.fn((alias: string) => { + if (!deletedAliases.includes(alias)) { + deletedAliases.push(alias) + } + }), + removeDeletedSshConfigAlias: vi.fn((alias: string) => { + deletedAliases = deletedAliases.filter((entry) => entry !== alias) + }), + clearDeletedSshConfigAliases: vi.fn(() => { + deletedAliases = [] }) } } @@ -324,4 +337,106 @@ describe('SshConnectionStore', () => { expect(result).toEqual([]) }) }) + + describe('deleted config host tombstones', () => { + function candidate(overrides: Partial & { configHost: string }): SshTarget { + return { + id: `tmp-${overrides.configHost}`, + label: overrides.configHost, + host: `${overrides.configHost}.example.com`, + port: 22, + username: '', + ...overrides + } + } + + // PRIMARY regression: deleting a config-sourced host must not let the next + // ~/.ssh/config sync resurrect it. + it('tombstones a deleted config-sourced host so re-import skips it', () => { + mockStore.addSshTarget({ + id: 'ssh-1', + label: 'mini', + configHost: 'mini', + host: 'mini.example.com', + port: 22, + username: 'ping', + source: 'ssh-config' + }) + + sshStore.removeTarget('ssh-1') + expect(mockStore.addDeletedSshConfigAlias).toHaveBeenCalledWith('mini') + + loadUserSshConfigMock.mockReturnValue([{ host: 'mini' }]) + sshConfigHostsToTargetsMock.mockReturnValue([candidate({ configHost: 'mini' })]) + + const result = sshStore.importFromSshConfig() + + expect(mockStore.addSshTarget).toHaveBeenCalledTimes(1) // only the seed insert + expect(result).toEqual([]) + }) + + it('does not tombstone a manual target on delete', () => { + mockStore.addSshTarget({ + id: 'ssh-1', + label: 'mini', + configHost: 'mini', + host: 'mini.example.com', + port: 22, + username: 'ping', + source: 'manual' + }) + + sshStore.removeTarget('ssh-1') + expect(mockStore.addDeletedSshConfigAlias).not.toHaveBeenCalled() + }) + + it('re-adding a deleted host reclaims its alias so sync stops suppressing it', () => { + mockStore.addDeletedSshConfigAlias('mini') + + sshStore.addTarget({ + label: 'mini', + configHost: 'mini', + host: '10.0.0.2', + port: 22, + username: 'ping' + }) + expect(mockStore.removeDeletedSshConfigAlias).toHaveBeenCalledWith('mini') + + loadUserSshConfigMock.mockReturnValue([{ host: 'mini' }]) + sshConfigHostsToTargetsMock.mockReturnValue([candidate({ configHost: 'mini' })]) + // Alias reclaimed, but it is now a manual target — still not re-inserted. + const result = sshStore.importFromSshConfig() + expect(result).toEqual([]) + }) + + it('editing a target reclaims its alias from the deleted set', () => { + mockStore.addSshTarget({ + id: 'ssh-1', + label: 'mini', + configHost: 'mini', + host: 'mini.example.com', + port: 22, + username: 'ping', + source: 'ssh-config' + }) + mockStore.addDeletedSshConfigAlias('mini') + + sshStore.updateTarget('ssh-1', { port: 2222, source: 'manual' }) + expect(mockStore.removeDeletedSshConfigAlias).toHaveBeenCalledWith('mini') + }) + + it('reAdopt clears all tombstones and re-imports the deleted host', () => { + mockStore.addDeletedSshConfigAlias('mini') + loadUserSshConfigMock.mockReturnValue([{ host: 'mini' }]) + sshConfigHostsToTargetsMock.mockReturnValue([candidate({ configHost: 'mini' })]) + + const result = sshStore.importFromSshConfig({ reAdopt: true }) + + expect(mockStore.clearDeletedSshConfigAliases).toHaveBeenCalled() + expect(mockStore.addSshTarget).toHaveBeenCalledWith( + expect.objectContaining({ configHost: 'mini', source: 'ssh-config' }) + ) + expect(result).toHaveLength(1) + }) + }) }) diff --git a/src/main/ssh/ssh-connection-store.ts b/src/main/ssh/ssh-connection-store.ts index d65bd42b9..975da8cdb 100644 --- a/src/main/ssh/ssh-connection-store.ts +++ b/src/main/ssh/ssh-connection-store.ts @@ -23,6 +23,9 @@ export class SshConnectionStore { source: target.source ?? 'manual', id: `ssh-${Date.now()}-${Math.random().toString(36).slice(2, 8)}` } + // Why: re-adding a host the user previously deleted is an explicit intent to + // keep it — lift any tombstone so config sync stops suppressing this alias. + this.reclaimAlias(full.configHost ?? full.label) this.store.addSshTarget(full) return full } @@ -51,19 +54,49 @@ export class SshConnectionStore { } updateTarget(id: string, updates: Partial>): SshTarget | null { - return this.store.updateSshTarget(id, updates) + const updated = this.store.updateSshTarget(id, updates) + if (updated) { + // Why: actively editing a target reclaims its alias from the deleted set, + // so an edit can never leave the host tombstoned. + this.reclaimAlias(updated.configHost ?? updated.label) + } + return updated } removeTarget(id: string): void { + const target = this.store.getSshTarget(id) + // Why: deleting a config-managed target must record a tombstone; otherwise + // the next ~/.ssh/config sync re-inserts it verbatim (the config entry still + // exists on disk) and the host reappears. Manual targets need no tombstone — + // sync never re-adds them. + if (target && isConfigManagedTarget(target)) { + const alias = target.configHost ?? target.label + if (alias) { + this.store.addDeletedSshConfigAlias(alias) + } + } this.store.removeSshTarget(id) } + private reclaimAlias(alias: string | undefined): void { + if (alias) { + this.store.removeDeletedSshConfigAlias(alias) + } + } + /** * Sync targets from ~/.ssh/config: insert new hosts, update existing * config-sourced ones in place (so a rotated port takes effect), never touch * manual targets. Returns the inserted and updated targets. */ - importFromSshConfig(): SshTarget[] { + importFromSshConfig(options?: { reAdopt?: boolean }): SshTarget[] { + // Why: the explicit Import action re-adopts every config host, so it clears + // all tombstones first. The passive on-open sync passes no flag and keeps + // deleted hosts suppressed. + if (options?.reAdopt) { + this.store.clearDeletedSshConfigAliases() + } + const deletedAliases = new Set(this.store.getDeletedSshConfigAliases()) const configHosts = loadUserSshConfig() const existingTargets = this.store.getSshTargets() // Map config-managed targets (and legacy targets that strongly look like @@ -102,6 +135,11 @@ export class SshConnectionStore { // A manual target owns this alias — never clobber it. continue } + if (deletedAliases.has(alias)) { + // The user deleted this config host — stay deleted until they re-add it + // or re-adopt config explicitly. + continue + } if (processedAliases.has(alias)) { continue } @@ -156,6 +194,16 @@ export function isRuntimeOwnedSshTarget(target: SshTarget): boolean { return target.owner?.type === 'on-demand-runtime' } +function isConfigManagedTarget(target: SshTarget): boolean { + // Why: a target is subject to config sync (and therefore needs a tombstone on + // delete) when it is explicitly config-sourced, or a legacy import that sync + // still adopts. Manual targets are excluded — sync never re-adds them. + return ( + target.source === 'ssh-config' || + (target.source === undefined && isLegacyConfigImportTarget(target)) + ) +} + function isLegacyConfigImportTarget(target: SshTarget): boolean { const alias = target.configHost ?? target.label // Why: legacy manual and imported targets both lack `source`. Only adopt the diff --git a/src/main/ssh/ssh-connection-utils.test.ts b/src/main/ssh/ssh-connection-utils.test.ts index ed10780ca..0c578cff7 100644 --- a/src/main/ssh/ssh-connection-utils.test.ts +++ b/src/main/ssh/ssh-connection-utils.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: SSH connection utility tests share mocked filesystem and environment setup across auth, proxy, and retry helpers. */ import { EventEmitter } from 'node:events' import { afterEach, describe, expect, it, vi, beforeEach } from 'vitest' import { join } from 'node:path' diff --git a/src/main/ssh/ssh-filesystem-stream-reader.ts b/src/main/ssh/ssh-filesystem-stream-reader.ts index cda490c85..2147ed0ef 100644 --- a/src/main/ssh/ssh-filesystem-stream-reader.ts +++ b/src/main/ssh/ssh-filesystem-stream-reader.ts @@ -148,6 +148,10 @@ export async function readFileViaStream( expectedSeq += 1 receivedChunks += 1 bytesReceived += decoded.length + // Why: credit-based flow control — the relay caps unacked chunks so bulk + // stream frames cannot queue unbounded ahead of interactive pty.data + // frames on the shared SSH channel. Old relays ignore this notification. + mux.notify('fs.streamAck', { streamId: id, seq }) } const handleEnd = (params: Record): void => { @@ -260,7 +264,9 @@ export async function readFileViaStream( unsubscribers.push(onDispose) void mux - .request('fs.readFileStream', { filePath }) + // Why: flowControl declares this client acks each chunk, letting a new + // relay pace the pump. Old relays ignore the extra param and flood. + .request('fs.readFileStream', { filePath, flowControl: 'ack' }) .then((rawMetadata) => { if (settled) { return diff --git a/src/main/ssh/ssh-relay-native-deps-install.test.ts b/src/main/ssh/ssh-relay-native-deps-install.test.ts index 0cedf1aff..2b63b3a2d 100644 --- a/src/main/ssh/ssh-relay-native-deps-install.test.ts +++ b/src/main/ssh/ssh-relay-native-deps-install.test.ts @@ -1,8 +1,3 @@ -/* eslint-disable max-lines -- Why: pinning every layer that should have - caught the original "node-pty not available" bug (chained shell, package - ordering, probe shape, channel-failure surfacing, .bashrc-noise immunity, - platform-tagged logs) requires keeping these scenarios in one file so the - shared mock connection and exec-response fixture stay aligned. */ // Why: regression coverage for the install-probe contract. The original // "node-pty is not available" bug shipped because every layer that should // have caught it (chained shell, swallowing catch, dir-only probe) was diff --git a/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts b/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts index 31b357ca0..3de35a65f 100644 --- a/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts +++ b/src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: this integration spec keeps the SSH relay, -agent-hook server, and replay/interrupt ordering fixtures together so regressions -cover the full mux-to-main path. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { Store } from '../persistence' diff --git a/src/main/ssh/ssh-relay-session.test.ts b/src/main/ssh/ssh-relay-session.test.ts index aa616dd15..0dfa2edc8 100644 --- a/src/main/ssh/ssh-relay-session.test.ts +++ b/src/main/ssh/ssh-relay-session.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: relay session tests need one shared mocked -provider/multiplexer harness to cover establish, reconnect, detach, and dispose -state transitions without duplicating brittle setup. */ import { describe, it, expect, vi, beforeEach } from 'vitest' import { SshRelaySession } from './ssh-relay-session' import type { SshConnection } from './ssh-connection' diff --git a/src/main/startup/renderer-heap-headroom.test.ts b/src/main/startup/renderer-heap-headroom.test.ts new file mode 100644 index 000000000..88b1baa0f --- /dev/null +++ b/src/main/startup/renderer-heap-headroom.test.ts @@ -0,0 +1,121 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { computeRendererHeapCeilingMb } from './renderer-heap-headroom' + +vi.mock('electron', () => ({ + app: { + commandLine: { + appendSwitch: vi.fn(), + getSwitchValue: vi.fn(() => '') + } + } +})) + +afterEach(() => { + vi.restoreAllMocks() +}) + +const GIB = 1024 * 1024 * 1024 + +describe('computeRendererHeapCeilingMb', () => { + it('leaves Chromium default (null) below the ~8 GB gate to avoid OS memory pressure', () => { + expect(computeRendererHeapCeilingMb(4 * GIB)).toBeNull() + expect(computeRendererHeapCeilingMb(6 * GIB)).toBeNull() // 6 GB reports ~5.7 GiB + expect(computeRendererHeapCeilingMb(7 * GIB)).toBeNull() // below the 7.5 GiB gate + }) + + it('includes 8 GB machines that report below 8 GiB (Linux MemTotal excludes reserved RAM)', () => { + // A real 8 GB Linux box reports ~7.7 GiB; it must still get the headroom. + expect(computeRendererHeapCeilingMb(7.7 * GIB)).toBe(3072) + expect(computeRendererHeapCeilingMb(7.5 * GIB)).toBe(3072) + }) + + it('raises the ceiling toward the 4 GB pointer-compression cage, floored and capped', () => { + expect(computeRendererHeapCeilingMb(8 * GIB)).toBe(3072) // floor: 8 GB default ~2.2 GB -> 3072 + expect(computeRendererHeapCeilingMb(12 * GIB)).toBe(4096) // 0.4*12 -> 4096 (cage) + expect(computeRendererHeapCeilingMb(16 * GIB)).toBe(4096) // cage cap + expect(computeRendererHeapCeilingMb(128 * GIB)).toBe(4096) // cage cap, never higher + }) + + it('honors a positive ORCA_RENDERER_HEAP_MB override regardless of RAM', () => { + expect(computeRendererHeapCeilingMb(4 * GIB, '5000')).toBe(5000) + expect(computeRendererHeapCeilingMb(128 * GIB, '4096')).toBe(4096) + }) + + it('opts out (null) for default/off/none/0/negative overrides', () => { + for (const value of ['default', 'off', 'none', '0', '-1']) { + expect(computeRendererHeapCeilingMb(16 * GIB, value)).toBeNull() + } + }) + + it('opts out (null) for a fractional override that would floor to 0 (never emits max-old-space-size=0)', () => { + for (const value of ['0.5', '0.9', '0.0001']) { + expect(computeRendererHeapCeilingMb(16 * GIB, value)).toBeNull() + } + }) + + it('falls through to RAM tiers for blank/invalid overrides', () => { + expect(computeRendererHeapCeilingMb(16 * GIB, '')).toBe(4096) + expect(computeRendererHeapCeilingMb(16 * GIB, 'abc')).toBe(4096) + }) + + it('returns null for a non-finite / non-positive RAM reading', () => { + expect(computeRendererHeapCeilingMb(Number.NaN)).toBeNull() + expect(computeRendererHeapCeilingMb(0)).toBeNull() + }) +}) + +describe('enableRendererHeapHeadroom', () => { + it('appends --max-old-space-size as a js-flags switch on a RAM-capable machine', async () => { + const { app } = await import('electron') + const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') + + vi.mocked(app.commandLine.appendSwitch).mockClear() + vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('') + + enableRendererHeapHeadroom({ totalMemoryBytes: 16 * GIB, env: {} }) + + expect(app.commandLine.appendSwitch).toHaveBeenCalledWith( + 'js-flags', + '--max-old-space-size=4096' + ) + }) + + it('does not set a switch on low-RAM machines', async () => { + const { app } = await import('electron') + const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') + + vi.mocked(app.commandLine.appendSwitch).mockClear() + vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('') + + enableRendererHeapHeadroom({ totalMemoryBytes: 4 * GIB, env: {} }) + + expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('js-flags', expect.anything()) + }) + + it('preserves an explicit prior --max-old-space-size instead of stacking a second value', async () => { + const { app } = await import('electron') + const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') + + vi.mocked(app.commandLine.appendSwitch).mockClear() + vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('--max-old-space-size=2048') + + enableRendererHeapHeadroom({ totalMemoryBytes: 16 * GIB, env: {} }) + + expect(app.commandLine.appendSwitch).not.toHaveBeenCalledWith('js-flags', expect.anything()) + }) + + it('merges with an unrelated existing js-flags value', async () => { + const { app } = await import('electron') + const { enableRendererHeapHeadroom } = await import('./renderer-heap-headroom') + + vi.mocked(app.commandLine.appendSwitch).mockClear() + vi.mocked(app.commandLine.getSwitchValue).mockReturnValue('--no-opt') + + enableRendererHeapHeadroom({ totalMemoryBytes: 16 * GIB, env: {} }) + + expect(app.commandLine.appendSwitch).toHaveBeenCalledWith( + 'js-flags', + '--no-opt --max-old-space-size=4096' + ) + }) +}) diff --git a/src/main/startup/renderer-heap-headroom.ts b/src/main/startup/renderer-heap-headroom.ts new file mode 100644 index 000000000..78ea8907c --- /dev/null +++ b/src/main/startup/renderer-heap-headroom.ts @@ -0,0 +1,102 @@ +import { app } from 'electron' +import { totalmem } from 'node:os' + +const RENDERER_HEAP_ENV_VAR = 'ORCA_RENDERER_HEAP_MB' +const BYTES_PER_GIB = 1024 * 1024 * 1024 +// Why: Chromium sizes the renderer's V8 old-space heap from a physical-memory +// heuristic (~RAM/4), so an 8 GB machine caps the renderer near ~2.2 GB even +// though V8's pointer-compression cage allows up to ~4 GB. Heavy Orca sessions +// (many agent terminals × scrollback, PR/git caches, React tree) legitimately +// reach that low default and V8 aborts with an OOM — the dominant renderer +// crash in the crash channel. Reclaim the unused headroom up to the 4 GB cage +// on machines that have the RAM. Requests above 4096 are silently capped by the +// pointer-compression cage, so 4096 is the real ceiling — we cannot go higher. +// Machines below ~8 GB keep Chromium's default: raising their ceiling would +// trade a clean OOM for OS memory-pressure kills / swap thrash. +// Why 7.5 not 8: os.totalmem() on Linux reports MemTotal, which excludes +// kernel/firmware-reserved RAM, so a real 8 GB machine reports ~7.7 GiB. Gating +// at exactly 8 would wrongly exclude 8 GB Linux boxes (a crashing population) +// while still cleanly excluding 6 GB machines (which report ~5.7 GiB). +const RENDERER_HEAP_MIN_TOTAL_GIB = 7.5 +const RENDERER_HEAP_RAM_FRACTION = 0.4 +const RENDERER_HEAP_FLOOR_MB = 3072 +// V8 pointer-compression cage hard limit; --max-old-space-size above this is ignored. +const RENDERER_HEAP_CAP_MB = 4096 + +type HeapOverride = number | 'disable' | undefined + +function parseRendererHeapOverrideMb(value: string | undefined): HeapOverride { + if (value === undefined) { + return undefined + } + const normalized = value.trim().toLowerCase() + if (normalized === '') { + return undefined + } + // Why: give operators an explicit opt-out (and E2E a way to pin the default) + // without editing the RAM tiers. + if (normalized === 'default' || normalized === 'off' || normalized === 'none') { + return 'disable' + } + const parsed = Number(normalized) + // Why: ignore an unparseable value (typo) and fall through to the RAM tiers, + // but treat an explicit non-positive number as an opt-out. + if (!Number.isFinite(parsed)) { + return undefined + } + if (parsed <= 0) { + return 'disable' + } + // Why: a fractional value in (0,1) floors to 0, which would emit an invalid + // --max-old-space-size=0. Treat a floored-to-0 override as an opt-out too. + const flooredMb = Math.floor(parsed) + return flooredMb <= 0 ? 'disable' : flooredMb +} + +/** + * Renderer V8 old-space ceiling (MB) to request via --max-old-space-size, or + * null to keep Chromium's physical-memory default. Pure so the RAM tiers and + * the env override are unit-testable without spawning Electron. + */ +export function computeRendererHeapCeilingMb( + totalMemoryBytes: number, + envOverride?: string +): number | null { + const override = parseRendererHeapOverrideMb(envOverride) + if (override === 'disable') { + return null + } + if (typeof override === 'number') { + return override + } + if (!Number.isFinite(totalMemoryBytes) || totalMemoryBytes <= 0) { + return null + } + const totalGib = totalMemoryBytes / BYTES_PER_GIB + if (totalGib < RENDERER_HEAP_MIN_TOTAL_GIB) { + return null + } + const targetMb = Math.floor(totalGib * RENDERER_HEAP_RAM_FRACTION) * 1024 + return Math.min(RENDERER_HEAP_CAP_MB, Math.max(RENDERER_HEAP_FLOOR_MB, targetMb)) +} + +export function enableRendererHeapHeadroom( + options: { totalMemoryBytes?: number; env?: NodeJS.ProcessEnv } = {} +): void { + const totalMemoryBytes = options.totalMemoryBytes ?? totalmem() + const envOverride = (options.env ?? process.env)[RENDERER_HEAP_ENV_VAR] + const ceilingMb = computeRendererHeapCeilingMb(totalMemoryBytes, envOverride) + if (ceilingMb === null) { + return + } + const existing = app.commandLine.getSwitchValue('js-flags') + // Why: respect an explicit --max-old-space-size someone already set (e.g. via + // ELECTRON_EXTRA_LAUNCH_ARGS) instead of stacking a second, ignored value. + if (existing.includes('--max-old-space-size')) { + return + } + const flag = `--max-old-space-size=${ceilingMb}` + // Why: js-flags is process-wide and must be set before app 'ready' so it + // reaches renderer/utility V8 isolates when Chromium spawns them. + app.commandLine.appendSwitch('js-flags', existing ? `${existing} ${flag}` : flag) +} diff --git a/src/main/startup/run-electron-vite-dev.test.ts b/src/main/startup/run-electron-vite-dev.test.ts index 7a30d115b..214656337 100644 --- a/src/main/startup/run-electron-vite-dev.test.ts +++ b/src/main/startup/run-electron-vite-dev.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: this integration-style wrapper suite shares - process cleanup and fake Electron CLI fixtures across related regressions. */ import { existsSync, mkdtempSync, readFileSync, readlinkSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' diff --git a/src/main/terminal-history.test.ts b/src/main/terminal-history.test.ts index c5e8e2ca8..a9750bb60 100644 --- a/src/main/terminal-history.test.ts +++ b/src/main/terminal-history.test.ts @@ -1,7 +1,3 @@ -/* eslint-disable max-lines -- Why: history scoping touches shell detection, env -injection, fallback patching, WSL translation, cleanup, and GC with a TOCTOU age -guard — covering each path in one test file keeps assertions co-located with the -shared mock harness rather than splitting across files. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const { diff --git a/src/main/updater.check-failure.test.ts b/src/main/updater.check-failure.test.ts index 2ecf0c855..1b5c1dfc7 100644 --- a/src/main/updater.check-failure.test.ts +++ b/src/main/updater.check-failure.test.ts @@ -217,4 +217,54 @@ describe('updater check failure handling', () => { await vi.advanceTimersByTimeAsync(ONE_HOUR_MS - THIRTY_SECONDS_MS) expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2) }) + + it('backs off consecutive failing background retries instead of re-checking hourly forever', async () => { + vi.useFakeTimers() + makeBenignCheckFailure('Unable to find latest version on GitHub') + + const sendMock = vi.fn() + const mainWindow = { webContents: { send: sendMock } } + + const { setupAutoUpdater, checkForUpdates } = await import('./updater') + + setupAutoUpdater(mainWindow as never, { getLastUpdateCheckAt: () => Date.now() }) + checkForUpdates() + await vi.advanceTimersByTimeAsync(0) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(1) + + // First retry keeps the fast 1h cadence (release-publishing windows). + await vi.advanceTimersByTimeAsync(ONE_HOUR_MS) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2) + + // Second retry doubles to 2h: nothing at +1h, fires by +2h. + await vi.advanceTimersByTimeAsync(ONE_HOUR_MS) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(ONE_HOUR_MS) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(3) + + // Third retry doubles to 4h. + await vi.advanceTimersByTimeAsync(2 * ONE_HOUR_MS) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(2 * ONE_HOUR_MS) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(4) + + // A completed check resets the backoff to the fast retry. + autoUpdaterMock.checkForUpdates.mockImplementation(() => { + autoUpdaterMock.emit('checking-for-update') + queueMicrotask(() => { + autoUpdaterMock.emit('update-not-available', { version: '1.0.51' }) + }) + return Promise.resolve(null) + }) + checkForUpdates() + await vi.advanceTimersByTimeAsync(0) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(5) + + makeBenignCheckFailure('Unable to find latest version on GitHub') + checkForUpdates() + await vi.advanceTimersByTimeAsync(0) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(6) + await vi.advanceTimersByTimeAsync(ONE_HOUR_MS) + expect(autoUpdaterMock.checkForUpdates).toHaveBeenCalledTimes(7) + }) }) diff --git a/src/main/updater.ts b/src/main/updater.ts index 99553eadf..bc9c9d9b6 100644 --- a/src/main/updater.ts +++ b/src/main/updater.ts @@ -6,6 +6,7 @@ import type { UpdateCheckOptions, UpdateStatus } from '../shared/types' import { killAllPty } from './ipc/pty' import { withUpdaterSpan } from './observability/instrumentation' import { loadElectronAutoUpdater, type ElectronAutoUpdater } from './electron-updater-loader' +import { writeMainThreadDiagnosticMarker } from './diagnostics/main-thread-churn-probe' import { beginMacUpdateDownload, deferMacQuitUntilInstallerReady, @@ -34,6 +35,12 @@ type ReleaseFeedPreflightResult = 'ready' | 'not-available' const AUTO_UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000 const AUTO_UPDATE_RETRY_INTERVAL_MS = 60 * 60 * 1000 +// Why: a persistently-failing feed (blocked domain, proxy, GHE mirror) used +// to re-arm the retry at an exact 1h cadence forever — the recurring hourly +// macOS Performance Diagnostics signature in issue #7576. Double the retry +// delay per consecutive failure up to this cap; any completed check resets. +// Release-publishing windows resolve within the first (still 1h) retry. +const MAX_AUTO_UPDATE_RETRY_INTERVAL_MS = 6 * 60 * 60 * 1000 const NUDGE_POLL_INTERVAL_MS = 30 * 60 * 1000 const NUDGE_ACTIVATION_COOLDOWN_MS = 5 * 60 * 1000 const QUIT_AND_INSTALL_DELAY_MS = 100 @@ -384,6 +391,9 @@ function beginUpdateCheckAttempt(): number { updateCheckAttemptSequence += 1 activeUpdateCheckAttemptId = updateCheckAttemptSequence armUpdateCheckStallTimer(activeUpdateCheckAttemptId) + // Why: issue #7576's warnings recurred at the retry cadence; field captures + // need a timestamp for each check attempt to confirm or rule the updater out. + writeMainThreadDiagnosticMarker('updater-check-attempt') return activeUpdateCheckAttemptId } @@ -690,7 +700,20 @@ export function getUpdateStatus(): UpdateStatus { return currentStatus } +let consecutiveAutomaticRetrySchedules = 0 + function scheduleAutomaticUpdateCheck(delayMs: number): void { + let effectiveDelayMs = delayMs + // All retry-cadence callers (here and updater-events) pass exactly this + // constant, so keying the backoff on it keeps one choke point instead of + // threading a flag through seven schedule sites. + if (delayMs === AUTO_UPDATE_RETRY_INTERVAL_MS) { + effectiveDelayMs = Math.min( + AUTO_UPDATE_RETRY_INTERVAL_MS * 2 ** consecutiveAutomaticRetrySchedules, + MAX_AUTO_UPDATE_RETRY_INTERVAL_MS + ) + consecutiveAutomaticRetrySchedules += 1 + } if (autoUpdateCheckTimer) { clearTimeout(autoUpdateCheckTimer) } @@ -700,10 +723,11 @@ function scheduleAutomaticUpdateCheck(delayMs: number): void { // background attempt scheduled in the main process instead of tying checks // to relaunches or renderer lifetime. runBackgroundUpdateCheck() - }, delayMs) + }, effectiveDelayMs) } function recordCompletedUpdateCheck(): void { + consecutiveAutomaticRetrySchedules = 0 persistLastUpdateCheckAt?.(Date.now()) } diff --git a/src/main/window/attach-main-window-services.test.ts b/src/main/window/attach-main-window-services.test.ts index 192e6e8f7..718711b62 100644 --- a/src/main/window/attach-main-window-services.test.ts +++ b/src/main/window/attach-main-window-services.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: attachMainWindowServices centralizes main-window IPC wiring; keeping its integration-style mocks together avoids brittle cross-file setup. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { Store } from '../persistence' diff --git a/src/main/workspace-space-analysis.test.ts b/src/main/workspace-space-analysis.test.ts index d6b24b3df..bfee52956 100644 --- a/src/main/workspace-space-analysis.test.ts +++ b/src/main/workspace-space-analysis.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: scan, cancellation, SSH fallback, and compaction tests share temp-repo fixtures. */ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index a6cf04e7d..6387f62eb 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -2814,7 +2814,7 @@ export type PreloadApi = { updates: Partial> }) => Promise removeTarget: (args: { id: string }) => Promise - importConfig: () => Promise + importConfig: (args?: { reAdopt?: boolean }) => Promise connect: (args: { targetId: string }) => Promise disconnect: (args: { targetId: string }) => Promise terminateSessions: (args: { targetId: string }) => Promise diff --git a/src/preload/index.ts b/src/preload/index.ts index ba7760a5b..b3dedf9e8 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -3837,7 +3837,8 @@ const api = { removeTarget: (args: { id: string }): Promise => ipcRenderer.invoke('ssh:removeTarget', args), - importConfig: (): Promise => ipcRenderer.invoke('ssh:importConfig'), + importConfig: (args?: { reAdopt?: boolean }): Promise => + ipcRenderer.invoke('ssh:importConfig', args), connect: (args: { targetId: string }): Promise => ipcRenderer.invoke('ssh:connect', args), diff --git a/src/relay/dispatcher.test.ts b/src/relay/dispatcher.test.ts index 5598ae46e..5ab997c9d 100644 --- a/src/relay/dispatcher.test.ts +++ b/src/relay/dispatcher.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: dispatcher behavior is stateful across - primary, socket, timeout, and cancellation paths; keeping fixtures shared - makes regression tests easier to audit. */ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { RelayDispatcher } from './dispatcher' import { @@ -398,4 +395,119 @@ describe('RelayDispatcher', () => { expect(listener).toHaveBeenCalledWith(1) }) + + describe('notifyBulk (bulk lane backpressure)', () => { + it('resolves immediately when the sink accepts the frame', async () => { + const frames: Buffer[] = [] + const bulkDispatcher = new RelayDispatcher((data) => { + frames.push(Buffer.from(data)) + return true + }) + try { + await bulkDispatcher.notifyBulk('bulk.event', { seq: 0 }) + expect(frames).toHaveLength(1) + const frame = decodeFirstFrame(frames[0]) + const msg = JSON.parse(frame.payload.toString()) as JsonRpcNotification + expect(msg.method).toBe('bulk.event') + } finally { + bulkDispatcher.dispose() + } + }) + + it('holds the next bulk frame until the saturated sink drains', async () => { + const frames: Buffer[] = [] + const drainWaiters = new Set<() => void>() + const bulkDispatcher = new RelayDispatcher( + (data) => { + frames.push(Buffer.from(data)) + return false + }, + { waitWriteDrain: (cb) => drainWaiters.add(cb) } + ) + try { + let firstSettled = false + const first = bulkDispatcher.notifyBulk('bulk.event', { seq: 0 }).then(() => { + firstSettled = true + }) + void bulkDispatcher.notifyBulk('bulk.event', { seq: 1 }) + await vi.advanceTimersByTimeAsync(0) + + // First frame written, but its send has not settled and the second + // frame is not admitted while the sink stays saturated. + expect(frames).toHaveLength(1) + expect(firstSettled).toBe(false) + + for (const cb of Array.from(drainWaiters)) { + drainWaiters.delete(cb) + cb() + } + await first + await vi.advanceTimersByTimeAsync(0) + expect(frames).toHaveLength(2) + } finally { + bulkDispatcher.dispose() + } + }) + + it('interactive notify() frames are not gated behind a stalled bulk lane', async () => { + const frames: Buffer[] = [] + const bulkDispatcher = new RelayDispatcher( + (data) => { + frames.push(Buffer.from(data)) + return false + }, + { waitWriteDrain: () => {} } + ) + try { + void bulkDispatcher.notifyBulk('bulk.event', { seq: 0 }) + void bulkDispatcher.notifyBulk('bulk.event', { seq: 1 }) + await vi.advanceTimersByTimeAsync(0) + expect(frames).toHaveLength(1) + + bulkDispatcher.notify('pty.data', { id: 'pty-1', data: 'x' }) + expect(frames).toHaveLength(2) + const msg = JSON.parse( + decodeFirstFrame(frames[1]).payload.toString() + ) as JsonRpcNotification + expect(msg.method).toBe('pty.data') + } finally { + bulkDispatcher.dispose() + } + }) + + it('releases a parked bulk send when the dispatcher is disposed', async () => { + const bulkDispatcher = new RelayDispatcher(() => false, { waitWriteDrain: () => {} }) + const pending = bulkDispatcher.notifyBulk('bulk.event', { seq: 0 }) + await vi.advanceTimersByTimeAsync(0) + bulkDispatcher.dispose() + await expect(pending).resolves.toBeUndefined() + }) + + it('targets only the requested client and resolves for missing clients', async () => { + const primaryFrames: Buffer[] = [] + const secondaryFrames: Buffer[] = [] + const bulkDispatcher = new RelayDispatcher((data) => { + primaryFrames.push(Buffer.from(data)) + return true + }) + try { + const secondaryId = bulkDispatcher.attachClient((data) => { + secondaryFrames.push(Buffer.from(data)) + return true + }) + + await bulkDispatcher.notifyBulk('bulk.event', { seq: 0 }, { clientId: secondaryId }) + expect(primaryFrames).toHaveLength(0) + expect(secondaryFrames).toHaveLength(1) + + await expect( + bulkDispatcher.notifyBulk('bulk.event', { seq: 1 }, { clientId: 999 }) + ).resolves.toBeUndefined() + expect(primaryFrames).toHaveLength(0) + expect(secondaryFrames).toHaveLength(1) + } finally { + bulkDispatcher.dispose() + } + }) + }) }) diff --git a/src/relay/dispatcher.ts b/src/relay/dispatcher.ts index 41809a4d7..427d90e6a 100644 --- a/src/relay/dispatcher.ts +++ b/src/relay/dispatcher.ts @@ -27,10 +27,28 @@ export type MethodHandler = ( export type NotificationHandler = (params: Record, context: RequestContext) => void +/** Sink write. Returning literal `false` signals saturation (Node stream + * semantics); `void`/`true` mean the frame was accepted. */ +export type RelayClientWrite = (data: Buffer) => boolean | void + +export type RelayClientSinkOptions = { + /** One-shot: invoke `cb` once when the sink can accept more data again + * (stream 'drain'), or when the sink is permanently dead (error/close) so + * bulk senders waiting on it never hang. */ + waitWriteDrain?: (cb: () => void) => void +} + type RelayClient = { id: number decoder: FrameDecoder - write: (data: Buffer) => void + write: RelayClientWrite + waitWriteDrain?: (cb: () => void) => void + /** Pending resolvers for bulk sends stalled on sink saturation. Flushed on + * drain, write failure, detach, setWrite, and dispose so no pump hangs. */ + drainWaiters: Set<() => void> + /** Serializes bulk-lane sends per client so at most one bulk frame is + * admitted past the sink's high-water mark at a time. */ + bulkChain: Promise nextOutgoingSeq: number highestReceivedSeq: number generation: number @@ -58,8 +76,8 @@ export class RelayDispatcher { private nextClientId = 1 private nextRequestId = 1 - constructor(write: (data: Buffer) => void) { - this.primaryClient = this.createClient(write) + constructor(write: RelayClientWrite, sinkOptions?: RelayClientSinkOptions) { + this.primaryClient = this.createClient(write, sinkOptions) this.clients.set(this.primaryClient.id, this.primaryClient) this.startKeepalive() } @@ -75,10 +93,14 @@ export class RelayDispatcher { // never acks the new client's frames until the new client's seq catches // up - causing the client's unacked-timeout checker to accumulate stale // timestamps that could eventually fire a false connection-dead signal. - setWrite(write: (data: Buffer) => void): void { + setWrite(write: RelayClientWrite, sinkOptions?: RelayClientSinkOptions): void { this.requestAborts.abortClient(this.primaryClient.id) this.primaryClient.write = write + this.primaryClient.waitWriteDrain = sinkOptions?.waitWriteDrain this.primaryClient.closed = false + // Why: the saturated sink the waiters were parked on no longer exists; + // wake stalled bulk senders so they re-evaluate against the new sink. + this.flushDrainWaiters(this.primaryClient) this.resetClient(this.primaryClient) } @@ -89,14 +111,15 @@ export class RelayDispatcher { this.requestAborts.abortClient(this.primaryClient.id) this.primaryClient.generation++ this.primaryClient.closed = true + this.flushDrainWaiters(this.primaryClient) this.notifyClientDetached(this.primaryClient.id) } // Why: synced remote workspaces can have more than one Orca client attached // to the same relay. Frame sequence numbers and JSON-RPC request ids are per // SSH channel, so each socket client needs independent protocol state. - attachClient(write: (data: Buffer) => void): number { - const client = this.createClient(write) + attachClient(write: RelayClientWrite, sinkOptions?: RelayClientSinkOptions): number { + const client = this.createClient(write, sinkOptions) this.clients.set(client.id, client) return client.id } @@ -109,6 +132,7 @@ export class RelayDispatcher { this.requestAborts.abortClient(clientId) client.generation++ client.closed = true + this.flushDrainWaiters(client) this.clients.delete(clientId) this.notifyClientDetached(clientId) } @@ -165,6 +189,90 @@ export class RelayDispatcher { } } + /** + * Bulk-lane notification. Sends are serialized per client and the returned + * promise resolves only after the sink accepted the frame without reporting + * saturation (or the client went away). Bulk producers (file streams) await + * this between frames so interactive frames (pty.data echo) never queue + * behind an unbounded backlog on the shared SSH channel. + * + * With `clientId`, the frame goes only to that client — stream chunks have + * exactly one consumer, and broadcasting them would let one slow secondary + * client stall everyone. A missing/closed target resolves immediately; the + * caller's staleness check owns aborting the stream. + */ + notifyBulk( + method: string, + params?: Record, + opts?: { clientId?: number } + ): Promise { + if (this.disposed) { + return Promise.resolve() + } + const msg: JsonRpcNotification = { + jsonrpc: '2.0', + method, + ...(params !== undefined ? { params } : {}) + } + const targets = + opts?.clientId !== undefined + ? [this.clients.get(opts.clientId)].filter((c): c is RelayClient => c !== undefined) + : Array.from(this.clients.values()) + const waits: Promise[] = [] + for (const client of targets) { + if (client.closed) { + continue + } + // Why: the frame is encoded inside the chain step, not at call time — + // sequence numbers must be assigned in actual write order. + const step = client.bulkChain.then(() => { + if (this.disposed || client.closed) { + return + } + const accepted = this.sendFrame(client, msg) + if (accepted === false) { + return this.waitForClientDrain(client) + } + return undefined + }) + client.bulkChain = step.catch(() => {}) + waits.push(step) + } + if (waits.length === 0) { + return Promise.resolve() + } + return Promise.all(waits).then(() => {}) + } + + private waitForClientDrain(client: RelayClient): Promise { + if (this.disposed || client.closed || !client.waitWriteDrain) { + return Promise.resolve() + } + return new Promise((resolve) => { + let settled = false + const finish = (): void => { + if (settled) { + return + } + settled = true + client.drainWaiters.delete(finish) + resolve() + } + client.drainWaiters.add(finish) + try { + client.waitWriteDrain!(finish) + } catch { + finish() + } + }) + } + + private flushDrainWaiters(client: RelayClient): void { + for (const waiter of Array.from(client.drainWaiters)) { + waiter() + } + } + requestPrimary( method: string, params?: Record, @@ -236,14 +344,20 @@ export class RelayDispatcher { // Why: dispose means this relay instance cannot send responses anymore; // abort in-flight request work so stale SSH-side scans/watchers release. this.requestAborts.abortAll() + for (const client of this.clients.values()) { + this.flushDrainWaiters(client) + } } - private createClient(write: (data: Buffer) => void): RelayClient { + private createClient(write: RelayClientWrite, sinkOptions?: RelayClientSinkOptions): RelayClient { const id = this.nextClientId++ const client: RelayClient = { id, decoder: new FrameDecoder((frame) => this.handleFrame(client, frame)), write, + waitWriteDrain: sinkOptions?.waitWriteDrain, + drainWaiters: new Set(), + bulkChain: Promise.resolve(), nextOutgoingSeq: 1, highestReceivedSeq: 0, generation: 0, @@ -387,13 +501,13 @@ export class RelayDispatcher { private sendFrame( client: RelayClient, msg: JsonRpcRequest | JsonRpcResponse | JsonRpcNotification - ): void { + ): boolean | void { if (this.disposed || client.closed) { return } const seq = client.nextOutgoingSeq++ const frame = encodeJsonRpcFrame(msg, seq, client.highestReceivedSeq) - this.writeFrame(client, frame) + return this.writeFrame(client, frame) } private startKeepalive(): void { @@ -416,12 +530,13 @@ export class RelayDispatcher { this.keepaliveTimer.unref() } - private writeFrame(client: RelayClient, frame: Buffer): void { + private writeFrame(client: RelayClient, frame: Buffer): boolean | void { try { - client.write(frame) + return client.write(frame) } catch (err) { client.closed = true client.generation++ + this.flushDrainWaiters(client) if (client !== this.primaryClient) { this.clients.delete(client.id) this.notifyClientDetached(client.id) diff --git a/src/relay/fs-handler-file-read.ts b/src/relay/fs-handler-file-read.ts index 45a0685b8..003172c08 100644 --- a/src/relay/fs-handler-file-read.ts +++ b/src/relay/fs-handler-file-read.ts @@ -1,7 +1,7 @@ import { open, readFile, stat } from 'node:fs/promises' import { extname } from 'node:path' import type { RelayDispatcher, RequestContext } from './dispatcher' -import { STREAM_CHUNK_SIZE, RelayErrorCode } from './protocol' +import { STREAM_ACK_WINDOW_CHUNKS, STREAM_CHUNK_SIZE, RelayErrorCode } from './protocol' import type { RelayStreamRegistry, TooManyStreamsError } from './fs-stream-registry' import { BINARY_PROBE_BYTES, @@ -61,11 +61,21 @@ type StreamChunkReader = { ): Promise<{ bytesRead: number }> } +export type StreamPumpOptions = { + /** Client that requested the stream. Chunks go only to it — broadcasting + * bulk frames would let one slow secondary client stall the requester. */ + clientId?: number + /** True when the client declared `flowControl: 'ack'` — it sends + * fs.streamAck per processed chunk and the pump caps unacked chunks. */ + paceWithAcks: boolean +} + export async function readRelayFileStreamMetadata( filePath: string, dispatcher: RelayDispatcher, registry: RelayStreamRegistry, - context: RequestContext + context: RequestContext, + pumpOptions?: StreamPumpOptions ): Promise { const stats = await stat(filePath) const mimeType = IMAGE_MIME_TYPES[extname(filePath).toLowerCase()] @@ -106,8 +116,9 @@ export async function readRelayFileStreamMetadata( // Why: pumpChunks owns its own try/finally for handle release; the outer // setImmediate kicks the pump off the metadata-response task so the client // sees the response before the first chunk frame. + const resolvedPumpOptions = pumpOptions ?? { paceWithAcks: false } setImmediate(() => { - void pumpChunks(streamId, stats.size, dispatcher, registry, context) + void pumpChunks(streamId, stats.size, dispatcher, registry, context, resolvedPumpOptions) }) return { @@ -126,7 +137,8 @@ async function pumpChunks( totalSize: number, dispatcher: RelayDispatcher, registry: RelayStreamRegistry, - context: RequestContext + context: RequestContext, + pumpOptions: StreamPumpOptions ): Promise { const entry = registry.get(streamId) if (!entry) { @@ -150,6 +162,27 @@ async function pumpChunks( endReason = 'aborted' break } + // Why: credit window — bulk chunks share one ordered SSH channel with + // interactive pty.data frames. Waiting for client acks bounds how many + // stream bytes a keystroke echo can queue behind, and yields the relay + // event loop so incoming keystrokes are handled between chunks. + if (pumpOptions.paceWithAcks) { + while ( + seq - registry.ackedThroughSeq(streamId) > STREAM_ACK_WINDOW_CHUNKS && + !context.isStale() && + !registry.isAborted(streamId) + ) { + await registry.waitForAck(streamId) + } + if (context.isStale()) { + endReason = 'stale' + break + } + if (registry.isAborted(streamId)) { + endReason = 'aborted' + break + } + } const want = Math.min(STREAM_CHUNK_SIZE, totalSize - offset) const bytesRead = await readFullStreamChunk(entry.handle, buffer, want, offset) if (bytesRead !== want) { @@ -167,7 +200,14 @@ async function pumpChunks( break } const data = buffer.subarray(0, bytesRead).toString('base64') - dispatcher.notify('fs.streamChunk', { streamId, seq, data }) + // Why: the bulk lane waits out sink saturation, so a flood of chunk + // frames cannot pile up in the outbound pipe ahead of interactive + // pty.data frames written via plain notify(). + await dispatcher.notifyBulk( + 'fs.streamChunk', + { streamId, seq, data }, + pumpOptions.clientId !== undefined ? { clientId: pumpOptions.clientId } : undefined + ) offset += bytesRead seq += 1 } diff --git a/src/relay/fs-handler-stream.test.ts b/src/relay/fs-handler-stream.test.ts index d71dbf8c0..c7624afce 100644 --- a/src/relay/fs-handler-stream.test.ts +++ b/src/relay/fs-handler-stream.test.ts @@ -34,6 +34,9 @@ function createMockDispatcher() { notify: vi.fn((method: string, params?: Record) => { notifications.push({ method, params }) }), + notifyBulk: vi.fn(async (method: string, params?: Record): Promise => { + notifications.push({ method, params }) + }), _notifications: notifications, callRequest( method: string, @@ -278,6 +281,61 @@ describe('FsHandler readFileStream', () => { expect(err).toBeNull() }) + it('parks the pump at the ack credit window and resumes on fs.streamAck', async () => { + const filePath = path.join(tmpDir, 'paced.png') + const content = Buffer.alloc(1536 * 1024, 0x42) // 6 chunks + writeFileSync(filePath, content) + + const meta = (await dispatcher.callRequest( + 'fs.readFileStream', + { filePath, flowControl: 'ack' }, + { isStale: () => false } + )) as { streamId: number } + + // Window of 4 admits seqs 0..3; seq 4 must wait for an ack. + await waitFor(() => collectStream(dispatcher).chunks.length === 4) + await flush(10) + expect(collectStream(dispatcher).chunks.length).toBe(4) + expect(collectStream(dispatcher).end).toBeNull() + + // Ack one chunk → exactly one more is admitted. + dispatcher.callNotification('fs.streamAck', { streamId: meta.streamId, seq: 0 }) + await waitFor(() => collectStream(dispatcher).chunks.length === 5) + await flush(10) + expect(collectStream(dispatcher).chunks.length).toBe(5) + + for (let seq = 1; seq < 6; seq += 1) { + dispatcher.callNotification('fs.streamAck', { streamId: meta.streamId, seq }) + } + await waitFor(() => collectStream(dispatcher).end !== null) + + const { chunks, err } = collectStream(dispatcher) + expect(err).toBeNull() + const reassembled = Buffer.concat(chunks.map((c) => Buffer.from(c.data, 'base64'))) + expect(reassembled.equals(content)).toBe(true) + }) + + it('releases a pump parked on the ack window when the stream is cancelled', async () => { + const filePath = path.join(tmpDir, 'parked-cancel.png') + writeFileSync(filePath, Buffer.alloc(4 * 1024 * 1024, 0x42)) // 16 chunks + + const meta = (await dispatcher.callRequest( + 'fs.readFileStream', + { filePath, flowControl: 'ack' }, + { isStale: () => false } + )) as { streamId: number } + + await waitFor(() => collectStream(dispatcher).chunks.length === 4) + dispatcher.callNotification('fs.cancelStream', { streamId: meta.streamId }) + + const registry = (handler as unknown as { streamRegistry: { size(): number } }).streamRegistry + await waitFor(() => registry.size() === 0) + + const { end, err } = collectStream(dispatcher) + expect(end).toBeNull() + expect(err).toBeNull() + }) + it('rejects the 17th concurrent stream with TooManyStreams', async () => { const paths: string[] = [] for (let i = 0; i < 17; i++) { diff --git a/src/relay/fs-handler.test.ts b/src/relay/fs-handler.test.ts index b90a786f7..7d5354cf4 100644 --- a/src/relay/fs-handler.test.ts +++ b/src/relay/fs-handler.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: this suite covers relay filesystem RPCs, - Space scans, file watcher lifecycle edges, and cross-platform path behavior together. */ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { FsHandler } from './fs-handler' import { MAX_TEXT_FILE_SIZE } from './fs-handler-utils' diff --git a/src/relay/fs-handler.ts b/src/relay/fs-handler.ts index 0c4a263f1..c6564c51f 100644 --- a/src/relay/fs-handler.ts +++ b/src/relay/fs-handler.ts @@ -86,7 +86,13 @@ export class FsHandler { constructor(dispatcher: RelayDispatcher, _context: RelayContext) { this.dispatcher = dispatcher this.registerHandlers() - this.dispatcher.onClientDetached?.((clientId) => this.releaseClientWatches(clientId)) + this.dispatcher.onClientDetached?.((clientId) => { + this.releaseClientWatches(clientId) + // Why: a detached client's fs.streamAck frames will never arrive; wake + // any pump parked on the ack window so it re-checks staleness and exits + // instead of stranding its open file handle. + this.streamRegistry.wakeAllAckWaiters() + }) } private registerHandlers(): void { @@ -113,6 +119,7 @@ export class FsHandler { this.dispatcher.onRequest('fs.watch', (p, context) => this.watch(p, context)) this.dispatcher.onNotification('fs.unwatch', (p, context) => this.unwatch(p, context)) this.dispatcher.onNotification('fs.cancelStream', (p) => this.cancelStream(p)) + this.dispatcher.onNotification('fs.streamAck', (p) => this.streamAck(p)) } private async readDir(params: Record) { @@ -148,7 +155,13 @@ export class FsHandler { private async readFileStream(params: Record, context?: RequestContext) { const filePath = expandTilde(params.filePath as string) const ctx = context ?? { clientId: 0, isStale: () => false } - return readRelayFileStreamMetadata(filePath, this.dispatcher, this.streamRegistry, ctx) + return readRelayFileStreamMetadata(filePath, this.dispatcher, this.streamRegistry, ctx, { + // Why: only target the requesting client when the dispatcher actually + // routed this request (context present) — direct-call tests and legacy + // paths keep broadcast semantics. + ...(context ? { clientId: context.clientId } : {}), + paceWithAcks: params.flowControl === 'ack' + }) } private async tempDir(): Promise { @@ -162,6 +175,14 @@ export class FsHandler { } } + private streamAck(params: Record): void { + const streamId = params.streamId as number | undefined + const seq = params.seq as number | undefined + if (typeof streamId === 'number' && typeof seq === 'number') { + this.streamRegistry.recordAck(streamId, seq) + } + } + private async writeFile(params: Record) { const filePath = expandTilde(params.filePath as string) const content = params.content as string diff --git a/src/relay/fs-stream-pty-echo-backpressure.integration.test.ts b/src/relay/fs-stream-pty-echo-backpressure.integration.test.ts new file mode 100644 index 000000000..8cca27878 --- /dev/null +++ b/src/relay/fs-stream-pty-echo-backpressure.integration.test.ts @@ -0,0 +1,295 @@ +/** + * Regression: SSH typing latency under bulk file-stream load. + * + * The relay and the client share ONE ordered SSH channel. If the relay + * enqueues an entire file's fs.streamChunk frames into the outbound pipe + * at once, an interactive pty.data echo emitted mid-stream queues behind + * megabytes of bulk data and typing feels seconds-slow. + * + * These tests model the SSH channel as a congestible in-memory pipe and + * assert deterministic byte bounds instead of wall-clock latency: + * - with a saturated sink, the relay stalls the pump on write backpressure + * so at most ~1 chunk frame sits ahead of a pty echo; + * - with a fast sink but an unresponsive client, the fs.streamAck credit + * window bounds the in-flight backlog; + * - legacy clients that never ack still receive the full stream. + */ +import { describe, expect, it, beforeEach, afterEach } from 'vitest' +import { mkdtempSync, writeFileSync } from 'node:fs' +import { rm } from 'node:fs/promises' +import * as path from 'node:path' +import { tmpdir } from 'node:os' +import { randomBytes } from 'node:crypto' + +import { + SshChannelMultiplexer, + type MultiplexerTransport +} from '../main/ssh/ssh-channel-multiplexer' +import { readFileViaStream } from '../main/ssh/ssh-filesystem-stream-reader' + +import { RelayDispatcher } from './dispatcher' +import { RelayContext } from './context' +import { FsHandler } from './fs-handler' +import { STREAM_CHUNK_SIZE } from './protocol' + +// One framed fs.streamChunk: 256KB raw → base64 (4/3) + JSON envelope + header. +const FRAMED_CHUNK_BYTES = Math.ceil((STREAM_CHUNK_SIZE * 4) / 3) + 512 +// Node pipe/socket sinks report saturation via write() === false past the HWM. +const SINK_HIGH_WATER_MARK = 64 * 1024 + +async function waitUntil( + predicate: () => boolean, + what: string, + timeoutMs = 10_000 +): Promise { + const deadline = Date.now() + timeoutMs + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error(`waitUntil timed out: ${what}`) + } + await new Promise((r) => setImmediate(r)) + } +} + +/** Waits until `read()` stops changing for `stableTurns` macrotask turns. */ +async function waitUntilSettled(read: () => number, stableTurns = 25): Promise { + let last = read() + let stable = 0 + while (stable < stableTurns) { + await new Promise((r) => setImmediate(r)) + const current = read() + if (current === last) { + stable += 1 + } else { + stable = 0 + last = current + } + } +} + +type Harness = { + mux: SshChannelMultiplexer + dispatcher: RelayDispatcher + fsHandler: FsHandler + queuedBytes: () => number + /** Deliver every queued relay→client buffer to the client mux. */ + deliverAll: () => void + /** Start delivering continuously on each macrotask turn. */ + startAutoDeliver: () => void + dispose: () => void +} + +function createHarness(opts: { congested: boolean }): Harness { + let relayFeed: ((data: Buffer) => void) | null = null + const clientDataCallbacks: ((data: Buffer) => void)[] = [] + + const clientTransport: MultiplexerTransport = { + write: (data: Buffer) => { + // Client → relay: keystrokes and acks flow on the opposite direction of + // the duplex channel; they are not blocked by relay→client congestion. + setImmediate(() => relayFeed?.(data)) + }, + onData: (cb) => { + clientDataCallbacks.push(cb) + }, + onClose: () => {} + } + + const outQueue: Buffer[] = [] + let queuedBytes = 0 + const drainWaiters = new Set<() => void>() + const fireDrainIfIdle = (): void => { + if (queuedBytes > 0) { + return + } + for (const cb of Array.from(drainWaiters)) { + drainWaiters.delete(cb) + cb() + } + } + + const dispatcher = new RelayDispatcher( + (data: Buffer) => { + outQueue.push(data) + queuedBytes += data.length + if (!opts.congested) { + return true + } + return queuedBytes < SINK_HIGH_WATER_MARK + }, + { + waitWriteDrain: (cb: () => void) => { + drainWaiters.add(cb) + fireDrainIfIdle() + } + } + ) + relayFeed = (data: Buffer) => dispatcher.feed(data) + + const deliverAll = (): void => { + while (outQueue.length > 0) { + const buf = outQueue.shift()! + queuedBytes -= buf.length + for (const cb of clientDataCallbacks) { + cb(buf) + } + } + fireDrainIfIdle() + } + + let autoDeliverTimer: ReturnType | null = null + const startAutoDeliver = (): void => { + if (autoDeliverTimer) { + return + } + autoDeliverTimer = setInterval(deliverAll, 1) + } + + const context = new RelayContext() + const fsHandler = new FsHandler(dispatcher, context) + const mux = new SshChannelMultiplexer(clientTransport) + + return { + mux, + dispatcher, + fsHandler, + queuedBytes: () => queuedBytes, + deliverAll, + startAutoDeliver, + dispose: () => { + if (autoDeliverTimer) { + clearInterval(autoDeliverTimer) + } + mux.dispose() + dispatcher.dispose() + fsHandler.dispose() + } + } +} + +describe('fs.readFileStream vs pty.data echo head-of-line blocking', () => { + let tmpDir: string + + beforeEach(() => { + tmpDir = mkdtempSync(path.join(tmpdir(), 'relay-stream-hol-')) + }) + + afterEach(async () => { + await rm(tmpDir, { recursive: true, force: true }) + }) + + it('bounds bulk bytes queued ahead of a pty echo when the channel is congested', async () => { + const harness = createHarness({ congested: true }) + try { + const filePath = path.join(tmpDir, 'big.png') + const original = randomBytes(3 * 1024 * 1024) // 12 chunks + writeFileSync(filePath, original) + + // Relay-side fake PTY: echoes input back immediately, mirroring + // PtyHandler's interactive fast path (dispatcher.notify on echo). + let queuedBytesAheadOfEcho = -1 + harness.dispatcher.onNotification('pty.data', (params) => { + queuedBytesAheadOfEcho = harness.queuedBytes() + harness.dispatcher.notify('pty.data', { id: params.id, data: params.data }) + }) + + const readPromise = readFileViaStream(harness.mux, filePath) + // Deliver until the client has the stream metadata, then congest fully. + await waitUntil(() => harness.queuedBytes() > 0, 'metadata response queued') + harness.deliverAll() + // Let the pump run to whatever bound it enforces (pre-fix: whole file). + await waitUntil(() => harness.queuedBytes() > 0, 'first chunk queued') + await waitUntilSettled(() => harness.queuedBytes()) + + // Type one key while the stream is congested. + harness.mux.notify('pty.data', { id: 'pty-1', data: 'x' }) + await waitUntil(() => queuedBytesAheadOfEcho >= 0, 'echo emitted by relay') + + // The echo must not sit behind an unbounded chunk backlog: at most one + // in-flight bulk frame (the write that saturated the sink) plus slack. + expect(queuedBytesAheadOfEcho).toBeLessThan(2 * FRAMED_CHUNK_BYTES) + + // Un-congest: the stream must still complete with intact content. + harness.startAutoDeliver() + const result = await readPromise + expect(Buffer.from(result.content, 'base64').equals(original)).toBe(true) + } finally { + harness.dispose() + } + }, 30_000) + + it('caps in-flight chunks via the fs.streamAck credit window when the client stalls', async () => { + const harness = createHarness({ congested: false }) + try { + const filePath = path.join(tmpDir, 'big.png') + writeFileSync(filePath, randomBytes(3 * 1024 * 1024)) // 12 chunks + + const receivedSeqs: number[] = [] + harness.mux.onNotificationByMethod('fs.streamChunk', (params) => { + receivedSeqs.push(params.seq as number) + }) + let streamEnded = false + harness.mux.onNotificationByMethod('fs.streamEnd', () => { + streamEnded = true + }) + + harness.startAutoDeliver() + // Raw ack-capable request without sending any acks: models a client + // whose main thread is too busy to process chunks. + const metadata = (await harness.mux.request('fs.readFileStream', { + filePath, + flowControl: 'ack' + })) as { streamId: number } + + await waitUntil(() => receivedSeqs.length > 0, 'first chunk received') + await waitUntilSettled(() => receivedSeqs.length) + + // Without acks the relay must stop at the credit window, not flood + // the remaining chunks. + expect(receivedSeqs.length).toBeLessThanOrEqual(5) + expect(streamEnded).toBe(false) + + // Acking releases the window and the stream completes. + const totalChunks = 12 + for (let seq = 0; seq < totalChunks; seq += 1) { + harness.mux.notify('fs.streamAck', { streamId: metadata.streamId, seq }) + } + await waitUntil(() => streamEnded, 'stream completed after acks') + expect(receivedSeqs).toEqual(Array.from({ length: totalChunks }, (_, i) => i)) + } finally { + harness.dispose() + } + }, 30_000) + + it('still delivers the full stream to legacy clients that never ack', async () => { + const harness = createHarness({ congested: false }) + try { + const filePath = path.join(tmpDir, 'legacy.png') + const original = randomBytes(1024 * 1024 + 12345) + writeFileSync(filePath, original) + + const chunks = new Map() + let streamEnded = false + harness.mux.onNotificationByMethod('fs.streamChunk', (params) => { + chunks.set(params.seq as number, Buffer.from(params.data as string, 'base64')) + }) + harness.mux.onNotificationByMethod('fs.streamEnd', () => { + streamEnded = true + }) + + harness.startAutoDeliver() + // Legacy request shape: no flowControl param, and no acks ever sent. + await harness.mux.request('fs.readFileStream', { filePath }) + await waitUntil(() => streamEnded, 'legacy stream completed') + + const reassembled = Buffer.concat( + Array.from(chunks.entries()) + .sort(([a], [b]) => a - b) + .map(([, buf]) => buf) + ) + expect(reassembled.equals(original)).toBe(true) + } finally { + harness.dispose() + } + }, 30_000) +}) diff --git a/src/relay/fs-stream-registry.ts b/src/relay/fs-stream-registry.ts index e0bf2a5ed..2bca76c94 100644 --- a/src/relay/fs-stream-registry.ts +++ b/src/relay/fs-stream-registry.ts @@ -1,9 +1,14 @@ import type { FileHandle } from 'node:fs/promises' -import { MAX_CONCURRENT_STREAMS, RelayErrorCode } from './protocol' +import { MAX_CONCURRENT_STREAMS, RelayErrorCode, STREAM_ACK_STALL_RECHECK_MS } from './protocol' type StreamEntry = { handle: FileHandle aborted: boolean + /** Highest chunk seq the client acknowledged (in-order; -1 = none yet). */ + ackedThroughSeq: number + /** Pumps parked on the ack credit window. Woken by acks, abort, release, + * and a periodic stall recheck so a vanished client cannot strand a pump. */ + ackWaiters: Set<() => void> } export class TooManyStreamsError extends Error { @@ -22,7 +27,12 @@ export class RelayStreamRegistry { throw new TooManyStreamsError() } const streamId = this.nextId++ - this.streams.set(streamId, { handle, aborted: false }) + this.streams.set(streamId, { + handle, + aborted: false, + ackedThroughSeq: -1, + ackWaiters: new Set() + }) return streamId } @@ -30,6 +40,7 @@ export class RelayStreamRegistry { const entry = this.streams.get(streamId) if (entry) { entry.aborted = true + this.wakeAckWaiters(entry) } } @@ -41,11 +52,65 @@ export class RelayStreamRegistry { return this.streams.get(streamId) } + recordAck(streamId: number, seq: number): void { + const entry = this.streams.get(streamId) + if (!entry || typeof seq !== 'number' || !Number.isFinite(seq)) { + return + } + if (seq > entry.ackedThroughSeq) { + entry.ackedThroughSeq = seq + } + this.wakeAckWaiters(entry) + } + + ackedThroughSeq(streamId: number): number { + return this.streams.get(streamId)?.ackedThroughSeq ?? Number.MAX_SAFE_INTEGER + } + + /** Resolves on the next ack/abort/release for this stream, or after the + * stall-recheck interval so callers can re-evaluate staleness. */ + waitForAck(streamId: number): Promise { + const entry = this.streams.get(streamId) + if (!entry || entry.aborted) { + return Promise.resolve() + } + return new Promise((resolve) => { + let settled = false + const timer = setTimeout(() => finish(), STREAM_ACK_STALL_RECHECK_MS) + timer.unref?.() + const finish = (): void => { + if (settled) { + return + } + settled = true + clearTimeout(timer) + entry.ackWaiters.delete(finish) + resolve() + } + entry.ackWaiters.add(finish) + }) + } + + /** Wake every parked pump (all streams) so it re-checks staleness — used + * when a client detaches and its acks will never arrive. */ + wakeAllAckWaiters(): void { + for (const entry of this.streams.values()) { + this.wakeAckWaiters(entry) + } + } + + private wakeAckWaiters(entry: StreamEntry): void { + for (const waiter of Array.from(entry.ackWaiters)) { + waiter() + } + } + async release(streamId: number): Promise { const entry = this.streams.get(streamId) if (!entry) { return } + this.wakeAckWaiters(entry) this.streams.delete(streamId) try { await entry.handle.close() diff --git a/src/relay/protocol.ts b/src/relay/protocol.ts index 66818efaf..267f6ef48 100644 --- a/src/relay/protocol.ts +++ b/src/relay/protocol.ts @@ -48,6 +48,17 @@ export const TIMEOUT_MS = 20_000 export const STREAM_CHUNK_SIZE = 256 * 1024 export const MAX_CONCURRENT_STREAMS = 16 +/** Max unacked fs.streamChunk frames in flight per stream when the client + * requested `flowControl: 'ack'`. Bounds how many bulk bytes an interactive + * pty.data frame can queue behind on the shared SSH channel (~1MB raw) while + * keeping the pipe full across one ack round-trip on fast links. */ +export const STREAM_ACK_WINDOW_CHUNKS = 4 + +/** Safety-valve poll interval for a pump stalled on acks: re-checks stream + * abort/staleness so a client that vanished mid-stream cannot park the pump + * (and its open file handle) forever. */ +export const STREAM_ACK_STALL_RECHECK_MS = 1_000 + export const RelayErrorCode = { TooManyStreams: -33006, StreamProtocolError: -33007 @@ -109,7 +120,12 @@ export function encodeKeepAliveFrame(id: number, ack: number): Buffer { } export class FrameDecoder { - private buffer = Buffer.alloc(0) + // Why: feed() sits on the hot receive path. Rebuilding one contiguous + // buffer per feed (Buffer.concat) re-copies every already-buffered byte for + // each incoming chunk — O(n²) per large frame. A chunk list assembles each + // frame exactly once instead. + private chunks: Buffer[] = [] + private bufferedLength = 0 private onFrame: (frame: DecodedFrame) => void private onError: ((err: Error) => void) | null @@ -119,23 +135,32 @@ export class FrameDecoder { } feed(chunk: Buffer | Uint8Array): void { - this.buffer = Buffer.concat([this.buffer, chunk]) + const buf = Buffer.isBuffer(chunk) + ? chunk + : Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + if (buf.length > 0) { + this.chunks.push(buf) + this.bufferedLength += buf.length + } - while (this.buffer.length >= HEADER_LENGTH) { - const length = this.buffer.readUInt32BE(9) + while (this.bufferedLength >= HEADER_LENGTH) { + const header = this.peekBytes(HEADER_LENGTH) + const length = header.readUInt32BE(9) const totalLength = HEADER_LENGTH + length + if (this.bufferedLength < totalLength) { + // Not fully received yet (also holds oversized frames until they can + // be skipped whole, keeping the decoder synchronized). + break + } + if (length > MAX_MESSAGE_SIZE) { // Why: Throwing here would leave the buffer in a partially consumed // state — subsequent feed() calls would try to parse the leftover // payload bytes as a new header, corrupting every future frame. // Instead we skip the entire oversized frame so the decoder stays // synchronized with the stream. - if (this.buffer.length < totalLength) { - // Haven't received the full oversized payload yet; wait for more data. - break - } - this.buffer = this.buffer.subarray(totalLength) + this.discardBytes(totalLength) const err = new Error(`Frame payload too large: ${length} bytes — discarded`) if (this.onError) { this.onError(err) @@ -145,23 +170,20 @@ export class FrameDecoder { continue } - if (this.buffer.length < totalLength) { - break - } - + const framed = this.takeBytes(totalLength) const frame: DecodedFrame = { - type: this.buffer[0], - id: this.buffer.readUInt32BE(1), - ack: this.buffer.readUInt32BE(5), - payload: this.buffer.subarray(HEADER_LENGTH, totalLength) + type: framed[0], + id: framed.readUInt32BE(1), + ack: framed.readUInt32BE(5), + payload: framed.subarray(HEADER_LENGTH, totalLength) } - this.buffer = this.buffer.subarray(totalLength) this.onFrame(frame) } } reset(): void { - this.buffer = Buffer.alloc(0) + this.chunks = [] + this.bufferedLength = 0 } // Why: at the handshake → dispatcher transition, the next consumer must @@ -169,10 +191,74 @@ export class FrameDecoder { // frame. This returns and clears the decoder's internal residue so the // caller can hand it to the dispatcher (or stdout pipe) without loss. drain(): Buffer { - const out = this.buffer - this.buffer = Buffer.alloc(0) + const out = + this.chunks.length === 1 ? this.chunks[0] : Buffer.concat(this.chunks, this.bufferedLength) + this.reset() return out } + + /** View of the first `count` buffered bytes without consuming them. */ + private peekBytes(count: number): Buffer { + const first = this.chunks[0] + if (first.length >= count) { + return first + } + const out = Buffer.allocUnsafe(count) + let copied = 0 + for (const part of this.chunks) { + copied += part.copy(out, copied, 0, Math.min(part.length, count - copied)) + if (copied >= count) { + break + } + } + return out + } + + /** Consume and return the first `count` buffered bytes (single copy). */ + private takeBytes(count: number): Buffer { + const first = this.chunks[0] + if (first.length === count) { + this.chunks.shift() + this.bufferedLength -= count + return first + } + if (first.length > count) { + this.chunks[0] = first.subarray(count) + this.bufferedLength -= count + return first.subarray(0, count) + } + const out = Buffer.allocUnsafe(count) + let copied = 0 + while (copied < count) { + const part = this.chunks[0] + const take = Math.min(part.length, count - copied) + part.copy(out, copied, 0, take) + copied += take + if (take === part.length) { + this.chunks.shift() + } else { + this.chunks[0] = part.subarray(take) + } + } + this.bufferedLength -= count + return out + } + + /** Consume the first `count` buffered bytes without assembling them. */ + private discardBytes(count: number): void { + let remaining = count + while (remaining > 0) { + const part = this.chunks[0] + if (part.length <= remaining) { + this.chunks.shift() + remaining -= part.length + } else { + this.chunks[0] = part.subarray(remaining) + remaining = 0 + } + } + this.bufferedLength -= count + } } export function parseJsonRpcMessage(payload: Buffer): JsonRpcMessage { diff --git a/src/relay/relay.ts b/src/relay/relay.ts index c930a244b..992252279 100644 --- a/src/relay/relay.ts +++ b/src/relay/relay.ts @@ -373,15 +373,44 @@ async function main(): Promise { // write to a dead pipe, silently failing or throwing EPIPE. When a // socket client reconnects, setWrite swaps the callback to the socket. let stdoutAlive = true - const dispatcher = new RelayDispatcher((data) => { - if (stdoutAlive) { + // Why: one-shot waiters parked by the dispatcher's bulk lane when stdout + // reports saturation (write() === false). Flushed on 'drain' and on every + // stdout-death path so a stalled file-stream pump never outlives the pipe + // it was waiting on. + const stdoutDrainWaiters = new Set<() => void>() + const flushStdoutDrainWaiters = (): void => { + for (const cb of Array.from(stdoutDrainWaiters)) { + stdoutDrainWaiters.delete(cb) + cb() + } + } + process.stdout.on('drain', flushStdoutDrainWaiters) + const dispatcher = new RelayDispatcher( + (data) => { + if (!stdoutAlive) { + return + } try { - process.stdout.write(data) + // Why: surface Node's backpressure signal to the dispatcher so bulk + // frames (fs.streamChunk) wait for drain instead of queueing megabytes + // ahead of interactive pty.data frames on the SSH channel. + return process.stdout.write(data) } catch { stdoutAlive = false + flushStdoutDrainWaiters() + return undefined + } + }, + { + waitWriteDrain: (cb) => { + if (!stdoutAlive) { + cb() + return + } + stdoutDrainWaiters.add(cb) } } - }) + ) const context = new RelayContext() @@ -680,11 +709,35 @@ async function main(): Promise { ) cancelGrace('socket client accepted') - const clientId = dispatcher.attachClient((data) => { - if (!sock.destroyed) { - sock.write(data) + // Why: same backpressure surface as the stdout sink — bulk frames wait + // for the socket to drain so they cannot bury interactive PTY frames. + const sockDrainWaiters = new Set<() => void>() + const flushSockDrainWaiters = (): void => { + for (const cb of Array.from(sockDrainWaiters)) { + sockDrainWaiters.delete(cb) + cb() } - }) + } + sock.on('drain', flushSockDrainWaiters) + sock.on('close', flushSockDrainWaiters) + sock.on('error', flushSockDrainWaiters) + const clientId = dispatcher.attachClient( + (data) => { + if (!sock.destroyed) { + return sock.write(data) + } + return undefined + }, + { + waitWriteDrain: (cb) => { + if (sock.destroyed) { + cb() + return + } + sockDrainWaiters.add(cb) + } + } + ) socketClients.set(sock, clientId) // Why: bytes that arrived in the same TCP send as the handshake frame @@ -889,6 +942,7 @@ async function main(): Promise { // before the grace period starts. process.stdout.on('error', () => { stdoutAlive = false + flushStdoutDrainWaiters() dispatcher.invalidateClient() }) @@ -934,6 +988,7 @@ async function main(): Promise { // dead so the primary client write callback becomes a no-op while // socket clients, if any, keep their own live transports. stdoutAlive = false + flushStdoutDrainWaiters() dispatcher.invalidateClient() if (socketClients.size === 0) { startGrace('stdin ended') @@ -942,6 +997,7 @@ async function main(): Promise { process.stdin.on('error', () => { stdoutAlive = false + flushStdoutDrainWaiters() dispatcher.invalidateClient() if (socketClients.size === 0) { startGrace('stdin error') diff --git a/src/relay/subprocess.test.ts b/src/relay/subprocess.test.ts index 059e5739f..4d19542b9 100644 --- a/src/relay/subprocess.test.ts +++ b/src/relay/subprocess.test.ts @@ -1,4 +1,3 @@ -/* oxlint-disable max-lines -- Why: subprocess coverage shares one bundled relay artifact; splitting this file would rebuild the same daemon bundle across suites and make these lifecycle tests slower/flakier. */ import { afterAll, beforeAll, describe, expect, it, afterEach } from 'vitest' import { existsSync, mkdtempSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs' import { rm } from 'node:fs/promises' diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 72f93b7bd..cb881ea97 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -112,10 +112,11 @@ import { } from './lib/workspace-session' import { createSessionWriteSubscriber } from './lib/session-write-subscriber' import { - fetchWorkspaceSessionFromHosts, + fetchWorkspaceSessionWithRuntimeHostOwners, patchWorkspaceSessionByHost, persistWorkspaceSessionByHostSync } from './lib/workspace-session-host-persistence' +import { collectFolderWorkspaceKeysFromSession } from './lib/workspace-session-hydration-keys' import { getStartupErrorFallbackUI, hydratePersistedUIAfterStartupRead @@ -158,6 +159,7 @@ import { type KeybindingContext, type PhysicalModifierToken } from '../../shared/keybindings' +import { toRuntimeExecutionHostId, type ExecutionHostId } from '../../shared/execution-host' import { ModifierDoubleTapDetector, toModifierDoubleTapEvent @@ -180,6 +182,17 @@ const hasCustomTitleBar = shouldRenderDesktopWindowChrome({ isWebClient: isPairedWebClientWindow() }) +async function listRuntimeSessionHostIdsForStartup(): Promise { + try { + return (await window.api.runtimeEnvironments.list()).map((environment) => + toRuntimeExecutionHostId(environment.id) + ) + } catch (err) { + console.warn('Failed to list runtime session hosts for startup:', err) + return [] + } +} + function getKeybindingContext(target: EventTarget | null): KeybindingContext { return target instanceof HTMLElement && target.classList.contains('xterm-helper-textarea') ? 'terminal' @@ -855,17 +868,15 @@ function App(): React.JSX.Element { // Load settings first so a persisted remote runtime does not boot against // the local filesystem and then hydrate stale local workspace state. await timeRendererStartupStep('fetch-settings', () => actions.fetchSettings()) - // Why: these three reads are main-side store/file reads with no - // dependency on anything fetched below, so start them now and await - // them at their original positions — the round-trips overlap the - // repo/worktree scans instead of queuing after them. Browser session - // profiles are deliberately NOT started early: on a remote runtime - // they route through a runtime RPC that may not be connected this - // early, and a failed fetch clears the profile list. The floating - // .catch marks the rejection handled if an earlier awaited step - // throws first; each await still rethrows its own failure. - const uiGetPromise = timeRendererStartupStep('ui-get', () => window.api.ui.get()) - uiGetPromise.catch(() => {}) + // Why: keybindings + onboarding are main-side reads with no dependency + // on the catalog/session steps below, so start them now and await them + // at their original positions — the round-trips overlap the local + // catalog scans instead of queuing after them. Browser session profiles + // are deliberately NOT started early: on a remote runtime they route + // through a runtime RPC that may not be connected this early, and a + // failed fetch clears the profile list. The floating .catch marks the + // rejection handled if an earlier awaited step throws first; each await + // still rethrows its own failure. const keybindingsPromise = timeRendererStartupStep('fetch-keybindings', () => actions.fetchKeybindings() ) @@ -874,36 +885,11 @@ function App(): React.JSX.Element { window.api.onboarding.get() ) onboardingPromise.catch(() => {}) - // Why: load local + every configured runtime environment (not just the - // active one) so a cold start that restored a remote workspace doesn't - // hide local repos. The sidebar "All hosts" scope then shows them all. - await timeRendererStartupStep('fetch-repos', () => actions.fetchReposForAllHosts()) - // Why: project-groups/folder-workspaces read neither the repos store nor - // worktrees, so once repos land they can overlap the per-repo - // `git worktree list` fan-out (#7225) instead of queuing ahead of it — a - // slow remote host's 15s scope RPCs no longer block the scan. folders - // still follow project-groups (they read projectGroups); all settle - // before the hydrate steps below. - const projectScopeChain = (async () => { - await timeRendererStartupStep('fetch-project-groups', () => - actions.fetchProjectGroupsForAllHosts() - ) - await timeRendererStartupStep('fetch-folder-workspaces', () => - actions.fetchFolderWorkspacesForAllHosts() - ) - })() - // Why: worktrees + lineage both fan out `git worktree list` per repo on - // the main process. Running them concurrently lets it share one - // in-flight scan per repo instead of paying the process-spawn fan-out - // twice back-to-back — the dominant renderer-chain cost on Windows - // (issue #7225). Lineage only reads settings + its own slice, so it - // does not depend on the worktrees fetch having landed. - await Promise.all([ - projectScopeChain, - timeRendererStartupStep('fetch-worktrees', () => actions.fetchAllWorktrees()), - timeRendererStartupStep('fetch-worktree-lineage', () => actions.fetchWorktreeLineage()) - ]) - const persistedUI = await uiGetPromise + // Why: hydrate persisted UI immediately after ui.get() so first paint + // reflects saved view settings before the catalog scans below. ui.get() + // is awaited (not overlapped) because the hydrate must land before the + // local-first catalog/session steps run. + const persistedUI = await timeRendererStartupStep('ui-get', () => window.api.ui.get()) uiHydrated = timeRendererStartupSyncStep('hydrate-persisted-ui', () => hydratePersistedUIAfterStartupRead({ persistedUI, @@ -911,20 +897,49 @@ function App(): React.JSX.Element { hydratePersistedUI: actions.hydratePersistedUI }) ) + const startupRuntimeHostIds = await timeRendererStartupStep( + 'list-runtime-session-hosts', + listRuntimeSessionHostIdsForStartup + ) + // Why: first paint needs local data and persisted view settings, but + // saved remote runtimes can spend the full connect timeout. Load only + // the local catalog here; remotes refresh after hydration below. + await timeRendererStartupStep('fetch-repos-local', () => + actions.fetchReposForAllHosts({ remoteHosts: 'skip' }) + ) + await timeRendererStartupStep('fetch-project-groups-local', () => + actions.fetchProjectGroupsForAllHosts({ remoteHosts: 'skip' }) + ) + await timeRendererStartupStep('fetch-folder-workspaces-local', () => + actions.fetchFolderWorkspacesForAllHosts({ remoteHosts: 'skip' }) + ) + await timeRendererStartupStep('fetch-worktrees', () => + actions.fetchAllWorktrees({ hydrationPurge: 'defer' }) + ) // Why: runtime-owned worktree slices live in per-host partitions. - // Repos were fetched above, so the known runtime hosts are derivable - // here; merge their slices into the unified session the hydrators - // expect. An unreadable host partition is skipped (fail-soft). - const session = await timeRendererStartupStep('session-get', () => - fetchWorkspaceSessionFromHosts(window.api.session, useAppStore.getState().repos) + // Remote catalogs now load after first paint, so include saved runtime + // host ids from local settings to restore their persisted session slices + // without waiting on network reachability. Unreadable partitions skip. + const sessionRead = await timeRendererStartupStep('session-get', () => + fetchWorkspaceSessionWithRuntimeHostOwners( + window.api.session, + useAppStore.getState().repos, + startupRuntimeHostIds + ) ) await keybindingsPromise if (!cancelled) { + const sessionHydrationOptions = { + additionalValidWorkspaceKeys: collectFolderWorkspaceKeysFromSession(sessionRead.session) + } timeRendererStartupSyncStep('hydrate-session-stores', () => { - actions.hydrateWorkspaceSession(session) - actions.hydrateTabsSession(session) - actions.hydrateEditorSession(session) - actions.hydrateBrowserSession(session) + actions.hydrateWorkspaceSession(sessionRead.session, { + ...sessionHydrationOptions, + runtimeHostIdByWorkspaceSessionKey: sessionRead.runtimeHostIdByWorkspaceSessionKey + }) + actions.hydrateTabsSession(sessionRead.session, sessionHydrationOptions) + actions.hydrateEditorSession(sessionRead.session, sessionHydrationOptions) + actions.hydrateBrowserSession(sessionRead.session, sessionHydrationOptions) }) // Why: prune lastVisitedAtByWorktreeId entries whose worktrees // no longer exist. Must run AFTER hydration — before this point, @@ -952,7 +967,7 @@ function App(): React.JSX.Element { // tabs through pty.attach on the relay. Passphrase-protected targets // are deferred to tab focus to avoid stacking credential dialogs at // startup before the user has context. - const connectionIds = session.activeConnectionIdsAtShutdown ?? [] + const connectionIds = sessionRead.session.activeConnectionIdsAtShutdown ?? [] if (connectionIds.length > 0) { try { const SSH_RECONNECT_TIMEOUT_MS = 15_000 @@ -1064,6 +1079,23 @@ function App(): React.JSX.Element { logRendererStartupDiagnostic('startup-hydration-done', { durationMs: Math.round(performance.now() - startupStartedAt) }) + void (async () => { + try { + await timeRendererStartupStep('remote-catalog-refresh', async () => { + await actions.fetchReposForAllHosts() + await actions.fetchProjectGroupsForAllHosts() + await actions.fetchFolderWorkspacesForAllHosts() + }) + if (!cancelled) { + await timeRendererStartupStep('remote-worktree-refresh', async () => { + await actions.fetchAllWorktrees() + await actions.fetchWorktreeLineage() + }) + } + } catch (err) { + console.warn('Remote startup catalog refresh failed:', err) + } + })() } } catch (error) { // Why (issue #1158): previously this catch called hydrateWorkspaceSession diff --git a/src/renderer/src/app-startup-routing.test.ts b/src/renderer/src/app-startup-routing.test.ts index 81135b32c..6109a53d8 100644 --- a/src/renderer/src/app-startup-routing.test.ts +++ b/src/renderer/src/app-startup-routing.test.ts @@ -3,41 +3,64 @@ import { join } from 'node:path' import { describe, expect, it } from 'vitest' describe('renderer startup runtime routing', () => { - it('loads settings before repo and worktree hydration', () => { + it('hydrates persisted UI before local catalog and worktree hydration', () => { const source = readFileSync(join(process.cwd(), 'src/renderer/src/App.tsx'), 'utf8') const startupBlockStart = source.indexOf('void (async () => {') - const startupBlockEnd = source.indexOf('const persistedUI = await uiGetPromise') + const startupBlockEnd = source.indexOf("timeRendererStartupStep('session-get'") const startupBlock = source.slice(startupBlockStart, startupBlockEnd) const settingsIndex = startupBlock.indexOf('actions.fetchSettings()') - expect(settingsIndex).toBeGreaterThanOrEqual(0) - expect(settingsIndex).toBeLessThan(startupBlock.indexOf('actions.fetchReposForAllHosts()')) - expect(settingsIndex).toBeLessThan(startupBlock.indexOf('actions.fetchAllWorktrees()')) - }) - - it('overlaps sidebar scope loads with worktree hydration before session hydration', () => { - const source = readFileSync(join(process.cwd(), 'src/renderer/src/App.tsx'), 'utf8') - const startupBlockStart = source.indexOf('void (async () => {') - const startupBlockEnd = source.indexOf('const persistedUI = await uiGetPromise') - const startupBlock = source.slice(startupBlockStart, startupBlockEnd) - - const reposIndex = startupBlock.indexOf('actions.fetchReposForAllHosts()') - const scopeChainIndex = startupBlock.indexOf('const projectScopeChain = (async () => {') - const projectGroupsIndex = startupBlock.indexOf('actions.fetchProjectGroupsForAllHosts()') - const folderWorkspacesIndex = startupBlock.indexOf('actions.fetchFolderWorkspacesForAllHosts()') - const promiseAllIndex = startupBlock.indexOf('await Promise.all([') - const awaitedScopeChainIndex = startupBlock.indexOf('projectScopeChain', promiseAllIndex) - const worktreesIndex = startupBlock.indexOf('actions.fetchAllWorktrees()') + const uiGetIndex = startupBlock.indexOf("timeRendererStartupStep('ui-get'") + const hydrateUiIndex = startupBlock.indexOf( + "timeRendererStartupSyncStep('hydrate-persisted-ui'" + ) + const localReposIndex = startupBlock.indexOf( + "actions.fetchReposForAllHosts({ remoteHosts: 'skip' })" + ) + const localGroupsIndex = startupBlock.indexOf( + "actions.fetchProjectGroupsForAllHosts({ remoteHosts: 'skip' })" + ) + const localFoldersIndex = startupBlock.indexOf( + "actions.fetchFolderWorkspacesForAllHosts({ remoteHosts: 'skip' })" + ) + const localWorktreesIndex = startupBlock.indexOf( + "actions.fetchAllWorktrees({ hydrationPurge: 'defer' })" + ) const lineageIndex = startupBlock.indexOf('actions.fetchWorktreeLineage()') - expect(reposIndex).toBeGreaterThanOrEqual(0) - expect(scopeChainIndex).toBeGreaterThan(reposIndex) - expect(projectGroupsIndex).toBeGreaterThan(scopeChainIndex) - expect(folderWorkspacesIndex).toBeGreaterThan(projectGroupsIndex) - expect(promiseAllIndex).toBeGreaterThan(scopeChainIndex) - expect(awaitedScopeChainIndex).toBeGreaterThan(promiseAllIndex) - expect(worktreesIndex).toBeGreaterThan(promiseAllIndex) - expect(lineageIndex).toBeGreaterThan(promiseAllIndex) + expect(settingsIndex).toBeGreaterThanOrEqual(0) + expect(startupBlockEnd).toBeGreaterThan(startupBlockStart) + expect(settingsIndex).toBeLessThan(uiGetIndex) + expect(uiGetIndex).toBeLessThan(hydrateUiIndex) + expect(hydrateUiIndex).toBeLessThan(localReposIndex) + expect(localReposIndex).toBeLessThan(localGroupsIndex) + expect(localGroupsIndex).toBeLessThan(localFoldersIndex) + expect(localFoldersIndex).toBeLessThan(localWorktreesIndex) + expect(lineageIndex).toBe(-1) + }) + + it('refreshes remote catalogs after startup hydration succeeds', () => { + const source = readFileSync(join(process.cwd(), 'src/renderer/src/App.tsx'), 'utf8') + const hydrationDoneIndex = source.indexOf( + "logRendererStartupDiagnostic('startup-hydration-done'" + ) + const remoteCatalogIndex = source.indexOf("timeRendererStartupStep('remote-catalog-refresh'") + const remoteWorktreeIndex = source.indexOf("timeRendererStartupStep('remote-worktree-refresh'") + const lineageIndex = source.indexOf('actions.fetchWorktreeLineage()') + + expect(hydrationDoneIndex).toBeGreaterThanOrEqual(0) + expect(hydrationDoneIndex).toBeLessThan(remoteCatalogIndex) + expect(remoteCatalogIndex).toBeLessThan(remoteWorktreeIndex) + expect(remoteWorktreeIndex).toBeLessThan(lineageIndex) + expect(source.slice(remoteCatalogIndex, remoteWorktreeIndex)).toContain( + 'actions.fetchReposForAllHosts()' + ) + expect(source.slice(remoteCatalogIndex, remoteWorktreeIndex)).toContain( + 'actions.fetchProjectGroupsForAllHosts()' + ) + expect(source.slice(remoteCatalogIndex, remoteWorktreeIndex)).toContain( + 'actions.fetchFolderWorkspacesForAllHosts()' + ) }) it('waits for first-window startup services before terminal reconnect', () => { diff --git a/src/renderer/src/assets/main.css b/src/renderer/src/assets/main.css index 08f39a8b6..f028b6413 100644 --- a/src/renderer/src/assets/main.css +++ b/src/renderer/src/assets/main.css @@ -1904,13 +1904,14 @@ text-underline-offset: 2px; } -/* Why: Monaco owns Peek References scrollables and auto-hides faded needed - vertical thumbs while the widget stays open; revalidate these classes on upgrade. */ +/* Why: Monaco's faded scrollbar uses the class `invisible`, which collides with + Tailwind's `.invisible` utility (visibility: hidden) — so also restore visibility. */ .monaco-editor .reference-zone-widget .monaco-scrollable-element > .scrollbar.vertical.invisible.fade { opacity: 1; + visibility: visible; pointer-events: auto; } diff --git a/src/renderer/src/components/CodexRestartChip.tsx b/src/renderer/src/components/CodexRestartChip.tsx index fa644f79d..960703e87 100644 --- a/src/renderer/src/components/CodexRestartChip.tsx +++ b/src/renderer/src/components/CodexRestartChip.tsx @@ -1,7 +1,9 @@ import { useEffect, useId, useMemo, useRef, useState } from 'react' +import { useShallow } from 'zustand/react/shallow' import { RefreshCw } from 'lucide-react' import { Button } from '@/components/ui/button' import { useAppStore } from '../store' +import { selectCodexRestartInputs } from './codex-restart-chip-inputs' import { translate } from '@/i18n/i18n' import { shouldFocusMobileDriverAction } from './terminal-pane/mobile-driver-overlay-focus' import { @@ -73,8 +75,14 @@ export default function CodexRestartChip({ worktreeId: string }): React.JSX.Element | null { const tabs = useAppStore((s) => s.tabsByWorktree[worktreeId] ?? EMPTY_TABS) - const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) - const codexRestartNoticeByPtyId = useAppStore((s) => s.codexRestartNoticeByPtyId) + // Why: both of these maps churn on unrelated pty lifecycle events (ptyIdsByTabId + // on attach/detach; codexRestartNoticeByPtyId is re-spread even when empty on + // pty teardown), so subscribe to them only while a restart notice actually + // exists. Otherwise this per-worktree chip re-rendered on every pty event to + // compute "no notice → render nothing". See codex-restart-chip-inputs. + const { ptyIdsByTabId, codexRestartNoticeByPtyId } = useAppStore( + useShallow(selectCodexRestartInputs) + ) const staleWorktreePtyIds = useMemo( () => collectStalePtyIdsForTabs({ diff --git a/src/renderer/src/components/GitHubItemDialog.tsx b/src/renderer/src/components/GitHubItemDialog.tsx index 863928204..5d45f1f78 100644 --- a/src/renderer/src/components/GitHubItemDialog.tsx +++ b/src/renderer/src/components/GitHubItemDialog.tsx @@ -3848,7 +3848,21 @@ function PRActionsPanel({ const actionItem = { ...item, state: localState } const mergePresentation = presentGitHubPRMergeState(actionItem) const mergeMethods = resolveGitHubPRMergeMethods(actionItem.mergeMethodSettings) - const sourceSettings = getTaskSourceRuntimeSettings(sourceContext) + const repoOwnerSettings = useAppStore( + useShallow((s) => getSettingsForRepoRuntimeOwner(s, repoId ?? item.repoId ?? null)) + ) + const sourceSettings = useMemo(() => { + if (sourceContext?.provider !== 'github') { + return repoOwnerSettings + } + const sourceRuntimeSettings = getTaskSourceRuntimeSettings(sourceContext) + return sourceRuntimeSettings.activeRuntimeEnvironmentId + ? ({ + ...repoOwnerSettings, + ...sourceRuntimeSettings + } as typeof repoOwnerSettings) + : repoOwnerSettings + }, [repoOwnerSettings, sourceContext]) const mergeTarget = getActiveRuntimeTarget(sourceSettings) const canMutateWithRepoContext = !!repoPath || !!projectOrigin || mergeTarget.kind === 'environment' diff --git a/src/renderer/src/components/UpdateCard.test.ts b/src/renderer/src/components/UpdateCard.test.ts index 510ec81d7..9d4b75094 100644 --- a/src/renderer/src/components/UpdateCard.test.ts +++ b/src/renderer/src/components/UpdateCard.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: the update-card behavior is easiest to verify as one - lifecycle-oriented suite because the store caching and visibility rules interact directly. */ import { createStore, type StoreApi } from 'zustand/vanilla' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getDefaultUIState } from '../../../shared/constants' diff --git a/src/renderer/src/components/WorktreeJumpPalette.tsx b/src/renderer/src/components/WorktreeJumpPalette.tsx index 4c310972e..0b18f5f3f 100644 --- a/src/renderer/src/components/WorktreeJumpPalette.tsx +++ b/src/renderer/src/components/WorktreeJumpPalette.tsx @@ -1,5 +1,6 @@ /* oxlint-disable max-lines */ import React, { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react' +import { useShallow } from 'zustand/react/shallow' import { useTranslation } from 'react-i18next' import { toast } from 'sonner' import { @@ -14,6 +15,7 @@ import { } from 'lucide-react' import { useAppStore } from '@/store' import { getRepoMapFromState, useAllWorktrees } from '@/store/selectors' +import { selectPaletteStatusInputs } from './worktree-jump-palette-status-inputs' import { CommandDialog, CommandInput, @@ -193,6 +195,10 @@ type PaletteListEntry = PaletteItem | CreateWorktreePaletteItem | SectionHeader const CREATE_WORKSPACE_QUICK_ACTION_ITEM_ID = `quick-action:${CREATE_WORKSPACE_QUICK_ACTION_ID}` +// Why: comfortably outlast the CommandDialog close animation (~150–200ms) so the +// gated status maps stay live until the fading rows are gone from the DOM. +const PALETTE_STATUS_INPUTS_LINGER_MS = 300 + function getComposerPrefetchRepoId( state: ReturnType, initialRepoId?: string @@ -337,21 +343,44 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null { const projectHostSetups = useAppStore((s) => s.projectHostSetups) const detectedWorktreesByRepo = useAppStore((s) => s.detectedWorktreesByRepo) const pendingWorktreeCreations = useAppStore((s) => s.pendingWorktreeCreations) - const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) - // Why: getWorktreeStatus needs per-pane titles so split-pane tabs with a - // working agent in a non-focused pane still surface as 'working' in the - // jump palette. Without this, clicking between panes would desync the - // palette's spinner from the sidebar's spinner. - const runtimePaneTitlesByTabId = useAppStore((s) => s.runtimePaneTitlesByTabId) - // Why: ptyIdsByTabId is the live-pty source of truth — without it, - // getWorktreeStatus would treat slept tabs as live (their preserved - // tab.ptyId is a wake-hint sessionId, not a liveness signal) and the jump - // palette dot would lie green even though the sidebar dot is correctly grey. - const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) - const terminalLayoutsByTabId = useAppStore((s) => s.terminalLayoutsByTabId) + // Why: keep the (very hot) status maps subscribed through the dialog's close + // animation. `visible` flips false synchronously on close, but the CommandDialog + // content stays mounted while it fades/zooms out — dropping the maps to empty + // there would flash the switcher rows empty/reordered mid-animation. Linger a + // beat past close, then let the gate drop the subscription. + const [statusInputsLingering, setStatusInputsLingering] = useState(false) + useEffect(() => { + if (visible) { + setStatusInputsLingering(true) + return + } + const timer = window.setTimeout( + () => setStatusInputsLingering(false), + PALETTE_STATUS_INPUTS_LINGER_MS + ) + return () => window.clearTimeout(timer) + }, [visible]) + // Why: these five status maps drive per-worktree live/working dots and the + // switcher sort, but only matter while the palette is active. Two of them + // (agentStatusByPaneKey, runtimePaneTitlesByTabId) get a new identity on every + // agent-status / pane-title write app-wide, so subscribing to them while the + // always-mounted palette is closed re-rendered it on unrelated terminals. Gate + // the subscription on active-or-still-closing: a shared frozen constant while + // inactive keeps useShallow referentially equal across the churn, and the live + // maps flow through the instant the palette opens. + // - runtimePaneTitlesByTabId: split-pane tabs with a working agent in a + // non-focused pane still surface as 'working' (matches the sidebar spinner). + // - ptyIdsByTabId: the live-pty source of truth — slept tabs keep a wake-hint + // sessionId in tab.ptyId, so without it the palette dot would lie green. + const { + agentStatusByPaneKey, + runtimePaneTitlesByTabId, + ptyIdsByTabId, + terminalLayoutsByTabId, + tabsByWorktree + } = useAppStore(useShallow((s) => selectPaletteStatusInputs(s, visible || statusInputsLingering))) const prCache = useAppStore((s) => s.prCache) const issueCache = useAppStore((s) => s.issueCache) - const agentStatusByPaneKey = useAppStore((s) => s.agentStatusByPaneKey) const migrationUnsupportedByPtyId = useAppStore((s) => s.migrationUnsupportedByPtyId) const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) const activeTabType = useAppStore((s) => s.activeTabType) diff --git a/src/renderer/src/components/codex-restart-chip-inputs.test.ts b/src/renderer/src/components/codex-restart-chip-inputs.test.ts new file mode 100644 index 000000000..ad6412efd --- /dev/null +++ b/src/renderer/src/components/codex-restart-chip-inputs.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from 'vitest' +import { shallow } from 'zustand/shallow' +import { + EMPTY_CODEX_RESTART_INPUTS, + selectCodexRestartInputs, + type CodexRestartInputsState +} from './codex-restart-chip-inputs' + +describe('selectCodexRestartInputs', () => { + it('returns the frozen empty bundle while no restart notice exists', () => { + const state: CodexRestartInputsState = { + ptyIdsByTabId: { 'tab-1': ['pty-1'] }, + codexRestartNoticeByPtyId: {} + } + expect(selectCodexRestartInputs(state)).toBe(EMPTY_CODEX_RESTART_INPUTS) + + // Churning EITHER map while no notice exists must NOT change the selected + // reference, so a useShallow subscription skips the re-render. This covers + // the pty-teardown path that re-spreads codexRestartNoticeByPtyId even empty. + const churnedPty: CodexRestartInputsState = { + ...state, + ptyIdsByTabId: { 'tab-1': ['pty-2'], 'tab-2': ['pty-3'] } + } + const churnedNotice: CodexRestartInputsState = { + ptyIdsByTabId: state.ptyIdsByTabId, + codexRestartNoticeByPtyId: {} // fresh empty object, same as a teardown re-spread + } + expect(selectCodexRestartInputs(churnedPty)).toBe(EMPTY_CODEX_RESTART_INPUTS) + expect(selectCodexRestartInputs(churnedNotice)).toBe(EMPTY_CODEX_RESTART_INPUTS) + expect(shallow(selectCodexRestartInputs(state), selectCodexRestartInputs(churnedNotice))).toBe( + true + ) + }) + + it('exposes both live maps the instant a restart notice exists', () => { + const ptyIdsByTabId = { 'tab-1': ['pty-1'] } + const codexRestartNoticeByPtyId = { 'pty-1': {} as never } + const state: CodexRestartInputsState = { ptyIdsByTabId, codexRestartNoticeByPtyId } + const selected = selectCodexRestartInputs(state) + // Live references pass straight through so the stale-pty memo + notice lookup derive fully. + expect(selected.ptyIdsByTabId).toBe(ptyIdsByTabId) + expect(selected.codexRestartNoticeByPtyId).toBe(codexRestartNoticeByPtyId) + expect(selected).not.toBe(EMPTY_CODEX_RESTART_INPUTS) + }) + + it('shallow-changes only when a live map reference changes while a notice exists', () => { + const ptyIdsByTabId = { 'tab-1': ['pty-1'] } + const s1: CodexRestartInputsState = { + ptyIdsByTabId, + codexRestartNoticeByPtyId: { 'pty-1': {} as never } + } + const r1 = selectCodexRestartInputs(s1) + expect(shallow(r1, selectCodexRestartInputs(s1))).toBe(true) + + const s2: CodexRestartInputsState = { ...s1, ptyIdsByTabId: { 'tab-1': ['pty-9'] } } + expect(shallow(r1, selectCodexRestartInputs(s2))).toBe(false) + }) +}) diff --git a/src/renderer/src/components/codex-restart-chip-inputs.ts b/src/renderer/src/components/codex-restart-chip-inputs.ts new file mode 100644 index 000000000..eec46f6a8 --- /dev/null +++ b/src/renderer/src/components/codex-restart-chip-inputs.ts @@ -0,0 +1,37 @@ +import type { AppState } from '@/store/types' + +export type CodexRestartInputsState = Pick + +export type CodexRestartInputs = CodexRestartInputsState + +// Why: shared frozen bundle returned while no Codex restart notice exists — the +// overwhelmingly common case. CodexRestartChip is mounted once per worktree +// Terminal (visible AND hidden-measurable) and once per split group, and reads +// these two maps only to find panes carrying a restart notice, which appear only +// on a Codex account switch. BOTH churn on unrelated pty lifecycle: +// ptyIdsByTabId gets a fresh identity on every pty register/attach/detach, and +// codexRestartNoticeByPtyId is re-spread into a new object even when empty on the +// pty exit/teardown path (terminals.ts clearTabPtyId). Subscribing to either +// re-rendered every mounted chip on that churn. Gate both behind notice-existence +// so idle chips keep the same reference and stop reacting; behavior is identical +// (no notice -> [] stale ids -> null render). Frozen so the singleton can't be +// mutated. +export const EMPTY_CODEX_RESTART_INPUTS: CodexRestartInputs = Object.freeze({ + ptyIdsByTabId: {}, + codexRestartNoticeByPtyId: {} +}) + +/** + * Expose the pty and restart-notice maps to the chip only while at least one + * Codex restart notice is live; otherwise return a stable frozen bundle so a + * `useShallow` subscription skips re-renders on unrelated pty-lifecycle churn. + */ +export function selectCodexRestartInputs(s: CodexRestartInputsState): CodexRestartInputs { + if (Object.keys(s.codexRestartNoticeByPtyId).length === 0) { + return EMPTY_CODEX_RESTART_INPUTS + } + return { + ptyIdsByTabId: s.ptyIdsByTabId, + codexRestartNoticeByPtyId: s.codexRestartNoticeByPtyId + } +} diff --git a/src/renderer/src/components/dashboard/useNow.test.ts b/src/renderer/src/components/dashboard/useNow.test.ts index b36d6dc19..304eb190a 100644 --- a/src/renderer/src/components/dashboard/useNow.test.ts +++ b/src/renderer/src/components/dashboard/useNow.test.ts @@ -1,7 +1,12 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { createSharedNowClock } from './useNow' describe('createSharedNowClock', () => { + afterEach(() => { + // Only the hidden-window test stubs `document`; unstub so it can't leak. + vi.unstubAllGlobals() + }) + it('shares one timer across subscribers and clears it when idle', () => { let now = 1_000 const intervalCallbacks: (() => void)[] = [] @@ -65,4 +70,54 @@ describe('createSharedNowClock', () => { expect(second).toHaveBeenCalledTimes(1) expect(setIntervalMock).toHaveBeenCalledTimes(2) }) + + it('does not arm the timer while hidden and catches up when the window becomes visible', () => { + let visibilityState: DocumentVisibilityState = 'hidden' + const documentListeners = new Map void>() + vi.stubGlobal('document', { + get visibilityState() { + return visibilityState + }, + addEventListener: vi.fn((event: string, listener: () => void) => { + documentListeners.set(event, listener) + }), + removeEventListener: vi.fn() + }) + + let now = 1_000 + const handle = {} as ReturnType + const setIntervalMock = vi.fn(() => handle) + const clearIntervalMock = vi.fn() + const listener = vi.fn() + const clock = createSharedNowClock(30_000, { + now: () => now, + setInterval: setIntervalMock, + clearInterval: clearIntervalMock + }) + + const unsubscribe = clock.subscribe(listener) + // Hidden on mount: no timer armed, no forced render, snapshot untouched. + expect(setIntervalMock).not.toHaveBeenCalled() + expect(listener).not.toHaveBeenCalled() + expect(clock.getSnapshot()).toBe(1_000) + + // Becoming visible catches the stale label up and arms the shared timer. + now = 90_000 + visibilityState = 'visible' + documentListeners.get('visibilitychange')?.() + expect(listener).toHaveBeenCalledTimes(1) + expect(clock.getSnapshot()).toBe(90_000) + expect(setIntervalMock).toHaveBeenCalledTimes(1) + + // Hiding again stops the shared timer so it stops ticking in the background. + visibilityState = 'hidden' + documentListeners.get('visibilitychange')?.() + expect(clearIntervalMock).toHaveBeenCalledWith(handle) + + unsubscribe() + expect(document.removeEventListener).toHaveBeenCalledWith( + 'visibilitychange', + documentListeners.get('visibilitychange') + ) + }) }) diff --git a/src/renderer/src/components/dashboard/useNow.ts b/src/renderer/src/components/dashboard/useNow.ts index bb7c1ad42..aa965e95f 100644 --- a/src/renderer/src/components/dashboard/useNow.ts +++ b/src/renderer/src/components/dashboard/useNow.ts @@ -1,9 +1,13 @@ import { useSyncExternalStore } from 'react' +import { + installWindowVisibilityInterval, + type WindowVisibilityIntervalTimer +} from '@/lib/window-visibility-interval' type ClockDeps = { now: () => number - setInterval: (callback: () => void, intervalMs: number) => ReturnType - clearInterval: (handle: ReturnType) => void + setInterval: (callback: () => void, intervalMs: number) => WindowVisibilityIntervalTimer + clearInterval: (handle: WindowVisibilityIntervalTimer) => void } type SharedNowClock = { @@ -22,7 +26,7 @@ export function createSharedNowClock( } ): SharedNowClock { let now = deps.now() - let timer: ReturnType | null = null + let stopInterval: (() => void) | null = null const listeners = new Set<() => void>() const tick = (): void => { @@ -36,18 +40,24 @@ export function createSharedNowClock( getSnapshot: () => now, subscribe: (listener) => { listeners.add(listener) - if (!timer) { - // Why: all mounted relative-time labels at the same cadence can share - // one timer. Refresh immediately on restart so remounted labels don't - // display the stale timestamp left from the previous subscriber set. - tick() - timer = deps.setInterval(tick, intervalMs) + if (!stopInterval) { + // Why: all mounted relative-time labels at this cadence share one + // visibility-gated timer. installWindowVisibilityInterval runs tick + // immediately on (re)start — so remounted or newly-visible labels catch + // up at once — and pauses the interval while the window is hidden, so + // backgrounded agent rows stop re-rendering for ticks no one can see. + stopInterval = installWindowVisibilityInterval({ + run: tick, + intervalMs, + setIntervalFn: deps.setInterval, + clearIntervalFn: deps.clearInterval + }) } return () => { listeners.delete(listener) - if (listeners.size === 0 && timer) { - deps.clearInterval(timer) - timer = null + if (listeners.size === 0 && stopInterval) { + stopInterval() + stopInterval = null } } } diff --git a/src/renderer/src/components/editor/editor-autosave-controller.test.ts b/src/renderer/src/components/editor/editor-autosave-controller.test.ts index 8493536a2..9d50997d9 100644 --- a/src/renderer/src/components/editor/editor-autosave-controller.test.ts +++ b/src/renderer/src/components/editor/editor-autosave-controller.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: autosave behavior depends on event wiring, - dirty drafts, remote routing, quiesce, and failure cleanup in one harness. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createStore, type StoreApi } from 'zustand/vanilla' import { createEditorSlice } from '@/store/slices/editor' diff --git a/src/renderer/src/components/emulator-pane/EmulatorPane.tsx b/src/renderer/src/components/emulator-pane/EmulatorPane.tsx index 742ff08df..476c79e23 100644 --- a/src/renderer/src/components/emulator-pane/EmulatorPane.tsx +++ b/src/renderer/src/components/emulator-pane/EmulatorPane.tsx @@ -29,7 +29,8 @@ export default function EmulatorPane({ tab, worktreeId, isActive = true }: Emula previewUrl, wsUrl, streamKey, - isLive + isLive, + visualOrientation } = useEmulatorPaneSession({ worktreeId, tabId: tab?.id, @@ -80,6 +81,7 @@ export default function EmulatorPane({ tab, worktreeId, isActive = true }: Emula deviceName={displayName} loading={loading} isLive={isLive} + visualOrientation={visualOrientation} isActive={isActive} onTap={(x, y) => void sendTap(x, y)} onGesture={(points) => void sendGesture(points)} diff --git a/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.test.ts b/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.test.ts index 9cfd4d265..f1c567e9f 100644 --- a/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.test.ts +++ b/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it } from 'vitest' -import { fitDeviceFrameToPane, resolveDeviceFrameKind } from './emulator-device-frame-layout' +import { + fitDeviceFrameToPane, + resolveDeviceFrameKind, + resolveVisualScreenAspectRatio, + resolveVisualStreamGeometry +} from './emulator-device-frame-layout' describe('resolveDeviceFrameKind', () => { it('prefers device names over aspect-ratio fallback', () => { @@ -13,6 +18,42 @@ describe('resolveDeviceFrameKind', () => { }) }) +describe('resolveVisualScreenAspectRatio', () => { + it('uses the requested orientation even when the stream canvas has not swapped yet', () => { + const portraitStream = { width: 390, height: 844 } + + expect(resolveVisualScreenAspectRatio(portraitStream, 'portrait')).toBeCloseTo(390 / 844) + expect(resolveVisualScreenAspectRatio(portraitStream, 'landscape')).toBeCloseTo(844 / 390) + }) + + it('uses the requested orientation only before a stream frame arrives', () => { + expect(resolveVisualScreenAspectRatio(null, 'portrait')).toBeCloseTo(9 / 19) + expect(resolveVisualScreenAspectRatio(null, 'landscape')).toBeCloseTo(19 / 9) + }) +}) + +describe('resolveVisualStreamGeometry', () => { + it('uses visual orientation for the interactive screen rectangle', () => { + const geometry = resolveVisualStreamGeometry({ width: 390, height: 844 }, 'landscape') + + expect(geometry.size).toEqual({ + width: 844, + height: 390 + }) + expect(geometry.streamRotation).toBe(90) + }) + + it('rotates a stale landscape stream back into portrait geometry', () => { + const geometry = resolveVisualStreamGeometry({ width: 844, height: 390 }, 'portrait') + + expect(geometry.size).toEqual({ + width: 390, + height: 844 + }) + expect(geometry.streamRotation).toBe(-90) + }) +}) + describe('fitDeviceFrameToPane', () => { it('fits a phone shell and hardware controls inside the pane', () => { const pane = { width: 600, height: 1000 } @@ -50,4 +91,15 @@ describe('fitDeviceFrameToPane', () => { expect(layout?.shellWidth).toBeGreaterThan(1) expect(layout?.shellHeight).toBeGreaterThan(1) }) + + it('fits the entire phone frame as landscape after a device rotation', () => { + const pane = { width: 1000, height: 600 } + const aspectRatio = resolveVisualScreenAspectRatio({ width: 844, height: 390 }, 'landscape') + const layout = fitDeviceFrameToPane(pane, aspectRatio, 'phone') + + expect(layout).not.toBeNull() + expect(layout?.width).toBeLessThanOrEqual(pane.width) + expect(layout?.height).toBeLessThanOrEqual(pane.height) + expect(layout ? layout.shellWidth / layout.shellHeight : 0).toBeGreaterThan(1) + }) }) diff --git a/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.ts b/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.ts index 62aac8367..0948ad3db 100644 --- a/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.ts +++ b/src/renderer/src/components/emulator-pane/emulator-device-frame-layout.ts @@ -5,6 +5,8 @@ export type StreamSize = { height: number } +export type EmulatorDeviceVisualOrientation = 'portrait' | 'landscape' + export type PaneSize = { width: number height: number @@ -23,6 +25,12 @@ export type DeviceFrameLayout = { sideButtonThickness: number } +export type VisualStreamGeometry = { + aspectRatio: number + size: StreamSize | null + streamRotation: -90 | 0 | 90 +} + const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value)) const FIT_MARGIN_PX = 0.5 @@ -40,6 +48,38 @@ export function resolveDeviceFrameKind( return screenAspectRatio > 0.62 && screenAspectRatio < 1.62 ? 'tablet' : 'phone' } +export function resolveVisualScreenAspectRatio( + streamSize: StreamSize | null, + visualOrientation: EmulatorDeviceVisualOrientation +): number { + return resolveVisualStreamGeometry(streamSize, visualOrientation).aspectRatio +} + +export function resolveVisualStreamGeometry( + streamSize: StreamSize | null, + visualOrientation: EmulatorDeviceVisualOrientation +): VisualStreamGeometry { + // Why: serve-sim can keep the same canvas dimensions after rotate; the pane's + // physical frame and input rect still need to follow the successful request. + const width = streamSize?.width ?? 9 + const height = streamSize?.height ?? 19 + const shortSide = Math.min(width, height) + const longSide = Math.max(width, height) + const visualSize = + visualOrientation === 'landscape' + ? { width: longSide, height: shortSide } + : { width: shortSide, height: longSide } + const streamIsLandscape = streamSize ? streamSize.width > streamSize.height : false + const visualIsLandscape = visualOrientation === 'landscape' + const streamRotation = + streamSize && streamIsLandscape !== visualIsLandscape ? (visualIsLandscape ? 90 : -90) : 0 + return { + aspectRatio: visualSize.width / visualSize.height, + size: streamSize ? visualSize : null, + streamRotation + } +} + function fitScreenToPane(paneSize: PaneSize | null, aspectRatio: number): PaneSize | null { if (!paneSize || paneSize.width <= 0 || paneSize.height <= 0 || aspectRatio <= 0) { return null diff --git a/src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx b/src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx index 12409234f..b2a9621ba 100644 --- a/src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx +++ b/src/renderer/src/components/emulator-pane/emulator-device-frame-visibility.test.tsx @@ -67,6 +67,7 @@ async function renderFrame(isActive: boolean): Promise { wsUrl="ws://127.0.0.1:3100/ws" loading={false} isLive={true} + visualOrientation="portrait" isActive={isActive} onTap={vi.fn()} onGesture={vi.fn()} diff --git a/src/renderer/src/components/emulator-pane/emulator-device-frame.input.test.tsx b/src/renderer/src/components/emulator-pane/emulator-device-frame.input.test.tsx index b32824bb9..dd198c82b 100644 --- a/src/renderer/src/components/emulator-pane/emulator-device-frame.input.test.tsx +++ b/src/renderer/src/components/emulator-pane/emulator-device-frame.input.test.tsx @@ -99,6 +99,7 @@ function renderFrame(props?: { wsUrl="ws://127.0.0.1:3100/ws" loading={false} isLive={true} + visualOrientation="portrait" isActive={true} onTap={props?.onTap ?? vi.fn()} onGesture={props?.onGesture ?? vi.fn()} diff --git a/src/renderer/src/components/emulator-pane/emulator-device-frame.tsx b/src/renderer/src/components/emulator-pane/emulator-device-frame.tsx index 7f9e2cda8..9b278241d 100644 --- a/src/renderer/src/components/emulator-pane/emulator-device-frame.tsx +++ b/src/renderer/src/components/emulator-pane/emulator-device-frame.tsx @@ -9,7 +9,9 @@ import { } from 'react' import { fitDeviceFrameToPane, + resolveVisualStreamGeometry, resolveDeviceFrameKind, + type EmulatorDeviceVisualOrientation, type StreamSize } from './emulator-device-frame-layout' import { @@ -25,12 +27,10 @@ import { type PointerSample } from './emulator-screen-gesture' import { PhoneHardwareButtons } from './emulator-phone-hardware-buttons' -import { EmulatorScreenStreamContent } from './emulator-screen-stream-content' +import { EmulatorScreenSurface } from './emulator-screen-surface' import { useEmulatorControlStream } from './use-emulator-control-stream' import { useEmulatorPaneSize } from './use-emulator-pane-size' import { useEmulatorScreenKeyboard } from './use-emulator-screen-keyboard' -import { getEmulatorScreenAriaLabel } from './emulator-screen-aria-label' -import { cn } from '@/lib/utils' type EmulatorDeviceFrameProps = { previewUrl?: string @@ -39,8 +39,8 @@ type EmulatorDeviceFrameProps = { deviceName?: string loading: boolean isLive: boolean - /** False when the pane is backgrounded (hidden tab/worktree). Gates the frame - * stream so a parked emulator stops decoding, matching the pane's visibility. */ + visualOrientation: EmulatorDeviceVisualOrientation + /** False when backgrounded; parks the stream with the pane's visibility. */ isActive: boolean onTap: (x: number, y: number) => void onGesture: (points: EmulatorGesturePoint[]) => void @@ -55,11 +55,10 @@ type PendingWheelGesture = { timerId: number | null } -type ScreenCoordinateEvent = { - clientX: number - clientY: number - currentTarget: HTMLDivElement -} +type ScreenCoordinateEvent = Pick< + PointerEvent, + 'clientX' | 'clientY' | 'currentTarget' +> export function EmulatorDeviceFrame({ previewUrl, @@ -68,6 +67,7 @@ export function EmulatorDeviceFrame({ deviceName, loading, isLive, + visualOrientation, isActive, onTap, onGesture @@ -81,6 +81,10 @@ export function EmulatorDeviceFrame({ const wheelGestureRef = useRef(null) const [streamError, setStreamError] = useState(false) const [streamSize, setStreamSize] = useState(null) + const visualStreamGeometry = useMemo( + () => resolveVisualStreamGeometry(streamSize, visualOrientation), + [streamSize, visualOrientation] + ) const canInteract = isLive && !loading && !streamError const { cancelKeyboardFrames, sendKeyboardFrames, sendTouch } = useEmulatorControlStream( wsUrl, @@ -103,9 +107,9 @@ export function EmulatorDeviceFrame({ mapClientPointToSimulatorScreen( { clientX: event.clientX, clientY: event.clientY }, event.currentTarget.getBoundingClientRect(), - streamSize + visualStreamGeometry.size ), - [streamSize] + [visualStreamGeometry.size] ) const sendGesturePoints = useCallback( @@ -262,7 +266,7 @@ export function EmulatorDeviceFrame({ const action = resolveEmulatorPointerAction( samples, event.currentTarget.getBoundingClientRect(), - streamSize + visualStreamGeometry.size ) if (!action) { return @@ -273,7 +277,7 @@ export function EmulatorDeviceFrame({ sendGesturePoints(action.points) } }, - [canInteract, mapEventToScreenPoint, onTap, sendGesturePoints, sendTouch, streamSize] + [canInteract, mapEventToScreenPoint, onTap, sendGesturePoints, sendTouch, visualStreamGeometry] ) const handleWheel = useCallback( @@ -290,7 +294,7 @@ export function EmulatorDeviceFrame({ deltaY: event.deltaY }, event.currentTarget.getBoundingClientRect(), - streamSize + visualStreamGeometry.size ) if (!delta) { return @@ -317,7 +321,7 @@ export function EmulatorDeviceFrame({ timerId: window.setTimeout(flushWheelGesture, WHEEL_GESTURE_IDLE_MS) } }, - [canInteract, flushWheelGesture, sendTouch, streamSize] + [canInteract, flushWheelGesture, sendTouch, visualStreamGeometry] ) const handleStreamSize = useCallback((size: NonNullable) => { @@ -331,20 +335,16 @@ export function EmulatorDeviceFrame({ setStreamError(true) }, []) - // Why: only decode frames while the pane is visible. A backgrounded but still - // attached emulator otherwise keeps running the WebCodecs H.264 decode / MJPEG - // blob churn against a hidden canvas, with frames still flowing over IPC (and - // the network for paired SSH/remote clients). The session stays attached, so - // the stream re-fires within a frame on re-show. Mirrors the browser pane's - // park-when-hidden behavior. + // Why: hidden panes still receive emulator frames, including over SSH, so + // parking the stream avoids background decode/IPC churn while staying attached. const showStream = isActive && isLive && Boolean(previewUrl) - const screenAspectRatio = streamSize ? streamSize.width / streamSize.height : 9 / 19 - const screenAspectRatioStyle = streamSize - ? `${streamSize.width} / ${streamSize.height}` - : '9 / 19' + const streamAspectRatio = streamSize ? streamSize.width / streamSize.height : 9 / 19 + // Why: serve-sim may keep portrait-sized pixels for portrait-locked apps; the + // physical frame still follows the last successful rotate request. + const screenAspectRatio = visualStreamGeometry.aspectRatio const frameKind = useMemo( - () => resolveDeviceFrameKind(deviceName, screenAspectRatio), - [deviceName, screenAspectRatio] + () => resolveDeviceFrameKind(deviceName, streamAspectRatio), + [deviceName, streamAspectRatio] ) const frameLayout = useMemo( () => fitDeviceFrameToPane(paneSize, screenAspectRatio, frameKind), @@ -376,43 +376,28 @@ export function EmulatorDeviceFrame({ borderRadius: frameLayout ? `${frameLayout.outerRadius}px` : '54px' }} > -
- {/* Why: the stream is the actual emulator screen; fake in-screen - chrome doubles up with iOS's real status bar and makes bezels lie. */} - -
+ previewUrl={previewUrl} + screenAspectRatio={screenAspectRatio} + showStream={Boolean(showStream)} + streamError={streamError} + streamKey={streamKey} + streamRotation={visualStreamGeometry.streamRotation} + /> diff --git a/src/renderer/src/components/emulator-pane/emulator-device-row-mapping.ts b/src/renderer/src/components/emulator-pane/emulator-device-row-mapping.ts new file mode 100644 index 000000000..b778034f1 --- /dev/null +++ b/src/renderer/src/components/emulator-pane/emulator-device-row-mapping.ts @@ -0,0 +1,20 @@ +import type { SimulatorDeviceRow } from './emulator-pane-types' + +// Raw shape returned by the unified `emulator.listDevices` RPC (iOS simulators + Android AVDs). +export type RawEmulatorDevice = { + id: string + name: string + state: string + detail?: string + isAvailable?: boolean +} + +export function toSimulatorDeviceRows(raw: RawEmulatorDevice[]): SimulatorDeviceRow[] { + return raw.map((device) => ({ + name: device.name, + udid: device.id, + state: device.state === 'booted' ? 'Booted' : 'Shutdown', + runtime: device.detail, + isAvailable: device.isAvailable + })) +} diff --git a/src/renderer/src/components/emulator-pane/emulator-screen-gesture.test.ts b/src/renderer/src/components/emulator-pane/emulator-screen-gesture.test.ts index b199863bd..3d22461c5 100644 --- a/src/renderer/src/components/emulator-pane/emulator-screen-gesture.test.ts +++ b/src/renderer/src/components/emulator-pane/emulator-screen-gesture.test.ts @@ -5,6 +5,7 @@ import { resolveEmulatorWheelDelta, resolveEmulatorPointerAction } from './emulator-screen-gesture' +import { resolveVisualStreamGeometry } from './emulator-device-frame-layout' const rect = { left: 10, @@ -114,4 +115,22 @@ describe('emulator screen gestures', () => { }) ).toBeNull() }) + + it('maps the full landscape screen while the stream canvas shape settles', () => { + const landscapeRect = { + left: 0, + top: 0, + width: 400, + height: 200 + } + const stalePortraitStream = { width: 390, height: 844 } + + expect( + mapClientPointToSimulatorScreen( + { clientX: 380, clientY: 100 }, + landscapeRect, + resolveVisualStreamGeometry(stalePortraitStream, 'landscape').size + ) + ).toEqual({ x: 0.95, y: 0.5 }) + }) }) diff --git a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx index 141048430..af19c21e4 100644 --- a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx +++ b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.test.tsx @@ -90,7 +90,10 @@ afterEach(() => { vi.restoreAllMocks() }) -async function renderStream(streamKey = 'abc'): Promise { +async function renderStream( + streamKey = 'abc', + props?: { screenAspectRatio?: number; streamRotation?: -90 | 0 | 90 } +): Promise { await act(async () => { root.render( { onStreamError={vi.fn()} onStreamSize={vi.fn()} previewUrl="http://127.0.0.1:3100/stream.mjpeg" + screenAspectRatio={props?.screenAspectRatio} showStream={true} streamError={false} streamKey={streamKey} + streamRotation={props?.streamRotation} /> ) }) @@ -122,6 +127,24 @@ describe('EmulatorScreenStreamContent', () => { const img = container.querySelector('img') expect(img?.getAttribute('src')).toBe('blob:emulator-frame-1') + expect(img?.className).toContain('object-contain') + expect(img?.className).not.toContain('object-fill') + }) + + it('rotates mismatched stream media without stretching it', async () => { + await renderStream('abc', { screenAspectRatio: 844 / 390, streamRotation: 90 }) + + await act(async () => { + frameListeners[0]?.({ streamId: 'stream-1', bytes: new Uint8Array([1, 2, 3]).buffer }) + }) + + const img = container.querySelector('img') + expect(img?.className).toContain('object-contain') + expect(img?.className).toContain('absolute') + expect(img?.className).not.toContain('object-fill') + expect(img?.style.transform).toBe('translate(-50%, -50%) rotate(90deg)') + expect(img?.style.width).toBe(`${100 / (844 / 390)}%`) + expect(img?.style.height).toBe(`${100 * (844 / 390)}%`) }) it('clears the previous frame while a new stream key is connecting', async () => { diff --git a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx index 3e86ed145..4b83495e0 100644 --- a/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx +++ b/src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx @@ -1,8 +1,9 @@ import { Loader2 } from 'lucide-react' -import { useEffect } from 'react' +import { useEffect, type CSSProperties } from 'react' import { useEmulatorFrameStream } from './use-emulator-frame-stream' import { useEmulatorVideoStream } from './use-emulator-video-stream' import { translate } from '@/i18n/i18n' +import type { VisualStreamGeometry } from './emulator-device-frame-layout' type StreamSize = { height: number @@ -14,9 +15,11 @@ type EmulatorScreenStreamContentProps = { onStreamError: () => void onStreamSize: (size: StreamSize) => void previewUrl?: string + screenAspectRatio?: number showStream: boolean streamError: boolean streamKey?: string + streamRotation?: VisualStreamGeometry['streamRotation'] } // Android sessions stream H.264 over scrcpy://; iOS uses an MJPEG http URL. @@ -27,9 +30,11 @@ export function EmulatorScreenStreamContent({ onStreamError, onStreamSize, previewUrl, + screenAspectRatio = 9 / 19, showStream, streamError, - streamKey + streamKey, + streamRotation = 0 }: EmulatorScreenStreamContentProps) { const androidDeviceId = previewUrl && previewUrl.startsWith(SCRCPY_PREFIX) @@ -54,11 +59,18 @@ export function EmulatorScreenStreamContent({ } }, [frameStream.error, video.error, onStreamError]) + const mediaStyle = resolveStreamMediaStyle(streamRotation, screenAspectRatio) + const mediaClassName = + streamRotation === 0 + ? 'block h-full w-full bg-black object-contain' + : 'absolute left-1/2 top-1/2 block max-w-none bg-black object-contain' + if (androidDeviceId && showStream && !video.error) { return ( { const { naturalWidth, naturalHeight } = event.currentTarget @@ -123,3 +136,18 @@ export function EmulatorScreenStreamContent({ ) } + +function resolveStreamMediaStyle( + streamRotation: VisualStreamGeometry['streamRotation'], + screenAspectRatio: number +): CSSProperties | undefined { + if (streamRotation === 0 || screenAspectRatio <= 0) { + return undefined + } + return { + height: `${100 * screenAspectRatio}%`, + transform: `translate(-50%, -50%) rotate(${streamRotation}deg)`, + transformOrigin: 'center', + width: `${100 / screenAspectRatio}%` + } +} diff --git a/src/renderer/src/components/emulator-pane/emulator-screen-surface.tsx b/src/renderer/src/components/emulator-pane/emulator-screen-surface.tsx new file mode 100644 index 000000000..325116ff5 --- /dev/null +++ b/src/renderer/src/components/emulator-pane/emulator-screen-surface.tsx @@ -0,0 +1,103 @@ +import type { + ClipboardEventHandler, + FocusEventHandler, + KeyboardEventHandler, + PointerEventHandler, + WheelEventHandler +} from 'react' +import { cn } from '@/lib/utils' +import { getEmulatorScreenAriaLabel } from './emulator-screen-aria-label' +import { EmulatorScreenStreamContent } from './emulator-screen-stream-content' +import type { + DeviceFrameLayout, + StreamSize, + VisualStreamGeometry +} from './emulator-device-frame-layout' + +type EmulatorScreenSurfaceProps = { + frameLayout: DeviceFrameLayout | null + isLive: boolean + keyboardCaptureActive: boolean + loading: boolean + onBlur: FocusEventHandler + onKeyDown: KeyboardEventHandler + onPaste: ClipboardEventHandler + onPointerCancel: PointerEventHandler + onPointerDown: PointerEventHandler + onPointerMove: PointerEventHandler + onPointerUp: PointerEventHandler + onStreamError: () => void + onStreamSize: (size: StreamSize) => void + onWheel: WheelEventHandler + previewUrl?: string + screenAspectRatio: number + showStream: boolean + streamError: boolean + streamKey?: string + streamRotation: VisualStreamGeometry['streamRotation'] +} + +export function EmulatorScreenSurface({ + frameLayout, + isLive, + keyboardCaptureActive, + loading, + onBlur, + onKeyDown, + onPaste, + onPointerCancel, + onPointerDown, + onPointerMove, + onPointerUp, + onStreamError, + onStreamSize, + onWheel, + previewUrl, + screenAspectRatio, + showStream, + streamError, + streamKey, + streamRotation +}: EmulatorScreenSurfaceProps) { + return ( +
+ {/* Why: the stream is the actual emulator screen; fake in-screen chrome + doubles up with iOS's real status bar and makes bezels lie. */} + +
+ ) +} diff --git a/src/renderer/src/components/emulator-pane/use-emulator-pane-controls.ts b/src/renderer/src/components/emulator-pane/use-emulator-pane-controls.ts index c760c4f51..42f9d9cab 100644 --- a/src/renderer/src/components/emulator-pane/use-emulator-pane-controls.ts +++ b/src/renderer/src/components/emulator-pane/use-emulator-pane-controls.ts @@ -1,9 +1,13 @@ -import { useCallback, useRef } from 'react' +import { useCallback, useRef, useState } from 'react' import { callRuntimeRpc } from '@/runtime/runtime-rpc-client' +import type { EmulatorDeviceVisualOrientation } from './emulator-device-frame-layout' import type { EmulatorGesturePoint } from './emulator-screen-gesture' -export function useEmulatorPaneControls(worktreeId: string) { +export function useEmulatorPaneControls(worktreeId: string, onRotateSettled?: () => void) { const nextRotateOrientationRef = useRef<'landscape_left' | 'portrait'>('landscape_left') + const visualOrientationEpochRef = useRef(0) + const [visualOrientation, setVisualOrientation] = + useState('portrait') const sendTap = useCallback( async (x: number, y: number) => { @@ -28,13 +32,27 @@ export function useEmulatorPaneControls(worktreeId: string) { const sendRotate = useCallback(async () => { const orientation = nextRotateOrientationRef.current + const epoch = visualOrientationEpochRef.current await callRuntimeRpc({ kind: 'local' }, 'emulator.rotate', { orientation, worktree: worktreeId }) + if (visualOrientationEpochRef.current !== epoch) { + return null + } + const nextVisualOrientation = orientation === 'landscape_left' ? 'landscape' : 'portrait' + setVisualOrientation(nextVisualOrientation) nextRotateOrientationRef.current = orientation === 'landscape_left' ? 'portrait' : 'landscape_left' - }, [worktreeId]) + onRotateSettled?.() + return nextVisualOrientation + }, [onRotateSettled, worktreeId]) - return { sendTap, sendButton, sendGesture, sendRotate } + const resetVisualOrientation = useCallback(() => { + visualOrientationEpochRef.current += 1 + nextRotateOrientationRef.current = 'landscape_left' + setVisualOrientation('portrait') + }, []) + + return { sendTap, sendButton, sendGesture, sendRotate, visualOrientation, resetVisualOrientation } } 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 a3342c94c..a9a67bd11 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 @@ -49,6 +49,7 @@ const deviceList = devices.map((device) => ({ })) let attachDeferred: Deferred +let rotateDeferred: Deferred let container: HTMLDivElement let root: Root let latest: ReturnType | null = null @@ -113,6 +114,7 @@ describe('useEmulatorPaneSession', () => { globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean } ).IS_REACT_ACT_ENVIRONMENT = true attachDeferred = createDeferred() + rotateDeferred = createDeferred() latest = null consumePrelaunchedSimulatorSession(WORKTREE_ID) rememberPrelaunchedSimulatorSession(WORKTREE_ID, { @@ -133,6 +135,9 @@ describe('useEmulatorPaneSession', () => { if (method === 'emulator.attach') { return runtimeSuccess(await attachDeferred.promise) } + if (method === 'emulator.rotate') { + return runtimeSuccess(await rotateDeferred.promise) + } if (method === 'emulator.shutdown') { return runtimeSuccess({ deviceUdid: 'device-b' }) } @@ -196,6 +201,48 @@ describe('useEmulatorPaneSession', () => { expect(latest?.previewUrl).toBe('http://127.0.0.1:3200/stream.mjpeg') }) + it('ignores a rotate response from the previous session after switching devices', async () => { + await act(async () => { + root.render() + }) + await flushEffects() + + let rotatePromise: Promise = Promise.resolve() + await act(async () => { + rotatePromise = latest?.sendRotate() ?? Promise.resolve() + await Promise.resolve() + }) + + await act(async () => { + container.querySelector('button')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + await Promise.resolve() + }) + + await act(async () => { + rotateDeferred.resolve() + await rotatePromise + await Promise.resolve() + }) + + expect(latest?.visualOrientation).toBe('portrait') + + await act(async () => { + attachDeferred.resolve({ + attached: true, + info: { + deviceUdid: 'device-b', + displayName: 'iPhone B', + streamUrl: 'http://127.0.0.1:3200/stream.mjpeg', + wsUrl: 'ws://127.0.0.1:3200/ws' + } + }) + await attachDeferred.promise + await Promise.resolve() + }) + + expect(latest?.visualOrientation).toBe('portrait') + }) + it('keeps simulator discovery setup errors during auto attach', async () => { const message = 'Xcode Simulator tools are unavailable. Install full Xcode, open it once, then select it with `sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer`.' 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 0a1dac53c..2ac04a9ca 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 @@ -8,6 +8,7 @@ import { type SimulatorDeviceRow } from './emulator-pane-types' import { markSimulatorDeviceBooted, markSimulatorDeviceShutdown } from './emulator-device-state' +import { toSimulatorDeviceRows, type RawEmulatorDevice } from './emulator-device-row-mapping' import { useEmulatorPaneControls } from './use-emulator-pane-controls' import { useEmulatorPaneSessionEvents } from './use-emulator-pane-session-events' import { @@ -56,25 +57,25 @@ export function useEmulatorPaneSession({ const liveTargetRef = useRef(prelaunchedState.liveTarget) const deviceRefreshErrorRef = useRef(null) const suppressAutoAttachRef = useRef(false) - const { sendTap, sendButton, sendGesture, sendRotate } = useEmulatorPaneControls(worktreeId) + const refreshStreamKey = useCallback(() => setStreamKey(String(Date.now())), []) + const { + sendTap, + sendButton, + sendGesture, + sendRotate, + visualOrientation, + resetVisualOrientation + } = useEmulatorPaneControls(worktreeId, refreshStreamKey) const refreshDevices = useCallback(async (bootedTarget?: string | null) => { try { // Unified list so Android devices/AVDs appear alongside iOS simulators. - const raw = (await callRuntimeRpc({ kind: 'local' }, 'emulator.listDevices', {})) as { - id: string - name: string - state: string - detail?: string - isAvailable?: boolean - }[] - const list: SimulatorDeviceRow[] = raw.map((device) => ({ - name: device.name, - udid: device.id, - state: device.state === 'booted' ? 'Booted' : 'Shutdown', - runtime: device.detail, - isAvailable: device.isAvailable - })) + const raw = (await callRuntimeRpc( + { kind: 'local' }, + 'emulator.listDevices', + {} + )) as RawEmulatorDevice[] + const list = toSimulatorDeviceRows(raw) const next = markSimulatorDeviceBooted(list, bootedTarget) if (!mountedRef.current) { return next @@ -106,6 +107,9 @@ export function useEmulatorPaneSession({ if (attached && rows !== deviceRows) { setDevices(rows) } + if (attached && target && target !== liveTargetRef.current) { + resetVisualOrientation() + } const row = rows.find((d) => d.udid === target || d.name === target) const displayName = row?.name || deviceLabel(info) const enriched = { ...info, displayName, state: attached ? 'Booted' : info?.state } @@ -126,7 +130,7 @@ export function useEmulatorPaneSession({ useAppStore.getState().setTabLabel(tabId, displayName) } }, - [devices, tabId] + [devices, resetVisualOrientation, tabId] ) const clearSessionAfterShutdown = useCallback( @@ -141,13 +145,14 @@ export function useEmulatorPaneSession({ liveTargetRef.current = null suppressAutoAttachRef.current = true setStreamKey(null) + resetVisualOrientation() setError(null) if (tabId) { const row = devices.find((device) => device.udid === target || device.name === target) useAppStore.getState().setTabLabel(tabId, row?.name || 'Mobile Emulator') } }, - [devices, selectedUdid, session, tabId] + [devices, resetVisualOrientation, selectedUdid, session, tabId] ) const attach = useCallback( @@ -189,6 +194,7 @@ export function useEmulatorPaneSession({ setSession(null) setStreamKey(null) liveTargetRef.current = null + resetVisualOrientation() } const res = (await callRuntimeRpc({ kind: 'local' }, 'emulator.attach', { device: target, @@ -238,6 +244,7 @@ export function useEmulatorPaneSession({ devices, loading, refreshDevices, + resetVisualOrientation, selectedUdid, tabId, worktreeId @@ -301,6 +308,7 @@ export function useEmulatorPaneSession({ sendButton, sendGesture, sendRotate, + visualOrientation, displayName: view.displayName, previewUrl: view.previewUrl, wsUrl: view.wsUrl, diff --git a/src/renderer/src/components/github-item-dialog-merge-routing.test.ts b/src/renderer/src/components/github-item-dialog-merge-routing.test.ts new file mode 100644 index 000000000..8374fe94b --- /dev/null +++ b/src/renderer/src/components/github-item-dialog-merge-routing.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from 'vitest' +import { + getSettingsForRepoRuntimeOwner, + type RepoRuntimeOwnerState +} from '../lib/repo-runtime-owner' +import { getActiveRuntimeTarget } from '../runtime/runtime-rpc-client' +import type { TaskSourceContext } from '../../../shared/task-source-context' +import { getTaskSourceRuntimeSettings } from '../../../shared/task-source-context' + +// Why: mirrors the merge-routing decision inside GitHubItemDialog's +// PRActionsPanel so a revert to source-only routing (issue #6957) fails here. +// A runtime-owned repo whose GitHub source view is local must still merge on +// the owner runtime, not fall back to local `gh:mergePR`. +function resolveMergeTarget( + state: RepoRuntimeOwnerState, + repoId: string | null, + sourceContext: TaskSourceContext | null +): ReturnType { + const repoOwnerSettings = getSettingsForRepoRuntimeOwner(state, repoId) + const sourceSettings = + sourceContext?.provider !== 'github' + ? repoOwnerSettings + : (() => { + const sourceRuntimeSettings = getTaskSourceRuntimeSettings(sourceContext) + return sourceRuntimeSettings.activeRuntimeEnvironmentId + ? { ...repoOwnerSettings, ...sourceRuntimeSettings } + : repoOwnerSettings + })() + return getActiveRuntimeTarget(sourceSettings) +} + +function githubSource(hostId: TaskSourceContext['hostId']): TaskSourceContext { + return { kind: 'task-source', provider: 'github', projectId: 'p', hostId, repoId: 'repo-1' } +} + +describe('GitHubItemDialog PR merge routing', () => { + const runtimeOwnedRepo: RepoRuntimeOwnerState = { + settings: { activeRuntimeEnvironmentId: null }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'runtime:owner-runtime' }] + } + + it('routes a runtime-owned repo to its owner runtime when the source view is local (#6957)', () => { + expect(resolveMergeTarget(runtimeOwnedRepo, 'repo-1', githubSource('local'))).toEqual({ + kind: 'environment', + environmentId: 'owner-runtime' + }) + }) + + it('routes a runtime-owned repo to its owner runtime when there is no source context', () => { + expect(resolveMergeTarget(runtimeOwnedRepo, 'repo-1', null)).toEqual({ + kind: 'environment', + environmentId: 'owner-runtime' + }) + }) + + it('lets a runtime source override the repo owner when both are runtimes', () => { + expect( + resolveMergeTarget(runtimeOwnedRepo, 'repo-1', githubSource('runtime:source-runtime')) + ).toEqual({ kind: 'environment', environmentId: 'source-runtime' }) + }) + + it('keeps an explicitly-local repo on local IPC even while a runtime is focused', () => { + const localRepo: RepoRuntimeOwnerState = { + settings: { activeRuntimeEnvironmentId: 'focused-runtime' }, + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'local' }] + } + expect(resolveMergeTarget(localRepo, 'repo-1', githubSource('local'))).toEqual({ + kind: 'local' + }) + }) +}) diff --git a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts b/src/renderer/src/components/github-item-dialog-source-boundary.test.ts index deb287ca2..740d65f67 100644 --- a/src/renderer/src/components/github-item-dialog-source-boundary.test.ts +++ b/src/renderer/src/components/github-item-dialog-source-boundary.test.ts @@ -91,8 +91,8 @@ describe('GitHubItemDialog source host boundaries', () => { expect(source).toContain('sourceContext,') expect(cacheKeySection).toContain('sourceCacheScope') expect(source).toContain('getTaskSourceCacheScope(sourceContext)') - expect(matchInvalidationSection).toContain( - 'if (removed) {\n workItemDetailsCacheGeneration += 1' + expect(matchInvalidationSection).toMatch( + /if \(removed\) {\s+workItemDetailsCacheGeneration \+= 1/ ) }) @@ -190,7 +190,13 @@ describe('GitHubItemDialog source host boundaries', () => { 'function CommentReactions' ) - expect(actionsSection).toContain('getTaskSourceRuntimeSettings(sourceContext)') + expect(actionsSection).toContain('getSettingsForRepoRuntimeOwner(s, repoId ?? item.repoId') + expect(actionsSection).toContain('...repoOwnerSettings') + expect(actionsSection).toContain( + 'const sourceRuntimeSettings = getTaskSourceRuntimeSettings(sourceContext)' + ) + expect(actionsSection).toContain('sourceRuntimeSettings.activeRuntimeEnvironmentId') + expect(actionsSection).toContain('...sourceRuntimeSettings') expect(actionsSection).toContain('getActiveRuntimeTarget(sourceSettings)') expect(actionsSection).toContain( 'const canMergeWithRepoContext = !!repoPath || mergeTarget.kind ===' diff --git a/src/renderer/src/components/native-chat/native-chat-composer-scope-cache.test.ts b/src/renderer/src/components/native-chat/native-chat-composer-scope-cache.test.ts new file mode 100644 index 000000000..07867e8a5 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-composer-scope-cache.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect } from 'vitest' +import { + NATIVE_CHAT_COMPOSER_SCOPE_CACHE_MAX, + setBoundedScopeCacheEntry +} from './native-chat-composer-scope-cache' + +describe('setBoundedScopeCacheEntry', () => { + it('bounds the cache with LRU eviction, keeping re-set keys', () => { + const cache = new Map() + setBoundedScopeCacheEntry(cache, 'keep', 1) + + const total = NATIVE_CHAT_COMPOSER_SCOPE_CACHE_MAX + 20 + for (let i = 0; i < total; i += 1) { + setBoundedScopeCacheEntry(cache, `scope-${i}`, i) + if (i % 10 === 0) { + setBoundedScopeCacheEntry(cache, 'keep', 1) + } + } + + expect(cache.size).toBe(NATIVE_CHAT_COMPOSER_SCOPE_CACHE_MAX) + expect(cache.has('scope-0')).toBe(false) // oldest untouched entry evicted + expect(cache.has('keep')).toBe(true) // periodically re-set → retained + expect(cache.has(`scope-${total - 1}`)).toBe(true) // most recent retained + }) + + it('moves a re-set key to most-recent and updates its value', () => { + const cache = new Map() + setBoundedScopeCacheEntry(cache, 'a', 1) + setBoundedScopeCacheEntry(cache, 'b', 2) + setBoundedScopeCacheEntry(cache, 'a', 3) + + expect([...cache.keys()]).toEqual(['b', 'a']) + expect(cache.get('a')).toBe(3) + }) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-composer-scope-cache.ts b/src/renderer/src/components/native-chat/native-chat-composer-scope-cache.ts new file mode 100644 index 000000000..7a63f16f9 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-composer-scope-cache.ts @@ -0,0 +1,24 @@ +// Shared LRU bound for the native-chat composer's per-scope caches (draft text +// and image attachments), both keyed by `targetPtyId ?? terminalTabId`. The +// caches exist so an in-progress message survives the composer unmounting on a +// TUI/GUI toggle, but a scope key for a permanently-removed pane is never +// revisited, so without a bound its unsent entry would linger for the renderer's +// whole session. delete-then-set keeps the actively-edited scope most-recent so +// eviction only sheds the oldest untouched scopes. +export const NATIVE_CHAT_COMPOSER_SCOPE_CACHE_MAX = 128 + +export function setBoundedScopeCacheEntry( + cache: Map, + scopeKey: string, + value: T +): void { + cache.delete(scopeKey) + cache.set(scopeKey, value) + while (cache.size > NATIVE_CHAT_COMPOSER_SCOPE_CACHE_MAX) { + const oldest = cache.keys().next().value + if (oldest === undefined) { + break + } + cache.delete(oldest) + } +} diff --git a/src/renderer/src/components/native-chat/native-chat-draft-cache.test.ts b/src/renderer/src/components/native-chat/native-chat-draft-cache.test.ts index c12d661e3..7aa0f6585 100644 --- a/src/renderer/src/components/native-chat/native-chat-draft-cache.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-draft-cache.test.ts @@ -4,6 +4,7 @@ import { readNativeChatDraftCache, writeNativeChatDraftCache } from './native-chat-draft-cache' +import { NATIVE_CHAT_COMPOSER_SCOPE_CACHE_MAX } from './native-chat-composer-scope-cache' afterEach(() => { clearNativeChatDraftCacheForTests() @@ -26,4 +27,21 @@ describe('native-chat draft cache', () => { writeNativeChatDraftCache('pty-1', '') expect(readNativeChatDraftCache('pty-1')).toBe('') }) + + it('bounds the cache so unsent drafts for removed panes cannot accumulate', () => { + writeNativeChatDraftCache('keep', 'hot') + + const total = NATIVE_CHAT_COMPOSER_SCOPE_CACHE_MAX + 40 + for (let i = 0; i < total; i += 1) { + writeNativeChatDraftCache(`scope-${i}`, `draft-${i}`) + if (i % 20 === 0) { + writeNativeChatDraftCache('keep', 'hot') + } + } + + // Oldest untouched draft evicted; the actively-edited and most-recent survive. + expect(readNativeChatDraftCache('scope-0')).toBe('') + expect(readNativeChatDraftCache('keep')).toBe('hot') + expect(readNativeChatDraftCache(`scope-${total - 1}`)).toBe(`draft-${total - 1}`) + }) }) diff --git a/src/renderer/src/components/native-chat/native-chat-draft-cache.ts b/src/renderer/src/components/native-chat/native-chat-draft-cache.ts index 2c230c0a4..2a7537444 100644 --- a/src/renderer/src/components/native-chat/native-chat-draft-cache.ts +++ b/src/renderer/src/components/native-chat/native-chat-draft-cache.ts @@ -4,6 +4,8 @@ // the typed-but-unsent draft would be lost on every TUI/GUI round-trip. Mirrors // the attachment cache so both halves of an unsent message survive the toggle. +import { setBoundedScopeCacheEntry } from './native-chat-composer-scope-cache' + const draftCache = new Map() export function readNativeChatDraftCache(scopeKey: string): string { @@ -17,7 +19,8 @@ export function writeNativeChatDraftCache(scopeKey: string, draft: string): void draftCache.delete(scopeKey) return } - draftCache.set(scopeKey, draft) + // LRU-bounded so unsent drafts for permanently-removed panes can't accumulate. + setBoundedScopeCacheEntry(draftCache, scopeKey, draft) } export function clearNativeChatDraftCacheForTests(): void { diff --git a/src/renderer/src/components/native-chat/native-chat-runtime-owner.ts b/src/renderer/src/components/native-chat/native-chat-runtime-owner.ts index b01ae9d8f..02aaae1a6 100644 --- a/src/renderer/src/components/native-chat/native-chat-runtime-owner.ts +++ b/src/renderer/src/components/native-chat/native-chat-runtime-owner.ts @@ -5,7 +5,8 @@ import { import type { AppState } from '@/store/types' import { findTerminalTabWorktreeId } from './native-chat-file-link' -export type NativeChatRuntimeOwnerState = Pick & WorktreeRuntimeOwnerState +export type NativeChatRuntimeOwnerState = Pick & + WorktreeRuntimeOwnerState /** * The runtime owner id for a Native Chat pane, as a primitive — non-null only for diff --git a/src/renderer/src/components/native-chat/native-chat-session-transport.test.ts b/src/renderer/src/components/native-chat/native-chat-session-transport.test.ts index 0a39178a1..324cdd482 100644 --- a/src/renderer/src/components/native-chat/native-chat-session-transport.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-session-transport.test.ts @@ -20,7 +20,13 @@ const runtimeEnvironmentsSubscribe = vi.fn() const ENV = 'env-1' function message(id: string): NativeChatMessage { - return { id, role: 'assistant', blocks: [{ type: 'text', text: id }], timestamp: 1, source: 'transcript' } + return { + id, + role: 'assistant', + blocks: [{ type: 'text', text: id }], + timestamp: 1, + source: 'transcript' + } } function okEnvelope(result: unknown): { ok: true; result: unknown } { @@ -224,7 +230,11 @@ describe('runtime readSession error mapping', () => { expect( toRuntimeNativeChatErrorMessage( - new RuntimeRpcCallError({ id: 'r-1', ok: false, error: { code: 'method_not_found', message: 'x' } }) + new RuntimeRpcCallError({ + id: 'r-1', + ok: false, + error: { code: 'method_not_found', message: 'x' } + }) ) ).toEqual(tooOld) diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts index 926e9a2ea..e64512fc9 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-attachments.ts @@ -7,6 +7,7 @@ import { type NativeChatResolvedTarget } from './native-chat-composer-target' import type { NativeChatComposerImageAttachment } from './NativeChatComposerField' +import { setBoundedScopeCacheEntry } from './native-chat-composer-scope-cache' export type UseNativeChatComposerAttachmentsArgs = { attachmentScopeKey: string @@ -153,7 +154,8 @@ function writeNativeChatAttachmentCache( attachmentCache.delete(scopeKey) return } - attachmentCache.set(scopeKey, [...attachments]) + // LRU-bounded so pending attachments for permanently-removed panes can't accumulate. + setBoundedScopeCacheEntry(attachmentCache, scopeKey, [...attachments]) } export function clearNativeChatAttachmentCacheForTests(): void { diff --git a/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts b/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts index 31a0c5b3a..c2b6e5d7e 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-live-session.test.ts @@ -49,7 +49,13 @@ import { } from './use-native-chat-live-session' function assistant(id: string, text: string): NativeChatMessage { - return { id, role: 'assistant', blocks: [{ type: 'text', text }], timestamp: 2, source: 'transcript' } + return { + id, + role: 'assistant', + blocks: [{ type: 'text', text }], + timestamp: 2, + source: 'transcript' + } } function user(id: string, text: string): NativeChatMessage { @@ -176,7 +182,12 @@ describe('useNativeChatLiveSession — transport routing', () => { expect(transportFactory).toHaveBeenCalledWith('env-1') const transport = getMockTransport('env-1') - expect(transport.readSession).toHaveBeenCalledWith(AGENT, SESSION, expect.any(Number), undefined) + expect(transport.readSession).toHaveBeenCalledWith( + AGENT, + SESSION, + expect.any(Number), + undefined + ) expect(transport.subscribe).toHaveBeenCalledOnce() }) diff --git a/src/renderer/src/components/native-chat/use-native-chat-toggle-shortcut.ts b/src/renderer/src/components/native-chat/use-native-chat-toggle-shortcut.ts index cb5a1f7a3..5ae84dde5 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-toggle-shortcut.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-toggle-shortcut.ts @@ -2,7 +2,7 @@ import { useEffect } from 'react' import { useAppStore } from '../../store' import type { AgentType } from '../../../../shared/agent-status-types' import type { TerminalPaneLayoutNode } from '../../../../shared/types' -import { resolveTabAgentFromTitle } from '@/lib/use-tab-agent' +import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence' import { canToggleNativeChat } from './native-chat-availability' import { isMacPlatform, matchesNativeChatToggleShortcut } from './native-chat-shortcut' @@ -72,8 +72,8 @@ export function useNativeChatToggleShortcut(worktreeId: string, isWorktreeActive agentStatusByPaneKey: state.agentStatusByPaneKey }) const titleFallbackAgent = isNativeChatShortcutTitleFallbackSafe(terminalLayout?.root) - ? (resolveTabAgentFromTitle(tab.label ?? '') ?? - (terminalTab ? resolveTabAgentFromTitle(terminalTab.title) : null)) + ? (resolveCommittedTitleAgentType(tab.label ?? '') ?? + (terminalTab ? resolveCommittedTitleAgentType(terminalTab.title) : null)) : null if ( !canToggleNativeChat({ diff --git a/src/renderer/src/components/onboarding/NotificationStep.tsx b/src/renderer/src/components/onboarding/NotificationStep.tsx index 29bd0c87a..ef43e335c 100644 --- a/src/renderer/src/components/onboarding/NotificationStep.tsx +++ b/src/renderer/src/components/onboarding/NotificationStep.tsx @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: this onboarding step owns the full notification setup surface, including macOS guidance, sound choices, and upload controls. */ import { useCallback, useEffect, useRef, useState } from 'react' import { BellRing, FileAudio, Settings, Upload } from 'lucide-react' import { toast } from 'sonner' diff --git a/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx b/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx index a8de4d843..545b40955 100644 --- a/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx +++ b/src/renderer/src/components/right-sidebar/AiVaultSessionVirtualList.tsx @@ -154,7 +154,10 @@ export function AiVaultSessionVirtualList({ }) return ( -
+
{loading && sessionsCount === 0 ? : null} {!loading && sessionsCount === 0 && !error ? ( diff --git a/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx b/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx index 0b0dee707..f8067c7df 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorer.test.tsx @@ -19,7 +19,8 @@ import { shouldShowFindInFolderAction, shouldShowCopyFileAction, shouldShowOpenInTerminalAction, - shouldShowRemoteDownloadAction + shouldShowRemoteDownloadAction, + shouldShowViewFileAction } from './FileExplorerRow' import { FileExplorerVirtualRows } from './FileExplorerVirtualRows' import type { TreeNode } from './file-explorer-types' @@ -581,6 +582,11 @@ describe('FileExplorerRow collapse folder action', () => { expect(shouldShowOpenInTerminalAction(fileNode)).toBe(false) }) + it('only shows view file for files', () => { + expect(shouldShowViewFileAction(fileNode)).toBe(true) + expect(shouldShowViewFileAction(directoryNode)).toBe(false) + }) + it('shows remote download only for desktop SSH or Remote Host file-like rows', () => { const runtimeContext = { settings: { activeRuntimeEnvironmentId: 'runtime-1' }, @@ -775,6 +781,7 @@ describe('FileExplorerRow collapse folder action', () => { deleteShortcutLabel: 'Del', onClick: vi.fn(), onDoubleClick: vi.fn(), + onViewFile: vi.fn(), onContextMenuSelect: vi.fn(), onCopyPaths: vi.fn(), onStartNew: vi.fn(), @@ -827,6 +834,7 @@ describe('FileExplorerRow collapse folder action', () => { deleteShortcutLabel: 'Del', onClick: vi.fn(), onDoubleClick: vi.fn(), + onViewFile: vi.fn(), onContextMenuSelect: vi.fn(), onCopyPaths: vi.fn(), onStartNew: vi.fn(), @@ -879,6 +887,7 @@ describe('FileExplorerRow collapse folder action', () => { connectionId: 'ssh-1', onClick: vi.fn(), onDoubleClick: vi.fn(), + onViewFile: vi.fn(), onContextMenuSelect: vi.fn(), onCopyPaths: vi.fn(), onStartNew: vi.fn(), @@ -930,6 +939,7 @@ describe('FileExplorerRow collapse folder action', () => { deleteShortcutLabel: 'Del', onClick: vi.fn(), onDoubleClick: vi.fn(), + onViewFile: vi.fn(), onContextMenuSelect: vi.fn(), onCopyPaths: vi.fn(), onStartNew: vi.fn(), @@ -957,4 +967,57 @@ describe('FileExplorerRow collapse folder action', () => { expect(onOpenInTerminal).toHaveBeenCalledWith(directoryNode) }) + + it('passes the row node to the view file handler', () => { + const onViewFile = vi.fn() + const element = FileExplorerVirtualRows({ + virtualizer: { + getTotalSize: () => 26, + getVirtualItems: () => [{ index: 0, key: 'src', start: 0 }], + measureElement: vi.fn() + } as never, + inlineInputIndex: -1, + rowProjection: createFileExplorerRowProjection([fileNode]), + inlineInput: null, + handleInlineSubmit: vi.fn(), + dismissInlineInput: vi.fn(), + folderStatusByRelativePath: new Map(), + statusByRelativePath: new Map(), + ignoredByRelativePath: new Set(), + expanded: new Set(), + dirCache: {}, + selectedPaths: new Set(), + activeFileId: null, + flashingPath: null, + deleteShortcutLabel: 'Del', + onClick: vi.fn(), + onDoubleClick: vi.fn(), + onViewFile, + onContextMenuSelect: vi.fn(), + onCopyPaths: vi.fn(), + onStartNew: vi.fn(), + onStartRename: vi.fn(), + onDuplicate: vi.fn(), + onAddFolderAsProject: vi.fn(), + canAddFolderAsProject: () => false, + onOpenInTerminal: vi.fn(), + onRequestDelete: vi.fn(), + onCollapseFolderSubtree: vi.fn(), + onFindInFolder: vi.fn(), + onMoveDrop: vi.fn(), + onDragTargetChange: vi.fn(), + onDragSourceChange: vi.fn(), + onDragExpandDir: vi.fn(), + onNativeDragTargetChange: vi.fn(), + onNativeDragExpandDir: vi.fn(), + dropTargetDir: null, + dragSourcePath: null, + nativeDropTargetDir: null + }) + + const row = findFileExplorerRow(element) + ;(row.props.onViewFile as () => void)() + + expect(onViewFile).toHaveBeenCalledWith(fileNode) + }) }) diff --git a/src/renderer/src/components/right-sidebar/FileExplorer.tsx b/src/renderer/src/components/right-sidebar/FileExplorer.tsx index 83defe0e7..fb91c2196 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorer.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorer.tsx @@ -746,6 +746,7 @@ function FileExplorerFiles(): React.JSX.Element { runtimeDownloadContext={runtimeDownloadContext} onClick={handleRowClick} onDoubleClick={handleDoubleClick} + onViewFile={handleClick} onContextMenuSelect={preserveSelectionForContextMenu} onCopyPaths={copyPathsForNode} onStartNew={startNew} diff --git a/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx b/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx index 765c1071b..6c4ace896 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorerRow.tsx @@ -279,6 +279,7 @@ type FileExplorerRowProps = { selectionSize: number onClick: (event: React.MouseEvent) => void onDoubleClick: () => void + onViewFile: () => void onContextMenuSelect: () => void onCopyPaths: (pathKind: 'absolute' | 'relative') => void onStartNew: (type: 'file' | 'folder', dir: string, depth: number) => void @@ -310,6 +311,10 @@ export function shouldShowOpenInTerminalAction(node: TreeNode): boolean { return node.isDirectory } +export function shouldShowViewFileAction(node: TreeNode): boolean { + return !node.isDirectory +} + export function shouldShowRemoteDownloadAction( node: TreeNode, connectionId?: string | null, @@ -421,6 +426,7 @@ export function FileExplorerRow({ selectionSize, onClick, onDoubleClick, + onViewFile, onContextMenuSelect, onCopyPaths, onStartNew, @@ -712,6 +718,12 @@ export function FileExplorerRow({ )} )} + {shouldShowViewFileAction(node) && ( + + + {translate('auto.components.right.sidebar.FileExplorerRow.1d8e182c32', 'View File')} + + )} {!node.isDirectory && activeWorktreeId && ( diff --git a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx index fe4e71dd6..5c64a5a04 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRows.tsx @@ -30,6 +30,7 @@ type FileExplorerVirtualRowsProps = { runtimeDownloadContext?: RuntimeFileOperationArgs | null onClick: (node: TreeNode, event: React.MouseEvent) => void onDoubleClick: (node: TreeNode) => void + onViewFile: (node: TreeNode) => void onContextMenuSelect: (node: TreeNode) => void onCopyPaths: (node: TreeNode, pathKind: 'absolute' | 'relative') => void onStartNew: (type: 'file' | 'folder', parentPath: string, depth: number) => void @@ -74,6 +75,7 @@ export function FileExplorerVirtualRows(props: FileExplorerVirtualRowsProps): Re runtimeDownloadContext, onClick, onDoubleClick, + onViewFile, onContextMenuSelect, onCopyPaths, onStartNew, @@ -180,6 +182,7 @@ export function FileExplorerVirtualRows(props: FileExplorerVirtualRowsProps): Re selectionSize={selectedPaths.has(n.path) ? visibleSelectionCount : 1} onClick={(event) => onClick(n, event)} onDoubleClick={() => onDoubleClick(n)} + onViewFile={() => onViewFile(n)} onContextMenuSelect={() => onContextMenuSelect(n)} onCopyPaths={(pathKind) => onCopyPaths(n, pathKind)} onStartNew={onStartNew} diff --git a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx index 16236cbd7..d1388383c 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorerVirtualRowsAddProject.test.tsx @@ -70,6 +70,7 @@ describe('FileExplorerVirtualRows add-as-project action', () => { deleteShortcutLabel: 'Del', onClick: vi.fn(), onDoubleClick: vi.fn(), + onViewFile: vi.fn(), onContextMenuSelect: vi.fn(), onCopyPaths: vi.fn(), onStartNew: vi.fn(), diff --git a/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx b/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx index a9d1d9a46..3e490c7a9 100644 --- a/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx +++ b/src/renderer/src/components/right-sidebar/file-explorer-drag-scroll-marker.test.tsx @@ -73,6 +73,7 @@ function virtualRowsElement(nodes: TreeNode[]): React.JSX.Element { onDoubleClick: vi.fn(), onContextMenuSelect: vi.fn(), onCopyPaths: vi.fn(), + onViewFile: vi.fn(), onStartNew: vi.fn(), onStartRename: vi.fn(), onDuplicate: vi.fn(), diff --git a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts index 770aeb2e4..58f5c0643 100644 --- a/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts +++ b/src/renderer/src/components/right-sidebar/source-control-dropdown-items.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: the dropdown priority table is easier to audit when the row-state cases live together. */ import { describe, expect, it } from 'vitest' import { resolveDropdownItems, type DropdownActionInputs } from './source-control-dropdown-items' diff --git a/src/renderer/src/components/settings/AgentsPane.test.tsx b/src/renderer/src/components/settings/AgentsPane.test.tsx index d2915f198..2d69afaff 100644 --- a/src/renderer/src/components/settings/AgentsPane.test.tsx +++ b/src/renderer/src/components/settings/AgentsPane.test.tsx @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: Agents pane settings interactions share - store-backed queue fixtures that are easier to audit beside the UI helper coverage. */ import React from 'react' import { renderToStaticMarkup } from 'react-dom/server' import { beforeEach, describe, expect, it, vi } from 'vitest' diff --git a/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx b/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx index f7f43cff2..62412f2e2 100644 --- a/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx +++ b/src/renderer/src/components/settings/SettingsFormControls.font-autocomplete.test.tsx @@ -34,11 +34,33 @@ describe('FontAutocomplete', () => { } function getOptionLabels(): string[] { - return Array.from(container.querySelectorAll('[role="option"]')).map( + // Why: the dropdown portals to document.body so it can escape the settings + // section; options are intentionally not descendants of the container. + return Array.from(document.querySelectorAll('[role="option"]')).map( (option) => option.textContent?.trim() ?? '' ) } + function expectOptionsToBePortaled(): void { + expect(container.querySelector('[role="option"]')).toBeNull() + } + + function getScrollArea(): HTMLElement { + const scrollArea = document.querySelector('[data-slot="scroll-area"]') + if (!scrollArea) { + throw new Error('Font autocomplete scroll area not found') + } + return scrollArea + } + + function getScrollAreaViewport(): HTMLElement { + const viewport = document.querySelector('[data-slot="scroll-area-viewport"]') + if (!viewport) { + throw new Error('Font autocomplete scroll area viewport not found') + } + return viewport + } + async function typeIntoInput(input: HTMLInputElement, value: string): Promise { await act(async () => { // Why: React tracks controlled input values through the native setter, so @@ -76,10 +98,11 @@ describe('FontAutocomplete', () => { }) expect( - container + document .querySelector('[role="option"][aria-selected="true"]') ?.textContent?.trim() ).toBe('JetBrains Mono') + expectOptionsToBePortaled() }) it('shows the full list on focus when the committed font has multiple matching suggestions', async () => { @@ -109,6 +132,33 @@ describe('FontAutocomplete', () => { 'Cascadia Mono PL', 'Consolas' ]) + expectOptionsToBePortaled() + }) + + it('bounds the portaled list to the available popover height', async () => { + function Harness(): ReactNode { + const [value, setValue] = useState('Cascadia Mono') + return ( + + ) + } + + await act(async () => { + root.render() + }) + + await act(async () => { + getInput().focus() + }) + + expect(getScrollArea().style.maxHeight).toBe('var(--radix-popover-content-available-height)') + expect(getScrollAreaViewport().style.maxHeight).toBe( + 'var(--radix-popover-content-available-height)' + ) }) it('keeps typed searches filtered even after the value updates', async () => { diff --git a/src/renderer/src/components/settings/SettingsFormControls.tsx b/src/renderer/src/components/settings/SettingsFormControls.tsx index 3de7c6ec9..a8b5bbdef 100644 --- a/src/renderer/src/components/settings/SettingsFormControls.tsx +++ b/src/renderer/src/components/settings/SettingsFormControls.tsx @@ -6,6 +6,7 @@ import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react' import { ScrollArea } from '../ui/scroll-area' import { Input } from '../ui/input' import { Label } from '../ui/label' +import { Popover, PopoverAnchor, PopoverContent } from '../ui/popover' import { Check, ChevronsUpDown, CircleX } from 'lucide-react' import { normalizeColor, type TerminalThemeOption } from '@/lib/terminal-theme' import { MAX_THEME_RESULTS } from './SettingsConstants' @@ -618,21 +619,12 @@ export function FontAutocomplete({ } } - useEffect(() => { - if (!open) { - return + const handleOpenChange = (nextOpen: boolean): void => { + setOpen(nextOpen) + if (!nextOpen) { + setIsFilteringQuery(false) } - - const handlePointerDown = (event: MouseEvent): void => { - if (!rootRef.current?.contains(event.target as Node)) { - setOpen(false) - setIsFilteringQuery(false) - } - } - - document.addEventListener('mousedown', handlePointerDown) - return () => document.removeEventListener('mousedown', handlePointerDown) - }, [open]) + } const normalizedQuery = query.trim().toLowerCase() const normalizedValue = value.trim().toLowerCase() @@ -691,124 +683,158 @@ export function FontAutocomplete({ const focusInput = (): void => { inputRef.current?.focus() } + const popoverAvailableHeightStyle = { + // Why: tailwind-merge rewrites this arbitrary max-height class on the + // ScrollArea root, so keep the Radix available-height clamp as inline style. + maxHeight: 'var(--radix-popover-content-available-height)' + } as React.CSSProperties return (
-
- { - const next = e.target.value - setQuery(next) - setIsFilteringQuery(true) - onChange(next) - setOpen(true) - }} - onFocus={() => { - setIsFilteringQuery(false) - setOpen(true) - }} - onKeyDown={(e) => { - if (e.key === 'Escape') { - if (open) { - e.preventDefault() - setOpen(false) - setIsFilteringQuery(false) - } - return - } - - if (e.key === 'ArrowDown') { - e.preventDefault() - setOpen(true) - if (visibleSuggestions.length > 0) { - setHighlightedIndex((current) => - current < 0 ? 0 : Math.min(current + 1, visibleSuggestions.length - 1) - ) - } - return - } - - if (e.key === 'ArrowUp') { - e.preventDefault() - setOpen(true) - if (visibleSuggestions.length > 0) { - setHighlightedIndex((current) => - current < 0 ? visibleSuggestions.length - 1 : Math.max(current - 1, 0) - ) - } - return - } - - if (e.key === 'Enter' && open && highlightedIndex >= 0) { - const highlightedFont = visibleSuggestions[highlightedIndex] - if (highlightedFont) { - e.preventDefault() - commitValue(highlightedFont) - } - } - }} - placeholder={placeholder} - className="pr-18" - role="combobox" - aria-autocomplete="list" - aria-expanded={open} - aria-controls={listboxId} - aria-activedescendant={ - open && highlightedIndex >= 0 ? `${listboxId}-option-${highlightedIndex}` : undefined - } - /> -
- {query ? ( - - ) : null} - -
-
+ setOpen(true) + }} + onKeyDown={(e) => { + if (e.key === 'Escape') { + if (open) { + e.preventDefault() + setOpen(false) + setIsFilteringQuery(false) + } + return + } - {open ? ( -
- 8 ? 'h-64' : undefined}> + if (e.key === 'ArrowDown') { + e.preventDefault() + setOpen(true) + if (visibleSuggestions.length > 0) { + setHighlightedIndex((current) => + current < 0 ? 0 : Math.min(current + 1, visibleSuggestions.length - 1) + ) + } + return + } + + if (e.key === 'ArrowUp') { + e.preventDefault() + setOpen(true) + if (visibleSuggestions.length > 0) { + setHighlightedIndex((current) => + current < 0 ? visibleSuggestions.length - 1 : Math.max(current - 1, 0) + ) + } + return + } + + if (e.key === 'Enter' && open && highlightedIndex >= 0) { + const highlightedFont = visibleSuggestions[highlightedIndex] + if (highlightedFont) { + e.preventDefault() + commitValue(highlightedFont) + } + } + }} + placeholder={placeholder} + className="pr-18" + role="combobox" + aria-autocomplete="list" + aria-expanded={open} + aria-controls={listboxId} + aria-activedescendant={ + open && highlightedIndex >= 0 + ? `${listboxId}-option-${highlightedIndex}` + : undefined + } + /> +
+ {query ? ( + + ) : null} + +
+
+ + + {/* Why: portal the dropdown outside the settings section — an in-flow + absolute panel makes the highlighted option's scrollIntoView scroll + the whole settings pane, pushing the section content out of view. */} + e.preventDefault()} + onCloseAutoFocus={(e) => e.preventDefault()} + onInteractOutside={(e) => { + // Why: the input and its clear/toggle buttons are the anchor, not + // the content, so Radix would otherwise dismiss on every click there. + if (rootRef.current?.contains(e.target as Node)) { + e.preventDefault() + } + }} + > + 8 ? 'h-64' : undefined} + style={popoverAvailableHeightStyle} + viewportProps={{ style: popoverAvailableHeightStyle }} + >
{visibleSuggestions.length > 0 ? ( visibleSuggestions.map((font, index) => ( @@ -846,8 +872,8 @@ export function FontAutocomplete({ )}
-
- ) : null} + +
) } diff --git a/src/renderer/src/components/settings/SourceControlActionRepoOverrideNote.tsx b/src/renderer/src/components/settings/SourceControlActionRepoOverrideNote.tsx index ec389927e..b3ca7aa3e 100644 --- a/src/renderer/src/components/settings/SourceControlActionRepoOverrideNote.tsx +++ b/src/renderer/src/components/settings/SourceControlActionRepoOverrideNote.tsx @@ -32,11 +32,6 @@ function getRecipeOverrideFieldLabel(field: SourceControlActionRecipeOverrideFie 'auto.components.settings.SourceControlActionRepoOverrideNote.commandTemplate', 'Command template' ) - default: { - // Fail at compile time if the override-field union grows a new variant. - const _exhaustive: never = field - return _exhaustive - } } } diff --git a/src/renderer/src/components/settings/SshPane.tsx b/src/renderer/src/components/settings/SshPane.tsx index 3a00df1d0..1af4ba26f 100644 --- a/src/renderer/src/components/settings/SshPane.tsx +++ b/src/renderer/src/components/settings/SshPane.tsx @@ -254,7 +254,10 @@ export function SshPane(_props: SshPaneProps): React.JSX.Element { const handleImport = async (): Promise => { try { - const synced = (await window.api.ssh.importConfig()) as SshTarget[] + // Why: the explicit Import action re-adopts every ~/.ssh/config host, + // including ones the user previously deleted — clear tombstones so a + // deliberate re-import can bring them back. + const synced = (await window.api.ssh.importConfig({ reAdopt: true })) as SshTarget[] recordFeatureInteraction('ssh') if (mountedRef.current) { if (synced.length === 0) { diff --git a/src/renderer/src/components/settings/TerminalPane.pwsh.test.ts b/src/renderer/src/components/settings/TerminalPane.pwsh.test.ts index 070509382..a9655a416 100644 --- a/src/renderer/src/components/settings/TerminalPane.pwsh.test.ts +++ b/src/renderer/src/components/settings/TerminalPane.pwsh.test.ts @@ -1,6 +1,3 @@ -/* oxlint-disable max-lines -- Why: TerminalPane tests share a large mocked - settings harness; splitting the new Windows-shell cases would duplicate - brittle React/store mocks without improving coverage. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const mockStateValues: unknown[] = [] diff --git a/src/renderer/src/components/sidebar/WorktreeCard.test.ts b/src/renderer/src/components/sidebar/WorktreeCard.test.ts index 36ac370db..abc03a3c4 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.test.ts +++ b/src/renderer/src/components/sidebar/WorktreeCard.test.ts @@ -20,7 +20,6 @@ vi.mock('@/lib/agent-status', () => ({ import { getWorktreeStatus } from '@/lib/worktree-status' import { shouldBeginWorktreeRename } from './WorktreeCard' -import { deriveWorktreeCardStatus } from './worktree-card-status' function makeTerminalTab(title: string): TerminalTab { return { @@ -35,22 +34,6 @@ function makeTerminalTab(title: string): TerminalTab { } } -function makeAgentStatusEntry(args: { - paneKey: string - state: AgentStatusEntry['state'] - updatedAt?: number -}): AgentStatusEntry { - const updatedAt = args.updatedAt ?? 1_000 - return { - paneKey: args.paneKey, - state: args.state, - prompt: '', - updatedAt, - stateStartedAt: updatedAt, - stateHistory: [] - } -} - describe('getWorktreeStatus', () => { it('treats browser-only worktrees as active', () => { expect(getWorktreeStatus([], [{ id: 'browser-1' }], {})).toBe('active') @@ -59,67 +42,22 @@ describe('getWorktreeStatus', () => { it('keeps terminal agent states higher priority than browser presence', () => { // Why: liveness gate now requires ptyIdsByTabId, not tab.ptyId. Pass a // populated live-pty map so this assertion exercises the live-tab branch. + // Titles are real classifiable shapes: getWorktreeStatus reads the shared + // classifier through pane-agent-evidence, which this file does not mock. const livePtyIds = { 'tab-1': ['pty-1'] } expect( - getWorktreeStatus([makeTerminalTab('permission needed')], [{ id: 'browser-1' }], livePtyIds) + getWorktreeStatus( + [makeTerminalTab('Claude - action required')], + [{ id: 'browser-1' }], + livePtyIds + ) ).toBe('permission') expect( - getWorktreeStatus([makeTerminalTab('working hard')], [{ id: 'browser-1' }], livePtyIds) + getWorktreeStatus([makeTerminalTab('mimo working')], [{ id: 'browser-1' }], livePtyIds) ).toBe('working') }) }) -describe('deriveWorktreeCardStatus', () => { - it('keeps split-pane heuristics for panes without fresh explicit status', () => { - const status = deriveWorktreeCardStatus({ - tabs: [makeTerminalTab('claude [done]')], - browserTabs: [], - worktreeAgentEntries: [makeAgentStatusEntry({ paneKey: 'tab-1:1', state: 'done' })], - runtimePaneTitlesByTabId: { - 'tab-1': { - 1: 'claude [done]', - 2: 'codex [working]' - } - }, - now: 1_000 - }) - - expect(status).toBe('working') - }) - - it('lets fresh explicit status win over the matching pane title heuristic', () => { - const status = deriveWorktreeCardStatus({ - tabs: [makeTerminalTab('codex [working]')], - browserTabs: [], - worktreeAgentEntries: [makeAgentStatusEntry({ paneKey: 'tab-1:2', state: 'done' })], - runtimePaneTitlesByTabId: { - 'tab-1': { - 2: 'codex [working]' - } - }, - now: 1_000 - }) - - expect(status).toBe('done') - }) - - it('stays active when the only live terminal signal is the Claude agents screen', () => { - const status = deriveWorktreeCardStatus({ - tabs: [makeTerminalTab('claude agents')], - browserTabs: [], - worktreeAgentEntries: [], - runtimePaneTitlesByTabId: { - 'tab-1': { - 1: 'claude agents' - } - }, - now: 1_000 - }) - - expect(status).toBe('active') - }) -}) - describe('shouldBeginWorktreeRename', () => { it('matches unscoped legacy rename requests by worktree id', () => { expect(shouldBeginWorktreeRename({ worktreeId: 'wt-1' }, 'wt-1', 'all:wt-1')).toBe(true) diff --git a/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx b/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx index f3bd592f3..380bb9194 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardAgents.test.tsx @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: this suite shares a broad mocked sidebar - harness across compact/full mode, lineage, and image-note cases. */ import { renderToStaticMarkup } from 'react-dom/server' import type { ReactNode } from 'react' import { beforeEach, describe, expect, it, vi } from 'vitest' diff --git a/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx b/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx index b6a0f9f88..7bfda38d2 100644 --- a/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCardAgents.tsx @@ -1,13 +1,12 @@ -/* eslint-disable max-lines -- Why: this component keeps compact/full inline - agent rendering and lineage disclosure behavior together; splitting during - this bug fix would risk divergent parent-child row behavior. */ import React, { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useShallow } from 'zustand/react/shallow' import { useAppStore } from '@/store' import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane' import DashboardAgentRow from '@/components/dashboard/DashboardAgentRow' import { useNow } from '@/components/dashboard/useNow' import { deriveRunningAgentSendTargets } from '@/lib/running-agent-targets' +import { selectSendTargetInputs } from './worktree-card-send-target-inputs' import { useWorktreeAgentRows } from './useWorktreeAgentRows' import { cn } from '@/lib/utils' import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData' @@ -89,12 +88,15 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ const dropAgentStatus = useAppStore((s) => s.dropAgentStatus) const dismissRetainedAgent = useAppStore((s) => s.dismissRetainedAgent) const agentSendPopoverTargetMode = useAppStore((s) => s.agentSendPopoverTargetMode) - const agentStatusByPaneKey = useAppStore((s) => s.agentStatusByPaneKey) const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) - const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) - const terminalLayoutsByTabId = useAppStore((s) => s.terminalLayoutsByTabId) - const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) - const runtimePaneTitlesByTabId = useAppStore((s) => s.runtimePaneTitlesByTabId) + // Why: these five maps are read only to derive send-target eligibility, which + // matters only while the send-target popover targets THIS card. Two of them + // (runtimePaneTitlesByTabId, agentStatusByPaneKey) churn on every pane-title + // and agent-status write app-wide, so subscribing to them unconditionally made + // every mounted agent body re-render on unrelated terminals. Gate the + // subscription: return a stable empty constant when the popover isn't ours, so + // useShallow keeps the same result and idle bodies stop reacting to the churn. + const sendTargetInputs = useAppStore(useShallow((s) => selectSendTargetInputs(s, worktreeId))) const sendPromptToSidebarAgentTarget = useAppStore((s) => s.sendPromptToSidebarAgentTarget) const focusedAgentPaneKey = useFocusedAgentPaneKey(worktreeId) const compactAgentListRootRef = useRef(null) @@ -134,16 +136,7 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ } return new Map( - deriveRunningAgentSendTargets( - { - agentStatusByPaneKey, - tabsByWorktree, - terminalLayoutsByTabId, - ptyIdsByTabId, - runtimePaneTitlesByTabId - }, - worktreeId - ).map((target) => [ + deriveRunningAgentSendTargets(sendTargetInputs, worktreeId).map((target) => [ target.paneKey, agentSendPopoverTargetMode?.status === 'sending' && agentSendPopoverTargetMode.sendingPaneKey === target.paneKey @@ -159,12 +152,11 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({ agentStatusEpoch, agentSendPopoverTargetMode?.sendingPaneKey, agentSendPopoverTargetMode?.status, - agentStatusByPaneKey, isAgentSendTargetModeActive, - ptyIdsByTabId, - runtimePaneTitlesByTabId, - tabsByWorktree, - terminalLayoutsByTabId, + // sendTargetInputs is a stable empty constant while inactive and a + // shallow-compared bundle of the five maps while active, so it covers all + // five former deps in one reference. + sendTargetInputs, worktreeId ]) diff --git a/src/renderer/src/components/sidebar/smart-attention.test.ts b/src/renderer/src/components/sidebar/smart-attention.test.ts index c4fbd18ce..96b54f9a5 100644 --- a/src/renderer/src/components/sidebar/smart-attention.test.ts +++ b/src/renderer/src/components/sidebar/smart-attention.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines */ import { describe, expect, it } from 'vitest' import { AGENT_STATUS_STALE_AFTER_MS, diff --git a/src/renderer/src/components/sidebar/smart-attention.ts b/src/renderer/src/components/sidebar/smart-attention.ts index 4ca27a7c4..ae0d7542d 100644 --- a/src/renderer/src/components/sidebar/smart-attention.ts +++ b/src/renderer/src/components/sidebar/smart-attention.ts @@ -1,4 +1,4 @@ -import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status' +import { classifyTitleActivity, isExplicitAgentStatusFresh } from '@/lib/pane-agent-evidence' import { migrationUnsupportedToAgentStatusEntry } from '@/lib/migration-unsupported-agent-entry' import { tabHasLivePty } from '@/lib/tab-has-live-pty' import { resolveRuntimePaneTitleLeafId } from '@/lib/runtime-pane-title-leaf-id' @@ -308,7 +308,7 @@ export function buildAttentionByWorktree( } panes.push({ kind: 'title', - status: detectAgentStatusFromTitle(title), + status: classifyTitleActivity(title), worktreeLastActivityAt: worktree.lastActivityAt }) } @@ -318,7 +318,7 @@ export function buildAttentionByWorktree( // titles or hook entries exist for this tab. panes.push({ kind: 'title', - status: detectAgentStatusFromTitle(tab.title), + status: classifyTitleActivity(tab.title), worktreeLastActivityAt: worktree.lastActivityAt }) } diff --git a/src/renderer/src/components/sidebar/smart-sort.test.ts b/src/renderer/src/components/sidebar/smart-sort.test.ts index cb61490c9..da10bf713 100644 --- a/src/renderer/src/components/sidebar/smart-sort.test.ts +++ b/src/renderer/src/components/sidebar/smart-sort.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines */ import { describe, expect, it } from 'vitest' import type { Repo, TerminalTab, Worktree } from '../../../../shared/types' import { diff --git a/src/renderer/src/components/sidebar/visible-worktrees.test.ts b/src/renderer/src/components/sidebar/visible-worktrees.test.ts index 25165df25..f403a8681 100644 --- a/src/renderer/src/components/sidebar/visible-worktrees.test.ts +++ b/src/renderer/src/components/sidebar/visible-worktrees.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines */ import { describe, expect, it } from 'vitest' import { computeClearFilterActions, diff --git a/src/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.ts b/src/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.ts new file mode 100644 index 000000000..03286c4f3 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { shallow } from 'zustand/shallow' +import type { AgentSendPopoverTargetMode } from '@/store/slices/ui' +import { + EMPTY_SEND_TARGET_INPUTS, + selectSendTargetInputs, + type SendTargetInputsState +} from './worktree-card-send-target-inputs' + +const BASE: SendTargetInputsState = { + agentSendPopoverTargetMode: null, + agentStatusByPaneKey: {}, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + ptyIdsByTabId: {}, + runtimePaneTitlesByTabId: {} +} + +function makeMode(worktreeId: string): AgentSendPopoverTargetMode { + return { + id: 'mode-1', + instanceId: 'inst-1', + worktreeId, + source: 'diff-notes', + prompt: 'do it', + label: 'Send', + launchSource: 'sidebar', + eligiblePaneKeys: [], + disabledPaneKeys: {}, + status: 'open' + } +} + +describe('selectSendTargetInputs', () => { + it('returns the shared empty constant when the popover does not target this worktree', () => { + // Inactive (popover closed): stable empty reference. + const inactive = selectSendTargetInputs(BASE, 'wt-A') + expect(inactive).toBe(EMPTY_SEND_TARGET_INPUTS) + + // Churning the hottest maps while inactive must NOT change the selected + // reference, so a useShallow subscription skips the re-render. + const churned: SendTargetInputsState = { + ...BASE, + runtimePaneTitlesByTabId: { 'tab-1': 'claude' }, + agentStatusByPaneKey: { 'tab-1:leaf-1': {} as never } + } + const afterChurn = selectSendTargetInputs(churned, 'wt-A') + expect(afterChurn).toBe(EMPTY_SEND_TARGET_INPUTS) + expect(shallow(inactive, afterChurn)).toBe(true) + }) + + it('stays the stable empty constant when the popover targets a different worktree', () => { + const s: SendTargetInputsState = { ...BASE, agentSendPopoverTargetMode: makeMode('wt-OTHER') } + expect(selectSendTargetInputs(s, 'wt-A')).toBe(EMPTY_SEND_TARGET_INPUTS) + }) + + it('exposes the live maps when the popover targets this worktree', () => { + const titles = { 'tab-1': 'claude' } + const s: SendTargetInputsState = { + ...BASE, + agentSendPopoverTargetMode: makeMode('wt-A'), + runtimePaneTitlesByTabId: titles + } + const active = selectSendTargetInputs(s, 'wt-A') + // Live map references pass straight through so eligibility derives correctly. + expect(active.runtimePaneTitlesByTabId).toBe(titles) + expect(active).not.toBe(EMPTY_SEND_TARGET_INPUTS) + }) + + it('shallow-changes only when a subscribed map reference actually changes while active', () => { + const titles = { 'tab-1': 'claude' } + const s1: SendTargetInputsState = { + ...BASE, + agentSendPopoverTargetMode: makeMode('wt-A'), + runtimePaneTitlesByTabId: titles + } + const r1 = selectSendTargetInputs(s1, 'wt-A') + + // Same underlying map refs -> shallow-equal -> no re-render. + expect(shallow(r1, selectSendTargetInputs(s1, 'wt-A'))).toBe(true) + + // A real pane-title write replaces the map ref -> shallow-unequal -> the + // open popover re-derives eligibility, exactly as before this change. + const s2: SendTargetInputsState = { ...s1, runtimePaneTitlesByTabId: { 'tab-1': 'codex' } } + expect(shallow(r1, selectSendTargetInputs(s2, 'wt-A'))).toBe(false) + }) +}) diff --git a/src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts b/src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts new file mode 100644 index 000000000..a7e7efadc --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts @@ -0,0 +1,47 @@ +import type { AppState } from '@/store/types' +import type { RunningAgentTargetState } from '@/lib/running-agent-targets' + +export type SendTargetInputsState = Pick< + AppState, + | 'agentSendPopoverTargetMode' + | 'agentStatusByPaneKey' + | 'tabsByWorktree' + | 'terminalLayoutsByTabId' + | 'ptyIdsByTabId' + | 'runtimePaneTitlesByTabId' +> + +// Why: shared stable reference returned whenever the send-target popover isn't +// targeting this card. useShallow keeps the same result across unrelated +// pane-title / agent-status churn, so idle agent bodies stop re-rendering. +// Frozen so this shared singleton can never be mutated by a consumer. +export const EMPTY_SEND_TARGET_INPUTS: RunningAgentTargetState = Object.freeze({ + agentStatusByPaneKey: {}, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + ptyIdsByTabId: {}, + runtimePaneTitlesByTabId: {} +}) + +/** + * Select the five maps `deriveRunningAgentSendTargets` needs — but only while + * the send-target popover targets this worktree. When it doesn't, return a + * stable empty constant so a useShallow-wrapped subscription stays referentially + * equal across the (very hot) pane-title / agent-status writes and skips the + * re-render that would otherwise fire on every mounted agent body app-wide. + */ +export function selectSendTargetInputs( + s: SendTargetInputsState, + worktreeId: string +): RunningAgentTargetState { + if (s.agentSendPopoverTargetMode?.worktreeId !== worktreeId) { + return EMPTY_SEND_TARGET_INPUTS + } + return { + agentStatusByPaneKey: s.agentStatusByPaneKey, + tabsByWorktree: s.tabsByWorktree, + terminalLayoutsByTabId: s.terminalLayoutsByTabId, + ptyIdsByTabId: s.ptyIdsByTabId, + runtimePaneTitlesByTabId: s.runtimePaneTitlesByTabId + } +} diff --git a/src/renderer/src/components/sidebar/worktree-card-status.ts b/src/renderer/src/components/sidebar/worktree-card-status.ts deleted file mode 100644 index 61daeb74c..000000000 --- a/src/renderer/src/components/sidebar/worktree-card-status.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status' -import type { WorktreeStatus } from '@/lib/worktree-status' -import { - AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusEntry -} from '../../../../shared/agent-status-types' -import type { TerminalTab } from '../../../../shared/types' - -type WorktreeCardStatusInput = { - tabs: Pick[] - browserTabs: { id: string }[] - worktreeAgentEntries: AgentStatusEntry[] - runtimePaneTitlesByTabId: Record> - now?: number -} - -export function deriveWorktreeCardStatus({ - tabs, - browserTabs, - worktreeAgentEntries, - runtimePaneTitlesByTabId, - now = Date.now() -}: WorktreeCardStatusInput): WorktreeStatus { - const liveTabs = tabs.filter((tab) => tab.ptyId) - // Why: browser-only worktrees are still active from the user's point of - // view even when they have no PTY-backed terminal. The sidebar filter - // already treats them as active, so every navigation surface must reuse - // that rule instead of showing a misleading inactive dot. - const hasTerminals = liveTabs.length > 0 || browserTabs.length > 0 - if (!hasTerminals) { - return 'inactive' - } - - const freshByTabId = new Map() - const explicitPaneIdsByTabId = new Map>() - for (const entry of worktreeAgentEntries) { - if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { - continue - } - const colonIdx = entry.paneKey.indexOf(':') - // Why: paneKey must be `${tabId}:${paneId}`. Skip malformed entries (no - // colon or leading colon) rather than bucketing under "". - if (colonIdx <= 0) { - continue - } - const tabId = entry.paneKey.slice(0, colonIdx) - const paneId = entry.paneKey.slice(colonIdx + 1) - const bucket = freshByTabId.get(tabId) - if (bucket) { - bucket.push(entry) - } else { - freshByTabId.set(tabId, [entry]) - } - const explicitPaneIds = explicitPaneIdsByTabId.get(tabId) ?? new Set() - explicitPaneIds.add(paneId) - explicitPaneIdsByTabId.set(tabId, explicitPaneIds) - } - - let hasPermission = false - let hasWorking = false - let hasDone = false - for (const tab of liveTabs) { - const fresh = freshByTabId.get(tab.id) - if (fresh && fresh.length > 0) { - if (fresh.some((e) => e.state === 'blocked' || e.state === 'waiting')) { - hasPermission = true - } else if (fresh.some((e) => e.state === 'working')) { - hasWorking = true - } else if (fresh.some((e) => e.state === 'done')) { - hasDone = true - } - } - - const explicitPaneIds = explicitPaneIdsByTabId.get(tab.id) - const paneTitles = runtimePaneTitlesByTabId[tab.id] - if (paneTitles && Object.keys(paneTitles).length > 0) { - for (const [paneId, title] of Object.entries(paneTitles)) { - // Why: explicit hook status only supersedes the matching pane. Other - // split panes still need the title heuristic when hooks are absent. - if (explicitPaneIds?.has(paneId)) { - continue - } - const heuristic = detectAgentStatusFromTitle(title) - if (heuristic === 'permission') { - hasPermission = true - break - } - if (heuristic === 'working') { - hasWorking = true - } - } - continue - } - - if (fresh && fresh.length > 0) { - continue - } - - const heuristic = detectAgentStatusFromTitle(tab.title) - if (heuristic === 'permission') { - hasPermission = true - } else if (heuristic === 'working') { - hasWorking = true - } - } - - if (hasPermission) { - return 'permission' - } - if (hasWorking) { - return 'working' - } - // Why: surface 'done' as its own status so the sidebar dot turns blue - // (sky-500/80) — matching the dashboard's done color. A completed agent - // still has a live terminal, so 'inactive' would be misleading; calling - // it 'done' keeps the two surfaces in agreement on what the agent is. - if (hasDone) { - return 'done' - } - return 'active' -} diff --git a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts index 2b5efddeb..1c862b705 100644 --- a/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts @@ -1,9 +1,6 @@ import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' -import { - detectAgentStatusFromTitle, - getAgentLabel, - isClaudeManagementTitle -} from '@/lib/agent-status' +import { isClaudeManagementTitle } from '@/lib/agent-status' +import { classifyTitleActivity, resolveTitleActivityLabel } from '@/lib/pane-agent-evidence' import { tabHasLivePty } from '@/lib/tab-has-live-pty' import type { AgentStatusEntry, @@ -135,8 +132,8 @@ function buildTitleDerivedAgentRow(args: { // Why: `claude agents` is a live Claude Code Agent Teams surface, but the // shared detector keeps it neutral so runtime liveness probes do not treat // the management/list screen as active work. - const status = isClaudeAgentsTitle ? 'idle' : detectAgentStatusFromTitle(title) - const label = isClaudeAgentsTitle ? 'Claude Code' : getAgentLabel(title) + const status = isClaudeAgentsTitle ? 'idle' : classifyTitleActivity(title) + const label = isClaudeAgentsTitle ? 'Claude Code' : resolveTitleActivityLabel(title) if (!status || !label) { return null } @@ -199,7 +196,7 @@ export function resolveAgentTypeFromTerminalTitle( return null } const normalizedTitle = normalizeCompatibleAgentTitleForOwner(title, ownerAgentType) - const label = getAgentLabel(normalizedTitle) + const label = resolveTitleActivityLabel(normalizedTitle) return label ? (resolveCompatibleAgentTypeForOwner( resolveTitleDerivedAgentType(normalizedTitle, label), diff --git a/src/renderer/src/components/status-bar/mergeSnapshotAndSessions.test.ts b/src/renderer/src/components/status-bar/mergeSnapshotAndSessions.test.ts index e1b96f4b9..e542f90a8 100644 --- a/src/renderer/src/components/status-bar/mergeSnapshotAndSessions.test.ts +++ b/src/renderer/src/components/status-bar/mergeSnapshotAndSessions.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: this file co-locates tightly-coupled scenario - tests for the resource-usage merge function. Splitting them weakens the - single-source view of how snapshot + daemon-session inputs combine. */ import { describe, expect, it } from 'vitest' import type { MemorySnapshot, TerminalTab, WorktreeMemory } from '../../../../shared/types' import { mergeSnapshotAndSessions, UNATTRIBUTED_REPO_ID } from './mergeSnapshotAndSessions' diff --git a/src/renderer/src/components/status-bar/workspace-space-presentation.ts b/src/renderer/src/components/status-bar/workspace-space-presentation.ts index 85274483d..ad09532a6 100644 --- a/src/renderer/src/components/status-bar/workspace-space-presentation.ts +++ b/src/renderer/src/components/status-bar/workspace-space-presentation.ts @@ -1,4 +1,4 @@ -import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status' +import { classifyTitleActivity, isExplicitAgentStatusFresh } from '@/lib/pane-agent-evidence' import { tabHasLivePty } from '@/lib/tab-has-live-pty' import { AGENT_STATUS_STALE_AFTER_MS, @@ -82,12 +82,12 @@ function countTitleActiveAgentsForTab( const paneTitles = runtimePaneTitlesByTabId[tab.id] if (paneTitles && Object.keys(paneTitles).length > 0) { return Object.values(paneTitles).filter((title) => { - const status = detectAgentStatusFromTitle(title) + const status = classifyTitleActivity(title) return status === 'working' || status === 'permission' }).length } - const status = detectAgentStatusFromTitle(tab.title) + const status = classifyTitleActivity(tab.title) return status === 'working' || status === 'permission' ? 1 : 0 } diff --git a/src/renderer/src/components/tab-bar/TabBar.context-menu.test.ts b/src/renderer/src/components/tab-bar/TabBar.context-menu.test.ts index 9e313bccd..d580d2c8c 100644 --- a/src/renderer/src/components/tab-bar/TabBar.context-menu.test.ts +++ b/src/renderer/src/components/tab-bar/TabBar.context-menu.test.ts @@ -1,5 +1,3 @@ -/* oxlint-disable max-lines -- Why: keeping these mocked TabBar wiring cases - * together avoids duplicating the lightweight renderer harness. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const appStoreSnapshot: { @@ -61,6 +59,12 @@ vi.mock('react', async () => { } }) +// The headless React mock above stubs hooks, so zustand's useShallow (which +// calls useRef) has no dispatcher; make it a pass-through like the store mock. +vi.mock('zustand/react/shallow', () => ({ + useShallow: (selector: unknown) => selector +})) + vi.mock('lucide-react', () => ({ FilePlus: function FilePlus() { return null diff --git a/src/renderer/src/components/tab-bar/TabBar.tsx b/src/renderer/src/components/tab-bar/TabBar.tsx index 194174a59..e5e9c328a 100644 --- a/src/renderer/src/components/tab-bar/TabBar.tsx +++ b/src/renderer/src/components/tab-bar/TabBar.tsx @@ -4,6 +4,7 @@ * branches share little beyond drag data, so consolidating them would cost * more clarity than the ~5 lines of bloat is worth. */ import React, { useEffect, useMemo, useRef, useState } from 'react' +import { useShallow } from 'zustand/react/shallow' import { SortableContext } from '@dnd-kit/sortable' import { ChevronLeft, @@ -78,8 +79,8 @@ import { useTabStripOverflowNavigation } from './tab-strip-overflow-navigation' import { useTabStripDragScrollHandlers } from './tab-strip-drag-scroll' import { shouldShowWindowsShellMenu } from './windows-shell-menu-visibility' import { canToggleNativeChat } from '../native-chat/native-chat-availability' -import { findTabAgentEntry } from '../native-chat/native-chat-tab-agent-entry' -import { resolveTabAgentFromTitle } from '@/lib/use-tab-agent' +import { selectTabAgentTypesByTabId } from './tab-agent-types-by-tab-id' +import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence' const isWindows = navigator.userAgent.includes('Windows') const isMacOs = navigator.userAgent.includes('Mac') @@ -454,7 +455,13 @@ function TabBarInner({ // eligible when it launched an agent or has a live agent-status entry on any of // its panes (paneKey = `${unifiedTabId}:…`), mirroring the toggle button's gate. const toggleTabViewMode = useAppStore((s) => s.toggleTabViewMode) - const agentStatusByPaneKey = useAppStore((s) => s.agentStatusByPaneKey) + // Why: the strip only needs each tab's stable agent identity, but the whole + // agentStatusByPaneKey map churns on every working↔idle transition app-wide. + // Select a shallow-stable { tabId: agentType } projection so the strip + // re-renders only when a tab gains/loses/changes its agent, not on status flips. + const tabAgentTypesByTabId = useAppStore( + useShallow((s) => selectTabAgentTypesByTabId(s.agentStatusByPaneKey ?? {})) + ) const nativeChatEnabled = useAppStore((s) => s.settings?.experimentalNativeChat === true) // Why: Electron elements run in a separate process, so clicking @@ -1103,13 +1110,12 @@ function TabBarInner({ // Carry the agent *identity* (not just "an agent exists") so the // native-chat gate can reject unsupported agents like Grok. const resolvedAgent = - resolveTabAgentFromTitle(unifiedTabForItem?.label ?? '') ?? - resolveTabAgentFromTitle(terminalTab.title) + resolveCommittedTitleAgentType(unifiedTabForItem?.label ?? '') ?? + resolveCommittedTitleAgentType(terminalTab.title) // Key the live-agent lookup by the backing terminal tab id — // agent-status pane keys are `${terminalTab.id}:${leafId}`, and // the unified tab id can differ from it. - const detectedAgent = - findTabAgentEntry(agentStatusByPaneKey ?? {}, terminalTab.id)?.agentType ?? null + const detectedAgent = tabAgentTypesByTabId[terminalTab.id] ?? null const canToggleViewMode = unifiedTabForItem !== undefined && canToggleNativeChat({ diff --git a/src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts b/src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts index 1fa6e5809..9805727fe 100644 --- a/src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts +++ b/src/renderer/src/components/tab-bar/TabBar.windows-shell-launch.test.ts @@ -123,6 +123,12 @@ vi.mock('react', async () => { } }) +// The headless React mock above stubs hooks, so zustand's useShallow (which +// calls useRef) has no dispatcher; make it a pass-through like the store mock. +vi.mock('zustand/react/shallow', () => ({ + useShallow: (selector: unknown) => selector +})) + vi.mock('lucide-react', () => ({ FilePlus: function FilePlus() { return null diff --git a/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts new file mode 100644 index 000000000..75ac39956 --- /dev/null +++ b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import { shallow } from 'zustand/shallow' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { findTabAgentEntry } from '../native-chat/native-chat-tab-agent-entry' +import { selectTabAgentTypesByTabId } from './tab-agent-types-by-tab-id' + +function entry(partial: Partial): AgentStatusEntry { + return { state: 'working', updatedAt: 0, ...partial } as AgentStatusEntry +} + +describe('selectTabAgentTypesByTabId', () => { + it('maps each tab to its first pane agent type, matching findTabAgentEntry', () => { + const map: Record = { + 'tab-1:leaf-a': entry({ agentType: 'claude' }), + 'tab-1:leaf-b': entry({ agentType: 'codex' }), + 'tab-2:leaf-a': entry({ agentType: 'codex' }) + } + const projection = selectTabAgentTypesByTabId(map) + expect(projection).toEqual({ 'tab-1': 'claude', 'tab-2': 'codex' }) + + // Parity with the lookup it replaces, for every tab. + for (const tabId of ['tab-1', 'tab-2', 'tab-missing']) { + expect(projection[tabId] ?? null).toBe(findTabAgentEntry(map, tabId)?.agentType ?? null) + } + }) + + it('a first pane without an agentType yields null even if a later pane has one', () => { + const map: Record = { + 'tab-1:leaf-a': entry({ agentType: undefined }), + 'tab-1:leaf-b': entry({ agentType: 'claude' }) + } + // First matching pane wins (claims the tab) with no agentType -> null, exactly + // like findTabAgentEntry(...)?.agentType ?? null. + expect(selectTabAgentTypesByTabId(map)['tab-1'] ?? null).toBe( + findTabAgentEntry(map, 'tab-1')?.agentType ?? null + ) + }) + + it('stays shallow-equal across a working<->idle status flip (no re-render)', () => { + const working: Record = { + 'tab-1:leaf-a': entry({ agentType: 'claude', state: 'working' }) + } + // A status write replaces the entry object but not the agentType. + const done: Record = { + 'tab-1:leaf-a': entry({ agentType: 'claude', state: 'done' }) + } + expect(shallow(selectTabAgentTypesByTabId(working), selectTabAgentTypesByTabId(done))).toBe( + true + ) + }) + + it('shallow-changes when a tab gains or changes its agent', () => { + const before = selectTabAgentTypesByTabId({ + 'tab-1:leaf-a': entry({ agentType: 'claude' }) + }) + const gained = selectTabAgentTypesByTabId({ + 'tab-1:leaf-a': entry({ agentType: 'claude' }), + 'tab-2:leaf-a': entry({ agentType: 'codex' }) + }) + expect(shallow(before, gained)).toBe(false) + }) + + it('ignores malformed pane keys with no tab id', () => { + expect(selectTabAgentTypesByTabId({ ':leaf-a': entry({ agentType: 'claude' }) })).toEqual({}) + }) +}) diff --git a/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.ts b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.ts new file mode 100644 index 000000000..5fc8335a9 --- /dev/null +++ b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.ts @@ -0,0 +1,41 @@ +import type { AgentStatusEntry, AgentType } from '../../../../shared/agent-status-types' + +/** + * Project `agentStatusByPaneKey` down to the stable `{ terminalTabId: agentType }` + * the tab strip actually reads (to gate the native-chat view-mode toggle). + * + * Why: agent-status pane keys are `${terminalTab.id}:${leafId}` and the tab strip + * only needs each tab's agent *identity* — which is fixed for the life of the + * agent. The full `agentStatusByPaneKey` map, however, gets a new top-level + * identity on every working↔idle status transition app-wide, so subscribing to it + * whole re-rendered every mounted tab strip on unrelated status churn. Selecting + * this projection under `useShallow` keeps the result referentially equal across + * those transitions, so the strip re-renders only when a tab actually gains, loses, + * or changes its agent. + * + * First matching pane per tab wins, mirroring `findTabAgentEntry` exactly (tab ids + * are colon-free by construction, so the substring before the first `:` is the + * tab id). A pane whose entry has no `agentType` still claims the tab and yields + * `null`, identical to `findTabAgentEntry(...)?.agentType ?? null`. + */ +export function selectTabAgentTypesByTabId( + agentStatusByPaneKey: Record +): Record { + const byTabId: Record = {} + const claimed = new Set() + for (const [paneKey, entry] of Object.entries(agentStatusByPaneKey)) { + const colon = paneKey.indexOf(':') + if (colon <= 0) { + continue + } + const tabId = paneKey.slice(0, colon) + if (claimed.has(tabId)) { + continue + } + claimed.add(tabId) + if (entry.agentType != null) { + byTabId[tabId] = entry.agentType + } + } + return byTabId +} diff --git a/src/renderer/src/components/terminal-pane/agent-interrupt-inference.test.ts b/src/renderer/src/components/terminal-pane/agent-interrupt-inference.test.ts index 780137e11..fc4eb329c 100644 --- a/src/renderer/src/components/terminal-pane/agent-interrupt-inference.test.ts +++ b/src/renderer/src/components/terminal-pane/agent-interrupt-inference.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: this suite locks the interrupt inference state machine across several agent-specific keyboard semantics. */ import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import { diff --git a/src/renderer/src/components/terminal-pane/cache-timer-seeding.ts b/src/renderer/src/components/terminal-pane/cache-timer-seeding.ts index 6f788af3e..7b1d16522 100644 --- a/src/renderer/src/components/terminal-pane/cache-timer-seeding.ts +++ b/src/renderer/src/components/terminal-pane/cache-timer-seeding.ts @@ -1,4 +1,5 @@ -import { detectAgentStatusFromTitle, isClaudeAgent } from '@/lib/agent-status' +import { isClaudeAgent } from '@/lib/agent-status' +import { classifyTitleActivity } from '@/lib/pane-agent-evidence' export function shouldSeedCacheTimerOnInitialTitle(args: { rawTitle: string @@ -12,7 +13,7 @@ export function shouldSeedCacheTimerOnInitialTitle(args: { return false } - const status = detectAgentStatusFromTitle(rawTitle) + const status = classifyTitleActivity(rawTitle) if (status === null || status === 'working') { return false } diff --git a/src/renderer/src/components/terminal-pane/layout-serialization.test.ts b/src/renderer/src/components/terminal-pane/layout-serialization.test.ts index b72cc28a8..95b7bb092 100644 --- a/src/renderer/src/components/terminal-pane/layout-serialization.test.ts +++ b/src/renderer/src/components/terminal-pane/layout-serialization.test.ts @@ -1,5 +1,3 @@ -/* oxlint-disable max-lines -- Why: this test keeps split layout replay fixtures together so - * stable leaf-id migration regressions are visible in one focused suite. */ import { describe, expect, it, beforeAll, vi } from 'vitest' import type { TerminalPaneLayoutNode } from '../../../../shared/types' diff --git a/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.ts b/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.ts index e3527bf11..20f24fb69 100644 --- a/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.ts +++ b/src/renderer/src/components/terminal-pane/native-chat-leaf-title-agent.ts @@ -1,5 +1,5 @@ import type { TuiAgent } from '../../../../shared/types' -import { resolveTabAgentFromTitle } from '@/lib/use-tab-agent' +import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence' export type NativeChatLeafTitlePane = { id: number @@ -26,7 +26,7 @@ export function resolveNativeChatLeafTitleAgent({ } const targetPane = panes.find((pane) => pane.leafId === leafId) const paneAgent = targetPane - ? resolveTabAgentFromTitle(runtimePaneTitlesByPaneId[targetPane.id] ?? '') + ? resolveCommittedTitleAgentType(runtimePaneTitlesByPaneId[targetPane.id] ?? '') : null if (paneAgent) { return paneAgent @@ -36,5 +36,8 @@ export function resolveNativeChatLeafTitleAgent({ if (panes.length > 1) { return null } - return resolveTabAgentFromTitle(tabLabel ?? '') ?? resolveTabAgentFromTitle(terminalTitle ?? '') + return ( + resolveCommittedTitleAgentType(tabLabel ?? '') ?? + resolveCommittedTitleAgentType(terminalTitle ?? '') + ) } diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index 7d1874e13..aed0f383f 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -1007,6 +1007,221 @@ describe('connectPanePty', () => { }) }) + it('drives runtime title, tab title, and renderer policy from one title decision', async () => { + const { connectPanePty } = await import('./pty-connection') + const pane = createPane(1) + const transport = createMockTransport('pty-gemini') + transportFactoryQueue.push(transport) + const manager = createManager(1, 1) + const deps = createDeps() + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + const onTitleChange = createdTransportOptions[0]?.onTitleChange as + | ((title: string, rawTitle: string) => void) + | undefined + if (!onTitleChange) { + throw new Error('missing title callback') + } + onTitleChange('✦ Gemini CLI', '✦ Gemini CLI') + + // Display/runtime/tab title and the GPU gate all come from the same decision. + expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, '✦ Gemini CLI') + expect(deps.updateTabTitle).toHaveBeenCalledWith('tab-1', '✦ Gemini CLI') + // Genuine Gemini under the default `auto` setting takes the DOM fallback. + expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false) + }) + + it('keeps GPU enabled when a pane-scoped OMP owner emits a Gemini-looking title', async () => { + const { connectPanePty } = await import('./pty-connection') + const paneKey = makePaneKey('tab-1', LEAF_1) + mockStoreState = { + ...mockStoreState, + agentStatusByPaneKey: { + [paneKey]: { + paneKey, + agentType: 'omp', + state: 'working', + prompt: '', + updatedAt: Date.now(), + stateStartedAt: Date.now(), + stateHistory: [] + } + } + } as StoreState + const pane = createPane(1) + const transport = createMockTransport('pty-omp-gemini-cwd') + transportFactoryQueue.push(transport) + const manager = createManager(1, 1) + const deps = createDeps() + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + const onTitleChange = createdTransportOptions[0]?.onTitleChange as + | ((title: string, rawTitle: string) => void) + | undefined + if (!onTitleChange) { + throw new Error('missing title callback') + } + onTitleChange('✦ Gemini CLI', '✦ Gemini CLI') + + // Pane-scoped owner evidence outranks the raw title, so the fallback cannot fire. + expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, true) + expect(manager.setPaneGpuRendering).not.toHaveBeenCalledWith(1, false) + }) + + it('does not let one split pane title change another pane GPU state', async () => { + const { connectPanePty } = await import('./pty-connection') + const pane1 = createPane(1) + const pane2 = createPane(2) + const transport1 = createMockTransport('pty-split-1') + const transport2 = createMockTransport('pty-split-2') + transportFactoryQueue.push(transport1, transport2) + const manager = createManager(2, 1) + + connectPanePty(pane1 as never, manager as never, createDeps() as never) + connectPanePty(pane2 as never, manager as never, createDeps() as never) + await flushAsyncTicks() + const onTitleChange1 = createdTransportOptions[0]?.onTitleChange as + | ((title: string, rawTitle: string) => void) + | undefined + if (!onTitleChange1) { + throw new Error('missing title callback for split pane 1') + } + onTitleChange1('✦ Gemini CLI', '✦ Gemini CLI') + + const gpuCalls = manager.setPaneGpuRendering.mock.calls as [number, boolean][] + expect(gpuCalls.some(([paneId]) => paneId === 1)).toBe(true) + expect(gpuCalls.every(([paneId]) => paneId !== 2)).toBe(true) + }) + + it('DOM-gates a genuine Gemini split pane even when the tab launched a non-Gemini agent', async () => { + const { connectPanePty } = await import('./pty-connection') + // The shared tab.launchAgent must not veto the renderer for a sibling pane. + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { + 'wt-1': [{ id: 'tab-1', ptyId: 'tab-pty', launchAgent: 'omp' }] + } + } as StoreState + const pane1 = createPane(1) + const pane2 = createPane(2) + const transport1 = createMockTransport('pty-split-owner-1') + const transport2 = createMockTransport('pty-split-owner-2') + transportFactoryQueue.push(transport1, transport2) + const manager = createManager(2, 2) + + connectPanePty(pane1 as never, manager as never, createDeps() as never) + connectPanePty(pane2 as never, manager as never, createDeps() as never) + await flushAsyncTicks() + const onTitleChange2 = createdTransportOptions[1]?.onTitleChange as + | ((title: string, rawTitle: string) => void) + | undefined + if (!onTitleChange2) { + throw new Error('missing title callback for split pane 2') + } + onTitleChange2('✦ Gemini CLI', '✦ Gemini CLI') + + expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(2, false) + }) + + it('DOM-gates a genuine Gemini title in a pane whose launch agent was non-Gemini', async () => { + const { connectPanePty } = await import('./pty-connection') + const pane = createPane(1) + const transport = createMockTransport('pty-reused-gemini') + transportFactoryQueue.push(transport) + const manager = createManager(1, 1) + // Stale, never-cleared launch identity must not veto the renderer. + const deps = createDeps({ startup: { command: 'claude', launchAgent: 'claude' } }) + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + const onTitleChange = createdTransportOptions[0]?.onTitleChange as + | ((title: string, rawTitle: string) => void) + | undefined + if (!onTitleChange) { + throw new Error('missing title callback') + } + onTitleChange('✦ Gemini CLI', '✦ Gemini CLI') + + expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false) + }) + + it('DOM-gates a genuine Gemini title when the only pane row is a done non-Gemini agent', async () => { + const { connectPanePty } = await import('./pty-connection') + const paneKey = makePaneKey('tab-1', LEAF_1) + mockStoreState = { + ...mockStoreState, + agentStatusByPaneKey: { + [paneKey]: { + paneKey, + agentType: 'claude', + state: 'done', + prompt: '', + updatedAt: Date.now(), + stateStartedAt: Date.now(), + stateHistory: [] + } + } + } as StoreState + const pane = createPane(1) + const transport = createMockTransport('pty-reused-done-row') + transportFactoryQueue.push(transport) + const manager = createManager(1, 1) + const deps = createDeps() + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + const onTitleChange = createdTransportOptions[0]?.onTitleChange as + | ((title: string, rawTitle: string) => void) + | undefined + if (!onTitleChange) { + throw new Error('missing title callback') + } + onTitleChange('✦ Gemini CLI', '✦ Gemini CLI') + + // A `done` row is a leftover from a prior agent, so it must not veto. + expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false) + }) + + it('DOM-gates a genuine Gemini title when the only pane row is a stale non-Gemini agent', async () => { + const { connectPanePty } = await import('./pty-connection') + const paneKey = makePaneKey('tab-1', LEAF_1) + const staleAt = Date.now() - 60 * 60 * 1000 + mockStoreState = { + ...mockStoreState, + agentStatusByPaneKey: { + [paneKey]: { + paneKey, + agentType: 'claude', + state: 'working', + prompt: '', + updatedAt: staleAt, + stateStartedAt: staleAt, + stateHistory: [] + } + } + } as StoreState + const pane = createPane(1) + const transport = createMockTransport('pty-reused-stale-row') + transportFactoryQueue.push(transport) + const manager = createManager(1, 1) + const deps = createDeps() + + connectPanePty(pane as never, manager as never, deps as never) + await flushAsyncTicks() + const onTitleChange = createdTransportOptions[0]?.onTitleChange as + | ((title: string, rawTitle: string) => void) + | undefined + if (!onTitleChange) { + throw new Error('missing title callback') + } + onTitleChange('✦ Gemini CLI', '✦ Gemini CLI') + + // A stale working row (older than AGENT_STATUS_STALE_AFTER_MS) must not veto. + expect(manager.setPaneGpuRendering).toHaveBeenCalledWith(1, false) + }) + it('normalizes after shell word deletion edits a typed command to omp', async () => { const { connectPanePty } = await import('./pty-connection') enableActiveRuntimeEnvironment() diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index 1dead4f1c..8cefac661 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -3,12 +3,8 @@ import type { PaneManager, ManagedPane } from '@/lib/pane-manager/pane-manager' import type { ManagedPaneInternal } from '@/lib/pane-manager/pane-manager-types' import type { IBuffer, IDisposable } from '@xterm/xterm' import { resolveCursorAgentImeAnchor } from '@/lib/pane-manager/terminal-ime-anchor' -import { - detectAgentStatusFromTitle, - agentTypeToIconAgent, - isGeminiTerminalTitle, - isClaudeAgent -} from '@/lib/agent-status' +import { detectAgentStatusFromTitle, agentTypeToIconAgent, isClaudeAgent } from '@/lib/agent-status' +import { resolvePaneTitleDecision } from './terminal-title-evidence' import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph' import { useAppStore } from '@/store' import { getWorktreeMapFromState } from '@/store/selectors' @@ -165,7 +161,7 @@ import { normalizeCompatibleAgentTitleForOwner, resolveCompatibleAgentTypeForOwner } from '../../../../shared/agent-title-owner' -import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' +import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence' import { isExpectedAgentProcess, recognizeAgentProcessFromCommandLine @@ -1390,15 +1386,22 @@ export function connectPanePty( )?.title return runtimeTitle ?? tabTitle ?? null } - const hasFreshPaneAgentSurface = (): boolean => { - const state = useAppStore.getState() - const entry = state.agentStatusByPaneKey[cacheKey] - const now = Date.now() - const entryIsFresh = - entry && + // Why: a pane-scoped explicit row only counts as current ownership evidence + // when it is fresh and not already `done` — a stale or completed row is a + // leftover from a prior agent that may no longer own the shell. + const isFreshActivePaneAgentEntry = ( + entry: AgentStatusEntry | undefined + ): entry is AgentStatusEntry => { + return ( + !!entry && typeof entry.updatedAt === 'number' && - now - entry.updatedAt <= AGENT_STATUS_STALE_AFTER_MS - if (entryIsFresh && entry.state !== 'done') { + Date.now() - entry.updatedAt <= AGENT_STATUS_STALE_AFTER_MS && + entry.state !== 'done' + ) + } + const hasFreshPaneAgentSurface = (): boolean => { + const entry = useAppStore.getState().agentStatusByPaneKey[cacheKey] + if (isFreshActivePaneAgentEntry(entry)) { return true } const liveTitle = getLivePaneAgentTitle() @@ -1493,6 +1496,23 @@ export function connectPanePty( state.agentStatusByPaneKey[cacheKey]?.agentType ) } + // Why: the renderer veto (owner evidence beating a Gemini-looking title) must + // use only pane-scoped, CURRENT ownership. getAuthoritativePaneAgent leads + // with the tab-shared `tab.launchAgent` and a never-cleared + // `paneStartup.launchAgent`, which would let a sibling split pane or a reused + // pane keep WebGL for a genuine Gemini terminal (#7428 regression class). + // Launch identity is excluded, and the never-clearing startup seed + // (`paneStartup.initialAgentStatus`) too; a stale or `done` explicit row is + // ignored via the freshness predicate so a reused pane cannot inherit a prior + // agent's veto. Only live foreground command inference and a fresh, active + // hook row count. A genuine OMP/Pi pane stays protected owner-independently by + // the isPiAgentTitle guard inside isGeminiTerminalTitle. + const getPaneScopedRendererOwner = (): AgentType | undefined => { + const entry = useAppStore.getState().agentStatusByPaneKey[cacheKey] + return ( + commandInferredPaneAgent ?? (isFreshActivePaneAgentEntry(entry) ? entry.agentType : undefined) + ) + } const clearInferredInterruptWorkingTitle = (): void => { const state = useAppStore.getState() const currentTitle = state.runtimePaneTitlesByTabId?.[deps.tabId]?.[pane.id] @@ -1790,7 +1810,7 @@ export function connectPanePty( (entry) => entry.id === deps.tabId ) const title = currentTitle ?? tab?.title - if (!title || resolveExplicitTerminalTitleAgentType(title) === null) { + if (!title || resolveCommittedTitleAgentType(title) === null) { return } const neutralTitle = neutralTerminalTitle() @@ -2166,7 +2186,17 @@ export function connectPanePty( let allowInitialIdleCacheSeed = false const onTitleChange = (title: string, rawTitle: string): void => { - const paneTitle = normalizeCompatibleAgentTitleForOwner(title, getAuthoritativePaneAgent()) + // Why: one owner-aware decision drives the display label, the runtime/tab + // title, task-completion tracking, and the renderer gate, so raw title text + // can no longer disable GPU behind stronger owner evidence (#7428/#7447). + const decision = resolvePaneTitleDecision({ + normalizedTitle: title, + rawTitle, + displayOwnerAgentType: getAuthoritativePaneAgent(), + rendererOwnerAgentType: getPaneScopedRendererOwner(), + userGpuMode: useAppStore.getState().settings?.terminalGpuAcceleration ?? 'auto' + }) + const paneTitle = decision.displayTitle if ( shouldSuppressCodexAutoApprovalSyntheticTitle(paneTitle, { paneKey: cacheKey, @@ -2176,10 +2206,10 @@ export function connectPanePty( ) { return } - manager.setPaneGpuRendering(pane.id, !isGeminiTerminalTitle(rawTitle)) + manager.setPaneGpuRendering(pane.id, decision.rendererPolicy.gpuEnabled) deps.setRuntimePaneTitle(deps.tabId, pane.id, paneTitle) if (syncAgentTaskCompleteTrackingEnabled()) { - agentCompletionCoordinator.observeTitle(rawTitle) + agentCompletionCoordinator.observeTitle(decision.rawTitle) } // Why: only the focused pane should drive the tab title — otherwise two // agents in split panes cause rapid title flickering as each emits OSC diff --git a/src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts b/src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts index cbbbe6850..8cd870aec 100644 --- a/src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: fork flow tests share a mocked store and launch harness. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type { ManagedPane } from '@/lib/pane-manager/pane-manager' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' diff --git a/src/renderer/src/components/terminal-pane/terminal-renderer-policy.test.ts b/src/renderer/src/components/terminal-pane/terminal-renderer-policy.test.ts new file mode 100644 index 000000000..344e3df81 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-renderer-policy.test.ts @@ -0,0 +1,185 @@ +import { describe, expect, it } from 'vitest' +import type { AgentType } from '../../../../shared/agent-status-types' +import { resolvePaneRendererPolicy } from './terminal-renderer-policy' + +const GEMINI_WORKING = '✦' + +describe('resolvePaneRendererPolicy', () => { + describe('user GPU modes', () => { + it('keeps the content gate open under `off` for non-Gemini panes', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: 'zsh', + ownerAgentType: undefined, + userGpuMode: 'off' + }) + // Why: the mode gate downstream forces DOM; the gate stays open so a later + // switch to auto/on can re-attach without waiting for a new title frame. + expect(decision).toEqual({ + gpuEnabled: true, + reason: 'user-setting', + confidence: 'authoritative' + }) + }) + + it('DOM-gates a genuine Gemini pane under `off`', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: `${GEMINI_WORKING} Gemini CLI`, + ownerAgentType: 'gemini', + userGpuMode: 'off' + }) + expect(decision.gpuEnabled).toBe(false) + expect(decision.reason).toBe('user-setting') + }) + + it('forces GPU on under `on` even for a genuine Gemini pane', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: `${GEMINI_WORKING} Gemini CLI`, + ownerAgentType: 'gemini', + userGpuMode: 'on' + }) + // Why: agent compatibility exclusions must not override an explicit on. + expect(decision).toEqual({ + gpuEnabled: true, + reason: 'user-setting', + confidence: 'authoritative' + }) + }) + + it('enables GPU under `auto` for an ordinary shell', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: 'bash', + ownerAgentType: undefined, + userGpuMode: 'auto' + }) + expect(decision).toEqual({ + gpuEnabled: true, + reason: 'capability', + confidence: 'authoritative' + }) + }) + }) + + describe('WebGL capability and context-loss containment', () => { + it('disables GPU under `on` when WebGL is unavailable', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: 'bash', + ownerAgentType: undefined, + userGpuMode: 'on', + webglUnavailable: true + }) + expect(decision).toEqual({ + gpuEnabled: false, + reason: 'capability', + confidence: 'authoritative' + }) + }) + + it('disables GPU under `on` inside context-loss containment', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: 'bash', + ownerAgentType: undefined, + userGpuMode: 'on', + inContextLossContainment: true + }) + expect(decision).toEqual({ + gpuEnabled: false, + reason: 'context-loss', + confidence: 'authoritative' + }) + }) + + it('disables GPU under `auto` inside context-loss containment', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: 'bash', + ownerAgentType: undefined, + userGpuMode: 'auto', + inContextLossContainment: true + }) + expect(decision.gpuEnabled).toBe(false) + expect(decision.reason).toBe('context-loss') + }) + }) + + describe('Gemini compatibility fallback under `auto`', () => { + it('DOM-gates a genuine Gemini title with no authoritative owner', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: `${GEMINI_WORKING} Gemini CLI`, + ownerAgentType: undefined, + userGpuMode: 'auto' + }) + expect(decision).toEqual({ + gpuEnabled: false, + reason: 'agent-compatibility', + confidence: 'fallback' + }) + }) + + it('DOM-gates a genuine Gemini title with a Gemini owner at higher confidence', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: `${GEMINI_WORKING} Gemini CLI`, + ownerAgentType: 'gemini', + userGpuMode: 'auto' + }) + expect(decision).toEqual({ + gpuEnabled: false, + reason: 'agent-compatibility', + confidence: 'authoritative' + }) + }) + + it('keeps GPU on when a non-Gemini owner emits a Gemini-looking title', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: `${GEMINI_WORKING} Gemini CLI`, + ownerAgentType: 'omp', + userGpuMode: 'auto' + }) + // Why: OMP ownership is authoritative and outranks raw title text (#7428). + expect(decision.gpuEnabled).toBe(true) + expect(decision.reason).toBe('capability') + }) + + it('does not treat an `unknown` owner as an authoritative non-Gemini veto', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: `${GEMINI_WORKING} Gemini CLI`, + ownerAgentType: 'unknown', + userGpuMode: 'auto' + }) + expect(decision.gpuEnabled).toBe(false) + expect(decision.reason).toBe('agent-compatibility') + }) + }) + + describe('agent token text cannot flip renderer policy under authoritative owners', () => { + const AGENT_TOKENS = ['gemini', 'claude', 'codex', 'opencode', 'cursor', 'omp', 'pi'] as const + + for (const token of AGENT_TOKENS) { + it(`keeps GPU on when a title mentions "${token}" but owner is another agent`, () => { + const ownerAgentType: AgentType = token === 'claude' ? 'codex' : 'claude' + const decision = resolvePaneRendererPolicy({ + rawTitle: token, + ownerAgentType, + userGpuMode: 'auto' + }) + expect(decision.gpuEnabled).toBe(true) + }) + } + + it('keeps GPU on for an OMP owner whose title is exactly the Gemini token', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: 'gemini', + ownerAgentType: 'omp', + userGpuMode: 'auto' + }) + expect(decision.gpuEnabled).toBe(true) + }) + + it('keeps GPU on for a Pi owner whose title is exactly the Gemini token', () => { + const decision = resolvePaneRendererPolicy({ + rawTitle: 'gemini', + ownerAgentType: 'pi', + userGpuMode: 'auto' + }) + expect(decision.gpuEnabled).toBe(true) + }) + }) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-renderer-policy.ts b/src/renderer/src/components/terminal-pane/terminal-renderer-policy.ts new file mode 100644 index 000000000..f6d225dcd --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-renderer-policy.ts @@ -0,0 +1,107 @@ +import { isGeminiTerminalTitle } from '@/lib/agent-status' +import type { AgentType } from '../../../../shared/agent-status-types' +import type { GlobalSettings } from '../../../../shared/types' + +export type TerminalGpuAccelerationMode = GlobalSettings['terminalGpuAcceleration'] + +/** + * The resolved renderer decision for a pane. `gpuEnabled` is the content-compat + * gate passed to `setPaneGpuRendering`; the user-setting mode gate and WebGL + * capability/context-loss latches are still applied downstream by the pane + * manager, so this decision never has to force WebGL on when it is unavailable. + */ +export type RendererPolicyDecision = { + gpuEnabled: boolean + reason: 'user-setting' | 'capability' | 'context-loss' | 'agent-compatibility' + confidence: 'authoritative' | 'fallback' +} + +export type ResolvePaneRendererPolicyInput = { + rawTitle: string | null + ownerAgentType: AgentType | null | undefined + userGpuMode: TerminalGpuAccelerationMode + /** Set when the pane cannot obtain a WebGL context at all. */ + webglUnavailable?: boolean + /** Set when the pane is inside GPU crash/context-loss containment. */ + inContextLossContainment?: boolean +} + +// Why: an authoritative non-Gemini owner (OMP, Pi, Claude, a shell, …) outranks +// raw title text. 'unknown' is not authoritative, so it does not veto the +// title-derived Gemini fallback. +function isKnownNonGeminiOwner(ownerAgentType: AgentType | null | undefined): boolean { + return ( + typeof ownerAgentType === 'string' && + ownerAgentType !== '' && + ownerAgentType !== 'gemini' && + ownerAgentType !== 'unknown' + ) +} + +type GeminiCompatFallback = { + disable: boolean + confidence: 'authoritative' | 'fallback' +} + +// Why: keep the existing title-driven Gemini fallback, but let owner evidence +// veto it so a Pi/OMP pane whose cwd or session text mentions gemini is never +// forced onto the DOM renderer. +function resolveGeminiCompatFallback( + rawTitle: string | null, + ownerAgentType: AgentType | null | undefined +): GeminiCompatFallback { + if (!isGeminiTerminalTitle(rawTitle ?? '')) { + return { disable: false, confidence: 'authoritative' } + } + if (isKnownNonGeminiOwner(ownerAgentType)) { + return { disable: false, confidence: 'authoritative' } + } + return { disable: true, confidence: ownerAgentType === 'gemini' ? 'authoritative' : 'fallback' } +} + +/** + * Resolves the pane renderer (WebGL vs DOM content gate) from the user GPU + * setting, WebGL capability/context-loss state, and owner/title evidence. + * + * Precedence: user `off` keeps the effective renderer on DOM downstream while + * leaving the content gate open for a later mode switch; WebGL + * unavailable/context-loss force DOM; explicit `on` keeps GPU regardless of + * agent compatibility; `auto` applies the Gemini compatibility fallback only + * when owner evidence does not attribute the pane to another agent/shell. + */ +export function resolvePaneRendererPolicy( + input: ResolvePaneRendererPolicyInput +): RendererPolicyDecision { + const { rawTitle, ownerAgentType, userGpuMode } = input + + if (userGpuMode === 'off') { + // Why: the user-setting mode gate downstream already forces DOM. Mirror the + // title/owner content gate so a genuine Gemini pane stays DOM-gated while + // other panes keep the gate open for a later switch to `auto`/`on`. + const fallback = resolveGeminiCompatFallback(rawTitle, ownerAgentType) + // Why: carry the fallback's own confidence so identical inputs report the + // same confidence whether the effective mode is `off` or `auto`. + return { + gpuEnabled: !fallback.disable, + reason: 'user-setting', + confidence: fallback.confidence + } + } + + if (input.inContextLossContainment) { + return { gpuEnabled: false, reason: 'context-loss', confidence: 'authoritative' } + } + if (input.webglUnavailable) { + return { gpuEnabled: false, reason: 'capability', confidence: 'authoritative' } + } + + if (userGpuMode === 'on') { + return { gpuEnabled: true, reason: 'user-setting', confidence: 'authoritative' } + } + + const fallback = resolveGeminiCompatFallback(rawTitle, ownerAgentType) + if (fallback.disable) { + return { gpuEnabled: false, reason: 'agent-compatibility', confidence: fallback.confidence } + } + return { gpuEnabled: true, reason: 'capability', confidence: 'authoritative' } +} diff --git a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts index fd5c81c31..0f0c4cec3 100644 --- a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: terminal keyboard policy covers platform - * readline compatibility, pane management, and Option-as-Alt translation in - * one pure function; the cases need to stay adjacent. */ import { describe, expect, it } from 'vitest' import { resolveTerminalShortcutAction, diff --git a/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts new file mode 100644 index 000000000..960c354f5 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-title-evidence.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest' +import { resolvePaneDisplayTitle, resolvePaneTitleDecision } from './terminal-title-evidence' + +describe('resolvePaneDisplayTitle', () => { + it('normalizes a Pi-compatible title to the resolved OMP owner', () => { + expect(resolvePaneDisplayTitle('Pi ready', 'omp')).toBe('OMP ready') + }) + + it('passes an unowned title through unchanged', () => { + expect(resolvePaneDisplayTitle('bash', undefined)).toBe('bash') + }) +}) + +describe('resolvePaneTitleDecision', () => { + it('derives the display label and the renderer veto from a pane-scoped OMP owner', () => { + const decision = resolvePaneTitleDecision({ + normalizedTitle: 'Pi ready', + rawTitle: '✦ Gemini CLI', + displayOwnerAgentType: 'omp', + rendererOwnerAgentType: 'omp', + userGpuMode: 'auto' + }) + expect(decision.displayTitle).toBe('OMP ready') + expect(decision.rawTitle).toBe('✦ Gemini CLI') + // Why: the OMP owner renames the label and vetoes the Gemini glyph fallback. + expect(decision.rendererPolicy.gpuEnabled).toBe(true) + }) + + it('uses the renderer owner, not the display owner, for the GPU veto', () => { + const decision = resolvePaneTitleDecision({ + normalizedTitle: 'Pi ready', + rawTitle: '✦ Gemini CLI', + // Display label follows the sticky/tab-scoped owner, but the renderer veto + // sees no current pane-scoped owner, so the genuine Gemini pane goes DOM. + displayOwnerAgentType: 'omp', + rendererOwnerAgentType: undefined, + userGpuMode: 'auto' + }) + expect(decision.displayTitle).toBe('OMP ready') + expect(decision.rendererPolicy.gpuEnabled).toBe(false) + expect(decision.rendererPolicy.reason).toBe('agent-compatibility') + }) + + it('DOM-gates a genuine Gemini pane while preserving its raw title', () => { + const decision = resolvePaneTitleDecision({ + normalizedTitle: '✦ Gemini CLI', + rawTitle: '✦ Gemini CLI', + displayOwnerAgentType: 'gemini', + rendererOwnerAgentType: 'gemini', + userGpuMode: 'auto' + }) + expect(decision.rawTitle).toBe('✦ Gemini CLI') + expect(decision.rendererPolicy.gpuEnabled).toBe(false) + expect(decision.rendererPolicy.reason).toBe('agent-compatibility') + }) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts b/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts new file mode 100644 index 000000000..f89eb6bbe --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-title-evidence.ts @@ -0,0 +1,57 @@ +import { normalizeCompatibleAgentTitleForOwner } from '../../../../shared/agent-title-owner' +import type { AgentType } from '../../../../shared/agent-status-types' +import { + resolvePaneRendererPolicy, + type RendererPolicyDecision, + type TerminalGpuAccelerationMode +} from './terminal-renderer-policy' + +/** + * Owner-aware display label. Wraps the compatible-owner title normalization so + * the display label follows the resolved owner rather than raw wrapper text. + */ +export function resolvePaneDisplayTitle( + title: string, + ownerAgentType: AgentType | null | undefined +): string { + return normalizeCompatibleAgentTitleForOwner(title, ownerAgentType) +} + +/** + * The resolved decision for one OSC title frame: a single owner-aware display + * label plus the renderer policy, so `updateTabTitle`, `setRuntimePaneTitle`, + * task-completion tracking, and the GPU gate all consume one interpretation. + */ +export type PaneTitleDecision = { + displayTitle: string + rawTitle: string + rendererPolicy: RendererPolicyDecision +} + +export type ResolvePaneTitleDecisionInput = { + /** Normalized title from the transport (may already be display-shaped). */ + normalizedTitle: string + rawTitle: string + /** Owner used for the display label — may include sticky/tab-scoped launch + * identity, which is correct for the visible label. */ + displayOwnerAgentType: AgentType | null | undefined + /** Owner used for the renderer veto — must be pane-scoped and current so a + * sibling/reused pane's launch identity cannot keep GPU for a genuine + * Gemini pane. */ + rendererOwnerAgentType: AgentType | null | undefined + userGpuMode: TerminalGpuAccelerationMode + webglUnavailable?: boolean + inContextLossContainment?: boolean +} + +export function resolvePaneTitleDecision(input: ResolvePaneTitleDecisionInput): PaneTitleDecision { + const displayTitle = resolvePaneDisplayTitle(input.normalizedTitle, input.displayOwnerAgentType) + const rendererPolicy = resolvePaneRendererPolicy({ + rawTitle: input.rawTitle, + ownerAgentType: input.rendererOwnerAgentType, + userGpuMode: input.userGpuMode, + webglUnavailable: input.webglUnavailable, + inContextLossContainment: input.inContextLossContainment + }) + return { displayTitle, rawTitle: input.rawTitle, rendererPolicy } +} diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts index d4b976216..e8b59a3a4 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts @@ -20,8 +20,11 @@ vi.mock('./pane-helpers', () => ({ fitPanes: vi.fn(), focusActivePane: vi.fn() })) +const scheduleTabRevealWebglAtlasRecovery = vi.fn() vi.mock('./terminal-webgl-atlas-recovery', () => ({ - scheduleTerminalWebglAtlasRecovery: vi.fn() + // Why: the light-tab reveal must recover the atlas immediately, decoupled from + // the terminal-output debounce (which a background stream could otherwise defer). + scheduleTabRevealWebglAtlasRecovery: () => scheduleTabRevealWebglAtlasRecovery() })) type FakeManager = { @@ -63,6 +66,9 @@ describe('resumeTerminalVisibility reveal repaint', () => { expect(manager.scheduleRevealRepaint).toHaveBeenCalledTimes(1) expect(manager.resumeRendering).not.toHaveBeenCalled() + // Reveal recovery is immediate (not the terminal-output debounce), so a + // background stream in another pane cannot defer this tab's atlas rebuild. + expect(scheduleTabRevealWebglAtlasRecovery).toHaveBeenCalledTimes(1) }) it('schedules the repaint after rendering resumes on a heavy reveal', () => { diff --git a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts index fdf597c55..0c821e5d0 100644 --- a/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts +++ b/src/renderer/src/components/terminal-pane/terminal-visibility-resume.ts @@ -7,7 +7,7 @@ import { } from '@/lib/pane-manager/pane-terminal-output-scheduler' import { enforceTerminalCurrentScrollIntent } from '@/lib/pane-manager/terminal-scroll-intent' import { fitAndFocusPanes, fitPanes, focusActivePane } from './pane-helpers' -import { scheduleTerminalWebglAtlasRecovery } from './terminal-webgl-atlas-recovery' +import { scheduleTabRevealWebglAtlasRecovery } from './terminal-webgl-atlas-recovery' const VISIBLE_RESUME_FLUSH_CHARS = 256 * 1024 const WINDOW_WAKE_FLUSH_CHARS = 64 * 1024 @@ -62,7 +62,10 @@ export function resumeTerminalVisibility({ // overlay's delayed geometry fit. Still request hidden-output recovery: // agent TUIs can suppress hidden bytes until the pane is foregrounded. requestLightTabBacklogRecovery(manager) - scheduleTerminalWebglAtlasRecovery() + // Why: reveal recovery must be immediate, not the terminal-output debounce + // — a background agent streaming in another pane must not defer this tab's + // atlas rebuild. + scheduleTabRevealWebglAtlasRecovery() if (isActive) { focusActivePane(manager) } diff --git a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts index 4d09bddbc..93c696719 100644 --- a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts @@ -5,7 +5,9 @@ import { } from '@/lib/pane-manager/pane-manager-registry' import { scheduleImagePasteWebglAtlasRecovery, - scheduleTerminalWebglAtlasRecovery + scheduleTabRevealWebglAtlasRecovery, + scheduleTerminalWebglAtlasRecovery, + TERMINAL_OUTPUT_RECOVERY_QUIET_MS } from './terminal-webgl-atlas-recovery' describe('terminal WebGL atlas recovery', () => { @@ -28,6 +30,10 @@ describe('terminal WebGL atlas recovery', () => { for (const manager of registeredManagers.splice(0)) { unregisterLivePaneManager(manager) } + // Why: a test can leave the module-global debounce timer armed; clear the + // fake-timer queue before restoring real timers so no pending fire leaks + // into a later test. + vi.clearAllTimers() vi.useRealTimers() vi.unstubAllGlobals() }) @@ -145,7 +151,63 @@ describe('terminal WebGL atlas recovery', () => { expect(manager.refreshAllPanes).not.toHaveBeenCalled() }) - it('coalesces terminal-output atlas recovery across a redraw burst', () => { + it('recovers immediately on a tab reveal, not through the streaming debounce', () => { + // Regression guard (STA-1365 review): reveal recovery must stay immediate so a + // background agent streaming in another pane cannot defer a revealed tab's + // atlas rebuild. It shares the paste path's immediate burst, not the debounce. + vi.useFakeTimers() + const rafCallbacks: FrameRequestCallback[] = [] + vi.stubGlobal( + 'requestAnimationFrame', + vi.fn((callback: FrameRequestCallback) => { + rafCallbacks.push(callback) + return rafCallbacks.length + }) + ) + const manager = registerManager() + + scheduleTabRevealWebglAtlasRecovery() + // First burst leg fires on the next frame — no 200ms debounce wait. + rafCallbacks[0]?.(0) + expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) + expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + vi.advanceTimersByTime(120) + vi.advanceTimersByTime(380) + expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3) + expect(manager.refreshAllPanes).toHaveBeenCalledTimes(3) + }) + + it('does not recover mid-stream while terminal output keeps arriving', () => { + // Regression (STA-1365): an alternate-screen TUI requests atlas recovery on + // every redraw frame. Recovering mid-stream clears the shared glyph atlas and + // repaints every pane several times a second, which reads as a flicker. The + // debounce must swallow a sustained stream entirely until it goes quiet. + vi.useFakeTimers() + vi.stubGlobal( + 'requestAnimationFrame', + vi.fn((callback: FrameRequestCallback) => { + callback(0) + return 1 + }) + ) + const manager = registerManager() + + // Simulate ~1s of continuous streaming: a redraw chunk every 50ms, each + // shorter than the quiet window, so the debounce keeps resetting. + for (let elapsed = 0; elapsed < 1000; elapsed += 50) { + scheduleTerminalWebglAtlasRecovery() + vi.advanceTimersByTime(50) + } + + expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled() + expect(manager.refreshAllPanes).not.toHaveBeenCalled() + }) + + it('recovers exactly once after terminal output settles, not a 3-stage burst', () => { + // Brennan-approved single-recovery decision: the streaming settle fires one + // clear+refresh, not the rAF+120+500 burst, so a clear can only ever land + // after 200ms of global quiet. Advancing past the burst delays must add no + // further fires on the streaming path. vi.useFakeTimers() vi.stubGlobal( 'requestAnimationFrame', @@ -160,22 +222,96 @@ describe('terminal WebGL atlas recovery', () => { scheduleTerminalWebglAtlasRecovery() scheduleTerminalWebglAtlasRecovery() + // Still nothing before the quiet window elapses. + vi.advanceTimersByTime(199) + expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled() + + // Quiet window elapsed → exactly one clear+refresh for the coalesced stream. + vi.advanceTimersByTime(1) expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + + // The 120ms/500ms burst legs must NOT fire on the streaming path. + vi.advanceTimersByTime(120) + vi.advanceTimersByTime(380) + expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) + expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + }) + + it('does not clear mid-stream when a settle is followed by resumed streaming', () => { + // Cancelable invariant (STA-1365): a stream that pauses just over the quiet + // window lets the settle fire its single recovery during the gap, but the + // resumed chunks must not trigger any further clear while they keep arriving + // <200ms apart — the re-arm cancels the only pending handle (the debounce + // timer), so no clear lands mid-resumed-stream. + vi.useFakeTimers() + vi.stubGlobal( + 'requestAnimationFrame', + vi.fn((callback: FrameRequestCallback) => { + callback(0) + return 1 + }) + ) + const manager = registerManager() + + // Initial stream, then a gap just over the quiet window → one settle recovery. + for (let elapsed = 0; elapsed < 300; elapsed += 50) { + scheduleTerminalWebglAtlasRecovery() + vi.advanceTimersByTime(50) + } + vi.advanceTimersByTime(TERMINAL_OUTPUT_RECOVERY_QUIET_MS) + expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) + expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + + // Resume streaming: fire-count must stay pinned while chunks keep arriving. + for (let elapsed = 0; elapsed < 1000; elapsed += 50) { + scheduleTerminalWebglAtlasRecovery() + vi.advanceTimersByTime(50) + expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) + expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + } + }) + + it('coalesces the terminal-output callers onto one shared timer while paste stays immediate', () => { + // Cross-caller single-timer invariant: the terminal-output re-arm sites + // (foreground and hidden-output PTY writes) funnel through + // scheduleTerminalWebglAtlasRecovery and re-arm the one module-global debounce + // timer, so a single continuous stream (even a hidden one) keeps the recovery + // deferred for everyone. Image paste and tab reveal use their own immediate + // burst and are not coupled to the shared debounce timer. + vi.useFakeTimers() + const rafCallbacks: FrameRequestCallback[] = [] + vi.stubGlobal( + 'requestAnimationFrame', + vi.fn((callback: FrameRequestCallback) => { + rafCallbacks.push(callback) + return rafCallbacks.length + }) + ) + const manager = registerManager() + + // The terminal-output re-arm sites (foreground / hidden-output) both funnel + // through this one function; none may fire mid-stream. + for (let elapsed = 0; elapsed < 600; elapsed += 50) { + scheduleTerminalWebglAtlasRecovery() + vi.advanceTimersByTime(50) + } + expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled() + + // Global quiet → exactly one coalesced recovery for the whole shared stream. + vi.advanceTimersByTime(TERMINAL_OUTPUT_RECOVERY_QUIET_MS) + expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) + expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1) + + // Paste is independent: its own immediate 3-stage burst, not the shared timer. + manager.resetWebglTextureAtlases.mockClear() + manager.refreshAllPanes.mockClear() + scheduleImagePasteWebglAtlasRecovery() + rafCallbacks.at(-1)?.(0) + expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1) vi.advanceTimersByTime(120) - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(2) - expect(manager.refreshAllPanes).toHaveBeenCalledTimes(2) - scheduleTerminalWebglAtlasRecovery() - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(2) vi.advanceTimersByTime(380) expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3) expect(manager.refreshAllPanes).toHaveBeenCalledTimes(3) - - scheduleTerminalWebglAtlasRecovery() - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(4) - expect(manager.refreshAllPanes).toHaveBeenCalledTimes(4) - vi.advanceTimersByTime(500) - expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(6) - expect(manager.refreshAllPanes).toHaveBeenCalledTimes(6) }) }) diff --git a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts index 26c8dfa28..1912e0c0e 100644 --- a/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts +++ b/src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.ts @@ -2,7 +2,12 @@ import { resetAndRefreshAllTerminalWebglAtlases } from '@/lib/pane-manager/pane- const ATLAS_RECOVERY_DELAYS_MS = [120, 500] -let terminalOutputRecoveryScheduled = false +// Why: a streaming TUI requests output atlas recovery every frame; recovering +// mid-stream clears the shared atlas and repaints every pane, which flickers +// (STA-1365). Wait for output to go quiet so recovery runs once, on settle. +export const TERMINAL_OUTPUT_RECOVERY_QUIET_MS = 200 + +let terminalOutputRecoveryDebounceTimer: ReturnType | null = null function scheduleNextFrame(callback: () => void): void { if (typeof globalThis.requestAnimationFrame === 'function') { @@ -22,32 +27,35 @@ function resetAtlasesAndRefreshPanes(): void { } } -function scheduleAtlasRecoveryBurst(onComplete?: () => void): void { +function scheduleAtlasRecoveryBurst(): void { scheduleNextFrame(() => resetAtlasesAndRefreshPanes()) - for (const [index, delayMs] of ATLAS_RECOVERY_DELAYS_MS.entries()) { - globalThis.setTimeout(() => { - resetAtlasesAndRefreshPanes() - if (index === ATLAS_RECOVERY_DELAYS_MS.length - 1) { - onComplete?.() - } - }, delayMs) + for (const delayMs of ATLAS_RECOVERY_DELAYS_MS) { + globalThis.setTimeout(() => resetAtlasesAndRefreshPanes(), delayMs) } } export function scheduleImagePasteWebglAtlasRecovery(): void { // Why: image chips can redraw after bracketed paste parsing, so cover the - // short post-paste paint window with a few cheap atlas rebuilds. + // short post-paste paint window with a few cheap atlas rebuilds. Paste is a + // one-shot event, so recover immediately rather than debouncing. + scheduleAtlasRecoveryBurst() +} + +export function scheduleTabRevealWebglAtlasRecovery(): void { + // Why: a tab reveal is one-shot, so recover immediately — decoupled from the + // streaming debounce so a background stream can't defer a revealed tab's rebuild. scheduleAtlasRecoveryBurst() } export function scheduleTerminalWebglAtlasRecovery(): void { - if (terminalOutputRecoveryScheduled) { - return + // Why: terminal-output recovery (foreground + hidden PTY writes). Trailing-edge + // debounce so a clear only ever runs after 200ms of quiet — never mid-stream; + // a resumed stream cancels the pending timer, so a pause-then-resume can't leak. + if (terminalOutputRecoveryDebounceTimer != null) { + globalThis.clearTimeout(terminalOutputRecoveryDebounceTimer) } - terminalOutputRecoveryScheduled = true - // Why: TUI redraw bursts can corrupt xterm's shared WebGL glyph atlas without - // a context-loss event; coalesce resets so output storms do not queue timers. - scheduleAtlasRecoveryBurst(() => { - terminalOutputRecoveryScheduled = false - }) + terminalOutputRecoveryDebounceTimer = globalThis.setTimeout(() => { + terminalOutputRecoveryDebounceTimer = null + resetAtlasesAndRefreshPanes() + }, TERMINAL_OUTPUT_RECOVERY_QUIET_MS) } diff --git a/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts b/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts index 50d3b3bab..c97252353 100644 --- a/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts +++ b/src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: dispatch guards are interdependent, so these notification liveness and unread regressions stay together with one store mock. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dispatchTerminalNotification } from './use-notification-dispatch' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' diff --git a/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts b/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts index d1a97b33a..2a0c2f4f3 100644 --- a/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts +++ b/src/renderer/src/components/terminal-pane/use-notification-dispatch.ts @@ -1,6 +1,6 @@ import { useCallback } from 'react' import { useAppStore } from '@/store' -import { resolveExplicitTerminalTitleAgentType } from '../../../../shared/terminal-title-agent-type' +import { resolveCommittedTitleAgentType } from '@/lib/pane-agent-evidence' import { getRepoMapFromState, getWorktreeMapFromState } from '@/store/selectors' import { playDesktopNotificationSound } from '@/lib/desktop-notification-sound' import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' @@ -52,7 +52,7 @@ export function dispatchTerminalNotification( // not lend its prompt/agentType or timing id to this notification. const explicitTitleAgentType = event.source === 'agent-task-complete' && event.terminalTitle - ? resolveExplicitTerminalTitleAgentType(event.terminalTitle) + ? resolveCommittedTitleAgentType(event.terminalTitle) : null const storedAgentStatus = event.source === 'agent-task-complete' && event.paneKey diff --git a/src/renderer/src/components/worktree-jump-palette-status-inputs.test.ts b/src/renderer/src/components/worktree-jump-palette-status-inputs.test.ts new file mode 100644 index 000000000..62428a06f --- /dev/null +++ b/src/renderer/src/components/worktree-jump-palette-status-inputs.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { shallow } from 'zustand/shallow' +import { + EMPTY_PALETTE_STATUS_INPUTS, + selectPaletteStatusInputs, + type PaletteStatusInputsState +} from './worktree-jump-palette-status-inputs' + +const BASE: PaletteStatusInputsState = { + agentStatusByPaneKey: {}, + runtimePaneTitlesByTabId: {}, + ptyIdsByTabId: {}, + terminalLayoutsByTabId: {}, + tabsByWorktree: {} +} + +describe('selectPaletteStatusInputs', () => { + it('returns the shared frozen constant while inactive', () => { + const inactive = selectPaletteStatusInputs(BASE, false) + expect(inactive).toBe(EMPTY_PALETTE_STATUS_INPUTS) + + // Churning the hottest maps while inactive must NOT change the selected + // reference, so a useShallow subscription skips the re-render. + const churned: PaletteStatusInputsState = { + ...BASE, + runtimePaneTitlesByTabId: { 'tab-1': { 0: 'claude' } }, + agentStatusByPaneKey: { 'tab-1:leaf-1': {} as never } + } + const afterChurn = selectPaletteStatusInputs(churned, false) + expect(afterChurn).toBe(EMPTY_PALETTE_STATUS_INPUTS) + expect(shallow(inactive, afterChurn)).toBe(true) + }) + + it('exposes the live maps the instant it becomes active', () => { + const titles = { 'tab-1': { 0: 'claude' } } + const state: PaletteStatusInputsState = { ...BASE, runtimePaneTitlesByTabId: titles } + const active = selectPaletteStatusInputs(state, true) + // Live map references pass straight through so status/sort derive correctly. + expect(active.runtimePaneTitlesByTabId).toBe(titles) + expect(active).not.toBe(EMPTY_PALETTE_STATUS_INPUTS) + }) + + it('keeps the live maps during the close linger (active stays true while animating)', () => { + // The component holds `active` true through the close animation, so churn is + // still reflected — no empty-row flash while the dialog fades out. + const titles = { 'tab-1': { 0: 'claude' } } + const closing = selectPaletteStatusInputs({ ...BASE, runtimePaneTitlesByTabId: titles }, true) + expect(closing.runtimePaneTitlesByTabId).toBe(titles) + }) + + it('shallow-changes only when a subscribed map reference actually changes while active', () => { + const titles = { 'tab-1': { 0: 'claude' } } + const s1: PaletteStatusInputsState = { ...BASE, runtimePaneTitlesByTabId: titles } + const r1 = selectPaletteStatusInputs(s1, true) + + // Same underlying map refs -> shallow-equal -> no re-render. + expect(shallow(r1, selectPaletteStatusInputs(s1, true))).toBe(true) + + // A real pane-title write replaces the map ref -> shallow-unequal -> the + // open palette re-derives status/order, exactly as before this change. + const s2: PaletteStatusInputsState = { + ...s1, + runtimePaneTitlesByTabId: { 'tab-1': { 0: 'codex' } } + } + expect(shallow(r1, selectPaletteStatusInputs(s2, true))).toBe(false) + }) +}) diff --git a/src/renderer/src/components/worktree-jump-palette-status-inputs.ts b/src/renderer/src/components/worktree-jump-palette-status-inputs.ts new file mode 100644 index 000000000..57a62d3ae --- /dev/null +++ b/src/renderer/src/components/worktree-jump-palette-status-inputs.ts @@ -0,0 +1,56 @@ +import type { AppState } from '@/store/types' + +export type PaletteStatusInputsState = Pick< + AppState, + | 'agentStatusByPaneKey' + | 'runtimePaneTitlesByTabId' + | 'ptyIdsByTabId' + | 'terminalLayoutsByTabId' + | 'tabsByWorktree' +> + +export type PaletteStatusInputs = PaletteStatusInputsState + +// Why: shared frozen bundle returned whenever the Cmd+J jump palette isn't +// active. The two hottest maps here — agentStatusByPaneKey and +// runtimePaneTitlesByTabId — get a new top-level identity on every agent-status +// transition and every terminal pane-title write app-wide. The palette is always +// mounted (App.tsx renders ) and stays mounted for +// the whole session once opened, so subscribing to them while it's closed +// re-rendered the whole palette — and recomputed its per-worktree live/working-dot +// sort over every worktree — on unrelated terminal chatter. A useShallow +// subscription keeps this same reference across that churn, so the closed palette +// stops reacting. Frozen so the shared singleton can't be mutated. +export const EMPTY_PALETTE_STATUS_INPUTS: PaletteStatusInputs = Object.freeze({ + agentStatusByPaneKey: {}, + runtimePaneTitlesByTabId: {}, + ptyIdsByTabId: {}, + terminalLayoutsByTabId: {}, + tabsByWorktree: {} +}) + +/** + * Select the five status maps the jump palette needs to derive per-worktree + * live/working dots and switcher ordering — but only while it's `active` (open, + * or still animating closed). While inactive nothing is shown, so return a stable + * frozen constant that a `useShallow`-wrapped subscription keeps referentially + * equal across the (very hot) agent-status / pane-title writes, skipping the + * re-render that would otherwise fire on the always-mounted palette on every + * unrelated terminal. The instant it becomes active the live maps flow through + * and every derivation recomputes exactly as before. + */ +export function selectPaletteStatusInputs( + s: PaletteStatusInputsState, + active: boolean +): PaletteStatusInputs { + if (!active) { + return EMPTY_PALETTE_STATUS_INPUTS + } + return { + agentStatusByPaneKey: s.agentStatusByPaneKey, + runtimePaneTitlesByTabId: s.runtimePaneTitlesByTabId, + ptyIdsByTabId: s.ptyIdsByTabId, + terminalLayoutsByTabId: s.terminalLayoutsByTabId, + tabsByWorktree: s.tabsByWorktree + } +} diff --git a/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts b/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts index 9717f4ff6..d39e2aab2 100644 --- a/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts +++ b/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: notification edge cases share one module-scoped coordinator, so keeping setup and regression cases together prevents brittle cross-file mock resets. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types' import { YOLO_TUI_AGENT_ARGS } from '../../../shared/tui-agent-permissions' diff --git a/src/renderer/src/hooks/ipc-tab-switch.test.ts b/src/renderer/src/hooks/ipc-tab-switch.test.ts index c347a2808..1a1112b41 100644 --- a/src/renderer/src/hooks/ipc-tab-switch.test.ts +++ b/src/renderer/src/hooks/ipc-tab-switch.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: tab-switch shortcut behavior is shared by - * renderer and IPC entry points; keeping terminal, sequential, across-type, - * and MRU cases together makes regressions obvious. */ import { beforeEach, describe, expect, it, vi } from 'vitest' const { getStateMock, getActiveTabNavOrderMock } = vi.hoisted(() => ({ diff --git a/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts b/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts index 00aa3fe4f..51b552f34 100644 --- a/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts +++ b/src/renderer/src/hooks/useComposerState-host-context-boundaries.test.ts @@ -159,6 +159,40 @@ describe('useComposerState host-context boundaries', () => { expect(submitSection).toContain('runtimeEnvironmentId: folderTargetRuntimeEnvironmentId') }) + it('detects composer agents against the repo host: SSH, then runtime, then local (#7082)', () => { + // Why: a repo owned by a paired runtime must show the runtime's agents, not + // the local machine's. SSH stays first priority; runtime falls through before + // local so an SSH repo never double-detects. Regression guard for #7082. + const selectorSection = sourceBetween( + HOOK_SOURCE, + 'const detectedAgentList = useAppStore', + 'const ensureDetectedAgents = useAppStore' + ) + expect(selectorSection).toContain('if (isRemote) {') + expect(selectorSection).toContain('s.remoteDetectedAgentIds[connectionId]') + expect(selectorSection).toContain('if (runtimeEnvironmentId) {') + expect(selectorSection).toContain('s.runtimeDetectedAgentIds[runtimeEnvironmentId]') + expect(selectorSection).toContain('return s.detectedAgentIds') + // SSH branch is checked before the runtime branch. + expect(selectorSection.indexOf('if (isRemote) {')).toBeLessThan( + selectorSection.indexOf('if (runtimeEnvironmentId) {') + ) + + expect(HOOK_SOURCE).toContain( + 'const runtimeEnvironmentId = selectedRepoSettings?.activeRuntimeEnvironmentId?.trim() || null' + ) + + // Detection effect fans out to the same three hosts in the same order and + // re-runs when the runtime environment changes. + const detectSection = sourceBetween(HOOK_SOURCE, 'const detect = isRemote', 'void detect.then') + expect(detectSection).toContain('ensureRemoteDetectedAgents(connectionId)') + expect(detectSection).toContain('ensureRuntimeDetectedAgents(runtimeEnvironmentId)') + expect(detectSection).toContain('ensureDetectedAgents()') + expect(HOOK_SOURCE).toContain( + '}, [connectionId, runtimeEnvironmentId, isRemote, selectedRepoSshStatus, disabledTuiAgents])' + ) + }) + it('seeds initial workspace run target from the task source context', () => { expect( resolveInitialWorkspaceRunSeed({ diff --git a/src/renderer/src/hooks/useComposerState.ts b/src/renderer/src/hooks/useComposerState.ts index dc6e1aa19..d1316b986 100644 --- a/src/renderer/src/hooks/useComposerState.ts +++ b/src/renderer/src/hooks/useComposerState.ts @@ -1122,20 +1122,25 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS const [tuiAgent, setTuiAgent] = useState( persistDraft ? (newWorkspaceDraft?.agent ?? fallbackDefaultAgent) : fallbackDefaultAgent ) - // Why: when the selected repo is remote (has a connectionId), read the - // per-connection agent list instead of the local one. This ensures the - // Create Workspace dialog shows agents installed on the SSH host, not the - // local machine. + // Why: when the selected repo has a connectionId or runtime environment, read + // the per-host agent list instead of the local one. This ensures the Create + // Workspace dialog shows agents installed on the SSH host or paired runtime, + // not the local machine. const connectionId = selectedRepoConnectionId const isRemote = typeof connectionId === 'string' + const runtimeEnvironmentId = selectedRepoSettings?.activeRuntimeEnvironmentId?.trim() || null const detectedAgentList = useAppStore((s) => { if (isRemote) { return s.remoteDetectedAgentIds[connectionId] ?? null } + if (runtimeEnvironmentId) { + return s.runtimeDetectedAgentIds[runtimeEnvironmentId] ?? null + } return s.detectedAgentIds }) const ensureDetectedAgents = useAppStore((s) => s.ensureDetectedAgents) const ensureRemoteDetectedAgents = useAppStore((s) => s.ensureRemoteDetectedAgents) + const ensureRuntimeDetectedAgents = useAppStore((s) => s.ensureRuntimeDetectedAgents) const detectedAgentIds = useMemo | null>( () => (detectedAgentList ? new Set(detectedAgentList) : null), [detectedAgentList] @@ -1696,14 +1701,18 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS ]) // Why: detect agents for the selected repo. For local repos this runs once - // on mount (deduped by the store). For remote repos it re-runs when the - // selected repo changes so the agent list matches the SSH host. + // on mount (deduped by the store). For remote/runtime repos it re-runs when + // the selected repo changes so the agent list matches the correct host. useEffect(() => { if (isRemote && selectedRepoSshStatus !== 'connected') { return } let cancelled = false - const detect = isRemote ? ensureRemoteDetectedAgents(connectionId) : ensureDetectedAgents() + const detect = isRemote + ? ensureRemoteDetectedAgents(connectionId) + : runtimeEnvironmentId + ? ensureRuntimeDetectedAgents(runtimeEnvironmentId) + : ensureDetectedAgents() void detect.then((ids) => { if (cancelled) { return @@ -1722,11 +1731,11 @@ export function useComposerState(options: UseComposerStateOptions): UseComposerS return () => { cancelled = true } - // Why: re-run when connectionId changes (user picks a different repo) so - // detection targets the correct host. Draft/settings deps are intentionally - // excluded — detection is a best-effort PATH snapshot. + // Why: re-run when connectionId/runtimeEnvironmentId changes (user picks a + // different repo) so detection targets the correct host. Draft/settings deps + // are intentionally excluded — detection is a best-effort PATH snapshot. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [connectionId, isRemote, selectedRepoSshStatus, disabledTuiAgents]) + }, [connectionId, runtimeEnvironmentId, isRemote, selectedRepoSshStatus, disabledTuiAgents]) // Per-repo: load yaml hooks + issue command template. useEffect(() => { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index cf70af136..2d4efa1e1 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -8893,7 +8893,8 @@ "b234ab25b4": "Could not copy the file to the clipboard", "f9d7ca753d": "Copy Paths", "3161c4e425": "folder", - "e887fa4b2e": "Open in Terminal" + "e887fa4b2e": "Open in Terminal", + "1d8e182c32": "View File" }, "FileExplorerToolbar": { "d238264654": "Show Git Ignored Files", diff --git a/src/renderer/src/i18n/locales/es.json b/src/renderer/src/i18n/locales/es.json index 5d9b07de4..66a2b10f2 100644 --- a/src/renderer/src/i18n/locales/es.json +++ b/src/renderer/src/i18n/locales/es.json @@ -8893,7 +8893,8 @@ "b234ab25b4": "No se pudo copiar el archivo en el portapapeles", "f9d7ca753d": "Copiar rutas", "3161c4e425": "carpeta", - "e887fa4b2e": "Abrir en terminal" + "e887fa4b2e": "Abrir en terminal", + "1d8e182c32": "Ver archivo" }, "FileExplorerToolbar": { "d238264654": "Mostrar archivos ignorados por Git", diff --git a/src/renderer/src/i18n/locales/ja.json b/src/renderer/src/i18n/locales/ja.json index cafa057ad..2b76dba34 100644 --- a/src/renderer/src/i18n/locales/ja.json +++ b/src/renderer/src/i18n/locales/ja.json @@ -8893,7 +8893,8 @@ "b234ab25b4": "ファイルをクリップボードにコピーできませんでした", "f9d7ca753d": "パスのコピー", "3161c4e425": "フォルダ", - "e887fa4b2e": "ターミナルで開く" + "e887fa4b2e": "ターミナルで開く", + "1d8e182c32": "ファイルを表示" }, "FileExplorerToolbar": { "d238264654": "Git で無視されたファイルを表示", diff --git a/src/renderer/src/i18n/locales/ko.json b/src/renderer/src/i18n/locales/ko.json index f0e5e2328..646b74a42 100644 --- a/src/renderer/src/i18n/locales/ko.json +++ b/src/renderer/src/i18n/locales/ko.json @@ -8893,7 +8893,8 @@ "b234ab25b4": "파일을 클립보드에 복사하지 못했습니다", "f9d7ca753d": "경로 복사", "3161c4e425": "폴더", - "e887fa4b2e": "터미널에서 열기" + "e887fa4b2e": "터미널에서 열기", + "1d8e182c32": "파일 보기" }, "FileExplorerToolbar": { "d238264654": "Git이 무시한 파일 표시", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index d00704947..66de9505f 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -8893,7 +8893,8 @@ "b234ab25b4": "无法将文件复制到剪贴板", "f9d7ca753d": "复制路径", "3161c4e425": "文件夹", - "e887fa4b2e": "在终端中打开" + "e887fa4b2e": "在终端中打开", + "1d8e182c32": "查看文件" }, "FileExplorerToolbar": { "d238264654": "显示 Git 忽略的文件", diff --git a/src/renderer/src/lib/active-agent-note-target.ts b/src/renderer/src/lib/active-agent-note-target.ts index 5bbc1253a..9ee0dfc51 100644 --- a/src/renderer/src/lib/active-agent-note-target.ts +++ b/src/renderer/src/lib/active-agent-note-target.ts @@ -15,10 +15,10 @@ import { toRuntimeWorktreeSelector } from '@/runtime/runtime-worktree-selector' import { isTerminalLeafId, makePaneKey } from '../../../shared/stable-pane-id' import type { TerminalLayoutSnapshot } from '../../../shared/types' import { - detectAgentStatusFromTitle, - getAgentLabel, - isExplicitAgentStatusFresh -} from './agent-status' + classifyTitleActivity, + isExplicitAgentStatusFresh, + resolveTitleActivityLabel +} from '@/lib/pane-agent-evidence' import { resolveRuntimePaneTitleForLeaf } from './runtime-pane-title-leaf-id' const ACTIVE_AGENT_PROBE_RPC_TIMEOUT_MS = 3000 @@ -271,5 +271,5 @@ function getFocusedRuntimePaneTitle( } function isRecognizedAgentTitle(title: string): boolean { - return detectAgentStatusFromTitle(title) !== null && getAgentLabel(title) !== null + return classifyTitleActivity(title) !== null && resolveTitleActivityLabel(title) !== null } diff --git a/src/renderer/src/lib/agent-ready-wait.ts b/src/renderer/src/lib/agent-ready-wait.ts index 70cbb4ade..8bd7cb867 100644 --- a/src/renderer/src/lib/agent-ready-wait.ts +++ b/src/renderer/src/lib/agent-ready-wait.ts @@ -1,4 +1,4 @@ -import { detectAgentStatusFromTitle } from '../../../shared/agent-detection' +import { classifyTitleActivity } from '@/lib/pane-agent-evidence' import { isExpectedAgentProcess } from '../../../shared/agent-process-recognition' import { isShellProcess } from './tui-agent-startup' import { useAppStore } from '@/store' @@ -51,7 +51,7 @@ function titleSuggestsReady(tabId: string): boolean { } } } - return titles.some((title) => detectAgentStatusFromTitle(title) === 'idle') + return titles.some((title) => classifyTitleActivity(title) === 'idle') } /** diff --git a/src/renderer/src/lib/agent-send-title-status.ts b/src/renderer/src/lib/agent-send-title-status.ts index 11f949fde..9ae502936 100644 --- a/src/renderer/src/lib/agent-send-title-status.ts +++ b/src/renderer/src/lib/agent-send-title-status.ts @@ -1,4 +1,5 @@ -import { type AgentStatus, detectAgentStatusFromTitle, getAgentLabel } from './agent-status' +import type { AgentStatus } from './agent-status' +import { classifyTitleActivity, resolveTitleActivityLabel } from '@/lib/pane-agent-evidence' const EXPLICIT_IDLE_SEND_TITLE_RE = /(^|\s)(ready|idle|done)(\s|$|[.!?])/i const CLAUDE_IDLE_PREFIX = '\u2733' @@ -6,11 +7,11 @@ const GEMINI_IDLE_PREFIX = '\u25c7' const PI_IDLE_PREFIX = '\u03c0 - ' export function detectAgentSendTitleStatus(title: string | null | undefined): AgentStatus | null { - if (!title || getAgentLabel(title) === null) { + if (!title || resolveTitleActivityLabel(title) === null) { return null } - const status = detectAgentStatusFromTitle(title) + const status = classifyTitleActivity(title) if (status !== 'idle') { return status } diff --git a/src/renderer/src/lib/agent-startup-delayed-delivery.ts b/src/renderer/src/lib/agent-startup-delayed-delivery.ts index 9512b267c..5ca13944b 100644 --- a/src/renderer/src/lib/agent-startup-delayed-delivery.ts +++ b/src/renderer/src/lib/agent-startup-delayed-delivery.ts @@ -1,6 +1,13 @@ import { useAppStore } from '@/store' import type { AgentStartupPlan } from '@/lib/tui-agent-startup' import { parsePaneKey } from '../../../shared/stable-pane-id' +import { + agentStartupDeliveryKey as deliveryKey, + clearConsumedAgentStartupDeliveriesForTests, + isAgentStartupDeliveryConsumed, + markAgentStartupDeliveryConsumed, + releaseAgentStartupDeliveryConsumed +} from './agent-startup-delivery-guards' type AppStoreSnapshot = ReturnType @@ -13,7 +20,6 @@ type PendingAgentStartupDelivery = { } const pendingAgentStartupDeliveries = new Map() -const consumedAgentStartupDeliveries = new Set() const staleStartupRecheckTimers = new Map>() let unsubscribePendingAgentStartupDeliveries: (() => void) | null = null @@ -99,7 +105,7 @@ function stopPendingAgentStartupSubscriptionIfIdle(): void { export function queuePendingAgentStartupDelivery(delivery: PendingAgentStartupDelivery): void { const key = deliveryKey(delivery) - if (consumedAgentStartupDeliveries.has(key)) { + if (isAgentStartupDeliveryConsumed(key)) { return } pendingAgentStartupDeliveries.set(key, delivery) @@ -109,7 +115,7 @@ export function queuePendingAgentStartupDelivery(delivery: PendingAgentStartupDe export function resetAgentStartupDelayedDeliveryForTests(): void { pendingAgentStartupDeliveries.clear() - consumedAgentStartupDeliveries.clear() + clearConsumedAgentStartupDeliveriesForTests() for (const timer of staleStartupRecheckTimers.values()) { globalThis.clearTimeout(timer) } @@ -124,10 +130,10 @@ export function beginAgentStartupDeliveryAttempt(args: { launchToken: string }): boolean { const key = deliveryKey(args) - if (consumedAgentStartupDeliveries.has(key)) { + if (isAgentStartupDeliveryConsumed(key)) { return false } - consumedAgentStartupDeliveries.add(key) + markAgentStartupDeliveryConsumed(key) pendingAgentStartupDeliveries.delete(key) clearStaleStartupRecheck(key) return true @@ -138,13 +144,7 @@ export function releaseAgentStartupDeliveryAttempt(args: { tabId: string launchToken: string }): void { - consumedAgentStartupDeliveries.delete(deliveryKey(args)) -} - -function deliveryKey( - delivery: Pick -): string { - return `${delivery.worktreeId}\0${delivery.tabId}\0${delivery.launchToken}` + releaseAgentStartupDeliveryConsumed(deliveryKey(args)) } function flushPendingAgentStartupDeliveries(): void { diff --git a/src/renderer/src/lib/agent-startup-delivery-guards.ts b/src/renderer/src/lib/agent-startup-delivery-guards.ts new file mode 100644 index 000000000..5e1f4d71d --- /dev/null +++ b/src/renderer/src/lib/agent-startup-delivery-guards.ts @@ -0,0 +1,48 @@ +// Leaf module (imports nothing from the store) holding the consumed +// agent-startup-delivery guard set, so store slices can purge it on tab/worktree +// removal without creating a store → agent-startup-delayed-delivery → store +// import cycle. + +export function agentStartupDeliveryKey(delivery: { + worktreeId: string + tabId: string + launchToken: string +}): string { + return `${delivery.worktreeId}\0${delivery.tabId}\0${delivery.launchToken}` +} + +const consumedAgentStartupDeliveries = new Set() + +export function isAgentStartupDeliveryConsumed(key: string): boolean { + return consumedAgentStartupDeliveries.has(key) +} + +export function markAgentStartupDeliveryConsumed(key: string): void { + consumedAgentStartupDeliveries.add(key) +} + +export function releaseAgentStartupDeliveryConsumed(key: string): void { + consumedAgentStartupDeliveries.delete(key) +} + +export function clearConsumedAgentStartupDeliveriesForTests(): void { + consumedAgentStartupDeliveries.clear() +} + +// Why: one consumed guard is recorded per launch that reached delivery and is +// never released on the happy path, so guards for removed tabs/worktrees would +// accumulate for the renderer's whole session. Drop them when the owning tab is +// closed or its worktree is removed. +export function forgetAgentStartupDeliveriesForTabs(tabIds: Iterable): void { + const tabIdSet = tabIds instanceof Set ? tabIds : new Set(tabIds) + if (tabIdSet.size === 0) { + return + } + for (const key of consumedAgentStartupDeliveries) { + // agentStartupDeliveryKey() is `${worktreeId}\0${tabId}\0${launchToken}`. + const tabId = key.split('\0')[1] ?? '' + if (tabIdSet.has(tabId)) { + consumedAgentStartupDeliveries.delete(key) + } + } +} diff --git a/src/renderer/src/lib/agent-status-terminal-title.ts b/src/renderer/src/lib/agent-status-terminal-title.ts index d3162d526..c5c7bca56 100644 --- a/src/renderer/src/lib/agent-status-terminal-title.ts +++ b/src/renderer/src/lib/agent-status-terminal-title.ts @@ -1,4 +1,4 @@ -import { detectAgentStatusFromTitle } from '../../../shared/agent-detection' +import { classifyTitleActivity } from './pane-agent-evidence' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status-types' import { getSyntheticAgentTerminalTitle, @@ -26,7 +26,7 @@ function shouldReplaceCurrentTitle( if (!currentTitle?.trim()) { return true } - const currentStatus = detectAgentStatusFromTitle(currentTitle) + const currentStatus = classifyTitleActivity(currentTitle) if (currentStatus === 'working') { return true } diff --git a/src/renderer/src/lib/agent-status.test.ts b/src/renderer/src/lib/agent-status.test.ts index 5c5d5e96f..3a9215278 100644 --- a/src/renderer/src/lib/agent-status.test.ts +++ b/src/renderer/src/lib/agent-status.test.ts @@ -1,7 +1,3 @@ -/* eslint-disable max-lines -- - * Why: agent title detection is intentionally table-driven in one place so the - * supported title variants stay readable and regressions are easy to compare. - */ import { describe, expect, it, test, vi } from 'vitest' import { detectAgentStatusFromTitle, diff --git a/src/renderer/src/lib/agent-status.ts b/src/renderer/src/lib/agent-status.ts index 396181851..141da5c2a 100644 --- a/src/renderer/src/lib/agent-status.ts +++ b/src/renderer/src/lib/agent-status.ts @@ -1,9 +1,5 @@ import type { TerminalTab, TuiAgent, Worktree } from '../../../shared/types' -import type { - AgentStatusEntry, - AgentStatusState, - AgentType -} from '../../../shared/agent-status-types' +import type { AgentStatusState, AgentType } from '../../../shared/agent-status-types' import { tabHasLivePty } from './tab-has-live-pty' import type { WorktreeStatus } from './worktree-status' import { tuiAgentToAgentKind } from '../../../shared/agent-kind' @@ -23,11 +19,8 @@ export { isClaudeManagementTitle, getAgentLabel } from '../../../shared/agent-detection' -import { - type AgentStatus, - detectAgentStatusFromTitle, - getAgentLabel -} from '../../../shared/agent-detection' +import type { AgentStatus } from '../../../shared/agent-detection' +import { classifyTitleActivity, resolveTitleActivityLabel } from './pane-agent-evidence' type AgentQueryArgs = { tabsByWorktree: Record @@ -84,8 +77,8 @@ export function getWorkingAgentsPerWorktree({ const paneTitles = runtimePaneTitlesByTabId[tab.id] if (paneTitles && Object.keys(paneTitles).length > 0) { for (const [paneIdStr, title] of Object.entries(paneTitles)) { - if (detectAgentStatusFromTitle(title) === 'working') { - const label = getAgentLabel(title) + if (classifyTitleActivity(title) === 'working') { + const label = resolveTitleActivityLabel(title) if (label) { agents.push({ label, @@ -96,8 +89,8 @@ export function getWorkingAgentsPerWorktree({ } } } - } else if (detectAgentStatusFromTitle(tab.title) === 'working') { - const label = getAgentLabel(tab.title) + } else if (classifyTitleActivity(tab.title) === 'working') { + const label = resolveTitleActivityLabel(tab.title) if (label) { agents.push({ label, status: 'working', tabId: tab.id, paneId: null }) } @@ -210,16 +203,9 @@ export function agentKindForAgentType(agentType: AgentType | null | undefined): return tuiAgent ? tuiAgentToAgentKind(tuiAgent) : 'other' } -// Why: explicit agent status entries (from hook-based reports) can go stale if -// the agent process exits without sending a final update. This helper lets -// callers decide whether to trust the entry based on a configurable TTL. -export function isExplicitAgentStatusFresh( - entry: Pick, - now: number, - staleAfterMs: number -): boolean { - return now - entry.updatedAt <= staleAfterMs -} +// Why: the freshness gate moved into the pane-agent-evidence resolvers; the +// re-export keeps this module's many existing importers unchanged. +export { isExplicitAgentStatusFresh } from './pane-agent-evidence' /** * Map an explicit AgentStatusState to the visual Status used by @@ -297,13 +283,13 @@ function countWorkingAgentsForTab( // (for example restored-but-unvisited worktrees). if (paneTitles && Object.keys(paneTitles).length > 0) { for (const title of Object.values(paneTitles)) { - if (detectAgentStatusFromTitle(title) === 'working') { + if (classifyTitleActivity(title) === 'working') { count += 1 } } return count } - if (detectAgentStatusFromTitle(tab.title) === 'working') { + if (classifyTitleActivity(tab.title) === 'working') { count += 1 } return count diff --git a/src/renderer/src/lib/ai-vault-resume-command.test.ts b/src/renderer/src/lib/ai-vault-resume-command.test.ts index dc0345491..4d5db5d72 100644 --- a/src/renderer/src/lib/ai-vault-resume-command.test.ts +++ b/src/renderer/src/lib/ai-vault-resume-command.test.ts @@ -123,6 +123,52 @@ describe('ai vault resume command runtime', () => { ).toBe("cd 'C:\\Users\\alice\\repo' && claude '--resume' 'session one'") }) + it('queues a PowerShell-valid local OMP resume by absolute transcript path', () => { + // Regression: local rebuilds must forward session.filePath so OMP resumes by + // path, and queued Windows commands must match the live tab shell. + const state = makeState({ worktreePath: 'C:\\Users\\alice\\repo' }) + + const command = buildAiVaultResumeCommandForWorktree({ + state, + worktreeId: 'repo-1::worktree-1', + session: { + agent: 'omp', + sessionId: '019f27cd-4268-7000-96e7-62f42a55c144', + filePath: 'C:\\Users\\alice\\.omp\\agent\\sessions\\repo\\sess.jsonl', + cwd: 'C:\\Users\\alice\\repo', + codexHome: null + } + }) + + expect(command).toBe( + "Set-Location -LiteralPath 'C:\\Users\\alice\\repo'; omp --resume 'C:\\Users\\alice\\.omp\\agent\\sessions\\repo\\sess.jsonl'" + ) + expect(command).not.toContain('019f27cd-4268-7000-96e7-62f42a55c144') + }) + + it('keeps cmd quoting for local OMP resume when cmd.exe is configured', () => { + const state = makeState({ + worktreePath: 'C:\\Users\\alice\\repo', + terminalWindowsShell: 'cmd.exe' + }) + + expect( + buildAiVaultResumeCommandForWorktree({ + state, + worktreeId: 'repo-1::worktree-1', + session: { + agent: 'omp', + sessionId: '019f27cd-4268-7000-96e7-62f42a55c144', + filePath: 'C:\\Users\\alice\\.omp\\agent\\sessions\\repo\\sess.jsonl', + cwd: 'C:\\Users\\alice\\repo', + codexHome: null + } + }) + ).toBe( + 'cmd /d /s /c "cd /d ""C:\\Users\\alice\\repo"" && omp --resume ""C:\\Users\\alice\\.omp\\agent\\sessions\\repo\\sess.jsonl"""' + ) + }) + it('keeps the cmd wrapper for the copy-to-clipboard command on Windows', () => { // Regression guard: the copy path is self-contained for pasting into cmd.exe // and must stay cmd-wrapped even though the queued path now follows the shell. diff --git a/src/renderer/src/lib/ai-vault-resume-command.ts b/src/renderer/src/lib/ai-vault-resume-command.ts index 691d69efc..d71f3653f 100644 --- a/src/renderer/src/lib/ai-vault-resume-command.ts +++ b/src/renderer/src/lib/ai-vault-resume-command.ts @@ -26,7 +26,9 @@ type AiVaultResumeCommandSession = Pick< AiVaultSession, 'agent' | 'sessionId' | 'cwd' | 'codexHome' > & - Partial> + Partial< + Pick + > export type AiVaultResumeStartup = { command: string @@ -127,10 +129,15 @@ export function buildAiVaultResumeStartupForWorktree(args: { command: buildAiVaultResumeCommand({ agent: args.session.agent, sessionId: args.session.sessionId, + // Why: OMP resumes by absolute transcript path, so local rebuilds must + // forward it too — otherwise a custom OMP_CODING_AGENT_DIR / WSL-store + // session would resume by id against the default store and miss. + resumeFilePath: args.session.filePath, cwd: args.session.cwd, platform, commandOverride: args.commandOverride, - codexHome + codexHome, + shell: queuedShell }) } } diff --git a/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts b/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts index 166b7df7e..d50711e66 100644 --- a/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts +++ b/src/renderer/src/lib/floating-workspace-terminal-actions.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Focus, shortcut, creation, and switching cases share - * the same floating-workspace DOM/store fixtures. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' import type { Tab, TerminalTab } from '../../../shared/types' diff --git a/src/renderer/src/lib/foreground-terminal-tabs.ts b/src/renderer/src/lib/foreground-terminal-tabs.ts index 7824598db..925be716c 100644 --- a/src/renderer/src/lib/foreground-terminal-tabs.ts +++ b/src/renderer/src/lib/foreground-terminal-tabs.ts @@ -55,6 +55,15 @@ export function getForegroundTerminalTabLastSeenAtById(): Record return Object.fromEntries(foregroundTerminalTabLastSeenAtById) } +// Why: retired terminal tab ids never recur, so their last-seen timestamps would +// accumulate for the renderer's whole session. Drop them when a tab is closed or +// its worktree is removed (mirrors forgetAgentHibernationTabOutput). +export function forgetForegroundTerminalTabs(tabIds: Iterable): void { + for (const tabId of tabIds) { + foregroundTerminalTabLastSeenAtById.delete(tabId) + } +} + export function resetForegroundTerminalTabIdsForTests(): void { explicitForegroundTerminalTabIds = new Set() visibleTerminalTabClaimsByToken.clear() diff --git a/src/renderer/src/lib/launch-agent-background-session.test.ts b/src/renderer/src/lib/launch-agent-background-session.test.ts index f42f886fd..954a1314e 100644 --- a/src/renderer/src/lib/launch-agent-background-session.test.ts +++ b/src/renderer/src/lib/launch-agent-background-session.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: local/runtime launch tests share a mock harness. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT } from '@/constants/terminal' import { createCompatibleRuntimeStatusResponseIfNeeded } from '@/runtime/runtime-compatibility-test-fixture' diff --git a/src/renderer/src/lib/pane-agent-evidence.test.ts b/src/renderer/src/lib/pane-agent-evidence.test.ts new file mode 100644 index 000000000..0bd618e29 --- /dev/null +++ b/src/renderer/src/lib/pane-agent-evidence.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it } from 'vitest' +import { + AGENT_STATUS_STALE_AFTER_MS, + type AgentStatusEntry +} from '../../../shared/agent-status-types' +import { + classifyTitleActivity, + isExplicitAgentStatusFresh, + resolveCommittedTitleAgentType, + resolvePaneAgentActivity, + resolveTitleActivityLabel +} from './pane-agent-evidence' + +const NOW = 1_700_000_000_000 + +function entry(overrides: Partial = {}): AgentStatusEntry { + return { + paneKey: 'tab-1:leaf-1', + agentType: 'claude', + state: 'working', + prompt: '', + updatedAt: NOW, + stateStartedAt: NOW, + stateHistory: [], + ...overrides + } as AgentStatusEntry +} + +describe('isExplicitAgentStatusFresh', () => { + it('accepts an entry exactly at the staleness boundary', () => { + expect( + isExplicitAgentStatusFresh( + { updatedAt: NOW - AGENT_STATUS_STALE_AFTER_MS }, + NOW, + AGENT_STATUS_STALE_AFTER_MS + ) + ).toBe(true) + }) + + it('rejects an entry past the staleness boundary', () => { + expect( + isExplicitAgentStatusFresh( + { updatedAt: NOW - AGENT_STATUS_STALE_AFTER_MS - 1 }, + NOW, + AGENT_STATUS_STALE_AFTER_MS + ) + ).toBe(false) + }) +}) + +describe('classifyTitleActivity', () => { + it('classifies working, permission, idle, and unclassifiable titles', () => { + expect(classifyTitleActivity('mimo working')).toBe('working') + expect(classifyTitleActivity('Claude - action required')).toBe('permission') + expect(classifyTitleActivity('✳ Claude Code ready')).toBe('idle') + expect(classifyTitleActivity('vim')).toBe(null) + }) +}) + +describe('title agent identity facets', () => { + it('splits the bare Claude spinner into activity label without committed identity', () => { + expect(resolveTitleActivityLabel('⠋ compiling everything')).toBe('Claude Code') + expect(resolveCommittedTitleAgentType('⠋ compiling everything')).toBe(null) + }) + + it('commits identity when the title names the agent explicitly', () => { + expect(resolveTitleActivityLabel('✳ Claude Code working')).toBe('Claude Code') + expect(resolveCommittedTitleAgentType('✳ Claude Code working')).toBe('claude') + }) + + it('returns neither facet for a plain shell title', () => { + expect(resolveTitleActivityLabel('zsh')).toBe(null) + expect(resolveCommittedTitleAgentType('zsh')).toBe(null) + }) +}) + +describe('resolvePaneAgentActivity', () => { + it('reports a fresh hook row as the authoritative source and keeps the title layer visible', () => { + const decision = resolvePaneAgentActivity({ + explicitEntry: entry({ state: 'waiting' }), + liveTitle: '⠋ running the tests', + hasLivePty: true, + now: NOW + }) + expect(decision).toEqual({ + hookState: 'waiting', + hookAgentType: 'claude', + titleStatus: 'working', + source: 'hook', + confidence: 'authoritative', + livePtyRequired: false + }) + }) + + it('treats a stale hook row as absent and falls back to the title', () => { + const decision = resolvePaneAgentActivity({ + explicitEntry: entry({ updatedAt: NOW - AGENT_STATUS_STALE_AFTER_MS - 1 }), + liveTitle: '⠋ running the tests', + hasLivePty: true, + now: NOW + }) + expect(decision.hookState).toBe(null) + expect(decision.source).toBe('title') + expect(decision.confidence).toBe('fallback') + expect(decision.titleStatus).toBe('working') + expect(decision.livePtyRequired).toBe(false) + }) + + it('flags title-only evidence without a live PTY so liveness-gated consumers drop it', () => { + const decision = resolvePaneAgentActivity({ + explicitEntry: undefined, + liveTitle: '⠋ running the tests', + hasLivePty: false, + now: NOW + }) + expect(decision.source).toBe('title') + expect(decision.livePtyRequired).toBe(true) + }) + + it('reports none when there is no fresh hook and the title carries no status', () => { + const decision = resolvePaneAgentActivity({ + explicitEntry: undefined, + liveTitle: 'bash', + hasLivePty: true, + now: NOW + }) + expect(decision).toEqual({ + hookState: null, + hookAgentType: undefined, + titleStatus: null, + source: 'none', + confidence: 'authoritative', + livePtyRequired: false + }) + }) + + it('passes hook state through raw, including done', () => { + const decision = resolvePaneAgentActivity({ + explicitEntry: entry({ state: 'done' }), + liveTitle: null, + hasLivePty: true, + now: NOW + }) + expect(decision.hookState).toBe('done') + expect(decision.source).toBe('hook') + }) +}) diff --git a/src/renderer/src/lib/pane-agent-evidence.ts b/src/renderer/src/lib/pane-agent-evidence.ts new file mode 100644 index 000000000..4d6775895 --- /dev/null +++ b/src/renderer/src/lib/pane-agent-evidence.ts @@ -0,0 +1,121 @@ +import type { AgentStatus } from '../../../shared/agent-detection' +import { detectAgentStatusFromTitle, getAgentLabel } from '../../../shared/agent-detection' +import { resolveExplicitTerminalTitleAgentType } from '../../../shared/terminal-title-agent-type' +import type { TuiAgent } from '../../../shared/types' +import { + AGENT_STATUS_STALE_AFTER_MS, + type AgentStatusEntry, + type AgentStatusState, + type AgentType +} from '../../../shared/agent-status-types' + +// Why: explicit agent status entries (from hook-based reports) can go stale if +// the agent process exits without sending a final update. This helper lets +// callers decide whether to trust the entry based on a configurable TTL. +// (Moved here from agent-status.ts so the evidence resolvers below and the +// aggregate consumers share one gate without an import cycle.) +export function isExplicitAgentStatusFresh( + entry: Pick, + now: number, + staleAfterMs: number +): boolean { + return now - entry.updatedAt <= staleAfterMs +} + +/** + * Title-only activity classification for consumers whose product rule really + * is "what does this title say" (timer seeding, ready-wait polling, sort-epoch + * comparison, synthetic-title writing) — they combine no hook/liveness + * evidence, so routing them through the pane resolver would misstate intent. + */ +export function classifyTitleActivity(title: string): AgentStatus | null { + return detectAgentStatusFromTitle(title) +} + +/** + * The two facets of title-derived agent identity. The ACTIVITY LABEL treats + * Claude's bare status prefixes (spinner/`✳`/`. `/`* `) as Claude activity; + * COMMITTED identity rejects them — evidence that something runs is not proof + * of who. Consumers historically split on this by accident; pick the facet + * that matches the product rule, never both out of habit. + */ +export function resolveTitleActivityLabel(title: string): string | null { + return getAgentLabel(title) +} + +/** See resolveTitleActivityLabel — the strict facet for identity decisions. */ +export function resolveCommittedTitleAgentType(title: string): TuiAgent | null { + return resolveExplicitTerminalTitleAgentType(title) +} + +/** + * Combined pane activity evidence for aggregate consumers. The hook and title + * layers are exposed separately on purpose: consumers legitimately combine + * them differently (send targets let a live permission title override a fresh + * working hook; the worktree dot suppresses titles on hook-covered panes), so + * a single merged status would silently change behavior. + */ +export type AgentActivityDecision = { + /** Fresh (within AGENT_STATUS_STALE_AFTER_MS), pane-scoped hook state; null when absent or stale. */ + hookState: AgentStatusState | null + /** Agent identity from the fresh hook row, when one exists. */ + hookAgentType: AgentType | undefined + /** Title-derived status of the pane's live title, independent of hook state. */ + titleStatus: AgentStatus | null + /** Which evidence layer holds the strongest current claim. */ + source: 'hook' | 'title' | 'none' + confidence: 'authoritative' | 'fallback' + /** True when the only claim is a title without live-PTY proof — liveness-gated consumers must treat it as absent. */ + livePtyRequired: boolean +} + +export type ResolvePaneAgentActivityInput = { + explicitEntry: AgentStatusEntry | undefined + liveTitle: string | null + hasLivePty: boolean + now: number +} + +export function resolvePaneAgentActivity( + input: ResolvePaneAgentActivityInput +): AgentActivityDecision { + const freshEntry = + input.explicitEntry && + isExplicitAgentStatusFresh(input.explicitEntry, input.now, AGENT_STATUS_STALE_AFTER_MS) + ? input.explicitEntry + : null + const titleStatus = input.liveTitle !== null ? detectAgentStatusFromTitle(input.liveTitle) : null + if (freshEntry) { + return { + hookState: freshEntry.state, + hookAgentType: freshEntry.agentType, + titleStatus, + source: 'hook', + confidence: 'authoritative', + livePtyRequired: false + } + } + if (titleStatus !== null) { + return { + hookState: null, + hookAgentType: undefined, + titleStatus, + source: 'title', + confidence: 'fallback', + livePtyRequired: !input.hasLivePty + } + } + return { + hookState: null, + hookAgentType: undefined, + titleStatus: null, + source: 'none', + confidence: 'authoritative', + livePtyRequired: false + } +} + +// Deliberately absent: a resolvePaneAgentOwner precedence resolver. The only +// Phase 2 identity consumer (native-chat toggle) reads hook identity without a +// freshness gate, so a gated owner resolver would change its behavior; the +// owner resolver lands with its first real consumer in a later slice. diff --git a/src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts b/src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts index f132e786d..bc728ce7d 100644 --- a/src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts +++ b/src/renderer/src/lib/pane-manager/terminal-scroll-intent.test.ts @@ -53,12 +53,15 @@ class TestElement extends EventTarget { } closest(selector: string): TestElement | null { - if (!selector.startsWith('.')) { - return null - } - const className = selector.slice(1) - if (this.classList.contains(className)) { - return this + for (const candidate of selector.split(',')) { + const trimmed = candidate.trim() + if (!trimmed.startsWith('.')) { + continue + } + const className = trimmed.slice(1) + if (this.classList.contains(className)) { + return this + } } return this.parentElement?.closest(selector) ?? null } @@ -270,6 +273,56 @@ describe('terminal scroll intent', () => { disposable.dispose() }) + it.each(['xterm-scrollbar', 'xterm-slider'])( + 'tracks pointer-driven xterm %s scrolls as user intent', + (scrollbarClassName) => { + vi.stubGlobal('Element', TestElement) + const terminal = createTerminal({ viewportY: 100, baseY: 100 }) + const hostElement = new TestElement() + const scrollbarTarget = new TestElement(scrollbarClassName) + const scrollbarChild = new TestElement('xterm-scrollbar-child') + hostElement.append(scrollbarTarget) + scrollbarTarget.append(scrollbarChild) + const host = hostElement as unknown as HTMLElement + const disposable = attachTerminalScrollIntentTracking(terminal, host) + + terminal.buffer.active.viewportY = 50 + host.dispatchEvent(new Event('scroll')) + expect(getTerminalScrollIntentKind(terminal)).toBe('followOutput') + + scrollbarChild.dispatchEvent(new Event('pointerdown', { bubbles: true })) + scrollbarChild.dispatchEvent(new Event('scroll', { bubbles: true })) + expect(getTerminalScrollIntentKind(terminal)).toBe('pinnedViewport') + + disposable.dispose() + } + ) + + it('restores a scrollbar-dragged viewport instead of stale top intent', () => { + vi.stubGlobal('Element', TestElement) + const terminal = createTerminal({ viewportY: 0, baseY: 600 }) + const hostElement = new TestElement() + const scrollbar = new TestElement('xterm-scrollbar') + const slider = new TestElement('xterm-slider') + hostElement.append(scrollbar) + scrollbar.append(slider) + const host = hostElement as unknown as HTMLElement + const disposable = attachTerminalScrollIntentTracking(terminal, host, 'terminal-1') + + expect(getTerminalScrollIntentKind(terminal)).toBe('pinnedViewport') + + terminal.buffer.active.viewportY = 572 + slider.dispatchEvent(new Event('pointerdown', { bubbles: true })) + slider.dispatchEvent(new Event('scroll', { bubbles: true })) + + terminal.buffer.active.viewportY = 0 + enforceTerminalCurrentScrollIntent(terminal) + + expect(terminal.scrollToLine).toHaveBeenLastCalledWith(572) + expect(terminal.buffer.active.viewportY).toBe(572) + disposable.dispose() + }) + it('does not treat terminal body pointer activity as scrollbar intent', () => { vi.stubGlobal('Element', TestElement) const terminal = createTerminal({ viewportY: 100, baseY: 100 }) diff --git a/src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts b/src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts index 35537c11f..c0ab35f65 100644 --- a/src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts +++ b/src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts @@ -42,6 +42,14 @@ const terminalScrollIntentKeyByTerminal = new WeakMap< const terminalScrollIntentByKey = new Map() const BOTTOM_TOLERANCE_ROWS = 1 +const XTERM_SCROLL_INTENT_POINTER_TARGET_CLASSES = [ + 'xterm-viewport', + 'xterm-scrollbar', + 'xterm-slider' +] as const +const XTERM_SCROLL_INTENT_POINTER_TARGET_SELECTOR = XTERM_SCROLL_INTENT_POINTER_TARGET_CLASSES.map( + (className) => `.${className}` +).join(',') function readBufferSnapshot( terminal: TerminalScrollIntentTarget @@ -120,6 +128,14 @@ function safeScrollCall(fn: () => void): boolean { } } +function isTerminalScrollIntentPointerTarget(target: EventTarget | null): target is Element { + if (typeof Element === 'undefined' || !(target instanceof Element)) { + return false + } + // xterm's custom scrollbar uses separate thumb/track nodes from the viewport. + return target.closest(XTERM_SCROLL_INTENT_POINTER_TARGET_SELECTOR) !== null +} + export function markTerminalFollowOutput(terminal: TerminalScrollIntentTarget): void { writeIntent(terminal, 'followOutput') } @@ -255,11 +271,7 @@ export function attachTerminalScrollIntentTracking( } const onPointerDown = (event: PointerEvent): void => { - const target = event.target - pointerScrollActive = - typeof Element !== 'undefined' && - target instanceof Element && - (target.classList.contains('xterm-viewport') || target.closest('.xterm-viewport') !== null) + pointerScrollActive = isTerminalScrollIntentPointerTarget(event.target) } const onPointerDone = (): void => { diff --git a/src/renderer/src/lib/running-agent-targets.ts b/src/renderer/src/lib/running-agent-targets.ts index 332f419db..eedc06e36 100644 --- a/src/renderer/src/lib/running-agent-targets.ts +++ b/src/renderer/src/lib/running-agent-targets.ts @@ -1,11 +1,8 @@ import type { AppState } from '@/store/types' -import { - AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusEntry -} from '../../../shared/agent-status-types' +import type { AgentStatusEntry } from '../../../shared/agent-status-types' import type { TerminalTab } from '../../../shared/types' import { parsePaneKey } from '../../../shared/stable-pane-id' -import { isExplicitAgentStatusFresh } from './agent-status' +import { resolvePaneAgentActivity } from '@/lib/pane-agent-evidence' import { detectAgentSendTitleStatus } from './agent-send-title-status' import { resolveRuntimePaneTitleLeafResolution } from './runtime-pane-title-leaf-id' @@ -58,12 +55,23 @@ export function deriveRunningAgentSendTargets( : null let disabledReason: string | undefined + // Why: the shared resolver gates hook freshness; a null hookState means the + // entry is stale (entries here always exist), and otherwise carries the + // fresh entry.state. The live-title layer stays local because it needs the + // send-gated detector (label + strict idle-send gate), which the resolver's + // raw titleStatus does not reproduce. + const decision = resolvePaneAgentActivity({ + explicitEntry: entry, + liveTitle: null, + hasLivePty: ptyId !== null, + now + }) // Why: hook-backed rows can go stale while the same PTY is still a live // agent; live titles are the runtime proof that the row remains targetable. const liveTitleStatus = ptyId ? detectLiveAgentPaneStatus(state, parsed.tabId, parsed.leafId, tab.title) : null - if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { + if (decision.hookState === null) { if (liveTitleStatus === 'permission') { disabledReason = 'Agent needs permission' } else if (liveTitleStatus === null) { @@ -71,7 +79,7 @@ export function deriveRunningAgentSendTargets( } } else if (!ptyId) { disabledReason = 'Terminal is no longer available' - } else if (entry.state === 'blocked' || entry.state === 'waiting') { + } else if (decision.hookState === 'blocked' || decision.hookState === 'waiting') { disabledReason = 'Agent needs permission' } else if (liveTitleStatus === 'permission') { disabledReason = 'Agent needs permission' diff --git a/src/renderer/src/lib/setup-script-prompt.ts b/src/renderer/src/lib/setup-script-prompt.ts index b3cffcb5e..e60e3eaa7 100644 --- a/src/renderer/src/lib/setup-script-prompt.ts +++ b/src/renderer/src/lib/setup-script-prompt.ts @@ -112,6 +112,13 @@ export function filterSetupScriptPromptDismissalsToValidRepos( value: unknown, validRepoIds: Set ): string[] { + return sanitizeSetupScriptPromptDismissals(value).filter((entry) => { + const repoId = entry.slice(SETUP_SCRIPT_PROMPT_DISMISSAL_PREFIX.length) + return validRepoIds.has(repoId) + }) +} + +export function sanitizeSetupScriptPromptDismissals(value: unknown): string[] { if (!Array.isArray(value)) { return [] } @@ -121,8 +128,7 @@ export function filterSetupScriptPromptDismissalsToValidRepos( if (typeof entry !== 'string' || !entry.startsWith(SETUP_SCRIPT_PROMPT_DISMISSAL_PREFIX)) { continue } - const repoId = entry.slice(SETUP_SCRIPT_PROMPT_DISMISSAL_PREFIX.length) - if (validRepoIds.has(repoId) && !next.includes(entry)) { + if (!next.includes(entry)) { next.push(entry) } } diff --git a/src/renderer/src/lib/use-tab-agent.ts b/src/renderer/src/lib/use-tab-agent.ts index 6253ced22..40bf92d6f 100644 --- a/src/renderer/src/lib/use-tab-agent.ts +++ b/src/renderer/src/lib/use-tab-agent.ts @@ -13,8 +13,6 @@ import { import { resolveExplicitTerminalTitleAgentType } from '../../../shared/terminal-title-agent-type' import type { TerminalTab, TuiAgent } from '../../../shared/types' -export { resolveExplicitTerminalTitleAgentType as resolveTabAgentFromTitle } from '../../../shared/terminal-title-agent-type' - // A shell name, or the tab's neutral default title — where Orca's // inferred-interrupt reset parks it. Blank titles are no evidence either way. function titleShowsNoAgent(title: string, defaultTitle?: string): boolean { diff --git a/src/renderer/src/lib/workspace-session-host-persistence.test.ts b/src/renderer/src/lib/workspace-session-host-persistence.test.ts new file mode 100644 index 000000000..d2bf7336a --- /dev/null +++ b/src/renderer/src/lib/workspace-session-host-persistence.test.ts @@ -0,0 +1,386 @@ +import { describe, expect, it, vi } from 'vitest' +import { getDefaultWorkspaceSession } from '../../../shared/constants' +import type { WorkspaceSessionState } from '../../../shared/types' +import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../shared/workspace-scope' +import { + buildHostIdByWorktreeId, + fetchWorkspaceSessionFromHosts, + fetchWorkspaceSessionWithRuntimeHostOwners, + patchWorkspaceSessionByHost +} from './workspace-session-host-persistence' + +describe('fetchWorkspaceSessionFromHosts', () => { + it('reads saved runtime host partitions before runtime repos are loaded', async () => { + const worktreeId = 'remote-repo::/srv/remote-wt' + const localSession: WorkspaceSessionState = { + ...getDefaultWorkspaceSession(), + activeWorktreeId: 'local-wt' + } + const remoteSession: WorkspaceSessionState = { + ...getDefaultWorkspaceSession(), + tabsByWorktree: { + [worktreeId]: [ + { + id: 'remote-tab', + ptyId: null, + worktreeId, + title: 'Remote', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + } + const get = vi.fn(async (hostId?: string) => + hostId === 'runtime:env-1' ? remoteSession : localSession + ) + + const session = await fetchWorkspaceSessionFromHosts({ get }, [], ['runtime:env-1']) + + expect(get).toHaveBeenCalledWith() + expect(get).toHaveBeenCalledWith('runtime:env-1') + expect(session.activeWorktreeId).toBe('local-wt') + expect(session.tabsByWorktree[worktreeId]).toEqual(remoteSession.tabsByWorktree[worktreeId]) + }) + + it('returns runtime owners for worktrees loaded from runtime host partitions', async () => { + const worktreeId = 'remote-repo::/srv/remote-wt' + const get = vi.fn(async (hostId?: string): Promise => { + if (hostId === 'runtime:env-1') { + return { + ...getDefaultWorkspaceSession(), + tabsByWorktree: { + [worktreeId]: [ + { + id: 'remote-tab', + ptyId: null, + worktreeId, + title: 'Remote', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + } + } + return getDefaultWorkspaceSession() + }) + + const read = await fetchWorkspaceSessionWithRuntimeHostOwners({ get }, [], ['runtime:env-1']) + + expect(read.session.tabsByWorktree[worktreeId]).toHaveLength(1) + expect(read.runtimeHostIdByWorkspaceSessionKey).toEqual({ [worktreeId]: 'runtime:env-1' }) + }) + + it('normalizes canonical worktree session keys in runtime owner maps', async () => { + const worktreeId = 'remote-repo::/srv/remote-wt' + const workspaceKey = worktreeWorkspaceKey(worktreeId) + const get = vi.fn(async (hostId?: string): Promise => { + if (hostId === 'runtime:env-1') { + return { + ...getDefaultWorkspaceSession(), + tabsByWorktree: { + [workspaceKey]: [ + { + id: 'remote-tab', + ptyId: null, + worktreeId, + title: 'Remote', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + } + } + return getDefaultWorkspaceSession() + }) + + const read = await fetchWorkspaceSessionWithRuntimeHostOwners({ get }, [], ['runtime:env-1']) + + expect(read.runtimeHostIdByWorkspaceSessionKey).toEqual({ [worktreeId]: 'runtime:env-1' }) + }) + + it('returns runtime owners for folder workspace session keys', async () => { + const folderKey = folderWorkspaceKey('folder-1') + const get = vi.fn(async (hostId?: string): Promise => { + if (hostId === 'runtime:env-1') { + return { + ...getDefaultWorkspaceSession(), + activeWorkspaceKey: folderKey, + tabsByWorktree: { + [folderKey]: [ + { + id: 'remote-folder-tab', + ptyId: null, + worktreeId: folderKey, + title: 'Remote folder', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + } + } + return getDefaultWorkspaceSession() + }) + + const read = await fetchWorkspaceSessionWithRuntimeHostOwners({ get }, [], ['runtime:env-1']) + + expect(read.session.tabsByWorktree[folderKey]).toHaveLength(1) + expect(read.runtimeHostIdByWorkspaceSessionKey).toEqual({ [folderKey]: 'runtime:env-1' }) + }) + + it('returns runtime owners for sleeping-agent-only runtime worktrees', async () => { + const worktreeId = 'remote-repo::/srv/sleeping-wt' + const get = vi.fn(async (hostId?: string): Promise => { + if (hostId === 'runtime:env-1') { + return { + ...getDefaultWorkspaceSession(), + sleepingAgentSessionsByPaneKey: { + 'remote-tab:leaf-1': { + paneKey: 'remote-tab:leaf-1', + tabId: 'remote-tab', + worktreeId, + agent: 'codex', + providerSession: { key: 'session_id', id: 'codex-session-1' }, + prompt: 'finish the task', + state: 'working', + capturedAt: 1, + updatedAt: 1 + } + } + } + } + return getDefaultWorkspaceSession() + }) + + const read = await fetchWorkspaceSessionWithRuntimeHostOwners({ get }, [], ['runtime:env-1']) + + expect(read.session.sleepingAgentSessionsByPaneKey?.['remote-tab:leaf-1']?.worktreeId).toBe( + worktreeId + ) + expect(read.runtimeHostIdByWorkspaceSessionKey).toEqual({ [worktreeId]: 'runtime:env-1' }) + }) + + it('routes restored runtime folder workspace patches back to the runtime host', async () => { + const folderKey = folderWorkspaceKey('folder-1') + const patch = vi.fn().mockResolvedValue(undefined) + + await patchWorkspaceSessionByHost( + { get: vi.fn(), patch, setSync: vi.fn() }, + { + tabsByWorktree: { + [folderKey]: [ + { + id: 'remote-folder-tab', + ptyId: null, + worktreeId: folderKey, + title: 'Remote folder', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + }, + { + repos: [], + worktreesByRepo: {}, + restoredRuntimeHostIdByWorkspaceSessionKey: { [folderKey]: 'runtime:env-1' } + } + ) + + expect(patch).toHaveBeenCalledWith(expect.objectContaining({ tabsByWorktree: {} })) + expect(patch).toHaveBeenCalledWith( + expect.objectContaining({ + tabsByWorktree: expect.objectContaining({ + [folderKey]: expect.any(Array) + }) + }), + 'runtime:env-1' + ) + }) + + it('keeps catalog-known local folder workspace patches local over stale restored owners', async () => { + const folderKey = folderWorkspaceKey('folder-1') + const patch = vi.fn().mockResolvedValue(undefined) + + await patchWorkspaceSessionByHost( + { get: vi.fn(), patch, setSync: vi.fn() }, + { + tabsByWorktree: { + [folderKey]: [ + { + id: 'local-folder-tab', + ptyId: null, + worktreeId: folderKey, + title: 'Local folder', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + }, + { + repos: [], + folderWorkspaces: [{ id: 'folder-1', projectGroupId: 'group-1' }], + projectGroups: [{ id: 'group-1', executionHostId: 'local' }], + worktreesByRepo: {}, + restoredRuntimeHostIdByWorkspaceSessionKey: { [folderKey]: 'runtime:stale-env' } + } + ) + + expect(patch).toHaveBeenCalledTimes(1) + expect(patch.mock.calls[0][0]).toEqual( + expect.objectContaining({ + tabsByWorktree: expect.objectContaining({ + [folderKey]: expect.any(Array) + }) + }) + ) + expect(patch.mock.calls[0][1]).toBeUndefined() + }) + + it('routes placeholder-owned runtime worktree patches back to the runtime host', async () => { + const worktreeId = 'remote-repo::/srv/remote-wt' + const patch = vi.fn().mockResolvedValue(undefined) + + await patchWorkspaceSessionByHost( + { get: vi.fn(), patch, setSync: vi.fn() }, + { + tabsByWorktree: { + [worktreeId]: [ + { + id: 'remote-tab', + ptyId: null, + worktreeId, + title: 'Remote', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + }, + { + repos: [{ id: 'remote-repo', connectionId: null, executionHostId: 'runtime:env-1' }], + worktreesByRepo: { 'remote-repo': [{ id: worktreeId, repoId: 'remote-repo' }] } + } + ) + + expect(patch).toHaveBeenCalledWith(expect.objectContaining({ tabsByWorktree: {} })) + expect(patch).toHaveBeenCalledWith( + expect.objectContaining({ + tabsByWorktree: expect.objectContaining({ + [worktreeId]: expect.any(Array) + }) + }), + 'runtime:env-1' + ) + }) + + it('keeps same-id local repo worktrees in the local partition', async () => { + const localWorktreeId = 'same-repo::/Users/me/project' + const remoteWorktreeId = 'same-repo::/srv/project' + const patch = vi.fn().mockResolvedValue(undefined) + + await patchWorkspaceSessionByHost( + { get: vi.fn(), patch, setSync: vi.fn() }, + { + tabsByWorktree: { + [localWorktreeId]: [ + { + id: 'local-tab', + ptyId: null, + worktreeId: localWorktreeId, + title: 'Local', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ], + [remoteWorktreeId]: [ + { + id: 'remote-tab', + ptyId: null, + worktreeId: remoteWorktreeId, + title: 'Remote', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: 1 + } + ] + } + }, + { + repos: [ + { id: 'same-repo', connectionId: null, executionHostId: 'local' }, + { id: 'same-repo', connectionId: null, executionHostId: 'runtime:env-1' } + ], + worktreesByRepo: { + 'same-repo': [ + { id: localWorktreeId, repoId: 'same-repo' }, + { id: remoteWorktreeId, repoId: 'same-repo', hostId: 'runtime:env-1' } + ] + } + } + ) + + expect(patch).toHaveBeenCalledWith( + expect.objectContaining({ + tabsByWorktree: { + [localWorktreeId]: expect.any(Array) + } + }) + ) + expect(patch).toHaveBeenCalledWith( + expect.objectContaining({ + tabsByWorktree: expect.objectContaining({ + [remoteWorktreeId]: expect.any(Array) + }) + }), + 'runtime:env-1' + ) + }) + + it('defaults duplicate repo ids to local when the worktree has no host metadata', () => { + const owner = buildHostIdByWorktreeId({ + repos: [ + { id: 'same-repo', connectionId: null, executionHostId: 'local' }, + { id: 'same-repo', connectionId: null, executionHostId: 'runtime:env-1' } + ], + worktreesByRepo: { + 'same-repo': [{ id: 'same-repo::/local-only', repoId: 'same-repo' }] + } + }) + + expect(owner('same-repo::/local-only')).toBe('local') + }) + + it('routes canonical worktree keys using their raw worktree owner', () => { + const worktreeId = 'remote-repo::/srv/remote-wt' + const owner = buildHostIdByWorktreeId({ + repos: [], + worktreesByRepo: { + 'remote-repo': [{ id: worktreeId, repoId: 'remote-repo', hostId: 'runtime:env-1' }] + } + }) + + expect(owner(worktreeWorkspaceKey(worktreeId))).toBe('runtime:env-1') + }) +}) diff --git a/src/renderer/src/lib/workspace-session-host-persistence.ts b/src/renderer/src/lib/workspace-session-host-persistence.ts index 80d56c236..f59a827b7 100644 --- a/src/renderer/src/lib/workspace-session-host-persistence.ts +++ b/src/renderer/src/lib/workspace-session-host-persistence.ts @@ -10,6 +10,7 @@ import { parseExecutionHostId, type ExecutionHostId } from '../../../shared/execution-host' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' import { getRepoIdFromWorktreeId } from '../../../shared/worktree-id' import { mergeWorkspaceSessionsFromHosts, @@ -20,7 +21,10 @@ import { export type HostPersistenceState = { repos: readonly Pick[] - worktreesByRepo: Record[]> + projectGroups?: readonly { id: string; executionHostId?: string | null }[] + folderWorkspaces?: readonly { id: string; projectGroupId: string }[] + worktreesByRepo: Record[]> + restoredRuntimeHostIdByWorkspaceSessionKey?: Record } type SessionApi = { @@ -29,6 +33,119 @@ type SessionApi = { setSync: (args: WorkspaceSessionState, hostId?: ExecutionHostId) => void } +export type WorkspaceSessionHostRead = { + session: WorkspaceSessionState + runtimeHostIdByWorkspaceSessionKey: Record +} + +const WORKSPACE_SESSION_KEYED_FIELDS = [ + 'tabsByWorktree', + 'openFilesByWorktree', + 'activeFileIdByWorktree', + 'activeBrowserTabIdByWorktree', + 'activeTabTypeByWorktree', + 'activeTabIdByWorktree', + 'browserTabsByWorktree', + 'unifiedTabs', + 'tabGroups', + 'tabGroupLayouts', + 'activeGroupIdByWorktree', + 'lastVisitedAtByWorktreeId', + 'defaultTerminalTabsAppliedByWorktreeId' +] as const satisfies readonly (keyof WorkspaceSessionState)[] + +function isPlainRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) +} + +function normalizeWorkspaceSessionKeyForOwnerMap(value: string): string { + const scope = parseWorkspaceKey(value) + return scope?.type === 'worktree' ? scope.worktreeId : value +} + +function addWorkspaceSessionKeyForOwnerMap(ids: Set, value: unknown): void { + if (typeof value === 'string') { + ids.add(normalizeWorkspaceSessionKeyForOwnerMap(value)) + } +} + +function collectWorkspaceSessionKeysFromHostSession(session: WorkspaceSessionState): string[] { + const ids = new Set() + for (const field of WORKSPACE_SESSION_KEYED_FIELDS) { + const value = session[field] + if (isPlainRecord(value)) { + for (const id of Object.keys(value)) { + addWorkspaceSessionKeyForOwnerMap(ids, id) + } + } + } + for (const id of session.activeWorktreeIdsOnShutdown ?? []) { + addWorkspaceSessionKeyForOwnerMap(ids, id) + } + for (const pages of Object.values(session.browserPagesByWorkspace ?? {})) { + if (!Array.isArray(pages)) { + continue + } + for (const page of pages) { + addWorkspaceSessionKeyForOwnerMap(ids, page.worktreeId) + } + } + for (const record of Object.values(session.sleepingAgentSessionsByPaneKey ?? {})) { + // Why: a hibernated agent can be the only restored session evidence for a + // runtime worktree before its remote catalog answers. + addWorkspaceSessionKeyForOwnerMap(ids, record.worktreeId) + } + return [...ids] +} + +function buildRuntimeHostIdByWorkspaceSessionKey( + slices: HostSessionSlices +): Record { + const owners: Record = {} + for (const [hostId, slice] of nonLocalEntries(slices)) { + for (const worktreeId of collectWorkspaceSessionKeysFromHostSession(slice)) { + owners[worktreeId] = hostId + } + } + return owners +} + +function getRestoredRuntimeHostId( + owners: Record | undefined, + key: string +): ExecutionHostId | null { + const hostId = owners?.[key] + return hostId && parseExecutionHostId(hostId)?.kind === 'runtime' ? hostId : null +} + +function getFolderWorkspaceRuntimeHostId( + state: HostPersistenceState, + key: string +): ExecutionHostId { + const scope = parseWorkspaceKey(key) + if (scope?.type !== 'folder') { + return LOCAL_EXECUTION_HOST_ID + } + const workspace = state.folderWorkspaces?.find((entry) => entry.id === scope.folderWorkspaceId) + const group = workspace + ? state.projectGroups?.find((entry) => entry.id === workspace.projectGroupId) + : null + const parsed = parseExecutionHostId(group?.executionHostId) + if (parsed) { + return parsed.kind === 'runtime' ? parsed.id : LOCAL_EXECUTION_HOST_ID + } + if (workspace && group) { + // Why: once the folder and group catalogs are both known, a missing runtime + // owner is authoritative local/SSH persistence, not a startup gap. + return LOCAL_EXECUTION_HOST_ID + } + const restoredHostId = getRestoredRuntimeHostId( + state.restoredRuntimeHostIdByWorkspaceSessionKey, + key + ) + return restoredHostId ?? LOCAL_EXECUTION_HOST_ID +} + /** Map a worktree to the host partition it persists under. * * Why: only `runtime:*` worktrees are partitioned out. SSH-owned worktrees stay @@ -36,21 +153,43 @@ type SessionApi = { * the unified blob) and separately mirrors them to each target's remote * snapshot — partitioning them too would double-own that data. */ export function buildHostIdByWorktreeId(state: HostPersistenceState): HostIdByWorktreeId { - const repoById = new Map(state.repos.map((repo) => [repo.id, repo])) + const repoHostById = new Map() + for (const repo of state.repos) { + const hostId = getRepoExecutionHostId(repo) + const existing = repoHostById.get(repo.id) + // Why: repo ids can repeat across hosts; ambiguous repo-only ownership + // must not let a runtime placeholder steal local session state. + repoHostById.set(repo.id, existing === undefined ? hostId : existing === hostId ? hostId : null) + } const repoIdByWorktreeId = new Map() + const runtimeHostIdByWorktreeId = new Map() for (const worktrees of Object.values(state.worktreesByRepo)) { for (const worktree of worktrees) { repoIdByWorktreeId.set(worktree.id, worktree.repoId) + const parsedWorktreeHost = parseExecutionHostId(worktree.hostId) + if (parsedWorktreeHost?.kind === 'runtime') { + runtimeHostIdByWorktreeId.set(worktree.id, parsedWorktreeHost.id) + } } } return (worktreeId: string): ExecutionHostId => { - const repoId = repoIdByWorktreeId.get(worktreeId) ?? getRepoIdFromWorktreeId(worktreeId) - const repo = repoId ? repoById.get(repoId) : undefined - if (!repo) { + const workspaceScope = parseWorkspaceKey(worktreeId) + if (workspaceScope?.type === 'folder') { + return getFolderWorkspaceRuntimeHostId(state, worktreeId) + } + const rawWorktreeId = + workspaceScope?.type === 'worktree' ? workspaceScope.worktreeId : worktreeId + const worktreeHostId = runtimeHostIdByWorktreeId.get(rawWorktreeId) + if (worktreeHostId) { + return worktreeHostId + } + const repoId = repoIdByWorktreeId.get(rawWorktreeId) ?? getRepoIdFromWorktreeId(rawWorktreeId) + const repoHostId = repoId ? repoHostById.get(repoId) : undefined + if (!repoHostId) { return LOCAL_EXECUTION_HOST_ID } - const parsed = parseExecutionHostId(getRepoExecutionHostId(repo)) + const parsed = parseExecutionHostId(repoHostId) return parsed?.kind === 'runtime' ? parsed.id : LOCAL_EXECUTION_HOST_ID } } @@ -112,21 +251,37 @@ export function listKnownRuntimeHostIds( } /** Boot-time hydration: fetch the local partition plus one partition per known - * runtime host (repos are already loaded before session hydration in App.tsx) - * and merge them into the unified session the hydrators expect. + * runtime host (from loaded repos and saved runtime ids), then merge them into + * the unified session the hydrators expect. * * Fail-soft: a partition whose fetch rejects is skipped — boot proceeds with * the rest. Corrupt partitions never reach here; persistence zod-validates * each one and falls back to defaults on the main side. */ export async function fetchWorkspaceSessionFromHosts( api: Pick, - repos: readonly Pick[] + repos: readonly Pick[], + additionalRuntimeHostIds: readonly ExecutionHostId[] = [] ): Promise { + return (await fetchWorkspaceSessionWithRuntimeHostOwners(api, repos, additionalRuntimeHostIds)) + .session +} + +export async function fetchWorkspaceSessionWithRuntimeHostOwners( + api: Pick, + repos: readonly Pick[], + additionalRuntimeHostIds: readonly ExecutionHostId[] = [] +): Promise { const slices: HostSessionSlices = { [LOCAL_EXECUTION_HOST_ID]: await api.get() } + // Why: startup can know saved runtime session hosts before their repo + // catalogs hydrate, so include those partitions in the first read. + const runtimeHostIds = new Set([ + ...listKnownRuntimeHostIds(repos), + ...additionalRuntimeHostIds + ]) await Promise.all( - listKnownRuntimeHostIds(repos).map(async (hostId) => { + [...runtimeHostIds].map(async (hostId) => { try { slices[hostId] = await api.get(hostId) } catch (err) { @@ -134,5 +289,8 @@ export async function fetchWorkspaceSessionFromHosts( } }) ) - return mergeWorkspaceSessionsFromHosts(slices) + return { + session: mergeWorkspaceSessionsFromHosts(slices), + runtimeHostIdByWorkspaceSessionKey: buildRuntimeHostIdByWorkspaceSessionKey(slices) + } } diff --git a/src/renderer/src/lib/workspace-session-hydration-keys.ts b/src/renderer/src/lib/workspace-session-hydration-keys.ts new file mode 100644 index 000000000..15513b458 --- /dev/null +++ b/src/renderer/src/lib/workspace-session-hydration-keys.ts @@ -0,0 +1,81 @@ +import type { WorkspaceKey, WorkspaceSessionState } from '../../../shared/types' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' + +export type WorkspaceSessionHydrationOptions = { + additionalValidWorkspaceKeys?: readonly WorkspaceKey[] +} + +const WORKSPACE_KEYED_SESSION_FIELDS = [ + 'tabsByWorktree', + 'openFilesByWorktree', + 'activeFileIdByWorktree', + 'activeBrowserTabIdByWorktree', + 'activeTabTypeByWorktree', + 'activeTabIdByWorktree', + 'browserTabsByWorktree', + 'unifiedTabs', + 'tabGroups', + 'tabGroupLayouts', + 'activeGroupIdByWorktree', + 'lastVisitedAtByWorktreeId', + 'defaultTerminalTabsAppliedByWorktreeId' +] as const satisfies readonly (keyof WorkspaceSessionState)[] + +function isPlainRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) +} + +function addFolderWorkspaceKey(keys: Set, value: unknown): void { + if (typeof value !== 'string') { + return + } + const scope = parseWorkspaceKey(value) + if (scope?.type === 'folder') { + keys.add(value as WorkspaceKey) + } +} + +export function collectFolderWorkspaceKeysFromSession( + session: WorkspaceSessionState +): WorkspaceKey[] { + const keys = new Set() + + addFolderWorkspaceKey(keys, session.activeWorkspaceKey) + addFolderWorkspaceKey(keys, session.activeWorktreeId) + + for (const field of WORKSPACE_KEYED_SESSION_FIELDS) { + const value = session[field] + if (!isPlainRecord(value)) { + continue + } + for (const key of Object.keys(value)) { + addFolderWorkspaceKey(keys, key) + } + } + + for (const worktreeId of session.activeWorktreeIdsOnShutdown ?? []) { + addFolderWorkspaceKey(keys, worktreeId) + } + for (const pages of Object.values(session.browserPagesByWorkspace ?? {})) { + if (!Array.isArray(pages)) { + continue + } + for (const page of pages) { + addFolderWorkspaceKey(keys, page.worktreeId) + } + } + for (const record of Object.values(session.sleepingAgentSessionsByPaneKey ?? {})) { + addFolderWorkspaceKey(keys, record.worktreeId) + } + + return [...keys] +} + +export function addAdditionalValidWorkspaceKeys( + validWorkspaceIds: Set, + options?: WorkspaceSessionHydrationOptions +): void { + for (const key of options?.additionalValidWorkspaceKeys ?? []) { + validWorkspaceIds.add(key) + } +} diff --git a/src/renderer/src/lib/worktree-runtime-owner.test.ts b/src/renderer/src/lib/worktree-runtime-owner.test.ts index 1e8407bff..823705d10 100644 --- a/src/renderer/src/lib/worktree-runtime-owner.test.ts +++ b/src/renderer/src/lib/worktree-runtime-owner.test.ts @@ -62,11 +62,46 @@ describe('getSettingsForWorktreeRuntimeOwner', () => { expect(getExecutionHostIdForWorktree(state, 'folder:runtime-folder')).toBe('runtime:folder-env') }) + it('routes restored runtime folder workspaces before their catalog loads', () => { + const restoredFolderState: WorktreeRuntimeOwnerState = { + settings: { activeRuntimeEnvironmentId: 'focused-env' }, + folderWorkspaces: [], + projectGroups: [], + restoredRuntimeHostIdByWorkspaceSessionKey: { + 'folder:restored-folder': 'runtime:restored-env' + } + } + + expect( + getSettingsForWorktreeRuntimeOwner(restoredFolderState, 'folder:restored-folder') + ).toEqual({ + activeRuntimeEnvironmentId: 'restored-env' + }) + expect(getRuntimeEnvironmentIdForWorktree(restoredFolderState, 'folder:restored-folder')).toBe( + 'restored-env' + ) + expect( + getExplicitRuntimeEnvironmentIdForWorktree(restoredFolderState, 'folder:restored-folder') + ).toBe('restored-env') + expect(getExecutionHostIdForWorktree(restoredFolderState, 'folder:restored-folder')).toBe( + 'runtime:restored-env' + ) + }) + it('keeps explicit-local folder workspaces local even while a runtime is focused', () => { expect(getSettingsForWorktreeRuntimeOwner(state, 'folder:local-folder')).toEqual({ activeRuntimeEnvironmentId: null }) expect(getExecutionHostIdForWorktree(state, 'folder:local-folder')).toBe('local') + + const restoredOwnerState: WorktreeRuntimeOwnerState = { + ...state, + restoredRuntimeHostIdByWorkspaceSessionKey: { + 'folder:local-folder': 'runtime:stale-env' + } + } + expect(getRuntimeEnvironmentIdForWorktree(restoredOwnerState, 'folder:local-folder')).toBeNull() + expect(getExecutionHostIdForWorktree(restoredOwnerState, 'folder:local-folder')).toBe('local') }) it('keeps folder workspaces with their own SSH target off the focused runtime', () => { @@ -188,6 +223,17 @@ describe('getRuntimeSessionMirrorEnvironmentIds', () => { ]) }) + it('includes restored runtime folder owners before their catalog loads', () => { + expect( + getRuntimeSessionMirrorEnvironmentIds({ + settings: { activeRuntimeEnvironmentId: 'focused-env' }, + restoredRuntimeHostIdByWorkspaceSessionKey: { + 'folder:restored-folder': 'runtime:restored-env' + } + }) + ).toEqual(['focused-env', 'restored-env']) + }) + it('does not include local or SSH owners', () => { const localOnlyState: WorktreeRuntimeOwnerState = { settings: { activeRuntimeEnvironmentId: null }, diff --git a/src/renderer/src/lib/worktree-runtime-owner.ts b/src/renderer/src/lib/worktree-runtime-owner.ts index 859aeaaab..71acd81a2 100644 --- a/src/renderer/src/lib/worktree-runtime-owner.ts +++ b/src/renderer/src/lib/worktree-runtime-owner.ts @@ -3,7 +3,7 @@ import { parseExecutionHostId, toSshExecutionHostId } from '../../../shared/execution-host' -import type { ExecutionHostId } from '../../../shared/execution-host' +import type { ExecutionHostId, ParsedExecutionHost } from '../../../shared/execution-host' import type { FolderWorkspace, GlobalSettings, @@ -11,16 +11,19 @@ import type { Repo, Worktree } from '../../../shared/types' -import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { folderWorkspaceKey, parseWorkspaceKey } from '../../../shared/workspace-scope' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../shared/constants' import { getRepoIdFromWorktreeId } from '@/store/slices/worktree-helpers' +type RuntimeExecutionHost = Extract + export type WorktreeRuntimeOwnerState = { repos?: readonly Pick[] settings?: Pick | null worktreesByRepo?: Record[]> folderWorkspaces?: readonly Pick[] projectGroups?: readonly Pick[] + restoredRuntimeHostIdByWorkspaceSessionKey?: Record } function findWorktreeRecord( @@ -72,9 +75,26 @@ function getRuntimeEnvironmentIdForFolderWorkspace( ) { return null } + const restoredRuntimeHost = getRestoredRuntimeHostForFolderWorkspace(state, folderWorkspaceId) + if (restoredRuntimeHost) { + return restoredRuntimeHost.environmentId + } return state.settings?.activeRuntimeEnvironmentId?.trim() || null } +function getRestoredRuntimeHostForFolderWorkspace( + state: WorktreeRuntimeOwnerState, + folderWorkspaceId: string +): RuntimeExecutionHost | null { + // Why: runtime folder catalogs load after session hydration; the saved + // per-host session partition is the only owner evidence during that gap. + const workspaceKey = folderWorkspaceKey(folderWorkspaceId) + const parsed = parseExecutionHostId( + state.restoredRuntimeHostIdByWorkspaceSessionKey?.[workspaceKey] + ) + return parsed?.kind === 'runtime' ? parsed : null +} + function getExplicitRuntimeEnvironmentIdFromHost( executionHostId: string | null | undefined ): string | null { @@ -101,9 +121,16 @@ function getExplicitRuntimeEnvironmentIdForFolderWorkspace( state: WorktreeRuntimeOwnerState, folderWorkspaceId: string ): string | null { - return getExplicitRuntimeEnvironmentIdFromHost( - findFolderProjectGroup(state, folderWorkspaceId)?.executionHostId - ) + const folderWorkspace = findFolderWorkspace(state, folderWorkspaceId) + const projectGroup = findFolderProjectGroup(state, folderWorkspaceId) + const parsed = parseExecutionHostId(projectGroup?.executionHostId) + if (parsed) { + return parsed.kind === 'runtime' ? parsed.environmentId : null + } + if (folderWorkspace?.connectionId?.trim() || projectGroup?.connectionId?.trim()) { + return null + } + return getRestoredRuntimeHostForFolderWorkspace(state, folderWorkspaceId)?.environmentId ?? null } function getExecutionHostIdForFolderWorkspace( @@ -120,6 +147,10 @@ function getExecutionHostIdForFolderWorkspace( if (connectionId) { return toSshExecutionHostId(connectionId) } + const restoredRuntimeHost = getRestoredRuntimeHostForFolderWorkspace(state, folderWorkspaceId) + if (restoredRuntimeHost) { + return restoredRuntimeHost.id + } const environmentId = state.settings?.activeRuntimeEnvironmentId?.trim() return environmentId ? `runtime:${encodeURIComponent(environmentId)}` : 'local' } @@ -209,6 +240,12 @@ export function getRuntimeSessionMirrorEnvironmentIds(state: WorktreeRuntimeOwne ids.add(environmentId) } } + for (const hostId of Object.values(state.restoredRuntimeHostIdByWorkspaceSessionKey ?? {})) { + const parsed = parseExecutionHostId(hostId) + if (parsed?.kind === 'runtime') { + ids.add(parsed.environmentId) + } + } return [...ids].sort() } diff --git a/src/renderer/src/lib/worktree-status.ts b/src/renderer/src/lib/worktree-status.ts index 5018c7310..0c3c87bf0 100644 --- a/src/renderer/src/lib/worktree-status.ts +++ b/src/renderer/src/lib/worktree-status.ts @@ -1,4 +1,4 @@ -import { detectAgentStatusFromTitle } from '@/lib/agent-status' +import { classifyTitleActivity } from '@/lib/pane-agent-evidence' import { tabHasLivePty } from '@/lib/tab-has-live-pty' import { resolveRuntimePaneTitleLeafIdFromRoot } from '@/lib/runtime-pane-title-leaf-id' import type { @@ -91,7 +91,7 @@ function tabHasStatus( ) { continue } - if (detectAgentStatusFromTitle(title) === status) { + if (classifyTitleActivity(title) === status) { return true } } @@ -103,7 +103,7 @@ function tabHasStatus( if (agentStatusPaneIds && agentStatusPaneIds.size > 0) { return false } - return detectAgentStatusFromTitle(tab.title) === status + return classifyTitleActivity(tab.title) === status } export function getWorktreeStatusLabel(status: WorktreeStatus): string { diff --git a/src/renderer/src/runtime/runtime-git-client.test.ts b/src/renderer/src/runtime/runtime-git-client.test.ts index 909ca60c2..72b020df4 100644 --- a/src/renderer/src/runtime/runtime-git-client.test.ts +++ b/src/renderer/src/runtime/runtime-git-client.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: runtime git routing tests share compatibility-cache and IPC stubs; splitting would hide cross-environment contract drift. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { bulkDiscardRuntimeGitPaths, diff --git a/src/renderer/src/runtime/runtime-linear-client.test.ts b/src/renderer/src/runtime/runtime-linear-client.test.ts index 531e13660..57f182f83 100644 --- a/src/renderer/src/runtime/runtime-linear-client.test.ts +++ b/src/renderer/src/runtime/runtime-linear-client.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: runtime Linear routing cases stay together - so local preload fallback and SSH runtime transport parity are reviewed as one boundary. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { linearCreateIssue, diff --git a/src/renderer/src/runtime/runtime-rpc-client.test.ts b/src/renderer/src/runtime/runtime-rpc-client.test.ts index a7f9c225b..97280cb35 100644 --- a/src/renderer/src/runtime/runtime-rpc-client.test.ts +++ b/src/renderer/src/runtime/runtime-rpc-client.test.ts @@ -136,6 +136,133 @@ describe('runtime RPC client routing', () => { ]) }) + it('reuses recent remote compatibility failures during startup catalog bursts', async () => { + runtimeEnvironmentCall.mockResolvedValue({ + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'remote-runtime' } + }) + const target = { kind: 'environment', environmentId: 'env-offline' } as const + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + await expect( + callRuntimeRpc(target, 'projectGroup.list', undefined, { + reuseRecentCompatibilityFailure: true + }) + ).rejects.toThrow('offline') + await expect( + callRuntimeRpc(target, 'folderWorkspace.list', undefined, { + reuseRecentCompatibilityFailure: true + }) + ).rejects.toThrow('offline') + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual(['status.get']) + }) + + it('expires startup compatibility failures at the TTL boundary', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date(0)) + try { + let statusCalls = 0 + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + if (method === 'status.get') { + statusCalls += 1 + if (statusCalls === 1) { + return Promise.resolve({ + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + graphStatus: 'ready', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: method, + ok: true, + result: { ok: true }, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + const target = { kind: 'environment', environmentId: 'env-ttl' } as const + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + vi.setSystemTime(new Date(60_000)) + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).resolves.toEqual({ ok: true }) + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get', + 'status.get', + 'repo.list' + ]) + } finally { + vi.useRealTimers() + } + }) + + it('retries normal remote calls after a catalog-burst compatibility failure', async () => { + let statusCalls = 0 + runtimeEnvironmentCall.mockImplementation(({ method }: { method: string }) => { + if (method === 'status.get') { + statusCalls += 1 + if (statusCalls === 1) { + return Promise.resolve({ + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: 'status', + ok: true, + result: { + runtimeId: 'remote-runtime', + graphStatus: 'ready', + runtimeProtocolVersion: RUNTIME_PROTOCOL_VERSION, + minCompatibleRuntimeClientVersion: MIN_COMPATIBLE_RUNTIME_CLIENT_VERSION + }, + _meta: { runtimeId: 'remote-runtime' } + }) + } + return Promise.resolve({ + id: method, + ok: true, + result: { ok: true }, + _meta: { runtimeId: 'remote-runtime' } + }) + }) + const target = { kind: 'environment', environmentId: 'env-recovers' } as const + + await expect( + callRuntimeRpc(target, 'repo.list', undefined, { reuseRecentCompatibilityFailure: true }) + ).rejects.toThrow('offline') + await expect(callRuntimeRpc(target, 'git.status')).resolves.toEqual({ ok: true }) + + expect(runtimeEnvironmentCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get', + 'status.get', + 'git.status' + ]) + }) + it('checks advertised runtime capabilities after protocol compatibility', async () => { runtimeEnvironmentCall.mockResolvedValue({ id: 'status', diff --git a/src/renderer/src/runtime/runtime-rpc-client.ts b/src/renderer/src/runtime/runtime-rpc-client.ts index 9d9c90295..b9b1cb330 100644 --- a/src/renderer/src/runtime/runtime-rpc-client.ts +++ b/src/renderer/src/runtime/runtime-rpc-client.ts @@ -8,7 +8,15 @@ import { assertRuntimeStatusCompatible } from './runtime-protocol-compat' export type RuntimeClientTarget = { kind: 'local' } | { kind: 'environment'; environmentId: string } const RUNTIME_COMPATIBILITY_CACHE_MAX = 32 -const compatibleRuntimeEnvironments = new Map>() +const RECENT_RUNTIME_COMPATIBILITY_FAILURE_TTL_MS = 60_000 + +type RuntimeCompatibilityCacheEntry = { + check: Promise + failedAt: number | null + reuseFailure: boolean +} + +const runtimeCompatibilityChecks = new Map() export class RuntimeRpcCallError extends Error { readonly code: string @@ -54,10 +62,14 @@ export async function callRuntimeRpc( target: RuntimeClientTarget, method: string, params?: unknown, - options: { timeoutMs?: number; suppressFeatureInteraction?: boolean } = {} + options: { + timeoutMs?: number + suppressFeatureInteraction?: boolean + reuseRecentCompatibilityFailure?: boolean + } = {} ): Promise { if (target.kind === 'environment' && method !== 'status.get') { - await ensureRuntimeEnvironmentCompatible(target.environmentId, options.timeoutMs) + await ensureRuntimeEnvironmentCompatible(target.environmentId, options) } const nextParams = addFeatureInteractionSource(params, options) const response = @@ -84,61 +96,93 @@ function addFeatureInteractionSource( async function ensureRuntimeEnvironmentCompatible( environmentId: string, - timeoutMs?: number + options: { timeoutMs?: number; reuseRecentCompatibilityFailure?: boolean } = {} ): Promise { - const cached = compatibleRuntimeEnvironments.get(environmentId) + const cached = getCachedRuntimeCompatibilityCheck(environmentId, options) if (cached) { - compatibleRuntimeEnvironments.delete(environmentId) - compatibleRuntimeEnvironments.set(environmentId, cached) - await cached + await cached.check return } + const entry: RuntimeCompatibilityCacheEntry = { + check: Promise.resolve(), + failedAt: null, + reuseFailure: options.reuseRecentCompatibilityFailure === true + } const check = (async () => { const response = await window.api.runtimeEnvironments.call({ selector: environmentId, method: 'status.get', - timeoutMs + timeoutMs: options.timeoutMs }) const status = unwrapRuntimeRpcResult( response as RuntimeRpcResponse ) assertRuntimeStatusCompatible(status) })() - rememberRuntimeEnvironmentCompatibility(environmentId, check) + entry.check = check + rememberRuntimeEnvironmentCompatibility(environmentId, entry) try { await check } catch (error) { - if (compatibleRuntimeEnvironments.get(environmentId) === check) { - compatibleRuntimeEnvironments.delete(environmentId) + if (runtimeCompatibilityChecks.get(environmentId) === entry) { + // Why: startup asks each remote for repos, groups, then folders; an + // offline runtime should pay one timeout during that burst, not three. + entry.failedAt = Date.now() } throw error } } +function getCachedRuntimeCompatibilityCheck( + environmentId: string, + options: { reuseRecentCompatibilityFailure?: boolean } +): RuntimeCompatibilityCacheEntry | null { + const cached = runtimeCompatibilityChecks.get(environmentId) + if (!cached) { + return null + } + if ( + cached.failedAt !== null && + Date.now() - cached.failedAt >= RECENT_RUNTIME_COMPATIBILITY_FAILURE_TTL_MS + ) { + runtimeCompatibilityChecks.delete(environmentId) + return null + } + if ( + cached.failedAt !== null && + (!cached.reuseFailure || options.reuseRecentCompatibilityFailure !== true) + ) { + return null + } + runtimeCompatibilityChecks.delete(environmentId) + runtimeCompatibilityChecks.set(environmentId, cached) + return cached +} + function rememberRuntimeEnvironmentCompatibility( environmentId: string, - check: Promise + entry: RuntimeCompatibilityCacheEntry ): void { // Why: saved/removed remote runtimes can churn through unique ids in long - // renderer sessions; successful compatibility promises should not grow forever. - compatibleRuntimeEnvironments.delete(environmentId) - compatibleRuntimeEnvironments.set(environmentId, check) - while (compatibleRuntimeEnvironments.size > RUNTIME_COMPATIBILITY_CACHE_MAX) { - const oldest = compatibleRuntimeEnvironments.keys().next().value + // renderer sessions; compatibility cache entries should not grow forever. + runtimeCompatibilityChecks.delete(environmentId) + runtimeCompatibilityChecks.set(environmentId, entry) + while (runtimeCompatibilityChecks.size > RUNTIME_COMPATIBILITY_CACHE_MAX) { + const oldest = runtimeCompatibilityChecks.keys().next().value if (oldest === undefined) { break } - compatibleRuntimeEnvironments.delete(oldest) + runtimeCompatibilityChecks.delete(oldest) } } export function clearRuntimeCompatibilityCache(environmentId?: string | null): void { const trimmed = environmentId?.trim() if (trimmed) { - compatibleRuntimeEnvironments.delete(trimmed) + runtimeCompatibilityChecks.delete(trimmed) return } - compatibleRuntimeEnvironments.clear() + runtimeCompatibilityChecks.clear() } export function markRuntimeEnvironmentCompatible(environmentId: string): void { @@ -146,7 +190,11 @@ export function markRuntimeEnvironmentCompatible(environmentId: string): void { if (!trimmed) { return } - rememberRuntimeEnvironmentCompatibility(trimmed, Promise.resolve()) + rememberRuntimeEnvironmentCompatibility(trimmed, { + check: Promise.resolve(), + failedAt: null, + reuseFailure: false + }) } export async function getRuntimeEnvironmentStatus( diff --git a/src/renderer/src/runtime/sync-runtime-graph-terminal-layout.test.ts b/src/renderer/src/runtime/sync-runtime-graph-terminal-layout.test.ts index fa86f2766..6095f4e18 100644 --- a/src/renderer/src/runtime/sync-runtime-graph-terminal-layout.test.ts +++ b/src/renderer/src/runtime/sync-runtime-graph-terminal-layout.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: this file keeps terminal session publication - * fixtures together so split-pane and split-tab parity assertions do not drift. */ import { describe, expect, it } from 'vitest' import { buildMobileSessionTabSnapshots } from './sync-runtime-graph' import type { AppState } from '../store/types' diff --git a/src/renderer/src/store/slices/agent-status-retained-leak.test.ts b/src/renderer/src/store/slices/agent-status-retained-leak.test.ts new file mode 100644 index 000000000..2259af3cf --- /dev/null +++ b/src/renderer/src/store/slices/agent-status-retained-leak.test.ts @@ -0,0 +1,126 @@ +/** + * Memory-leak regression: retainedAgentsByPaneKey must stay bounded. + * + * `retainedAgentsByPaneKey` is a Record keyed by ephemeral paneKey + * (`${tabId}:${leafId}`, where leafId is a fresh UUID minted per pane and never + * reused). Every agent that finishes and then vanishes from the live map is + * snapshotted here via `retainAgents`. Each snapshot is a full RetainedAgentEntry + * — an AgentStatusEntry (which carries an up-to-8KB lastAssistantMessage, an + * up-to-16KB interactivePrompt, a prompt, and up to 20 stateHistory rows) plus a + * full TerminalTab snapshot. + * + * Before the fix, `retainAgents` only ever wrote entries and never capped them, + * so the map grew monotonically with the number of distinct completed-agent + * paneKeys observed. The only removal paths are worktree removal + * (`pruneRetainedAgents`) and explicit user dismissal — neither of which runs + * while a long-lived worktree stays open. Under a multi-hour multi-agent / + * orchestration session (sub-agents complete continuously), this large-payload + * accumulator is the dominant driver of the renderer JS-heap OOM seen in the + * Windows crash bundles (heap climbing to the 3586 MB old-space limit). + * + * The fix caps it to MAX_RETAINED_AGENTS, evicting the oldest-retained keys + * (insertion order == retention order, so the newest completions survive). + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { TerminalTab } from '../../../../shared/types' +import type { RetainedAgentEntry } from './agent-status' +import { createTestStore } from './store-test-helpers' + +// MAX_RETAINED_AGENTS is module-private; mirror its value here. +const MAX_RETAINED_AGENTS = 500 + +// Approximate the worst-case per-entry payload the production type permits, so +// the leak's byte weight (not just entry count) is visible in the assertions. +const BIG_ASSISTANT_MESSAGE = 'a'.repeat(8 * 1024) +const BIG_INTERACTIVE_PROMPT = 'q'.repeat(16 * 1024) + +function makeRetained(index: number, worktreeId = 'wt-x'): RetainedAgentEntry { + const paneKey = `tab-${index}:leaf-${index}` + const entry: AgentStatusEntry = { + state: 'done', + prompt: `prompt ${index}`, + updatedAt: index, + stateStartedAt: index, + paneKey, + stateHistory: [], + lastAssistantMessage: BIG_ASSISTANT_MESSAGE, + interactivePrompt: BIG_INTERACTIVE_PROMPT + } + return { + entry, + worktreeId, + tab: { id: `tab-${index}`, title: 'claude' } as unknown as TerminalTab, + agentType: 'claude', + startedAt: index + } +} + +describe('retainedAgentsByPaneKey stays bounded (leak regression)', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('caps retainedAgentsByPaneKey and keeps the most recently retained keys', () => { + const store = createTestStore() + + // Drive the production retention path with more distinct ephemeral paneKeys + // than the cap allows — one call per completion, as production does. + const total = MAX_RETAINED_AGENTS + 200 + for (let i = 0; i < total; i++) { + store.getState().retainAgents([makeRetained(i)]) + } + + const retained = store.getState().retainedAgentsByPaneKey + // Bounded — not `total`. Without the cap this is MAX_RETAINED_AGENTS + 200. + expect(Object.keys(retained)).toHaveLength(MAX_RETAINED_AGENTS) + + // The newest completions survive; the oldest are evicted. + expect(retained[`tab-${total - 1}:leaf-${total - 1}`]).toBeDefined() + expect(retained['tab-0:leaf-0']).toBeUndefined() + // The exact eviction boundary: everything before (total - cap) is gone. + expect( + retained[`tab-${total - MAX_RETAINED_AGENTS - 1}:leaf-${total - MAX_RETAINED_AGENTS - 1}`] + ).toBeUndefined() + expect( + retained[`tab-${total - MAX_RETAINED_AGENTS}:leaf-${total - MAX_RETAINED_AGENTS}`] + ).toBeDefined() + }) + + it('caps even when many completions are retained in a single batch', () => { + const store = createTestStore() + const total = MAX_RETAINED_AGENTS + 50 + const batch = Array.from({ length: total }, (_, i) => makeRetained(i)) + + store.getState().retainAgents(batch) + + const retained = store.getState().retainedAgentsByPaneKey + expect(Object.keys(retained)).toHaveLength(MAX_RETAINED_AGENTS) + expect(retained[`tab-${total - 1}:leaf-${total - 1}`]).toBeDefined() + expect(retained['tab-0:leaf-0']).toBeUndefined() + }) + + it('does not evict anything while under the cap', () => { + const store = createTestStore() + for (let i = 0; i < MAX_RETAINED_AGENTS; i++) { + store.getState().retainAgents([makeRetained(i)]) + } + const retained = store.getState().retainedAgentsByPaneKey + expect(Object.keys(retained)).toHaveLength(MAX_RETAINED_AGENTS) + expect(retained['tab-0:leaf-0']).toBeDefined() + }) + + it('re-retaining an existing paneKey overwrites in place and never grows the count', () => { + const store = createTestStore() + const first = makeRetained(0) + store.getState().retainAgents([first]) + // Same paneKey, fresh snapshot (e.g. a later status update for the same pane). + const updated = makeRetained(0) + updated.entry.prompt = 'updated' + store.getState().retainAgents([updated]) + + const retained = store.getState().retainedAgentsByPaneKey + expect(Object.keys(retained)).toHaveLength(1) + expect(retained['tab-0:leaf-0'].entry.prompt).toBe('updated') + }) +}) diff --git a/src/renderer/src/store/slices/agent-status.ts b/src/renderer/src/store/slices/agent-status.ts index 855790fe4..1ec81165c 100644 --- a/src/renderer/src/store/slices/agent-status.ts +++ b/src/renderer/src/store/slices/agent-status.ts @@ -215,6 +215,32 @@ export type AgentStatusSlice = { clearRetentionSuppressedPaneKeys: (paneKeys: string[]) => void } +// Why: retainedAgentsByPaneKey snapshots a completed agent (a full +// AgentStatusEntry — up to ~24KB of prompt/message text — plus a TerminalTab) +// per ephemeral paneKey. paneKeys never recur, and the map is pruned only on +// worktree removal or manual dismissal, so a long-lived worktree in a busy +// multi-agent session grows it without bound — the dominant driver of the +// renderer JS-heap OOM. Cap by insertion order (== retention order), evicting +// the oldest completions first so the newest — the ones a user is most likely +// to still care about — always survive. Evicted rows just stop showing in the +// recently-completed overlay. +const MAX_RETAINED_AGENTS = 500 + +function capRetainedAgents( + retained: Record, + maxEntries = MAX_RETAINED_AGENTS +): Record { + const keys = Object.keys(retained) + if (keys.length <= maxEntries) { + return retained + } + const capped: Record = {} + for (const key of keys.slice(keys.length - maxEntries)) { + capped[key] = retained[key] + } + return capped +} + function paneKeyMatchesAnyTabPrefix(paneKey: string, tabPrefixes: string[]): boolean { for (const prefix of tabPrefixes) { if (paneKey.startsWith(prefix)) { @@ -2147,7 +2173,10 @@ export const createAgentStatusSlice: StateCreator void deleteBrowserPageAnnotation: (pageId: string, annotationId: string) => void clearBrowserPageAnnotations: (pageId: string) => void - hydrateBrowserSession: (session: WorkspaceSessionState) => void + hydrateBrowserSession: ( + session: WorkspaceSessionState, + options?: WorkspaceSessionHydrationOptions + ) => void switchBrowserTabProfile: ( workspaceId: string, profileId: string | null, @@ -1504,7 +1511,7 @@ export const createBrowserSlice: StateCreator = return { browserAnnotationsByPageId: nextByPageId } }), - hydrateBrowserSession: (session) => { + hydrateBrowserSession: (session, options) => { const persistedTabsByWorktree = session.browserTabsByWorktree ?? {} const currentState = get() const validWorktreeIdsForCleanup = new Set( @@ -1516,6 +1523,7 @@ export const createBrowserSlice: StateCreator = for (const workspace of currentState.folderWorkspaces) { validWorktreeIdsForCleanup.add(folderWorkspaceKey(workspace.id)) } + addAdditionalValidWorkspaceKeys(validWorktreeIdsForCleanup, options) // Why: mirror closeBrowserTab's contract — reducers are pure, imperative // side effects bracket them. Compute dropped workspaces first, destroy @@ -1548,6 +1556,7 @@ export const createBrowserSlice: StateCreator = for (const workspace of s.folderWorkspaces) { validWorktreeIds.add(folderWorkspaceKey(workspace.id)) } + addAdditionalValidWorkspaceKeys(validWorktreeIds, options) const browserTabsByWorktree: Record = {} const browserPagesByWorkspace: Record = {} diff --git a/src/renderer/src/store/slices/bulk-worktree-purge-terminal-maps-leak.test.ts b/src/renderer/src/store/slices/bulk-worktree-purge-terminal-maps-leak.test.ts new file mode 100644 index 000000000..726e2b58f --- /dev/null +++ b/src/renderer/src/store/slices/bulk-worktree-purge-terminal-maps-leak.test.ts @@ -0,0 +1,127 @@ +/** + * Memory-leak regression: seven per-tab / per-pty terminal+agent store maps were + * evicted on the SINGLE removeWorktree path (via closeTab / shutdownWorktreeTerminals) + * but NOT on the BULK path — `buildWorktreePurgeState`, reached by removeProject, the + * external-worktree-removal authoritative-scan reconcile, and the hydration-stale + * reconcile. That path runs no terminal teardown, so before the fix each map stranded + * an entry per tab/pane of every externally-removed worktree for the renderer's whole + * session (unbounded across add/remove-repo cycles). tabId and ptyId are ephemeral, + * never-reused key spaces. + * + * Tab-keyed (evicted via the doomed-tab set): + * lastKnownRelayPtyIdByTabId, pendingInitialCwdByTabId, + * pendingIssueCommandSplitByTabId, pendingSetupSplitByTabId, pendingStartupByTabId + * Pty-keyed (evicted via the doomed-pty set derived from ptyIdsByTabId): + * codexRestartNoticeByPtyId, migrationUnsupportedByPtyId + */ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import type * as AgentStatusModule from '@/lib/agent-status' + +vi.mock('sonner', () => ({ + toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } +})) + +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + restorePtyDataHandlersAfterFailedShutdown: vi.fn(), + unregisterPtyDataHandlers: vi.fn() +})) + +vi.mock('@/lib/agent-status', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } +}) + +const mockApi = { + worktrees: { list: vi.fn().mockResolvedValue([]), remove: vi.fn().mockResolvedValue(undefined) }, + pty: { kill: vi.fn().mockResolvedValue(undefined) } +} + +// @ts-expect-error -- minimal window.api stub for the store under test +globalThis.window = { api: mockApi } + +import { createTestStore, seedStore, makeWorktree, makeTab } from './store-test-helpers' + +const WT1 = 'repo1::/path/wt1' +const WT2 = 'repo1::/path/wt2' +const TAB1 = 'tab-wt1' +const TAB2 = 'tab-wt2' +const PTY1 = 'pty-wt1' +const PTY2 = 'pty-wt2' + +function seedMaps(store: ReturnType): void { + seedStore(store, { + worktreesByRepo: { + repo1: [ + makeWorktree({ id: WT1, repoId: 'repo1', path: '/path/wt1' }), + makeWorktree({ id: WT2, repoId: 'repo1', path: '/path/wt2' }) + ] + }, + tabsByWorktree: { + [WT1]: [makeTab({ id: TAB1, worktreeId: WT1, ptyId: PTY1 })], + [WT2]: [makeTab({ id: TAB2, worktreeId: WT2, ptyId: PTY2 })] + }, + // Drives the doomed-ptyId derivation in buildWorktreePurgeState. + ptyIdsByTabId: { [TAB1]: [PTY1], [TAB2]: [PTY2] }, + lastKnownRelayPtyIdByTabId: { [TAB1]: PTY1, [TAB2]: PTY2 }, + pendingInitialCwdByTabId: { [TAB1]: '/path/wt1', [TAB2]: '/path/wt2' }, + pendingIssueCommandSplitByTabId: { + [TAB1]: { command: 'a' }, + [TAB2]: { command: 'b' } + }, + pendingSetupSplitByTabId: { + [TAB1]: { command: 'setup-a', direction: 'vertical' }, + [TAB2]: { command: 'setup-b', direction: 'vertical' } + }, + pendingStartupByTabId: { [TAB1]: { command: 'start-a' }, [TAB2]: { command: 'start-b' } }, + codexRestartNoticeByPtyId: { + [PTY1]: { previousAccountLabel: 'a1', nextAccountLabel: 'a2' }, + [PTY2]: { previousAccountLabel: 'b1', nextAccountLabel: 'b2' } + }, + migrationUnsupportedByPtyId: { + [PTY1]: { + ptyId: PTY1, + paneKey: `${TAB1}:leaf-1`, + reason: 'legacy-numeric-pane-key', + source: 'local', + updatedAt: 1 + }, + [PTY2]: { + ptyId: PTY2, + paneKey: `${TAB2}:leaf-1`, + reason: 'legacy-numeric-pane-key', + source: 'local', + updatedAt: 2 + } + } + }) +} + +describe('bulk worktree purge evicts the per-tab/per-pty terminal maps it previously leaked', () => { + beforeEach(() => vi.clearAllMocks()) + + it('drops removed worktree entries (both tabId- and ptyId-keyed), retains survivors', () => { + const store = createTestStore() + seedMaps(store) + + store.getState().purgeWorktreeTerminalState([WT1]) + const s = store.getState() + + // Removed worktree's tab/pty: every map evicted. + expect(s.lastKnownRelayPtyIdByTabId[TAB1]).toBeUndefined() + expect(s.pendingInitialCwdByTabId[TAB1]).toBeUndefined() + expect(s.pendingIssueCommandSplitByTabId[TAB1]).toBeUndefined() + expect(s.pendingSetupSplitByTabId[TAB1]).toBeUndefined() + expect(s.pendingStartupByTabId[TAB1]).toBeUndefined() + expect(s.codexRestartNoticeByPtyId[PTY1]).toBeUndefined() + expect(s.migrationUnsupportedByPtyId[PTY1]).toBeUndefined() + + // Surviving worktree's tab/pty: every entry retained (no over-eviction). + expect(s.lastKnownRelayPtyIdByTabId[TAB2]).toBe(PTY2) + expect(s.pendingInitialCwdByTabId[TAB2]).toBe('/path/wt2') + expect(s.pendingIssueCommandSplitByTabId[TAB2]).toEqual({ command: 'b' }) + expect(s.pendingSetupSplitByTabId[TAB2]).toEqual({ command: 'setup-b', direction: 'vertical' }) + expect(s.pendingStartupByTabId[TAB2]).toEqual({ command: 'start-b' }) + expect(s.codexRestartNoticeByPtyId[PTY2]).toBeDefined() + expect(s.migrationUnsupportedByPtyId[PTY2]).toBeDefined() + }) +}) diff --git a/src/renderer/src/store/slices/diffComments.test.ts b/src/renderer/src/store/slices/diffComments.test.ts index 3726098e8..e4862f129 100644 --- a/src/renderer/src/store/slices/diffComments.test.ts +++ b/src/renderer/src/store/slices/diffComments.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: this test file owns the diff-comments -slice's persistence, runtime routing, rollback, and compatibility behavior. */ import { describe, it, expect, vi, beforeEach } from 'vitest' import { create } from 'zustand' import type { AppState } from '../types' diff --git a/src/renderer/src/store/slices/editor.ts b/src/renderer/src/store/slices/editor.ts index 805a2f801..5b451cbbc 100644 --- a/src/renderer/src/store/slices/editor.ts +++ b/src/renderer/src/store/slices/editor.ts @@ -62,6 +62,10 @@ import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client' import { notifyHostOfMirroredEditorClose } from '@/runtime/close-mirrored-editor-tab' import { findWorktreeById, getRepoIdFromWorktreeId } from './worktree-helpers' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' +import { + addAdditionalValidWorkspaceKeys, + type WorkspaceSessionHydrationOptions +} from '@/lib/workspace-session-hydration-keys' import { createUntitledMarkdownFileWithTemplateSelection } from '@/lib/create-untitled-markdown' import { extractIpcErrorMessage } from '@/lib/ipc-error' import { translate } from '@/i18n/i18n' @@ -711,7 +715,10 @@ export type EditorSlice = { setPendingEditorReveal: (reveal: PendingEditorReveal | null) => void // Session hydration — restore editor files from persisted workspace session - hydrateEditorSession: (session: WorkspaceSessionState) => void + hydrateEditorSession: ( + session: WorkspaceSessionState, + options?: WorkspaceSessionHydrationOptions + ) => void } function openWorkspaceEditorItem( @@ -4222,7 +4229,7 @@ export const createEditorSlice: StateCreator = (s // Why: only edit-mode files are restored — diffs and conflict views depend on // transient git state that may have changed between sessions. Restoring them // would show stale data or fail to load entirely. - hydrateEditorSession: (session) => { + hydrateEditorSession: (session, options) => { set((s) => { const openFilesByWorktree = session.openFilesByWorktree ?? {} const persistedActiveFileIdByWorktree = session.activeFileIdByWorktree ?? {} @@ -4241,6 +4248,7 @@ export const createEditorSlice: StateCreator = (s for (const workspace of s.folderWorkspaces) { validWorktreeIds.add(folderWorkspaceKey(workspace.id)) } + addAdditionalValidWorkspaceKeys(validWorktreeIds, options) const openFiles: OpenFile[] = [] const editorDrafts: Record = {} diff --git a/src/renderer/src/store/slices/github.test.ts b/src/renderer/src/store/slices/github.test.ts index e17be5050..8cbe73b4f 100644 --- a/src/renderer/src/store/slices/github.test.ts +++ b/src/renderer/src/store/slices/github.test.ts @@ -127,6 +127,49 @@ function makePRRefreshWorktree(overrides: Partial = {}): Worktree { } } +function installLinkedPRClearStub( + store: ReturnType, + args: { + repoId: string + repoPath: string + branch: string + worktree: Worktree + } +) { + const cacheKey = `${args.repoId}::${args.branch}` + const updateWorktreeMeta = vi.fn( + async ( + worktreeId: string, + updates: Parameters[1], + options?: Parameters[2] + ) => { + const currentWorktree = store + .getState() + .worktreesByRepo[args.repoId]?.find((worktree) => worktree.id === worktreeId) + if (options?.shouldApply && !options.shouldApply(currentWorktree)) { + return + } + store.setState((state) => { + const nextWorktrees = { + ...state.worktreesByRepo, + [args.repoId]: (state.worktreesByRepo[args.repoId] ?? []).map((worktree) => + worktree.id === worktreeId ? { ...worktree, ...updates } : worktree + ) + } + const nextPRCache = { ...state.prCache } + delete nextPRCache[cacheKey] + return { worktreesByRepo: nextWorktrees, prCache: nextPRCache } as Partial + }) + } + ) + store.setState({ + repos: [{ id: args.repoId, path: args.repoPath, name: 'repo', kind: 'git' }], + worktreesByRepo: { [args.repoId]: [args.worktree] }, + updateWorktreeMeta + } as unknown as Partial) + return updateWorktreeMeta +} + function githubSourceContext( hostId: TaskSourceContext['hostId'], repoId = 'source-repo-id' @@ -2133,6 +2176,421 @@ describe('createGitHubSlice.fetchPRForBranch', () => { expect(store.getState().hostedReviewCache[hostedReviewCacheKey]).toBeUndefined() }) + it('clears a linked merged PR when the resolved PR definitively diverged from the request head', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/new-work' + const worktreeId = 'wt-diverged-linked-pr' + const worktree = makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree + }) + mockApi.gh.refreshPRNow.mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + headDivergedFromMergedPRAtOid: 'current-head' + }), + fetchedAt: 2 + }) + + await expect( + store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + ).resolves.toMatchObject({ number: 12 }) + + expect(updateWorktreeMeta).toHaveBeenCalledWith( + worktreeId, + { linkedPR: null }, + { shouldApply: expect.any(Function) } + ) + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBeNull() + expect(store.getState().prCache[`${repoId}::${branch}`]).toBeUndefined() + }) + + it('clears a linked merged PR on a fresh cache hit that already carries a head-scoped divergence signal', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/cached-diverged' + const worktreeId = 'wt-cached-diverged' + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + }) + store.setState({ + prCache: { + [`${repoId}::${branch}`]: { + data: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + headDivergedFromMergedPRAtOid: 'current-head' + }), + fetchedAt: Date.now() + } + } + } as unknown as Partial) + + const result = await store.getState().fetchPRForBranch(repoPath, branch, { + repoId, + worktreeId, + linkedPRNumber: 12 + }) + + expect(result).toMatchObject({ number: 12 }) + expect(mockApi.gh.refreshPRNow).not.toHaveBeenCalled() + expect(updateWorktreeMeta).toHaveBeenCalledWith( + worktreeId, + { linkedPR: null }, + { shouldApply: expect.any(Function) } + ) + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBeNull() + }) + + it('does not clear a linked merged PR when the request head equals the PR head', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/at-pr-head' + const worktreeId = 'wt-at-pr-head' + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'same-head', + linkedPR: 12 + }) + }) + mockApi.gh.refreshPRNow.mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'same-head', + headDivergedFromMergedPRAtOid: 'same-head' + }), + fetchedAt: 2 + }) + + await store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + + expect(updateWorktreeMeta).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBe(12) + }) + + it('does not clear a linked merged PR when the request head is confirmed contained', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/contained' + const worktreeId = 'wt-contained' + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'contained-head', + linkedPR: 12 + }) + }) + mockApi.gh.refreshPRNow.mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + confirmedContainedHeadOid: 'contained-head', + headDivergedFromMergedPRAtOid: 'contained-head' + }), + fetchedAt: 2 + }) + + await store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + + expect(updateWorktreeMeta).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBe(12) + }) + + it('does not clear a linked open PR even when a divergence bit is present', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/open-pr' + const worktreeId = 'wt-open-pr' + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + }) + mockApi.gh.refreshPRNow.mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ + number: 12, + state: 'open', + headSha: 'pr-head', + headDivergedFromMergedPRAtOid: 'current-head' + }), + fetchedAt: 2 + }) + + await store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + + expect(updateWorktreeMeta).not.toHaveBeenCalled() + }) + + it('does not clear a linked PR on a null PR result', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/null-pr' + const worktreeId = 'wt-null-pr' + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + }) + mockApi.gh.refreshPRNow.mockResolvedValueOnce({ kind: 'no-pr', fetchedAt: 2 }) + + await store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + + expect(updateWorktreeMeta).not.toHaveBeenCalled() + }) + + it('does not clear when divergence is unset even if containment does not match the head', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/unknown-probe' + const worktreeId = 'wt-unknown-probe' + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + }) + mockApi.gh.refreshPRNow.mockResolvedValueOnce({ + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + confirmedContainedHeadOid: 'other-head' + }), + fetchedAt: 2 + }) + + await store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + + expect(updateWorktreeMeta).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBe(12) + }) + + it('does not clear when the linked PR number changed before the lookup completed', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/relinked' + const worktreeId = 'wt-relinked' + let resolveRefresh: ( + value: Awaited> + ) => void = () => {} + const refresh = new Promise>>((resolve) => { + resolveRefresh = resolve + }) + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + }) + mockApi.gh.refreshPRNow.mockReturnValueOnce(refresh) + + const request = store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + store.setState({ + worktreesByRepo: { + [repoId]: [ + makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 13 + }) + ] + } + } as unknown as Partial) + resolveRefresh({ + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + headDivergedFromMergedPRAtOid: 'current-head' + }), + fetchedAt: 2 + }) + + await expect(request).resolves.toBeNull() + expect(updateWorktreeMeta).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBe(13) + }) + + it('does not clear when the worktree head moved after the lookup started', async () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/head-moved' + const worktreeId = 'wt-head-moved' + let resolveRefresh: ( + value: Awaited> + ) => void = () => {} + const refresh = new Promise>>((resolve) => { + resolveRefresh = resolve + }) + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'request-head', + linkedPR: 12 + }) + }) + mockApi.gh.refreshPRNow.mockReturnValueOnce(refresh) + + const request = store.getState().fetchPRForBranch(repoPath, branch, { + force: true, + repoId, + worktreeId, + linkedPRNumber: 12 + }) + store.setState({ + worktreesByRepo: { + [repoId]: [ + makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'new-head', + linkedPR: 12 + }) + ] + } + } as unknown as Partial) + resolveRefresh({ + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + headDivergedFromMergedPRAtOid: 'request-head' + }), + fetchedAt: 2 + }) + + await expect(request).resolves.toMatchObject({ number: 12 }) + expect(updateWorktreeMeta).toHaveBeenCalledWith( + worktreeId, + { linkedPR: null }, + { shouldApply: expect.any(Function) } + ) + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBe(12) + expect(store.getState().prCache[`${repoId}::${branch}`]).toMatchObject({ + data: expect.objectContaining({ number: 12 }) + }) + }) + it('preserves cached PR data when a forced coordinator refresh errors', async () => { const store = createTestStore() const repoPath = '/repo' @@ -2547,6 +3005,192 @@ describe('createGitHubSlice.fetchPRForBranch', () => { }) }) + it('clears a linked merged PR from a coordinator refresh event when the request head diverged', () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/coordinator-diverged' + const worktreeId = 'wt-coordinator-diverged' + const cacheKey = `${repoId}::${branch}` + const worktree = makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree + }) + + store.getState().applyGitHubPRRefreshEvent({ + sequence: 1, + reason: 'swr', + aliases: [ + { + cacheKey, + repoPath, + repoId, + branch, + worktreeId, + linkedPRNumber: 12, + currentHeadOid: 'current-head' + } + ], + outcome: { + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + headDivergedFromMergedPRAtOid: 'current-head' + }), + fetchedAt: 2 + } + }) + + expect(updateWorktreeMeta).toHaveBeenCalledWith( + worktreeId, + { linkedPR: null }, + { shouldApply: expect.any(Function) } + ) + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBeNull() + }) + + it('does not clear a linked merged PR from a coordinator refresh event without a request head', () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const branch = 'feature/coordinator-no-head' + const worktreeId = 'wt-coordinator-no-head' + const cacheKey = `${repoId}::${branch}` + const updateWorktreeMeta = installLinkedPRClearStub(store, { + repoId, + repoPath, + branch, + worktree: makePRRefreshWorktree({ + id: worktreeId, + repoId, + branch, + head: 'current-head', + linkedPR: 12 + }) + }) + + store.getState().applyGitHubPRRefreshEvent({ + sequence: 1, + reason: 'swr', + aliases: [ + { cacheKey, repoPath, repoId, branch, worktreeId, linkedPRNumber: 12, currentHeadOid: null } + ], + outcome: { + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + headDivergedFromMergedPRAtOid: 'current-head' + }), + fetchedAt: 2 + } + }) + + expect(updateWorktreeMeta).not.toHaveBeenCalled() + expect(store.getState().worktreesByRepo[repoId]?.[0]?.linkedPR).toBe(12) + }) + + it('clears only the diverged worktree when a PR-number-coalesced event fans out to sibling aliases', () => { + const store = createTestStore() + const repoPath = '/repo' + const repoId = 'repo-1' + const worktreeA = makePRRefreshWorktree({ + id: 'wt-a', + repoId, + branch: 'feature/a', + head: 'head-a', + linkedPR: 12 + }) + const worktreeB = makePRRefreshWorktree({ + id: 'wt-b', + repoId, + branch: 'feature/b', + head: 'head-b', + linkedPR: 12 + }) + const updateWorktreeMeta = vi.fn( + async ( + worktreeId: string, + updates: Parameters[1], + options?: Parameters[2] + ) => { + const current = store + .getState() + .worktreesByRepo[repoId]?.find((worktree) => worktree.id === worktreeId) + if (options?.shouldApply && !options.shouldApply(current)) { + return + } + store.setState((state) => ({ + worktreesByRepo: { + ...state.worktreesByRepo, + [repoId]: (state.worktreesByRepo[repoId] ?? []).map((worktree) => + worktree.id === worktreeId ? { ...worktree, ...updates } : worktree + ) + } + })) + } + ) + store.setState({ + repos: [{ id: repoId, path: repoPath, name: 'repo', kind: 'git' }], + worktreesByRepo: { [repoId]: [worktreeA, worktreeB] }, + updateWorktreeMeta + } as unknown as Partial) + + // The coordinator coalesces linked PR refreshes by PR number, so one probe + // (worktree A's head) is broadcast to both aliases. Only A actually diverged; + // B is still on a contained commit and must keep its link. + store.getState().applyGitHubPRRefreshEvent({ + sequence: 1, + reason: 'swr', + aliases: [ + { + cacheKey: `${repoId}::feature/a`, + repoPath, + repoId, + branch: 'feature/a', + worktreeId: 'wt-a', + linkedPRNumber: 12, + currentHeadOid: 'head-a' + }, + { + cacheKey: `${repoId}::feature/b`, + repoPath, + repoId, + branch: 'feature/b', + worktreeId: 'wt-b', + linkedPRNumber: 12, + currentHeadOid: 'head-b' + } + ], + outcome: { + kind: 'found', + pr: makePR({ + number: 12, + state: 'merged', + headSha: 'merged-pr-head', + headDivergedFromMergedPRAtOid: 'head-a' + }), + fetchedAt: 2 + } + }) + + const worktrees = store.getState().worktreesByRepo[repoId] ?? [] + expect(worktrees.find((worktree) => worktree.id === 'wt-a')?.linkedPR).toBeNull() + expect(worktrees.find((worktree) => worktree.id === 'wt-b')?.linkedPR).toBe(12) + }) + it('preserves visible cached PR data when a fallback refresh event misses', () => { const store = createTestStore() const repoPath = '/repo' diff --git a/src/renderer/src/store/slices/github.ts b/src/renderer/src/store/slices/github.ts index 8478c5198..7f980ac6a 100644 --- a/src/renderer/src/store/slices/github.ts +++ b/src/renderer/src/store/slices/github.ts @@ -1005,6 +1005,44 @@ function isStaleExactLinkedPRLookup( return findWorktreeById(state, worktreeId)?.linkedPR !== linkedPRNumber } +function shouldClearDivergedLinkedMergedPR(args: { + pr: PRInfo | null + linkedPRNumber: number | null + requestHeadOid: string | null +}): boolean { + const { pr, linkedPRNumber, requestHeadOid } = args + return ( + linkedPRNumber != null && + requestHeadOid !== null && + pr?.number === linkedPRNumber && + pr.state === 'merged' && + // Head-scoped: only clear the worktree whose exact head diverged, so a + // PR-number-coalesced refresh broadcast cannot clear a sibling worktree that + // is still on the PR's line of work. + pr.headDivergedFromMergedPRAtOid === requestHeadOid && + pr.headSha !== requestHeadOid && + pr.confirmedContainedHeadOid !== requestHeadOid + ) +} + +function shouldApplyDivergedLinkedPRClear(args: { + worktree: Pick | undefined + linkedPRNumber: number + branch: string + requestHeadOid: string | null +}): boolean { + const { worktree, linkedPRNumber, branch, requestHeadOid } = args + return ( + Boolean(worktree) && + requestHeadOid !== null && + worktree?.linkedPR === linkedPRNumber && + worktree.branch.replace(/^refs\/heads\//, '') === branch && + worktree.head === requestHeadOid && + worktree.isBare !== true && + worktree.isArchived !== true + ) +} + function buildPRRefreshCandidate( state: AppState, worktree: Worktree, @@ -2801,6 +2839,10 @@ export const createGitHubSlice: StateCreator = (s } const counts = await Promise.all( repos.map(async (r) => { + // Why: same stampede cap as the item-fetch paths — without a slot, + // a 90-repo selection dispatches 90 concurrent count IPCs before the + // main-side rate-limit guard can see the first 403. + await acquireWorkItemSlot() try { const requestState = get() const repo = findRepoForGitHubOwner(requestState, r.repoId, r.path) @@ -2819,6 +2861,8 @@ export const createGitHubSlice: StateCreator = (s return await countGitHubWorkItemsForRepo(requestContext, { query: query || undefined }) } catch { return 0 + } finally { + releaseWorkItemSlot() } }) ) @@ -2923,6 +2967,38 @@ export const createGitHubSlice: StateCreator = (s const linkedRefetch = cached?.data === null && (linkedPRNumber !== null || fallbackPRNumber !== null) if (!options?.force && !linkedRefetch && isFresh(cached)) { + // Why: a fresh cache hit still carries the head-scoped divergence signal. + // If a prior clear was declined because the head moved mid-request and the + // worktree is now back on that diverged head, clear the durable link the + // cache would otherwise keep serving until it expires. + if ( + options?.worktreeId && + linkedPRNumber != null && + cached?.data?.headDivergedFromMergedPRAtOid != null + ) { + const currentHeadOid = findWorktreeById(get(), options.worktreeId)?.head ?? null + if ( + shouldClearDivergedLinkedMergedPR({ + pr: cached.data, + linkedPRNumber, + requestHeadOid: currentHeadOid + }) + ) { + void get().updateWorktreeMeta( + options.worktreeId, + { linkedPR: null }, + { + shouldApply: (worktree) => + shouldApplyDivergedLinkedPRClear({ + worktree, + linkedPRNumber, + branch, + requestHeadOid: currentHeadOid + }) + } + ) + } + } return cached.data } @@ -2953,6 +3029,7 @@ export const createGitHubSlice: StateCreator = (s const candidateWorktree = options?.worktreeId ? findWorktreeById(get(), options.worktreeId) : null + const requestHeadOid = candidateWorktree?.head ?? null const outcome = runtimeRepo ? await callRuntimeRpc( runtimeRepo.target, @@ -2961,7 +3038,7 @@ export const createGitHubSlice: StateCreator = (s repo: runtimeRepo.repo.id, branch, linkedPRNumber, - currentHeadOid: candidateWorktree?.head ?? null, + currentHeadOid: requestHeadOid, ...(fallbackPRNumber !== null ? { fallbackPRNumber, acceptMergedFallbackPR: fallbackPRSource !== null } : {}) @@ -2980,7 +3057,7 @@ export const createGitHubSlice: StateCreator = (s branch, cacheKey, worktreeId: options?.worktreeId, - currentHeadOid: candidateWorktree?.head ?? null, + currentHeadOid: requestHeadOid, linkedPRNumber, fallbackPRNumber, fallbackPRSource, @@ -3004,7 +3081,7 @@ export const createGitHubSlice: StateCreator = (s fallbackPRNumber, acceptMergedFallbackPR: fallbackPRNumber !== null && fallbackPRSource !== null, - currentHeadOid: candidateWorktree?.head ?? null + currentHeadOid: requestHeadOid }) .then((pr) => pr @@ -3054,6 +3131,27 @@ export const createGitHubSlice: StateCreator = (s if (didUpdatePRCache) { debouncedSaveCache(get()) } + if ( + options?.worktreeId && + linkedPRNumber != null && + shouldClearDivergedLinkedMergedPR({ pr, linkedPRNumber, requestHeadOid }) + ) { + // Why: only clear the durable link that produced this exact probe; + // branch/head drift means the stale result no longer owns the worktree. + void get().updateWorktreeMeta( + options.worktreeId, + { linkedPR: null }, + { + shouldApply: (worktree) => + shouldApplyDivergedLinkedPRClear({ + worktree, + linkedPRNumber, + branch, + requestHeadOid + }) + } + ) + } } if ( shouldPreserveExistingPRForFallbackMiss({ @@ -3773,6 +3871,34 @@ export const createGitHubSlice: StateCreator = (s }, applyGitHubPRRefreshEvent: (event) => { + // Why: the sidebar/left-list refresh for local repos flows through the main + // PR coordinator (not fetchPRForBranch), so it must run the same guarded + // clear when main stamps a merged linked PR whose head has diverged. + const divergedLinkedPRClears: { + worktreeId: string + linkedPRNumber: number + branch: string + requestHeadOid: string | null + }[] = [] + if (event.outcome?.kind === 'found') { + const pr = event.outcome.pr + for (const alias of event.aliases) { + const linkedPRNumber = alias.linkedPRNumber ?? null + const requestHeadOid = alias.currentHeadOid ?? null + if ( + alias.worktreeId && + linkedPRNumber != null && + shouldClearDivergedLinkedMergedPR({ pr, linkedPRNumber, requestHeadOid }) + ) { + divergedLinkedPRClears.push({ + worktreeId: alias.worktreeId, + linkedPRNumber, + branch: alias.branch, + requestHeadOid + }) + } + } + } let didUpdatePRCache = false set((s) => { const nextSequences = { ...s.prRefreshSequences } @@ -3969,6 +4095,21 @@ export const createGitHubSlice: StateCreator = (s if (didUpdatePRCache && event.outcome && event.outcome.kind !== 'upstream-error') { debouncedSaveCache(get()) } + for (const clear of divergedLinkedPRClears) { + void get().updateWorktreeMeta( + clear.worktreeId, + { linkedPR: null }, + { + shouldApply: (worktree) => + shouldApplyDivergedLinkedPRClear({ + worktree, + linkedPRNumber: clear.linkedPRNumber, + branch: clear.branch, + requestHeadOid: clear.requestHeadOid + }) + } + ) + } }, refreshAllGitHub: () => { diff --git a/src/renderer/src/store/slices/hosted-review.test.ts b/src/renderer/src/store/slices/hosted-review.test.ts index 7bd6c4f3d..b5a91fe6a 100644 --- a/src/renderer/src/store/slices/hosted-review.test.ts +++ b/src/renderer/src/store/slices/hosted-review.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: hosted-review tests cover runtime routing, -hinted cache revalidation, provider discovery, and PR cache reconciliation. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { create } from 'zustand' import type { AppState } from '../types' diff --git a/src/renderer/src/store/slices/new-markdown.test.ts b/src/renderer/src/store/slices/new-markdown.test.ts index 3a8d22eb7..b0f1ebb99 100644 --- a/src/renderer/src/store/slices/new-markdown.test.ts +++ b/src/renderer/src/store/slices/new-markdown.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines */ - import { createStore, type StoreApi } from 'zustand/vanilla' import { describe, expect, it } from 'vitest' import { createEditorSlice } from './editor' diff --git a/src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts b/src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts new file mode 100644 index 000000000..a47110ddf --- /dev/null +++ b/src/renderer/src/store/slices/repos-all-hosts-folder-workspaces.test.ts @@ -0,0 +1,265 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { createTestStore } from './store-test-helpers' +import type { FolderWorkspace, ProjectGroup, Repo } from '../../../../shared/types' +import { + createCompatibleRuntimeStatusResponseIfNeeded, + type RuntimeEnvironmentCallRequest +} from '../../runtime/runtime-compatibility-test-fixture' +import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' + +const localRepo: Repo = { + id: 'local-repo', + path: '/local', + displayName: 'Local', + badgeColor: '#000', + addedAt: 1 +} + +const remoteRepo: Repo = { + id: 'remote-repo', + path: '/srv/repo', + displayName: 'Remote', + badgeColor: '#000', + addedAt: 1 +} + +const localProjectGroup: ProjectGroup = { + id: 'local-group', + name: 'Local group', + parentPath: '/local', + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 +} + +const remoteProjectGroup: ProjectGroup = { + id: 'remote-group', + name: 'Remote group', + parentPath: '/srv', + parentGroupId: null, + createdFrom: 'manual', + tabOrder: 0, + isCollapsed: false, + color: null, + createdAt: 1, + updatedAt: 1 +} + +const localFolderWorkspace: FolderWorkspace = { + id: 'local-folder', + projectGroupId: 'local-group', + name: 'Local folder', + folderPath: '/local', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1, + createdAt: 1, + updatedAt: 1 +} + +const remoteFolderWorkspace: FolderWorkspace = { + id: 'remote-folder', + projectGroupId: 'remote-group', + name: 'Remote folder', + folderPath: '/srv', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 1, + createdAt: 1, + updatedAt: 1 +} + +const reposList = vi.fn() +const projectsList = vi.fn() +const listHostSetups = vi.fn() +const projectGroupsList = vi.fn() +const folderWorkspacesList = vi.fn() +const runtimeEnvironmentsList = vi.fn() +const runtimeEnvironmentCall = vi.fn() +const runtimeEnvironmentTransportCall = vi.fn() +const dispatchEventMock = vi.fn() + +beforeEach(() => { + clearRuntimeCompatibilityCacheForTests() + reposList.mockReset() + projectsList.mockReset() + listHostSetups.mockReset() + projectGroupsList.mockReset() + folderWorkspacesList.mockReset() + runtimeEnvironmentsList.mockReset() + runtimeEnvironmentCall.mockReset() + runtimeEnvironmentTransportCall.mockReset() + dispatchEventMock.mockReset() + + reposList.mockResolvedValue([localRepo]) + projectsList.mockResolvedValue([]) + listHostSetups.mockResolvedValue([]) + projectGroupsList.mockResolvedValue([localProjectGroup]) + folderWorkspacesList.mockResolvedValue([localFolderWorkspace]) + runtimeEnvironmentsList.mockResolvedValue([{ id: 'env-1', name: 'lobster' }]) + runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + if (args.method === 'repo.list') { + return { + id: 'rpc-repo-list', + ok: true, + result: { repos: [remoteRepo] }, + _meta: { runtimeId: 'runtime-remote' } + } + } + if (args.method === 'projectGroup.list') { + return { + id: 'rpc-project-group-list', + ok: true, + result: { groups: [remoteProjectGroup] }, + _meta: { runtimeId: 'runtime-remote' } + } + } + if (args.method === 'folderWorkspace.list') { + return { + id: 'rpc-folder-workspace-list', + ok: true, + result: { folderWorkspaces: [remoteFolderWorkspace] }, + _meta: { runtimeId: 'runtime-remote' } + } + } + return { + id: 'rpc-other', + ok: true, + result: { projects: [], setups: [] }, + _meta: { runtimeId: 'runtime-remote' } + } + }) + runtimeEnvironmentTransportCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) + }) + + vi.stubGlobal('window', { + api: { + repos: { list: reposList }, + projects: { list: projectsList, listHostSetups }, + projectGroups: { list: projectGroupsList }, + folderWorkspaces: { list: folderWorkspacesList }, + runtimeEnvironments: { + call: runtimeEnvironmentTransportCall, + list: runtimeEnvironmentsList + } + }, + dispatchEvent: dispatchEventMock + }) +}) + +describe('all-host folder workspace startup catalogs', () => { + it('loads project groups and folder workspaces for every host', async () => { + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + const restoredFolderKey = folderWorkspaceKey('remote-folder') + store.setState({ + restoredRuntimeHostIdByWorkspaceSessionKey: { + [restoredFolderKey]: 'runtime:env-1', + 'remote-repo::/srv/repo': 'runtime:env-1' + } + }) + + await store.getState().fetchProjectGroupsForAllHosts() + await store.getState().fetchFolderWorkspacesForAllHosts() + + expect(store.getState().projectGroups).toEqual([ + { ...localProjectGroup, executionHostId: 'local' }, + { ...remoteProjectGroup, executionHostId: 'runtime:env-1' } + ]) + expect(store.getState().folderWorkspaces.map((workspace) => workspace.id)).toEqual([ + 'local-folder', + 'remote-folder' + ]) + expect(store.getState().restoredRuntimeHostIdByWorkspaceSessionKey).toEqual({ + 'remote-repo::/srv/repo': 'runtime:env-1' + }) + + const missingGroupStore = createTestStore() + missingGroupStore.setState({ + settings: { activeRuntimeEnvironmentId: 'env-1' } as never, + projectGroups: [localProjectGroup], + restoredRuntimeHostIdByWorkspaceSessionKey: { [restoredFolderKey]: 'runtime:env-1' } + }) + await missingGroupStore.getState().fetchFolderWorkspacesForAllHosts() + + expect(missingGroupStore.getState().restoredRuntimeHostIdByWorkspaceSessionKey).toEqual({ + [restoredFolderKey]: 'runtime:env-1' + }) + }) + + it('keeps local project groups and folder workspaces when a runtime is unreachable', async () => { + runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { + if (args.method === 'projectGroup.list' || args.method === 'folderWorkspace.list') { + throw new Error('runtime_unreachable') + } + return { + id: 'rpc-other', + ok: true, + result: { repos: [], projects: [], setups: [] }, + _meta: { runtimeId: 'runtime-remote' } + } + }) + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + + await store.getState().fetchProjectGroupsForAllHosts() + await store.getState().fetchFolderWorkspacesForAllHosts() + + expect(store.getState().projectGroups).toEqual([ + { ...localProjectGroup, executionHostId: 'local' } + ]) + expect(store.getState().folderWorkspaces).toEqual([localFolderWorkspace]) + }) + + it('does not repeat offline runtime compatibility probes across startup catalog loads', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + runtimeEnvironmentTransportCall.mockResolvedValue({ + id: 'status', + ok: false, + error: { code: 'runtime_unavailable', message: 'offline' }, + _meta: { runtimeId: 'runtime-remote' } + }) + const store = createTestStore() + store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) + const restoredFolderKey = folderWorkspaceKey('remote-folder') + store.setState({ + restoredRuntimeHostIdByWorkspaceSessionKey: { + [restoredFolderKey]: 'runtime:env-1' + } + }) + + try { + await store.getState().fetchReposForAllHosts() + await store.getState().fetchProjectGroupsForAllHosts() + await store.getState().fetchFolderWorkspacesForAllHosts() + + expect(store.getState().repos).toEqual([{ ...localRepo, executionHostId: 'local' }]) + expect(store.getState().projectGroups).toEqual([ + { ...localProjectGroup, executionHostId: 'local' } + ]) + expect(store.getState().folderWorkspaces).toEqual([localFolderWorkspace]) + expect(runtimeEnvironmentTransportCall.mock.calls.map((call) => call[0].method)).toEqual([ + 'status.get' + ]) + expect(store.getState().restoredRuntimeHostIdByWorkspaceSessionKey).toEqual({ + [restoredFolderKey]: 'runtime:env-1' + }) + } finally { + warn.mockRestore() + } + }) +}) diff --git a/src/renderer/src/store/slices/repos-all-hosts.test.ts b/src/renderer/src/store/slices/repos-all-hosts.test.ts index 6471776b3..c54d0a7ed 100644 --- a/src/renderer/src/store/slices/repos-all-hosts.test.ts +++ b/src/renderer/src/store/slices/repos-all-hosts.test.ts @@ -12,6 +12,7 @@ import { type RuntimeEnvironmentCallRequest } from '../../runtime/runtime-compatibility-test-fixture' import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client' +import { getSetupScriptPromptDismissalKey } from '../../lib/setup-script-prompt' const localRepo: Repo = { id: 'local-repo', @@ -684,44 +685,109 @@ describe('fetchReposForAllHosts', () => { expect(store.getState().repos.map((repo) => repo.id)).toEqual(['local-repo']) }) - it('loads project groups and folder workspaces for every host', async () => { + it('can load only the local catalog slice for first-paint startup', async () => { const store = createTestStore() - store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) - await store.getState().fetchProjectGroupsForAllHosts() - await store.getState().fetchFolderWorkspacesForAllHosts() - - expect(store.getState().projectGroups).toEqual([ - { ...localProjectGroup, executionHostId: 'local' }, - { ...remoteProjectGroup, executionHostId: 'runtime:env-1' } - ]) - expect(store.getState().folderWorkspaces.map((workspace) => workspace.id)).toEqual([ - 'local-folder', - 'remote-folder' - ]) - }) - - it('keeps local project groups and folder workspaces when a runtime is unreachable', async () => { - runtimeEnvironmentCall.mockImplementation((args: RuntimeEnvironmentCallRequest) => { - if (args.method === 'projectGroup.list' || args.method === 'folderWorkspace.list') { - throw new Error('runtime_unreachable') - } - return { - id: 'rpc-other', - ok: true, - result: { repos: [], projects: [], setups: [] }, - _meta: { runtimeId: 'runtime-remote' } - } - }) - const store = createTestStore() - store.setState({ settings: { activeRuntimeEnvironmentId: 'env-1' } as never }) - - await store.getState().fetchProjectGroupsForAllHosts() - await store.getState().fetchFolderWorkspacesForAllHosts() + await store.getState().fetchReposForAllHosts({ remoteHosts: 'skip' }) + await store.getState().fetchProjectGroupsForAllHosts({ remoteHosts: 'skip' }) + await store.getState().fetchFolderWorkspacesForAllHosts({ remoteHosts: 'skip' }) + expect(runtimeEnvironmentsList).not.toHaveBeenCalled() + expect(runtimeEnvironmentTransportCall).not.toHaveBeenCalled() + expect(store.getState().repos).toEqual([{ ...localRepo, executionHostId: 'local' }]) expect(store.getState().projectGroups).toEqual([ { ...localProjectGroup, executionHostId: 'local' } ]) expect(store.getState().folderWorkspaces).toEqual([localFolderWorkspace]) }) + + it('preserves remote repo filters during first-paint local catalog refresh', async () => { + const store = createTestStore() + const remoteDismissalKey = getSetupScriptPromptDismissalKey('remote-repo') + const staleDismissalKey = getSetupScriptPromptDismissalKey('stale-repo') + store.setState({ + activeRepoId: 'remote-repo', + filterRepoIds: ['remote-repo', 'stale-repo'], + setupScriptPromptDismissedRepoIds: [remoteDismissalKey, staleDismissalKey], + trustedOrcaHooks: { + 'remote-repo': { all: { approvedAt: 1 } }, + 'stale-repo': { all: { approvedAt: 2 } } + } + }) + + await store.getState().fetchReposForAllHosts({ remoteHosts: 'skip' }) + + expect(store.getState().activeRepoId).toBe('remote-repo') + expect(store.getState().filterRepoIds).toEqual(['remote-repo', 'stale-repo']) + expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([ + remoteDismissalKey, + staleDismissalKey + ]) + expect(store.getState().trustedOrcaHooks).toEqual({ + 'remote-repo': { all: { approvedAt: 1 } }, + 'stale-repo': { all: { approvedAt: 2 } } + }) + + await store.getState().fetchReposForAllHosts() + + expect(store.getState().activeRepoId).toBe('remote-repo') + expect(store.getState().filterRepoIds).toEqual(['remote-repo']) + expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([remoteDismissalKey]) + expect(store.getState().trustedOrcaHooks).toEqual({ + 'remote-repo': { all: { approvedAt: 1 } } + }) + }) + + it('starts remote repo catalog loads concurrently for all configured runtimes', async () => { + runtimeEnvironmentsList.mockResolvedValue([ + { id: 'env-1', name: 'first' }, + { id: 'env-2', name: 'second' } + ]) + const firstStatusResolvers = new Map void>() + let resolveBothStatusProbes = (): void => {} + const bothStatusProbesStarted = new Promise((resolve, reject) => { + const timeout = setTimeout( + () => reject(new Error('Timed out waiting for both runtime probes')), + 1_000 + ) + resolveBothStatusProbes = () => { + clearTimeout(timeout) + resolve() + } + }) + runtimeEnvironmentTransportCall.mockImplementation( + (args: RuntimeEnvironmentCallRequest & { selector?: string }) => { + if ( + args.method === 'status.get' && + args.selector && + !firstStatusResolvers.has(args.selector) + ) { + return new Promise((resolve) => { + firstStatusResolvers.set(args.selector!, resolve) + if (firstStatusResolvers.size === 2) { + resolveBothStatusProbes() + } + }) + } + return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeEnvironmentCall(args) + } + ) + const store = createTestStore() + + const load = store.getState().fetchReposForAllHosts() + await bothStatusProbesStarted + + expect([...firstStatusResolvers.keys()].sort()).toEqual(['env-1', 'env-2']) + for (const resolve of firstStatusResolvers.values()) { + resolve(createCompatibleRuntimeStatusResponseIfNeeded({ method: 'status.get' })) + } + await load + + expect( + store + .getState() + .repos.map((repo) => `${repo.id}:${repo.executionHostId}`) + .sort() + ).toEqual(['local-repo:local', 'remote-repo:runtime:env-1', 'remote-repo:runtime:env-2']) + }) }) diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index b44f4e177..da0cb011d 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -49,6 +49,7 @@ import { getRepoIdFromWorktreeId } from '../../../../shared/worktree-id' import { selectProjectGroupRemovalTargets } from './project-group-removal-targets' import { reconcileFetchedRepos } from './repo-identity-reconcile' import { splitRepoReorderByHost } from './repo-reorder-host-split' +import { omitSparsePresetsForRepos } from './sparse-presets' import { findRepoForHost, getRepoHostIdentity, @@ -76,7 +77,7 @@ import { toSshExecutionHostId } from '../../../../shared/execution-host' import { cleanupEphemeralVmRuntimesForDeleted } from '@/lib/ephemeral-vm-runtime-cleanup' -import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import { folderWorkspaceKey, parseWorkspaceKey } from '../../../../shared/workspace-scope' import { formatFolderWorkspaceCreateError } from '../../lib/folder-workspace-path-status' const ERROR_TOAST_DURATION = 60_000 @@ -126,6 +127,10 @@ export type DeleteProjectGroupWithContainedProjectsOptions = { removeContainedProjects: boolean } +type AllHostCatalogFetchOptions = { + remoteHosts?: 'include' | 'skip' +} + export type ProjectRemovalFailure = { projectId: string reason: string @@ -830,6 +835,93 @@ function mergeFetchedFolderWorkspacesForHost({ return mergeById(preserved, fetched) } +type FetchedRepoCatalog = { + repos: Repo[] + projectHostSetupCompatibility: ProjectHostSetupProjection + hostId: ReturnType +} + +type FetchedProjectGroupCatalog = { + projectGroups: ProjectGroup[] + hostId: ReturnType +} + +type FetchedFolderWorkspaceCatalog = { + folderWorkspaces: FolderWorkspace[] + hostId: ReturnType +} + +async function fetchRepoCatalogForTarget( + target: ReturnType +): Promise { + const fetchedRepos = + target.kind === 'local' + ? await window.api.repos.list() + : ( + await callRuntimeRpc<{ repos: Repo[] }>(target, 'repo.list', undefined, { + timeoutMs: 15_000, + reuseRecentCompatibilityFailure: true + }) + ).repos + const repos = fetchedRepos.map((repo) => repoWithFetchedOwner(repo, target)) + return { + repos, + projectHostSetupCompatibility: await fetchProjectHostSetupCompatibility(target, repos), + hostId: getRuntimeTargetHostId(target) + } +} + +function mergeFetchedRepoCatalog( + catalog: FetchedRepoCatalog, + currentRepos: readonly Repo[] +): { + repos: Repo[] + projectCompatibility: Pick + hostId: ReturnType +} { + const repos = mergeFetchedReposForHost(currentRepos, catalog.repos, catalog.hostId) + const projectCompatibility = mergeProjectHostSetupCompatibility( + projectCompatibilityFromRepos(repos), + catalog.projectHostSetupCompatibility + ) + return { repos, projectCompatibility, hostId: catalog.hostId } +} + +function filterTrustedOrcaHooksToValidRepos( + trust: AppState['trustedOrcaHooks'], + validRepoIds: Set +): AppState['trustedOrcaHooks'] { + const next: AppState['trustedOrcaHooks'] = {} + for (const [repoId, entry] of Object.entries(trust)) { + if (validRepoIds.has(repoId)) { + next[repoId] = entry + } + } + return next +} + +function clearRestoredFolderWorkspaceSessionOwners( + owners: AppState['restoredRuntimeHostIdByWorkspaceSessionKey'] | undefined, + state: Pick +): AppState['restoredRuntimeHostIdByWorkspaceSessionKey'] { + const next: AppState['restoredRuntimeHostIdByWorkspaceSessionKey'] = {} + for (const [key, hostId] of Object.entries(owners ?? {})) { + const scope = parseWorkspaceKey(key) + if (scope?.type !== 'folder') { + next[key] = hostId + continue + } + const workspace = state.folderWorkspaces.find((entry) => entry.id === scope.folderWorkspaceId) + if (workspace && !state.projectGroups.some((group) => group.id === workspace.projectGroupId)) { + // Why: folder workspace ownership is resolved through its project group. + // If that catalog is still missing, keep the restored host owner so a + // session write before the next retry does not move runtime tabs local. + next[key] = hostId + } + } + return next +} + async function fetchReposForTarget( target: ReturnType, currentRepos: readonly Repo[] @@ -838,49 +930,87 @@ async function fetchReposForTarget( projectCompatibility: Pick hostId: ReturnType }> { - const fetchedRepos = - target.kind === 'local' - ? await window.api.repos.list() - : ( - await callRuntimeRpc<{ repos: Repo[] }>(target, 'repo.list', undefined, { - timeoutMs: 15_000 - }) - ).repos - const hostId = getRuntimeTargetHostId(target) - const repos = fetchedRepos.map((repo) => repoWithFetchedOwner(repo, target)) - const fetchedProjectCompatibility = await fetchProjectHostSetupCompatibility(target, repos) - const reconciledRepos = mergeFetchedReposForHost(currentRepos, repos, hostId) - const projectCompatibility = - target.kind === 'local' - ? mergeProjectHostSetupCompatibility( - projectCompatibilityFromRepos(reconciledRepos), - fetchedProjectCompatibility - ) - : mergeProjectHostSetupCompatibility( - projectCompatibilityFromRepos(reconciledRepos), - fetchedProjectCompatibility - ) + return mergeFetchedRepoCatalog(await fetchRepoCatalogForTarget(target), currentRepos) +} - return { repos: reconciledRepos, projectCompatibility, hostId } +async function fetchProjectGroupCatalogForTarget( + target: ReturnType +): Promise { + const fetchedGroups = + target.kind === 'local' + ? await window.api.projectGroups.list() + : ( + await callRuntimeRpc<{ groups: ProjectGroup[] }>(target, 'projectGroup.list', undefined, { + timeoutMs: 15_000, + reuseRecentCompatibilityFailure: true + }) + ).groups + return { + projectGroups: fetchedGroups.map((group) => projectGroupWithFetchedOwner(group, target)), + hostId: getRuntimeTargetHostId(target) + } +} + +function mergeFetchedProjectGroupCatalog( + catalog: FetchedProjectGroupCatalog, + currentProjectGroups: readonly ProjectGroup[] +): { projectGroups: ProjectGroup[]; hostId: ReturnType } { + return { + projectGroups: mergeFetchedProjectGroupsForHost( + currentProjectGroups, + catalog.projectGroups, + catalog.hostId + ), + hostId: catalog.hostId + } } async function fetchProjectGroupsForTarget( target: ReturnType, currentProjectGroups: readonly ProjectGroup[] ): Promise<{ projectGroups: ProjectGroup[]; hostId: ReturnType }> { - const fetchedGroups = + return mergeFetchedProjectGroupCatalog( + await fetchProjectGroupCatalogForTarget(target), + currentProjectGroups + ) +} + +async function fetchFolderWorkspaceCatalogForTarget( + target: ReturnType +): Promise { + const fetchedFolderWorkspaces = target.kind === 'local' - ? await window.api.projectGroups.list() + ? await window.api.folderWorkspaces.list() : ( - await callRuntimeRpc<{ groups: ProjectGroup[] }>(target, 'projectGroup.list', undefined, { - timeoutMs: 15_000 - }) - ).groups - const hostId = getRuntimeTargetHostId(target) - const ownedGroups = fetchedGroups.map((group) => projectGroupWithFetchedOwner(group, target)) + await callRuntimeRpc<{ folderWorkspaces: FolderWorkspace[] }>( + target, + 'folderWorkspace.list', + undefined, + { timeoutMs: 15_000, reuseRecentCompatibilityFailure: true } + ) + ).folderWorkspaces return { - projectGroups: mergeFetchedProjectGroupsForHost(currentProjectGroups, ownedGroups, hostId), - hostId + folderWorkspaces: fetchedFolderWorkspaces, + hostId: getRuntimeTargetHostId(target) + } +} + +function mergeFetchedFolderWorkspaceCatalog( + catalog: FetchedFolderWorkspaceCatalog, + currentFolderWorkspaces: readonly FolderWorkspace[], + projectGroups: readonly ProjectGroup[] +): { + folderWorkspaces: FolderWorkspace[] + hostId: ReturnType +} { + return { + folderWorkspaces: mergeFetchedFolderWorkspacesForHost({ + previous: currentFolderWorkspaces, + fetched: catalog.folderWorkspaces, + projectGroups, + hostId: catalog.hostId + }), + hostId: catalog.hostId } } @@ -892,27 +1022,11 @@ async function fetchFolderWorkspacesForTarget( folderWorkspaces: FolderWorkspace[] hostId: ReturnType }> { - const fetchedFolderWorkspaces = - target.kind === 'local' - ? await window.api.folderWorkspaces.list() - : ( - await callRuntimeRpc<{ folderWorkspaces: FolderWorkspace[] }>( - target, - 'folderWorkspace.list', - undefined, - { timeoutMs: 15_000 } - ) - ).folderWorkspaces - const hostId = getRuntimeTargetHostId(target) - return { - folderWorkspaces: mergeFetchedFolderWorkspacesForHost({ - previous: currentFolderWorkspaces, - fetched: fetchedFolderWorkspaces, - projectGroups, - hostId - }), - hostId - } + return mergeFetchedFolderWorkspaceCatalog( + await fetchFolderWorkspaceCatalogForTarget(target), + currentFolderWorkspaces, + projectGroups + ) } async function listRuntimeEnvironmentsForAllHostLoad(): Promise<{ id: string }[]> { @@ -1155,12 +1269,12 @@ export type RepoSlice = { // Monotonic sequence so an overlapping fetchRepos can drop its own stale result (#7020). reposFetchGeneration: number fetchRepos: () => Promise - fetchReposForAllHosts: () => Promise + fetchReposForAllHosts: (options?: AllHostCatalogFetchOptions) => Promise fetchRuntimeEnvironmentRepos: (environmentId: string) => Promise fetchProjectGroups: () => Promise - fetchProjectGroupsForAllHosts: () => Promise + fetchProjectGroupsForAllHosts: (options?: AllHostCatalogFetchOptions) => Promise fetchFolderWorkspaces: () => Promise - fetchFolderWorkspacesForAllHosts: () => Promise + fetchFolderWorkspacesForAllHosts: (options?: AllHostCatalogFetchOptions) => Promise addRepo: () => Promise addRepoPath: ( path: string, @@ -1366,7 +1480,7 @@ export const createRepoSlice: StateCreator = (set, } }, - fetchReposForAllHosts: async () => { + fetchReposForAllHosts: async (options) => { // Why: a cold start that restores a remote workspace re-activates that // remote runtime environment, and fetching only the active host hides every // other host's repos (notably all local repos), which reads as "my projects @@ -1374,9 +1488,10 @@ export const createRepoSlice: StateCreator = (set, // sidebar "All hosts" scope shows them together regardless of which // environment is active. Each host fails soft: an unreachable/disconnected // host is skipped without blocking the others. - const applyResult = (result: Awaited>): void => { - const validRepoIds = new Set(result.repos.map((repo) => repo.id)) + const applyCatalog = (catalog: FetchedRepoCatalog): void => { + let hostRepos: Repo[] = [] set((s) => { + const result = mergeFetchedRepoCatalog(catalog, s.repos) const mergedProjectCompatibility = mergeFetchedProjectCompatibilityForHost({ previous: { projects: s.projects, @@ -1386,48 +1501,71 @@ export const createRepoSlice: StateCreator = (set, repos: result.repos, hostId: result.hostId }) + hostRepos = result.repos.filter((repo) => getRepoExecutionHostId(repo) === result.hostId) return { repos: result.repos, ...mergedProjectCompatibility, folderWorkspacePathStatuses: {}, - activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, - filterRepoIds: s.filterRepoIds.filter((projectId) => validRepoIds.has(projectId)), - setupScriptPromptDismissedRepoIds: filterSetupScriptPromptDismissalsToValidRepos( - s.setupScriptPromptDismissedRepoIds, - validRepoIds - ) + activeRepoId: s.activeRepoId, + filterRepoIds: s.filterRepoIds, + setupScriptPromptDismissedRepoIds: s.setupScriptPromptDismissedRepoIds } }) // Why: preserve the safe-auto fork sync that fetchRepos / // fetchRuntimeEnvironmentRepos schedule after merging each host, so // cold-start (which now routes through here) keeps updating safe-auto forks. - scheduleSafeAutoForkSync( - get, - result.repos.filter((repo) => getRepoExecutionHostId(repo) === result.hostId) - ) + scheduleSafeAutoForkSync(get, hostRepos) + } + const validateRepoScopedUi = (): void => { + set((s) => { + const validRepoIds = new Set(s.repos.map((repo) => repo.id)) + return { + activeRepoId: s.activeRepoId && validRepoIds.has(s.activeRepoId) ? s.activeRepoId : null, + filterRepoIds: s.filterRepoIds.filter((projectId) => validRepoIds.has(projectId)), + setupScriptPromptDismissedRepoIds: filterSetupScriptPromptDismissalsToValidRepos( + s.setupScriptPromptDismissedRepoIds, + validRepoIds + ), + trustedOrcaHooks: filterTrustedOrcaHooksToValidRepos(s.trustedOrcaHooks, validRepoIds) + } + }) } // Local first so local repos are present even if a remote fetch stalls. + let failed = false try { - applyResult(await fetchReposForTarget({ kind: 'local' }, get().repos)) + applyCatalog(await fetchRepoCatalogForTarget({ kind: 'local' })) } catch (err) { + failed = true console.error('Failed to fetch local repos for all-host load:', err) } + if (options?.remoteHosts === 'skip') { + return + } const environments = await listRuntimeEnvironmentsForAllHostLoad() - - // Sequential to avoid concurrent set() races on the merged repos array. - for (const environment of environments) { - try { - applyResult( - await fetchReposForTarget( - { kind: 'environment', environmentId: environment.id }, - get().repos + // Why: unreachable remotes can spend the full connect timeout; merge each + // resolved host through the state updater so parallel loads do not clobber. + await Promise.all( + environments.map(async (environment) => { + try { + applyCatalog( + await fetchRepoCatalogForTarget({ + kind: 'environment', + environmentId: environment.id + }) ) - ) - } catch (err) { - console.warn(`Skipped repos for runtime environment ${environment.id}:`, err) - } + } catch (err) { + failed = true + console.warn(`Skipped repos for runtime environment ${environment.id}:`, err) + } + }) + ) + // Why: first-paint startup intentionally loads only local repos before + // remotes answer. Validate repo-scoped UI only once every configured host has + // answered; otherwise an offline runtime would erase its saved filters. + if (!failed) { + validateRepoScopedUi() } }, @@ -1444,35 +1582,40 @@ export const createRepoSlice: StateCreator = (set, } }, - fetchProjectGroupsForAllHosts: async () => { + fetchProjectGroupsForAllHosts: async (options) => { // Why: startup renders an all-host sidebar; replacing groups with only the // active host would leave repos from other hosts visible but ungrouped. - const applyResult = (result: Awaited>): void => { - set({ - projectGroups: result.projectGroups, + const applyCatalog = (catalog: FetchedProjectGroupCatalog): void => { + set((s) => ({ + projectGroups: mergeFetchedProjectGroupCatalog(catalog, s.projectGroups).projectGroups, folderWorkspacePathStatuses: {} - }) + })) } try { - applyResult(await fetchProjectGroupsForTarget({ kind: 'local' }, get().projectGroups)) + applyCatalog(await fetchProjectGroupCatalogForTarget({ kind: 'local' })) } catch (err) { console.error('Failed to fetch local project groups for all-host load:', err) } + if (options?.remoteHosts === 'skip') { + return + } const environments = await listRuntimeEnvironmentsForAllHostLoad() - for (const environment of environments) { - try { - applyResult( - await fetchProjectGroupsForTarget( - { kind: 'environment', environmentId: environment.id }, - get().projectGroups + await Promise.all( + environments.map(async (environment) => { + try { + applyCatalog( + await fetchProjectGroupCatalogForTarget({ + kind: 'environment', + environmentId: environment.id + }) ) - ) - } catch (err) { - console.warn(`Skipped project groups for runtime environment ${environment.id}:`, err) - } - } + } catch (err) { + console.warn(`Skipped project groups for runtime environment ${environment.id}:`, err) + } + }) + ) }, fetchFolderWorkspaces: async () => { @@ -1489,43 +1632,54 @@ export const createRepoSlice: StateCreator = (set, } }, - fetchFolderWorkspacesForAllHosts: async () => { + fetchFolderWorkspacesForAllHosts: async (options) => { // Why: folder workspaces are owned through their project groups, so startup // must fetch groups first and then merge each host's folder slice. - const applyResult = ( - result: Awaited> - ): void => { - set({ - folderWorkspaces: result.folderWorkspaces, + const applyCatalog = (catalog: FetchedFolderWorkspaceCatalog): void => { + set((s) => ({ + folderWorkspaces: mergeFetchedFolderWorkspaceCatalog( + catalog, + s.folderWorkspaces, + s.projectGroups + ).folderWorkspaces, folderWorkspacePathStatuses: {} - }) + })) } + let failed = false try { - applyResult( - await fetchFolderWorkspacesForTarget( - { kind: 'local' }, - get().folderWorkspaces, - get().projectGroups - ) - ) + applyCatalog(await fetchFolderWorkspaceCatalogForTarget({ kind: 'local' })) } catch (err) { + failed = true console.error('Failed to fetch local folder workspaces for all-host load:', err) } + if (options?.remoteHosts === 'skip') { + return + } const environments = await listRuntimeEnvironmentsForAllHostLoad() - for (const environment of environments) { - try { - applyResult( - await fetchFolderWorkspacesForTarget( - { kind: 'environment', environmentId: environment.id }, - get().folderWorkspaces, - get().projectGroups + await Promise.all( + environments.map(async (environment) => { + try { + applyCatalog( + await fetchFolderWorkspaceCatalogForTarget({ + kind: 'environment', + environmentId: environment.id + }) ) + } catch (err) { + failed = true + console.warn(`Skipped folder workspaces for runtime environment ${environment.id}:`, err) + } + }) + ) + if (!failed) { + set((s) => ({ + restoredRuntimeHostIdByWorkspaceSessionKey: clearRestoredFolderWorkspaceSessionOwners( + s.restoredRuntimeHostIdByWorkspaceSessionKey, + s ) - } catch (err) { - console.warn(`Skipped folder workspaces for runtime environment ${environment.id}:`, err) - } + })) } }, @@ -2251,7 +2405,14 @@ export const createRepoSlice: StateCreator = (set, repo && !projectHostSetups.some((setup) => setup.projectId === result.project.id) ? s.projects.filter((project) => project.id !== result.project.id) : s.projects - return { repos, projects, projectHostSetups } + const survivingRepoIds = new Set(repos.map((r) => r.id)) + const removedRepoIds = s.repos.filter((r) => !survivingRepoIds.has(r.id)).map((r) => r.id) + return { + repos, + projects, + projectHostSetups, + ...omitSparsePresetsForRepos(s, removedRepoIds) + } }) return { ...result, repo } } catch (err) { @@ -2516,8 +2677,13 @@ export const createRepoSlice: StateCreator = (set, delete nextLastVisitedAtByWorktreeId[id] } } + const survivingRepoIds = new Set(nextRepos.map((r) => r.id)) + const removedRepoIds = s.repos.filter((r) => !survivingRepoIds.has(r.id)).map((r) => r.id) return { repos: nextRepos, + // Why: drop the removed repos' sparse-preset maps so they don't outlive + // the repo for the renderer's whole session. + ...omitSparsePresetsForRepos(s, removedRepoIds), ...mergeProjectCompatibilityForHostRepoChange({ previous: { projects: s.projects, projectHostSetups: s.projectHostSetups }, nextRepos, diff --git a/src/renderer/src/store/slices/sparse-presets-repo-removal-purge-leak.test.ts b/src/renderer/src/store/slices/sparse-presets-repo-removal-purge-leak.test.ts new file mode 100644 index 000000000..d03b84183 --- /dev/null +++ b/src/renderer/src/store/slices/sparse-presets-repo-removal-purge-leak.test.ts @@ -0,0 +1,70 @@ +/** + * Memory-leak regression: removing a repo must purge its sparse-preset maps. + * + * The four per-repo maps (`sparsePresetsByRepo`, `sparsePresetsLoadingByRepo`, + * `sparsePresetsLoadStatusByRepo`, `sparsePresetsErrorByRepo`) are populated + * lazily by `fetchSparsePresets` but were never pruned when a repo was removed, + * so orphaned entries accumulated for the renderer's whole session. repoIds are + * random UUIDs (never reused), so re-adding a repo cannot reclaim the old keys. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createTestStore, makeWorktree } from './store-test-helpers' +import type { Repo, SparsePreset } from '../../../../shared/types' + +const repo1: Repo = { id: 'repo-1', path: '/r1', displayName: 'R1', badgeColor: '#000', addedAt: 1 } +const repo2: Repo = { id: 'repo-2', path: '/r2', displayName: 'R2', badgeColor: '#111', addedAt: 2 } + +const reposRemove = vi.fn().mockResolvedValue(undefined) + +beforeEach(() => { + reposRemove.mockReset().mockResolvedValue(undefined) + vi.stubGlobal('window', { + api: { + repos: { remove: reposRemove }, + pty: { kill: vi.fn() }, + runtimeEnvironments: { call: vi.fn() } + } + }) +}) + +function preset(id: string, repoId: string): SparsePreset { + return { id, repoId, name: id, directories: ['src'], createdAt: 1, updatedAt: 1 } +} + +function seed(store: ReturnType): void { + store.setState({ + repos: [repo1, repo2], + worktreesByRepo: { + [repo1.id]: [makeWorktree({ id: 'repo-1::/r1/wt1', repoId: repo1.id, path: '/r1/wt1' })], + [repo2.id]: [makeWorktree({ id: 'repo-2::/r2/wt1', repoId: repo2.id, path: '/r2/wt1' })] + }, + sparsePresetsByRepo: { + [repo1.id]: [preset('p1', repo1.id)], + [repo2.id]: [preset('p2', repo2.id)] + }, + sparsePresetsLoadingByRepo: { [repo1.id]: false, [repo2.id]: false }, + sparsePresetsLoadStatusByRepo: { [repo1.id]: 'loaded', [repo2.id]: 'loaded' }, + sparsePresetsErrorByRepo: { [repo1.id]: 'stale', [repo2.id]: 'boom' } + }) +} + +describe('removeProject purges the removed repo sparse-preset maps (leak regression)', () => { + it('drops all four sparse-preset maps for the removed repo, keeps the surviving repo', async () => { + const store = createTestStore() + seed(store) + + await store.getState().removeProject(repo1.id) + + const s = store.getState() + // Removed repo: every sparse-preset map key is gone. + expect(repo1.id in s.sparsePresetsByRepo).toBe(false) + expect(repo1.id in s.sparsePresetsLoadingByRepo).toBe(false) + expect(repo1.id in s.sparsePresetsLoadStatusByRepo).toBe(false) + expect(repo1.id in s.sparsePresetsErrorByRepo).toBe(false) + // Surviving repo: retained (guard over-eviction). + expect(s.sparsePresetsByRepo[repo2.id]).toEqual([preset('p2', repo2.id)]) + expect(s.sparsePresetsLoadingByRepo[repo2.id]).toBe(false) + expect(s.sparsePresetsLoadStatusByRepo[repo2.id]).toBe('loaded') + expect(s.sparsePresetsErrorByRepo[repo2.id]).toBe('boom') + }) +}) diff --git a/src/renderer/src/store/slices/sparse-presets.ts b/src/renderer/src/store/slices/sparse-presets.ts index 5a111cad8..af118c770 100644 --- a/src/renderer/src/store/slices/sparse-presets.ts +++ b/src/renderer/src/store/slices/sparse-presets.ts @@ -26,6 +26,58 @@ export type SparsePresetsSlice = { removeSparsePreset: (args: { repoId: string; presetId: string }) => Promise } +type SparsePresetsMaps = Pick< + AppState, + | 'sparsePresetsByRepo' + | 'sparsePresetsLoadingByRepo' + | 'sparsePresetsLoadStatusByRepo' + | 'sparsePresetsErrorByRepo' +> + +// Why: the four per-repo sparse-preset maps are populated lazily per repo but +// were never pruned when a repo was removed, so orphaned entries accumulated for +// the renderer's whole session. Call this from the repo-removal reducers to drop +// entries for repos that no longer exist. Returns only the maps that changed so +// unrelated selectors don't re-run. +export function omitSparsePresetsForRepos( + s: SparsePresetsMaps, + removedRepoIds: Iterable +): Partial { + const removed = removedRepoIds instanceof Set ? removedRepoIds : new Set(removedRepoIds) + if (removed.size === 0) { + return {} + } + const omit = (obj: Record): Record => { + let changed = false + const out = { ...obj } + for (const id of removed) { + if (id in out) { + delete out[id] + changed = true + } + } + return changed ? out : obj + } + const result: Partial = {} + const byRepo = omit(s.sparsePresetsByRepo) + if (byRepo !== s.sparsePresetsByRepo) { + result.sparsePresetsByRepo = byRepo + } + const loading = omit(s.sparsePresetsLoadingByRepo) + if (loading !== s.sparsePresetsLoadingByRepo) { + result.sparsePresetsLoadingByRepo = loading + } + const status = omit(s.sparsePresetsLoadStatusByRepo) + if (status !== s.sparsePresetsLoadStatusByRepo) { + result.sparsePresetsLoadStatusByRepo = status + } + const error = omit(s.sparsePresetsErrorByRepo) + if (error !== s.sparsePresetsErrorByRepo) { + result.sparsePresetsErrorByRepo = error + } + return result +} + export const createSparsePresetsSlice: StateCreator = ( set, get diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts index d2f93e73a..7678d96f3 100644 --- a/src/renderer/src/store/slices/store-session-cascades.test.ts +++ b/src/renderer/src/store/slices/store-session-cascades.test.ts @@ -3,7 +3,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import type * as AgentStatusModule from '@/lib/agent-status' import type { BrowserTab, DetectedWorktreeListResult, Worktree } from '../../../../shared/types' import { isTerminalLeafId } from '../../../../shared/stable-pane-id' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import { + FLOATING_TERMINAL_WORKTREE_ID, + getDefaultWorkspaceSession +} from '../../../../shared/constants' +import { folderWorkspaceKey } from '../../../../shared/workspace-scope' // Mock sonner (imported by repos.ts) vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) @@ -531,6 +535,143 @@ describe('hydrateWorkspaceSession', () => { }) }) +describe('restored folder workspace hydration', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('keeps runtime folder workspace tabs, files, and browsers before remote catalogs load', () => { + const store = createTestStore() + const folderKey = folderWorkspaceKey('remote-folder') + const groupId = 'group-folder' + const editorFileId = '/srv/app/src/App.tsx' + const session = { + ...getDefaultWorkspaceSession(), + activeWorkspaceKey: folderKey, + activeWorktreeId: folderKey, + activeTabId: 'terminal-folder', + tabsByWorktree: { + [folderKey]: [makeTab({ id: 'terminal-folder', worktreeId: folderKey })] + }, + openFilesByWorktree: { + [folderKey]: [ + { + filePath: editorFileId, + relativePath: 'src/App.tsx', + worktreeId: folderKey, + language: 'typescript' + } + ] + }, + activeFileIdByWorktree: { [folderKey]: editorFileId }, + browserTabsByWorktree: { + [folderKey]: [ + makeBrowserTab({ + id: 'browser-folder', + worktreeId: folderKey, + url: 'https://example.com' + }) + ] + }, + browserPagesByWorkspace: { + 'browser-folder': [ + { + id: 'browser-page-folder', + workspaceId: 'browser-folder', + worktreeId: folderKey, + url: 'https://example.com', + title: 'Example', + loading: false, + faviconUrl: null, + canGoBack: false, + canGoForward: false, + loadError: null, + createdAt: 1 + } + ] + }, + activeBrowserTabIdByWorktree: { [folderKey]: 'browser-folder' }, + activeTabTypeByWorktree: { [folderKey]: 'browser' as const }, + unifiedTabs: { + [folderKey]: [ + { + id: 'terminal-folder', + entityId: 'terminal-folder', + groupId, + worktreeId: folderKey, + contentType: 'terminal' as const, + label: 'Terminal', + customLabel: null, + color: null, + sortOrder: 0, + createdAt: 1 + }, + { + id: editorFileId, + entityId: editorFileId, + groupId, + worktreeId: folderKey, + contentType: 'editor' as const, + label: 'App.tsx', + customLabel: null, + color: null, + sortOrder: 1, + createdAt: 2 + }, + { + id: 'browser-folder', + entityId: 'browser-folder', + groupId, + worktreeId: folderKey, + contentType: 'browser' as const, + label: 'Example', + customLabel: null, + color: null, + sortOrder: 2, + createdAt: 3 + } + ] + }, + tabGroups: { + [folderKey]: [ + { + id: groupId, + worktreeId: folderKey, + activeTabId: 'browser-folder', + tabOrder: ['terminal-folder', editorFileId, 'browser-folder'], + recentTabIds: ['terminal-folder', editorFileId, 'browser-folder'] + } + ] + }, + activeGroupIdByWorktree: { [folderKey]: groupId } + } + const options = { + additionalValidWorkspaceKeys: [folderKey], + runtimeHostIdByWorkspaceSessionKey: { [folderKey]: 'runtime:env-1' as const } + } + + store.getState().hydrateWorkspaceSession(session, options) + store.getState().hydrateTabsSession(session, options) + store.getState().hydrateEditorSession(session, options) + store.getState().hydrateBrowserSession(session, options) + + const state = store.getState() + expect(state.activeWorktreeId).toBe(folderKey) + expect(state.activeWorkspaceKey).toBe(folderKey) + expect(state.tabsByWorktree[folderKey]?.map((tab) => tab.id)).toEqual(['terminal-folder']) + expect(state.unifiedTabsByWorktree[folderKey]?.map((tab) => tab.id)).toEqual([ + 'terminal-folder', + editorFileId, + 'browser-folder' + ]) + expect(state.openFiles.map((file) => file.worktreeId)).toEqual([folderKey]) + expect(state.activeFileIdByWorktree[folderKey]).toBe(editorFileId) + expect(state.browserTabsByWorktree[folderKey]?.map((tab) => tab.id)).toEqual(['browser-folder']) + expect(state.browserPagesByWorkspace['browser-folder']?.[0]?.worktreeId).toBe(folderKey) + expect(state.activeTabTypeByWorktree[folderKey]).toBe('browser') + }) +}) + describe('hydrateBrowserSession', () => { beforeEach(() => { vi.clearAllMocks() diff --git a/src/renderer/src/store/slices/tab-worktree-orphan-map-purge-leak.test.ts b/src/renderer/src/store/slices/tab-worktree-orphan-map-purge-leak.test.ts new file mode 100644 index 000000000..f34c6627e --- /dev/null +++ b/src/renderer/src/store/slices/tab-worktree-orphan-map-purge-leak.test.ts @@ -0,0 +1,157 @@ +/** + * Memory-leak regression: three module-level maps keyed by tab/worktree id grew + * monotonically over a session because no removal path evicted their entries. + * + * - `detachedHeadAutoDerivedDisplayNames` (worktrees.ts) — worktree-keyed; only + * self-evicted when a branch reappeared, so a worktree removed while detached + * leaked its entry. + * - `foregroundTerminalTabLastSeenAtById` (lib/foreground-terminal-tabs) — + * tab-keyed; gained an entry per foregrounded tab, never dropped on close. + * - `consumedAgentStartupDeliveries` (lib/agent-startup-delivery-guards) — + * (worktreeId,tabId,launchToken)-keyed; one permanent guard per delivery, + * only released on the retry path, so removed tabs/worktrees leaked it. + * + * worktreeId and tabId are unbounded, ephemeral key spaces (fresh ids, never reused). + */ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import type * as AgentStatusModule from '@/lib/agent-status' +import { + getForegroundTerminalTabLastSeenAtById, + resetForegroundTerminalTabIdsForTests, + setForegroundTerminalTabIds +} from '@/lib/foreground-terminal-tabs' +import { + beginAgentStartupDeliveryAttempt, + resetAgentStartupDelayedDeliveryForTests +} from '@/lib/agent-startup-delayed-delivery' + +vi.mock('sonner', () => ({ + toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() } +})) + +vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({ + restorePtyDataHandlersAfterFailedShutdown: vi.fn(), + unregisterPtyDataHandlers: vi.fn() +})) + +vi.mock('@/lib/agent-status', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) } +}) + +const mockApi = { + worktrees: { + list: vi.fn().mockResolvedValue([]), + remove: vi.fn().mockResolvedValue(undefined), + forceDeletePreservedBranch: vi.fn().mockResolvedValue({ deleted: true }), + updateMeta: vi.fn().mockResolvedValue({}) + }, + pty: { kill: vi.fn().mockResolvedValue(undefined) }, + runtimeEnvironments: { call: vi.fn().mockResolvedValue({ ok: true, result: {} }) } +} + +// @ts-expect-error -- minimal window.api stub for the store under test +globalThis.window = { api: mockApi } + +import { createTestStore, seedStore, makeWorktree, makeTab } from './store-test-helpers' +import { + getDetachedHeadAutoDerivedDisplayNameForTests, + setDetachedHeadAutoDerivedDisplayNameForTests +} from './worktrees' + +const WT1 = 'repo1::/path/wt1' +const WT2 = 'repo1::/path/wt2' +const TAB1 = 'tab-wt1' +const TAB2 = 'tab-wt2' +const TOKEN1 = 'launch-1' +const TOKEN2 = 'launch-2' + +function seedMaps(store: ReturnType): void { + seedStore(store, { + worktreesByRepo: { + repo1: [ + makeWorktree({ id: WT1, repoId: 'repo1', path: '/path/wt1' }), + makeWorktree({ id: WT2, repoId: 'repo1', path: '/path/wt2' }) + ] + }, + tabsByWorktree: { + [WT1]: [makeTab({ id: TAB1, worktreeId: WT1 })], + [WT2]: [makeTab({ id: TAB2, worktreeId: WT2 })] + } + }) + setDetachedHeadAutoDerivedDisplayNameForTests(WT1, 'wt1 (a1b2c3d)') + setDetachedHeadAutoDerivedDisplayNameForTests(WT2, 'wt2 (e4f5g6h)') + // Records a last-seen timestamp for both tabs. + setForegroundTerminalTabIds([TAB1, TAB2]) + // Consumes a startup delivery guard for each tab. + expect( + beginAgentStartupDeliveryAttempt({ worktreeId: WT1, tabId: TAB1, launchToken: TOKEN1 }) + ).toBe(true) + expect( + beginAgentStartupDeliveryAttempt({ worktreeId: WT2, tabId: TAB2, launchToken: TOKEN2 }) + ).toBe(true) +} + +// A second begin returns false while the guard is still present, true once it is +// cleared — so this observes the consumed-set without reaching into internals. +function startupGuardCleared(worktreeId: string, tabId: string, launchToken: string): boolean { + return beginAgentStartupDeliveryAttempt({ worktreeId, tabId, launchToken }) +} + +describe('tab/worktree removal evicts the module maps it previously leaked', () => { + beforeEach(() => { + vi.clearAllMocks() + mockApi.worktrees.remove.mockResolvedValue(undefined) + resetForegroundTerminalTabIdsForTests() + resetAgentStartupDelayedDeliveryForTests() + }) + + afterEach(() => { + resetForegroundTerminalTabIdsForTests() + resetAgentStartupDelayedDeliveryForTests() + }) + + it('bulk purgeWorktreeTerminalState drops the removed worktree/tab entries only', () => { + const store = createTestStore() + seedMaps(store) + + store.getState().purgeWorktreeTerminalState([WT1]) + + // Removed worktree/tab: all three maps evicted. + expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT1)).toBeUndefined() + expect(getForegroundTerminalTabLastSeenAtById()[TAB1]).toBeUndefined() + expect(startupGuardCleared(WT1, TAB1, TOKEN1)).toBe(true) + // Surviving worktree/tab: retained (guard over-eviction). + expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT2)).toBe('wt2 (e4f5g6h)') + expect(getForegroundTerminalTabLastSeenAtById()[TAB2]).toBeGreaterThan(0) + expect(startupGuardCleared(WT2, TAB2, TOKEN2)).toBe(false) + }) + + it('single removeWorktree drops the removed worktree/tab entries only', async () => { + const store = createTestStore() + seedMaps(store) + + const result = await store.getState().removeWorktree(WT1) + expect(result).toEqual({ ok: true }) + + expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT1)).toBeUndefined() + expect(getForegroundTerminalTabLastSeenAtById()[TAB1]).toBeUndefined() + expect(startupGuardCleared(WT1, TAB1, TOKEN1)).toBe(true) + expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT2)).toBe('wt2 (e4f5g6h)') + expect(getForegroundTerminalTabLastSeenAtById()[TAB2]).toBeGreaterThan(0) + expect(startupGuardCleared(WT2, TAB2, TOKEN2)).toBe(false) + }) + + it('closeTab drops the closed tab foreground + startup entries only', () => { + const store = createTestStore() + seedMaps(store) + + store.getState().closeTab(TAB1) + + // closeTab is tab-scoped: the tab-keyed maps drop, the worktree-keyed one stays. + expect(getForegroundTerminalTabLastSeenAtById()[TAB1]).toBeUndefined() + expect(startupGuardCleared(WT1, TAB1, TOKEN1)).toBe(true) + expect(getForegroundTerminalTabLastSeenAtById()[TAB2]).toBeGreaterThan(0) + expect(startupGuardCleared(WT2, TAB2, TOKEN2)).toBe(false) + }) +}) diff --git a/src/renderer/src/store/slices/tabs.ts b/src/renderer/src/store/slices/tabs.ts index 00cf7fcc1..41fa3646d 100644 --- a/src/renderer/src/store/slices/tabs.ts +++ b/src/renderer/src/store/slices/tabs.ts @@ -35,6 +35,10 @@ import { createBrowserUuid } from '@/lib/browser-uuid' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' import { folderWorkspaceKey } from '../../../../shared/workspace-scope' +import { + addAdditionalValidWorkspaceKeys, + type WorkspaceSessionHydrationOptions +} from '@/lib/workspace-session-hydration-keys' export type TabSplitDirection = 'left' | 'right' | 'up' | 'down' @@ -172,7 +176,10 @@ export type TabsSlice = { renderableTabCount: number activeRenderableTabId: string | null } - hydrateTabsSession: (session: WorkspaceSessionState) => void + hydrateTabsSession: ( + session: WorkspaceSessionState, + options?: WorkspaceSessionHydrationOptions + ) => void } // Why: keep the TerminalTab (tabsByWorktree) pin in sync with the unified-tab @@ -2036,7 +2043,7 @@ export const createTabsSlice: StateCreator = (set, } }, - hydrateTabsSession: (session) => { + hydrateTabsSession: (session, options) => { const state = get() const validWorktreeIds = new Set( Object.values(state.worktreesByRepo) @@ -2047,6 +2054,7 @@ export const createTabsSlice: StateCreator = (set, for (const workspace of state.folderWorkspaces) { validWorktreeIds.add(folderWorkspaceKey(workspace.id)) } + addAdditionalValidWorkspaceKeys(validWorktreeIds, options) set(buildHydratedTabState(session, validWorktreeIds)) } }) diff --git a/src/renderer/src/store/slices/terminal-helpers.ts b/src/renderer/src/store/slices/terminal-helpers.ts index 397660556..7f42c049a 100644 --- a/src/renderer/src/store/slices/terminal-helpers.ts +++ b/src/renderer/src/store/slices/terminal-helpers.ts @@ -1,5 +1,5 @@ import type { TerminalLayoutSnapshot, TerminalTab } from '../../../../shared/types' -import { detectAgentStatusFromTitle } from '@/lib/agent-status' +import { classifyTitleActivity } from '@/lib/pane-agent-evidence' export function emptyLayoutSnapshot(): TerminalLayoutSnapshot { return { @@ -37,5 +37,5 @@ function getResetTitle(tab: TerminalTab, index: number): string { // Why: reset any recognized agent title on hydration. The prior-session // agent is no longer running after a restart, so showing a stale // "Claude done" or spinner would be misleading. - return detectAgentStatusFromTitle(tab.title) ? fallbackTitle : tab.title + return classifyTitleActivity(tab.title) ? fallbackTitle : tab.title } diff --git a/src/renderer/src/store/slices/terminals-hydration.test.ts b/src/renderer/src/store/slices/terminals-hydration.test.ts index e4b374231..9b913be95 100644 --- a/src/renderer/src/store/slices/terminals-hydration.test.ts +++ b/src/renderer/src/store/slices/terminals-hydration.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: hydration regressions share store setup and session invariants that are easier to audit together. */ import { beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) @@ -93,7 +92,11 @@ const mockApi = { globalThis.window = { api: mockApi } import type { WorkspaceSessionState } from '../../../../shared/types' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import { + FLOATING_TERMINAL_WORKTREE_ID, + getDefaultWorkspaceSession +} from '../../../../shared/constants' +import { folderWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope' import { createTestStore, makeLayout, makeTab, makeWorktree, seedStore } from './store-test-helpers' import { canGoBackWorktreeHistory } from './worktree-nav-history' @@ -139,6 +142,145 @@ describe('hydrateWorkspaceSession', () => { }) }) + it('hydrates runtime-owned tabs from host partitions before remote catalogs load', () => { + const store = createTestStore() + const worktreeId = 'remote-repo::/srv/remote-wt' + const session: WorkspaceSessionState = { + ...getDefaultWorkspaceSession(), + activeRepoId: 'remote-repo', + activeWorktreeId: worktreeId, + activeTabId: 'remote-tab', + activeWorktreeIdsOnShutdown: [worktreeId], + tabsByWorktree: { + [worktreeId]: [ + makeTab({ + id: 'remote-tab', + worktreeId, + ptyId: 'remote-session' + }) + ] + }, + remoteSessionIdsByTabId: { 'remote-tab': 'remote-session' } + } + + store.getState().hydrateWorkspaceSession(session, { + runtimeHostIdByWorkspaceSessionKey: { [worktreeId]: 'runtime:env-1' } + }) + + expect(store.getState().tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([ + 'remote-tab' + ]) + expect(store.getState().activeWorktreeId).toBe(worktreeId) + expect(store.getState().activeRepoId).toBe('remote-repo') + expect(store.getState().pendingReconnectWorktreeIds).toEqual([worktreeId]) + expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({ + 'remote-tab': 'remote-session' + }) + expect(store.getState().repos).toEqual([ + expect.objectContaining({ + id: 'remote-repo', + executionHostId: 'runtime:env-1' + }) + ]) + expect(store.getState().worktreesByRepo['remote-repo']).toEqual([ + expect.objectContaining({ + id: worktreeId, + hostId: 'runtime:env-1' + }) + ]) + }) + + it('avoids duplicate repo placeholders when a same-id local repo is already loaded', () => { + const store = createTestStore() + const worktreeId = 'same-repo::/srv/remote-wt' + store.setState({ + repos: [ + { + id: 'same-repo', + path: '/Users/me/same-repo', + displayName: 'Same repo', + badgeColor: '#000', + addedAt: 1, + connectionId: null, + executionHostId: 'local' + } + ], + worktreesByRepo: {} + }) + const session: WorkspaceSessionState = { + ...getDefaultWorkspaceSession(), + activeRepoId: 'same-repo', + activeWorktreeId: worktreeId, + activeTabId: 'remote-tab', + activeWorktreeIdsOnShutdown: [worktreeId], + tabsByWorktree: { + [worktreeId]: [ + makeTab({ + id: 'remote-tab', + worktreeId, + ptyId: 'remote-session' + }) + ] + } + } + + store.getState().hydrateWorkspaceSession(session, { + runtimeHostIdByWorkspaceSessionKey: { + [worktreeWorkspaceKey(worktreeId)]: 'runtime:env-1' + } + }) + + expect(store.getState().repos.map((repo) => `${repo.id}:${repo.executionHostId}`)).toEqual([ + 'same-repo:local' + ]) + expect(store.getState().worktreesByRepo['same-repo']).toEqual([ + expect.objectContaining({ id: worktreeId, hostId: 'runtime:env-1' }) + ]) + expect(store.getState().tabsByWorktree[worktreeId]?.map((tab) => tab.id)).toEqual([ + 'remote-tab' + ]) + }) + + it('hydrates runtime folder workspace tabs before remote folder catalogs load', () => { + const store = createTestStore() + const folderKey = folderWorkspaceKey('folder-1') + const session: WorkspaceSessionState = { + ...getDefaultWorkspaceSession(), + activeWorkspaceKey: folderKey, + activeWorktreeId: folderKey, + activeTabId: 'remote-folder-tab', + activeWorktreeIdsOnShutdown: [folderKey], + tabsByWorktree: { + [folderKey]: [ + makeTab({ + id: 'remote-folder-tab', + worktreeId: folderKey, + ptyId: 'remote-folder-session' + }) + ] + }, + remoteSessionIdsByTabId: { 'remote-folder-tab': 'remote-folder-session' } + } + + store.getState().hydrateWorkspaceSession(session, { + additionalValidWorkspaceKeys: [folderKey], + runtimeHostIdByWorkspaceSessionKey: { [folderKey]: 'runtime:env-1' } + }) + + expect(store.getState().tabsByWorktree[folderKey]?.map((tab) => tab.id)).toEqual([ + 'remote-folder-tab' + ]) + expect(store.getState().activeWorktreeId).toBe(folderKey) + expect(store.getState().activeWorkspaceKey).toBe(folderKey) + expect(store.getState().pendingReconnectWorktreeIds).toEqual([folderKey]) + expect(store.getState().pendingReconnectPtyIdByTabId).toEqual({ + 'remote-folder-tab': 'remote-folder-session' + }) + expect(store.getState().restoredRuntimeHostIdByWorkspaceSessionKey).toEqual({ + [folderKey]: 'runtime:env-1' + }) + }) + it('moves restored active focus from a dead split leaf to a pty-backed sibling', () => { const store = createTestStore() const worktreeId = 'repo1::/wt-1' diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 3b99e3837..a00aa3e54 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -2,6 +2,7 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { + Repo, SetupSplitDirection, Tab, TerminalLayoutSnapshot, @@ -15,7 +16,11 @@ import type { AgentProviderSessionMetadata, SleepingAgentLaunchConfig } from '../../../../shared/agent-session-resume' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../../../shared/constants' +import { + DEFAULT_REPO_BADGE_COLOR, + FLOATING_TERMINAL_WORKTREE_ID +} from '../../../../shared/constants' +import { parseExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' import { folderWorkspaceKey, parseWorkspaceKey, @@ -34,8 +39,11 @@ import { WINDOWS_GIT_BASH_SHELL } from '../../../../shared/windows-terminal-shel import type { AgentStartedTelemetry } from '../../lib/worktree-activation' import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph' import { forgetAgentHibernationTabOutput } from '@/lib/agent-hibernation-output-activity' +import { forgetForegroundTerminalTabs } from '@/lib/foreground-terminal-tabs' +import { forgetAgentStartupDeliveriesForTabs } from '@/lib/agent-startup-delivery-guards' import { clearTransientTerminalState, emptyLayoutSnapshot } from './terminal-helpers' -import { isClaudeAgent, detectAgentStatusFromTitle } from '@/lib/agent-status' +import { isClaudeAgent } from '@/lib/agent-status' +import { classifyTitleActivity } from '@/lib/pane-agent-evidence' import { buildOrphanTerminalCleanupPatch, getOrphanTerminalIds } from './terminal-orphan-helpers' import { dedupeTabOrder, @@ -65,6 +73,10 @@ import { focusTerminalTabSurface } from '@/lib/focus-terminal-tab-surface' import { getRuntimeEnvironmentIdForWorktree } from '@/lib/worktree-runtime-owner' import { getLocalProjectExecutionRuntimeContext } from '@/lib/local-preflight-context' import type { NativeChatLaunchPrompt } from '@/lib/native-chat-launch-prompt' +import { + addAdditionalValidWorkspaceKeys, + type WorkspaceSessionHydrationOptions +} from '@/lib/workspace-session-hydration-keys' import { collectHibernatedCompletionEvidenceForWorktree, collectSleepingAgentSessionRecordsForWorktree, @@ -120,6 +132,89 @@ function getFallbackTabTitle(tab: TerminalTab, index?: number): string { ) } +function getPathDisplayName(path: string, fallback: string): string { + const normalized = path.trim().replace(/[\\/]+$/g, '') + const basename = normalized.split(/[\\/]/).findLast(Boolean)?.trim() + return basename || fallback +} + +function buildRuntimeSessionPlaceholders({ + repos, + runtimeHostIdByWorkspaceSessionKey, + worktreesByRepo +}: { + repos: readonly Repo[] + runtimeHostIdByWorkspaceSessionKey: Record + worktreesByRepo: Record +}): { repos: Repo[]; worktreesByRepo: Record } { + let nextRepos = repos.slice() + let nextWorktreesByRepo = worktreesByRepo + for (const workspaceSessionKey of Object.keys(runtimeHostIdByWorkspaceSessionKey)) { + const hostId = runtimeHostIdByWorkspaceSessionKey[workspaceSessionKey] + if (parseExecutionHostId(hostId)?.kind !== 'runtime') { + continue + } + const workspaceScope = parseWorkspaceKey(workspaceSessionKey) + if (workspaceScope?.type === 'folder') { + continue + } + const worktreeId = + workspaceScope?.type === 'worktree' ? workspaceScope.worktreeId : workspaceSessionKey + const parsed = splitWorktreeId(worktreeId) + if (!parsed) { + continue + } + const existingRepo = nextRepos.some((repo) => repo.id === parsed.repoId) + if (!existingRepo) { + // Why: remote catalogs load after hydration, but host-split session + // writes need owner metadata. If any repo with this id already exists, + // avoid duplicate ids; the worktree placeholder below carries hostId. + nextRepos = [ + ...nextRepos, + { + id: parsed.repoId, + path: parsed.worktreePath, + displayName: getPathDisplayName(parsed.worktreePath, parsed.repoId), + badgeColor: DEFAULT_REPO_BADGE_COLOR, + addedAt: 0, + connectionId: null, + executionHostId: hostId + } + ] + } + const current = nextWorktreesByRepo[parsed.repoId] ?? [] + if (current.some((worktree) => worktree.id === worktreeId)) { + continue + } + const placeholder: Worktree = { + id: worktreeId, + repoId: parsed.repoId, + hostId, + displayName: getPathDisplayName(parsed.worktreePath, parsed.repoId), + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + path: parsed.worktreePath, + head: '', + branch: '', + isBare: false, + isMainWorktree: false + } + nextWorktreesByRepo = + nextWorktreesByRepo === worktreesByRepo ? { ...worktreesByRepo } : nextWorktreesByRepo + nextWorktreesByRepo[parsed.repoId] = [...current, placeholder] + } + return { repos: nextRepos, worktreesByRepo: nextWorktreesByRepo } +} + let terminalTabOwnerCacheSource: Record | null = null let terminalTabOwnerCache = new Map() @@ -415,6 +510,7 @@ export type TerminalSlice = { pendingIssueCommandSplitByTabId: Record }> tabBarOrderByWorktree: Record workspaceSessionReady: boolean + restoredRuntimeHostIdByWorkspaceSessionKey: Record defaultTerminalTabsAppliedByWorktreeId: Record markDefaultTerminalTabsApplied: (worktreeId: string) => void /** True only after hydrateWorkspaceSession ran from a real load of @@ -618,10 +714,17 @@ export type TerminalSlice = { setDeferredSshReconnectTargets: (targetIds: string[]) => void removeDeferredSshReconnectTarget: (targetId: string) => void removeDeferredSshSessionId: (tabId: string) => void - hydrateWorkspaceSession: (session: WorkspaceSessionState) => void + hydrateWorkspaceSession: ( + session: WorkspaceSessionState, + options?: HydrateWorkspaceSessionOptions + ) => void reconnectPersistedTerminals: (signal?: AbortSignal) => Promise } +export type HydrateWorkspaceSessionOptions = { + runtimeHostIdByWorkspaceSessionKey?: Record +} & WorkspaceSessionHydrationOptions + export const createTerminalSlice: StateCreator = (set, get) => ({ tabsByWorktree: {}, activeTabId: null, @@ -645,6 +748,7 @@ export const createTerminalSlice: StateCreator nativeChatLaunchPromptByTabId: {}, tabBarOrderByWorktree: {}, workspaceSessionReady: false, + restoredRuntimeHostIdByWorkspaceSessionKey: {}, defaultTerminalTabsAppliedByWorktreeId: {}, markDefaultTerminalTabsApplied: (worktreeId) => set((s) => { @@ -771,7 +875,7 @@ export const createTerminalSlice: StateCreator if (!tab.title || !isClaudeAgent(tab.title)) { continue } - const status = detectAgentStatusFromTitle(tab.title) + const status = classifyTitleActivity(tab.title) if (status === null || status === 'working') { continue } @@ -1236,6 +1340,10 @@ export const createTerminalSlice: StateCreator // a fresh leafId at epoch 0), so drop the panes' hibernation output epochs to // keep that module-level map from growing for the renderer's whole lifetime. forgetAgentHibernationTabOutput(tabId) + // Why: same rationale for the tab's foreground last-seen timestamp and any + // consumed agent-startup delivery guards — retired tab ids never recur. + forgetForegroundTerminalTabs([tabId]) + forgetAgentStartupDeliveriesForTabs([tabId]) for (const tabs of Object.values(get().unifiedTabsByWorktree)) { const workspaceItem = tabs.find( (entry) => entry.contentType === 'terminal' && entry.entityId === tabId @@ -1530,7 +1638,7 @@ export const createTerminalSlice: StateCreator // event fires. Bumping only on classification change keeps incidental // title noise (spinner frame, prompt suffix) from churning the sidebar. const classificationChanged = - detectAgentStatusFromTitle(prevTitle ?? '') !== detectAgentStatusFromTitle(title) + classifyTitleActivity(prevTitle ?? '') !== classifyTitleActivity(title) // Why: locate the owning worktree so we can suppress the sortEpoch // bump when the changing pane lives in the active worktree. Title // changes there are side-effects of the user's click (PTY remount on @@ -1573,7 +1681,7 @@ export const createTerminalSlice: StateCreator // Why: clearing a 'working'/'permission'-classified title back to none // changes the title-heuristic verdict for that pane, so the smart sort // needs a re-sort. See setRuntimePaneTitle for the rationale. - const hadClassification = detectAgentStatusFromTitle(prevTitle ?? '') !== null + const hadClassification = classifyTitleActivity(prevTitle ?? '') !== null // Why: same active-worktree gate as setRuntimePaneTitle — clears that // fire as a side-effect of a click-driven PTY teardown in the active // worktree must not re-rank the sidebar. Skip bumping when no owner is @@ -2741,16 +2849,21 @@ export const createTerminalSlice: StateCreator return data }, - hydrateWorkspaceSession: (session) => { + hydrateWorkspaceSession: (session, options) => { set((s) => { + const runtimeSessionPlaceholders = buildRuntimeSessionPlaceholders({ + repos: s.repos, + runtimeHostIdByWorkspaceSessionKey: options?.runtimeHostIdByWorkspaceSessionKey ?? {}, + worktreesByRepo: s.worktreesByRepo + }) const validWorktreeIds = new Set( - Object.values(s.worktreesByRepo) + Object.values(runtimeSessionPlaceholders.worktreesByRepo) .flat() .map((worktree) => worktree.id) ) - const knownRepoIds = new Set(s.repos.map((r) => r.id)) + const knownRepoIds = new Set(runtimeSessionPlaceholders.repos.map((r) => r.id)) const repoIdsWithLoadedWorktrees = new Set( - Object.entries(s.worktreesByRepo) + Object.entries(runtimeSessionPlaceholders.worktreesByRepo) .filter(([, worktrees]) => worktrees.length > 0) .map(([repoId]) => repoId) ) @@ -2766,6 +2879,7 @@ export const createTerminalSlice: StateCreator for (const workspace of s.folderWorkspaces) { validWorktreeIds.add(folderWorkspaceKey(workspace.id)) } + addAdditionalValidWorkspaceKeys(validWorktreeIds, options) for (const worktreeId of Object.keys(session.tabsByWorktree)) { const parsedWorkspaceKey = parseWorkspaceKey(worktreeId) if (parsedWorkspaceKey?.type === 'folder') { @@ -2841,9 +2955,10 @@ export const createTerminalSlice: StateCreator ) const fallbackActiveWorktreeId = !session.activeWorktreeId && session.activeRepoId && knownRepoIds.has(session.activeRepoId) - ? (s.worktreesByRepo[session.activeRepoId]?.find((worktree) => worktree.isMainWorktree) - ?.id ?? - s.worktreesByRepo[session.activeRepoId]?.[0]?.id ?? + ? (runtimeSessionPlaceholders.worktreesByRepo[session.activeRepoId]?.find( + (worktree) => worktree.isMainWorktree + )?.id ?? + runtimeSessionPlaceholders.worktreesByRepo[session.activeRepoId]?.[0]?.id ?? null) : null const activeWorktreeId = (() => { @@ -2866,7 +2981,8 @@ export const createTerminalSlice: StateCreator const activeTabId = session.activeTabId && validTabIds.has(session.activeTabId) ? session.activeTabId : null const activeRepoId = - session.activeRepoId && s.repos.some((repo) => repo.id === session.activeRepoId) + session.activeRepoId && + runtimeSessionPlaceholders.repos.some((repo) => repo.id === session.activeRepoId) ? session.activeRepoId : null @@ -2908,10 +3024,12 @@ export const createTerminalSlice: StateCreator // createOrAttach RPC, triggering reattach instead of a fresh spawn. const pendingReconnectPtyIdByTabId: Record = {} for (const worktreeId of pendingReconnectWorktreeIds) { - const worktree = Object.values(s.worktreesByRepo) + const worktree = Object.values(runtimeSessionPlaceholders.worktreesByRepo) .flat() .find((entry) => entry.id === worktreeId) - const repo = worktree ? s.repos.find((entry) => entry.id === worktree.repoId) : null + const repo = worktree + ? runtimeSessionPlaceholders.repos.find((entry) => entry.id === worktree.repoId) + : null if (repo?.connectionId) { continue } @@ -2963,8 +3081,10 @@ export const createTerminalSlice: StateCreator // data once SSH reconnects and fetchWorktrees runs. // Why: only SSH needs placeholders; local metadata should come from the // next successful fetch so the sidebar does not render synthetic entries. - const sshRepoIds = new Set(s.repos.filter((r) => r.connectionId).map((r) => r.id)) - const worktreesByRepo = { ...s.worktreesByRepo } + const sshRepoIds = new Set( + runtimeSessionPlaceholders.repos.filter((r) => r.connectionId).map((r) => r.id) + ) + const worktreesByRepo = { ...runtimeSessionPlaceholders.worktreesByRepo } for (const worktreeId of Object.keys(tabsByWorktree)) { const repoId = getRepoIdFromWorktreeId(worktreeId) if (!sshRepoIds.has(repoId)) { @@ -3017,6 +3137,9 @@ export const createTerminalSlice: StateCreator activeWorkspaceKey, activeTabId, activeTabIdByWorktree, + restoredRuntimeHostIdByWorkspaceSessionKey: + options?.runtimeHostIdByWorkspaceSessionKey ?? {}, + repos: runtimeSessionPlaceholders.repos, tabsByWorktree, worktreesByRepo, // Why: restore the per-worktree focus-recency map. Pruning of stale diff --git a/src/renderer/src/store/slices/ui.test.ts b/src/renderer/src/store/slices/ui.test.ts index 64899d1a1..6b4e88cbc 100644 --- a/src/renderer/src/store/slices/ui.test.ts +++ b/src/renderer/src/store/slices/ui.test.ts @@ -21,6 +21,7 @@ import { makePaneKey } from '../../../../shared/stable-pane-id' import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import type { TaskSourceContext } from '../../../../shared/task-source-context' +import { getSetupScriptPromptDismissalKey } from '../../lib/setup-script-prompt' const mocks = vi.hoisted(() => ({ sendNotesToActiveAgentSession: vi.fn(), @@ -763,6 +764,56 @@ describe('createUISlice hydratePersistedUI', () => { expect(store.getState().rightSidebarExplorerView).toBe('files') }) + it('preserves persisted repo filters until repos are loaded', () => { + const store = createUIStore() + const remoteDismissalKey = getSetupScriptPromptDismissalKey('remote-repo') + + store.getState().hydratePersistedUI( + makePersistedUI({ + filterRepoIds: ['remote-repo', 12 as never, 'stale-repo'], + trustedOrcaHooks: { + 'remote-repo': { all: { approvedAt: 1 } }, + 'bad-shape': 'yes' as never + }, + setupScriptPromptDismissedRepoIds: [remoteDismissalKey, 'remote-repo', remoteDismissalKey] + }) + ) + + expect(store.getState().filterRepoIds).toEqual(['remote-repo', 'stale-repo']) + expect(store.getState().trustedOrcaHooks).toEqual({ + 'remote-repo': { all: { approvedAt: 1 } } + }) + expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([remoteDismissalKey]) + }) + + it('validates persisted repo filters when repos are already loaded', () => { + const store = createUIStore() + const localDismissalKey = getSetupScriptPromptDismissalKey('local-repo') + const staleDismissalKey = getSetupScriptPromptDismissalKey('stale-repo') + store.setState({ + repos: [ + { id: 'local-repo', path: '/local', displayName: 'Local', badgeColor: '#000', addedAt: 1 } + ] + } as Partial) + + store.getState().hydratePersistedUI( + makePersistedUI({ + filterRepoIds: ['local-repo', 'stale-repo'], + trustedOrcaHooks: { + 'local-repo': { all: { approvedAt: 1 } }, + 'stale-repo': { all: { approvedAt: 2 } } + }, + setupScriptPromptDismissedRepoIds: [localDismissalKey, staleDismissalKey] + }) + ) + + expect(store.getState().filterRepoIds).toEqual(['local-repo']) + expect(store.getState().trustedOrcaHooks).toEqual({ + 'local-repo': { all: { approvedAt: 1 } } + }) + expect(store.getState().setupScriptPromptDismissedRepoIds).toEqual([localDismissalKey]) + }) + it('hydrates legacy persisted search tab as Explorer search', () => { const store = createUIStore() diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index c8e5f112e..3a0205cbe 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -89,7 +89,8 @@ import type { OrcaHookScriptKind } from '../../lib/orca-hook-trust' import type { SettingsNavTarget } from '@/lib/settings-navigation-types' import { filterSetupScriptPromptDismissalsToValidRepos, - getSetupScriptPromptDismissalKey + getSetupScriptPromptDismissalKey, + sanitizeSetupScriptPromptDismissals } from '../../lib/setup-script-prompt' import { DEFAULT_PET_ID, isBundledPetId } from '../../components/pet/pet-models' import { revokeCustomPetBlobUrl } from '../../components/pet/pet-blob-cache' @@ -349,12 +350,38 @@ function collectAcknowledgedAgentNotificationId({ } } -function filterTrustedOrcaHooksToValidRepos( - trust: PersistedTrustedOrcaHooks, - validRepoIds: Set -): PersistedTrustedOrcaHooks { +function isPlainPersistedRecord(value: unknown): value is Record { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value) +} + +function sanitizePersistedRepoIds(value: unknown): string[] { + if (!Array.isArray(value)) { + return [] + } + return value.filter((repoId): repoId is string => typeof repoId === 'string') +} + +function sanitizeTrustedOrcaHooks(trust: unknown): PersistedTrustedOrcaHooks { + if (!isPlainPersistedRecord(trust)) { + return {} + } const next: PersistedTrustedOrcaHooks = {} for (const [repoId, entry] of Object.entries(trust)) { + if (!isSafePersistedRecordKey(repoId) || !isPlainPersistedRecord(entry)) { + continue + } + next[repoId] = entry as PersistedTrustedOrcaHooks[string] + } + return next +} + +function filterTrustedOrcaHooksToValidRepos( + trust: unknown, + validRepoIds: Set +): PersistedTrustedOrcaHooks { + const sanitized = sanitizeTrustedOrcaHooks(trust) + const next: PersistedTrustedOrcaHooks = {} + for (const [repoId, entry] of Object.entries(sanitized)) { if (validRepoIds.has(repoId)) { next[repoId] = entry } @@ -362,6 +389,17 @@ function filterTrustedOrcaHooksToValidRepos( return next } +function hydrateTrustedOrcaHooks( + trust: unknown, + validRepoIds: Set +): PersistedTrustedOrcaHooks { + const sanitized = sanitizeTrustedOrcaHooks(trust) + if (validRepoIds.size === 0) { + return sanitized + } + return filterTrustedOrcaHooksToValidRepos(sanitized, validRepoIds) +} + function isSafePersistedRecordKey(key: string): boolean { return key !== '__proto__' && key !== 'constructor' && key !== 'prototype' } @@ -2192,6 +2230,7 @@ export const createUISlice: StateCreator = (set, get) hydratePersistedUI: (ui) => set((s) => { const validRepoIds = new Set(s.repos.map((repo) => repo.id)) + const persistedFilterRepoIds = sanitizePersistedRepoIds(ui.filterRepoIds) // Why: persisted UI from pre-rename builds used sidekick* keys. Read // those only as fallbacks so new pet* writes win immediately after upgrade. const customPets = Array.isArray(ui.customPets) @@ -2283,7 +2322,12 @@ export const createUISlice: StateCreator = (set, get) hideDefaultBranchWorkspace: ui.hideDefaultBranchWorkspace ?? false, hideAutomationGeneratedWorkspaces: ui.hideAutomationGeneratedWorkspaces === true, showDotfilesByWorktree: sanitizeShowDotfilesByWorktree(ui.showDotfilesByWorktree), - filterRepoIds: (ui.filterRepoIds ?? []).filter((repoId) => validRepoIds.has(repoId)), + // Why: startup hydrates UI before repo catalogs now. With no catalog + // loaded yet, defer repo-filter validation to the all-host repo refresh. + filterRepoIds: + validRepoIds.size === 0 + ? persistedFilterRepoIds + : persistedFilterRepoIds.filter((repoId) => validRepoIds.has(repoId)), collapsedGroups: new Set(ui.collapsedGroups ?? []), uiZoomLevel: ui.uiZoomLevel ?? 0, editorFontZoomLevel: ui.editorFontZoomLevel ?? 0, @@ -2332,14 +2376,14 @@ export const createUISlice: StateCreator = (set, get) typeof ui.contextualToursAutoEligible === 'boolean' ? ui.contextualToursAutoEligible : null, - trustedOrcaHooks: filterTrustedOrcaHooksToValidRepos( - ui.trustedOrcaHooks ?? {}, - validRepoIds - ), - setupScriptPromptDismissedRepoIds: filterSetupScriptPromptDismissalsToValidRepos( - ui.setupScriptPromptDismissedRepoIds, - validRepoIds - ), + trustedOrcaHooks: hydrateTrustedOrcaHooks(ui.trustedOrcaHooks, validRepoIds), + setupScriptPromptDismissedRepoIds: + validRepoIds.size === 0 + ? sanitizeSetupScriptPromptDismissals(ui.setupScriptPromptDismissedRepoIds) + : filterSetupScriptPromptDismissalsToValidRepos( + ui.setupScriptPromptDismissedRepoIds, + validRepoIds + ), setupGuideSidebarDismissed: ui.setupGuideSidebarDismissed === true, setupGuideBrowserMilestoneMigrated: ui.setupGuideBrowserMilestoneMigrated === true, setupGuideBrowserMilestoneLegacyComplete: diff --git a/src/renderer/src/store/slices/workspace-cleanup.test.ts b/src/renderer/src/store/slices/workspace-cleanup.test.ts index 116ec974d..3a5199e2a 100644 --- a/src/renderer/src/store/slices/workspace-cleanup.test.ts +++ b/src/renderer/src/store/slices/workspace-cleanup.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: cleanup store tests share a Zustand store - harness and mocked window API; splitting would obscure the state transitions. */ import { create } from 'zustand' import { describe, expect, it, vi } from 'vitest' import type { AppState } from '../types' diff --git a/src/renderer/src/store/slices/workspace-cleanup.ts b/src/renderer/src/store/slices/workspace-cleanup.ts index 357e4e74a..502cead19 100644 --- a/src/renderer/src/store/slices/workspace-cleanup.ts +++ b/src/renderer/src/store/slices/workspace-cleanup.ts @@ -21,7 +21,7 @@ import { type WorkspaceCleanupScanProgress, type WorkspaceCleanupScanResult } from '../../../../shared/workspace-cleanup' -import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status' +import { classifyTitleActivity, isExplicitAgentStatusFresh } from '@/lib/pane-agent-evidence' import { translate } from '@/i18n/i18n' export type WorkspaceCleanupFailure = { @@ -737,7 +737,7 @@ function hasWorkingTitleAgent(state: AppState, tabs: { id: string; title: string const titles = paneTitles && Object.keys(paneTitles).length > 0 ? Object.values(paneTitles) : [tab.title] for (const title of titles) { - const status = detectAgentStatusFromTitle(title) + const status = classifyTitleActivity(title) if (status === 'working' || status === 'permission') { return true } @@ -812,7 +812,7 @@ function hasIdleAgentTitleForPty( } function isIdleAgentTitle(title: string): boolean { - return detectAgentStatusFromTitle(title) === 'idle' + return classifyTitleActivity(title) === 'idle' } function getPaneKeyTabId(paneKey: AgentStatusEntry['paneKey']): string { diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index fbeee1fb7..bbc5575ae 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -112,7 +112,7 @@ export type WorktreeSlice = { hasHydratedWorktreePurge: boolean fetchDetectedWorktrees: (repoId: string) => Promise fetchWorktrees: (repoId: string, options?: { requireAuthoritative?: boolean }) => Promise - fetchAllWorktrees: () => Promise + fetchAllWorktrees: (options?: { hydrationPurge?: 'allow' | 'defer' }) => Promise fetchWorktreeLineage: () => Promise updateWorktreeLineage: ( worktreeId: string, diff --git a/src/renderer/src/store/slices/worktrees.test.ts b/src/renderer/src/store/slices/worktrees.test.ts index 58dfa5cb7..b9b5b0bdb 100644 --- a/src/renderer/src/store/slices/worktrees.test.ts +++ b/src/renderer/src/store/slices/worktrees.test.ts @@ -3241,6 +3241,29 @@ describe('removeWorktree state cleanup', () => { expect(getHostedReviewLinkMutationGenerationForTests(surviving.id)).toBeGreaterThan(0) }) + it('cleans up expandedPaneByTabId/canExpandPaneByTabId for removed worktree tabs', async () => { + const store = createTestStore() + const removed = makeWorktree({ id: 'repo1::/path/wt1', repoId: 'repo1', path: '/path/wt1' }) + const surviving = makeWorktree({ id: 'repo1::/path/wt2', repoId: 'repo1', path: '/path/wt2' }) + + store.setState({ + worktreesByRepo: { repo1: [removed, surviving] }, + tabsByWorktree: { + [removed.id]: [makeTerminalTab({ id: 'removed-tab', worktreeId: removed.id })], + [surviving.id]: [makeTerminalTab({ id: 'surviving-tab', worktreeId: surviving.id })] + }, + // Split panes write these even when false; only closeTab deleted them + // before, so removeWorktree used to strand them for the whole session. + expandedPaneByTabId: { 'removed-tab': true, 'surviving-tab': false }, + canExpandPaneByTabId: { 'removed-tab': false, 'surviving-tab': true } + } as unknown as Partial) + + await store.getState().removeWorktree(removed.id) + + expect(store.getState().expandedPaneByTabId).toEqual({ 'surviving-tab': false }) + expect(store.getState().canExpandPaneByTabId).toEqual({ 'surviving-tab': true }) + }) + it('cleans up automatic agent resume claims for removed worktree tabs', async () => { const store = createTestStore() const removed = makeWorktree({ @@ -5470,6 +5493,8 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => { const store = createTestStore() const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' }) const wtB = makeWorktree({ id: 'repoB::/b/wt1', repoId: 'repoB', path: '/b/wt1' }) + const folderWorkspace = makeFolderWorkspace({ id: 'folder-keep' }) + const folderKey = folderWorkspaceKey(folderWorkspace.id) mockApi.worktrees.list.mockImplementation(async ({ repoId }: { repoId: string }) => repoId === 'repoA' ? [wtA] : [wtB] @@ -5477,15 +5502,18 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => { store.setState({ repos: [repoA, repoB], + folderWorkspaces: [folderWorkspace], tabsByWorktree: { 'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }], 'repoA::/a/zombie': [{ id: 'tab-zombie', worktreeId: 'repoA::/a/zombie' }], - 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }] + 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }], + [folderKey]: [{ id: 'tab-folder', worktreeId: folderKey }] }, gitIgnoredPathsByWorktree: { 'repoA::/a/wt1': ['dist/'], 'repoA::/a/zombie': ['coverage/'], - 'repoB::/b/wt1': ['build/'] + 'repoB::/b/wt1': ['build/'], + [folderKey]: ['tmp/'] } } as unknown as Partial) @@ -5495,11 +5523,13 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => { expect(mockApi.worktrees.list).toHaveBeenCalledTimes(2) expect(store.getState().tabsByWorktree).toEqual({ 'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }], - 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }] + 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }], + [folderKey]: [{ id: 'tab-folder', worktreeId: folderKey }] }) expect(store.getState().gitIgnoredPathsByWorktree).toEqual({ 'repoA::/a/wt1': ['dist/'], - 'repoB::/b/wt1': ['build/'] + 'repoB::/b/wt1': ['build/'], + [folderKey]: ['tmp/'] }) // Second call must not re-run the purge even if new stale ids appear. @@ -5516,6 +5546,79 @@ describe('fetchAllWorktrees hydration-time purge (design §4.4)', () => { expect(store.getState().tabsByWorktree['repoA::/a/new-zombie']).toBeDefined() }) + it('can defer the first successful purge during local-only startup refresh', async () => { + const store = createTestStore() + const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' }) + const wtB = makeWorktree({ id: 'repoB::/b/wt1', repoId: 'repoB', path: '/b/wt1' }) + + mockApi.worktrees.list.mockImplementation(async ({ repoId }: { repoId: string }) => + repoId === 'repoA' ? [wtA] : [wtB] + ) + + store.setState({ + repos: [repoA, repoB], + tabsByWorktree: { + 'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }], + 'repoA::/a/zombie': [{ id: 'tab-zombie', worktreeId: 'repoA::/a/zombie' }], + 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }] + } + } as unknown as Partial) + + await store.getState().fetchAllWorktrees({ hydrationPurge: 'defer' }) + + expect(store.getState().hasHydratedWorktreePurge).toBe(false) + expect(store.getState().tabsByWorktree['repoA::/a/zombie']).toBeDefined() + + await store.getState().fetchAllWorktrees() + + expect(store.getState().hasHydratedWorktreePurge).toBe(true) + expect(store.getState().tabsByWorktree).toEqual({ + 'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }], + 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }] + }) + }) + + it('does not consume the one-shot purge before clean workspace session hydration', async () => { + const store = createTestStore() + const wtA = makeWorktree({ id: 'repoA::/a/wt1', repoId: 'repoA', path: '/a/wt1' }) + const wtB = makeWorktree({ id: 'repoB::/b/wt1', repoId: 'repoB', path: '/b/wt1' }) + + mockApi.worktrees.list.mockImplementation(async ({ repoId }: { repoId: string }) => + repoId === 'repoA' ? [wtA] : [wtB] + ) + + store.setState({ + workspaceSessionReady: false, + hydrationSucceeded: false, + repos: [repoA, repoB], + tabsByWorktree: { + 'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }], + 'repoA::/a/zombie': [{ id: 'tab-zombie', worktreeId: 'repoA::/a/zombie' }], + 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }] + } + } as unknown as Partial) + + await store.getState().fetchAllWorktrees() + + expect(store.getState().hasHydratedWorktreePurge).toBe(false) + expect(store.getState().tabsByWorktree['repoA::/a/zombie']).toBeDefined() + + store.setState({ workspaceSessionReady: true } as Partial) + await store.getState().fetchAllWorktrees() + + expect(store.getState().hasHydratedWorktreePurge).toBe(false) + expect(store.getState().tabsByWorktree['repoA::/a/zombie']).toBeDefined() + + store.setState({ hydrationSucceeded: true } as Partial) + await store.getState().fetchAllWorktrees() + + expect(store.getState().hasHydratedWorktreePurge).toBe(true) + expect(store.getState().tabsByWorktree).toEqual({ + 'repoA::/a/wt1': [{ id: 'tab-A', worktreeId: 'repoA::/a/wt1' }], + 'repoB::/b/wt1': [{ id: 'tab-B', worktreeId: 'repoB::/b/wt1' }] + }) + }) + // Why: multi-host regression — once hydration has fired, a mid-session // fetchAllWorktrees (e.g. triggered by switching focus) must NEVER purge // terminal state, even if a host transiently reports zero worktrees. The @@ -5849,6 +5952,8 @@ describe('purgeWorktreeTerminalState direct (design §4.4)', () => { 'tab-3': { panes: [] } }, ptyIdsByTabId: { 'tab-1': ['pty-1'], 'tab-2': ['pty-2'], 'tab-3': ['pty-3'] }, + expandedPaneByTabId: { 'tab-1': true, 'tab-2': false, 'tab-3': true }, + canExpandPaneByTabId: { 'tab-1': true, 'tab-2': true, 'tab-3': false }, runtimePaneTitlesByTabId: { 'tab-1': 'claude', 'tab-3': 'bash' }, automaticAgentResumeClaimsByTabId: { 'tab-1': { @@ -5914,6 +6019,8 @@ describe('purgeWorktreeTerminalState direct (design §4.4)', () => { }) expect(s.terminalLayoutsByTabId).toEqual({ 'tab-3': { panes: [] } }) expect(s.ptyIdsByTabId).toEqual({ 'tab-3': ['pty-3'] }) + expect(s.expandedPaneByTabId).toEqual({ 'tab-3': true }) + expect(s.canExpandPaneByTabId).toEqual({ 'tab-3': false }) expect(s.runtimePaneTitlesByTabId).toEqual({ 'tab-3': 'bash' }) expect(s.automaticAgentResumeClaimsByTabId).toEqual({ 'tab-3': { diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 5966530cc..d6882728e 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -42,6 +42,8 @@ import { moveFocusToRendererBeforeFocusedWebviewHidden } from './browser-webview import { toast } from 'sonner' import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord' import { forgetAgentHibernationTabOutput } from '@/lib/agent-hibernation-output-activity' +import { forgetForegroundTerminalTabs } from '@/lib/foreground-terminal-tabs' +import { forgetAgentStartupDeliveriesForTabs } from '@/lib/agent-startup-delivery-guards' import { branchName } from '@/lib/git-utils' import { markInputQuietSchedulerInput, scheduleAfterInputQuiet } from '@/lib/input-quiet-scheduler' import { clearSessionCommitDraftForWorktree } from '@/lib/source-control-commit-draft-session' @@ -1451,6 +1453,19 @@ export function resetHostedReviewLinkMutationGenerationForTests(): void { hostedReviewLinkWorktreeIdAliases.clear() } +export function setDetachedHeadAutoDerivedDisplayNameForTests( + worktreeId: string, + displayName: string +): void { + detachedHeadAutoDerivedDisplayNames.set(worktreeId, displayName) +} + +export function getDetachedHeadAutoDerivedDisplayNameForTests( + worktreeId: string +): string | undefined { + return detachedHeadAutoDerivedDisplayNames.get(worktreeId) +} + function hostedReviewLinksAreCleared(worktree: Worktree): boolean { return HOSTED_REVIEW_LINK_KEYS.every((key) => worktree[key] == null) && !worktree.pushTarget } @@ -1814,12 +1829,20 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial() + // Why: some terminal/agent maps are keyed by ptyId, not tabId. Collect the + // doomed panes' ptyIds now (while ptyIdsByTabId is still populated) so this + // bulk path can evict them the same way shutdownWorktreeTerminals does on the + // single-removeWorktree path. + const doomedPtyIds = new Set() const doomedBrowserWorkspaceIds = new Set() const doomedPageIds = new Set() const removedFileIds = new Set() for (const id of worktreeIdSet) { for (const tab of s.tabsByWorktree[id] ?? []) { doomedTabIds.add(tab.id) + for (const ptyId of s.ptyIdsByTabId[tab.id] ?? []) { + doomedPtyIds.add(ptyId) + } // Why: a removed worktree's panes are gone for good, so drop their // hibernation output epochs from that module-level map (mirrors the // hosted-review prune above). A future pane mints a fresh leafId at epoch 0. @@ -1828,7 +1851,14 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial(obj: Record): Record => { + let changed = false + const out = { ...obj } + for (const ptyId of doomedPtyIds) { + if (ptyId in out) { + delete out[ptyId] + changed = true + } + } + return changed ? out : obj + } // Pane-scoped maps are keyed by `${tabId}:${leafId}` (stable-pane-id); tabId // never contains ":", so the segment before the first ":" is the owning tab. const omitByPaneKeyTabPrefix = (obj: Record): Record => { @@ -1992,6 +2033,25 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial } }, - fetchAllWorktrees: async () => { + fetchAllWorktrees: async (options) => { const { repos } = get() // Why: once the one-shot hydration-time purge has fired, subsequent @@ -2433,10 +2493,31 @@ export const createWorktreeSlice: StateCreator // Defer; try again on the next fetchAllWorktrees call. return } + if ( + options?.hydrationPurge === 'defer' || + get().workspaceSessionReady === false || + get().hydrationSucceeded === false + ) { + // Why: startup first refreshes only local repos so the app can paint + // before remote runtime timeouts. Keep the one-shot purge available for + // the later all-host refresh, after a clean session hydrate and when + // remote worktree ids are known too. + return + } const validIds = new Set() // Why: floating is persisted renderer state, but not a repo worktree that // authoritative runtime scans can return. validIds.add(FLOATING_TERMINAL_WORKTREE_ID) + // Why: folder workspaces persist terminal tabs under `folder:` keys, + // but authoritative repo scans can never return those synthetic ids. + for (const workspace of get().folderWorkspaces ?? []) { + validIds.add(folderWorkspaceKey(workspace.id)) + } + for (const key of Object.keys(get().restoredRuntimeHostIdByWorkspaceSessionKey ?? {})) { + if (parseWorkspaceKey(key)?.type === 'folder') { + validIds.add(key) + } + } for (const result of Object.values(get().detectedWorktreesByRepo)) { if (!result.authoritative) { continue @@ -3077,6 +3158,13 @@ export const createWorktreeSlice: StateCreator const tabs = get().tabsByWorktree[worktreeId] ?? [] const tabIds = new Set(tabs.map((t) => t.id)) + // Why: this path deletes tabsByWorktree wholesale (not via closeTab), so + // purge the module-level maps keyed by this worktree/its tabs here too — + // matching buildWorktreePurgeState so retired ids don't accumulate. + detachedHeadAutoDerivedDisplayNames.delete(worktreeId) + forgetForegroundTerminalTabs(tabIds) + forgetAgentStartupDeliveriesForTabs(tabIds) + // Why: deletion is async (backend + terminal/browser teardown awaited // above), so snapshot the sidebar's current top-row anchor in the same // tick we remove the row. Recording at click time goes stale across the @@ -3098,12 +3186,19 @@ export const createWorktreeSlice: StateCreator ...s.automaticAgentResumeClaimsByTabId } const nextNativeChatLaunchPromptByTabId = { ...s.nativeChatLaunchPromptByTabId } + // Why: closeTab deletes these two per-tab maps but removeWorktree missed + // them, so a split pane's expand flags outlived its deleted worktree for + // the renderer's whole session. Purge them here to match closeTab. + const nextExpandedPaneByTabId = { ...s.expandedPaneByTabId } + const nextCanExpandPaneByTabId = { ...s.canExpandPaneByTabId } for (const tabId of tabIds) { delete nextLayouts[tabId] delete nextPtyIdsByTabId[tabId] delete nextRuntimePaneTitlesByTabId[tabId] delete nextAutomaticAgentResumeClaimsByTabId[tabId] delete nextNativeChatLaunchPromptByTabId[tabId] + delete nextExpandedPaneByTabId[tabId] + delete nextCanExpandPaneByTabId[tabId] } const nextDeleteState = { ...s.deleteStateByWorktreeId } delete nextDeleteState[worktreeId] @@ -3251,6 +3346,8 @@ export const createWorktreeSlice: StateCreator automaticAgentResumeClaimsByTabId: nextAutomaticAgentResumeClaimsByTabId, nativeChatLaunchPromptByTabId: nextNativeChatLaunchPromptByTabId, terminalLayoutsByTabId: nextLayouts, + expandedPaneByTabId: nextExpandedPaneByTabId, + canExpandPaneByTabId: nextCanExpandPaneByTabId, deleteStateByWorktreeId: nextDeleteState, baseStatusByWorktreeId: (() => { const nextStatus = { ...s.baseStatusByWorktreeId } diff --git a/src/renderer/src/web/web-preload-api.test.ts b/src/renderer/src/web/web-preload-api.test.ts index 0dd6b240f..4a1d7b36f 100644 --- a/src/renderer/src/web/web-preload-api.test.ts +++ b/src/renderer/src/web/web-preload-api.test.ts @@ -2490,6 +2490,7 @@ describe('web GitHub preload API', () => { repoId: 'repo-1', repoPath, branch: 'feature', + currentHeadOid: 'head-oid', linkedPRNumber: null, fallbackPRNumber: 9, fallbackPRSource: 'pr-cache' @@ -2510,6 +2511,7 @@ describe('web GitHub preload API', () => { branch: 'feature', linkedPRNumber: null, fallbackPRNumber: 9, + currentHeadOid: 'head-oid', acceptMergedFallbackPR: true } } diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index 8647c9b0d..5cf3a3c8e 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -1805,6 +1805,7 @@ function createGitHubApi(): WebGitHubApi { branch: candidate.branch, linkedPRNumber: candidate.linkedPRNumber ?? null, fallbackPRNumber: candidate.fallbackPRNumber ?? null, + currentHeadOid: candidate.currentHeadOid ?? null, ...(acceptMergedFallbackPR ? { acceptMergedFallbackPR: true } : {}) }) return pr diff --git a/src/renderer/src/web/web-runtime-client.test.ts b/src/renderer/src/web/web-runtime-client.test.ts index 2e6123118..8f7e500c3 100644 --- a/src/renderer/src/web/web-runtime-client.test.ts +++ b/src/renderer/src/web/web-runtime-client.test.ts @@ -1,6 +1,3 @@ -/* eslint-disable max-lines -- Why: these tests share one mocked browser - WebSocket/E2EE transport fixture, and splitting them would obscure the - subscription lifecycle regressions they cover. */ import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest' import WebSocket, { WebSocketServer } from 'ws' import { WebRuntimeClient } from './web-runtime-client' diff --git a/src/shared/ai-vault-resume-command.test.ts b/src/shared/ai-vault-resume-command.test.ts new file mode 100644 index 000000000..65fe12d4c --- /dev/null +++ b/src/shared/ai-vault-resume-command.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest' + +import { buildAiVaultResumeCommand } from './ai-vault-types' + +describe('buildAiVaultResumeCommand', () => { + it('wraps Windows cwd changes in cmd so PowerShell and cmd launch the same resume command', () => { + expect( + buildAiVaultResumeCommand({ + agent: 'codex', + sessionId: 'session-1', + cwd: 'C:\\Users\\Ada Lovelace\\repo', + platform: 'win32' + }) + ).toBe('cmd /d /s /c "cd /d ""C:\\Users\\Ada Lovelace\\repo"" && codex resume ""session-1"""') + }) + + it('carries non-default Codex homes in copied resume commands', () => { + expect( + buildAiVaultResumeCommand({ + agent: 'codex', + sessionId: 'session-1', + cwd: '/repo/app', + platform: 'darwin', + codexHome: '/Users/ada/Library/Application Support/Orca/codex-runtime-home/home' + }) + ).toBe( + "cd '/repo/app' && CODEX_HOME='/Users/ada/Library/Application Support/Orca/codex-runtime-home/home' codex resume 'session-1'" + ) + + expect( + buildAiVaultResumeCommand({ + agent: 'codex', + sessionId: 'session-1', + cwd: 'C:\\Users\\Ada Lovelace\\repo', + platform: 'win32', + codexHome: 'C:\\Users\\Ada\\AppData\\Roaming\\Orca\\codex-runtime-home\\home' + }) + ).toBe( + 'cmd /d /s /c "cd /d ""C:\\Users\\Ada Lovelace\\repo"" && set ""CODEX_HOME=C:\\Users\\Ada\\AppData\\Roaming\\Orca\\codex-runtime-home\\home"" && codex resume ""session-1"""' + ) + }) + + it('resumes OMP by absolute transcript path so it resolves across session-dir roots', () => { + expect( + buildAiVaultResumeCommand({ + agent: 'omp', + sessionId: '019f27cd-4268-7000-96e7-62f42a55c144', + resumeFilePath: + '/Users/ada/.omp/agent/sessions/repo/2026-07-03T11-30-29-357Z_019f27be/OmpScannerTests.jsonl', + cwd: '/Users/ada/repo', + platform: 'darwin' + }) + ).toBe( + "cd '/Users/ada/repo' && omp --resume '/Users/ada/.omp/agent/sessions/repo/2026-07-03T11-30-29-357Z_019f27be/OmpScannerTests.jsonl'" + ) + }) + + it('quotes queued OMP resume paths for the provided Windows shell', () => { + expect( + buildAiVaultResumeCommand({ + agent: 'omp', + sessionId: '019f27cd-4268-7000-96e7-62f42a55c144', + resumeFilePath: 'C:\\Users\\Ada Lovelace\\.omp\\agent\\sessions\\repo\\sess.jsonl', + cwd: 'C:\\Users\\Ada Lovelace\\repo', + platform: 'win32', + shell: 'powershell' + }) + ).toBe( + "Set-Location -LiteralPath 'C:\\Users\\Ada Lovelace\\repo'; omp --resume 'C:\\Users\\Ada Lovelace\\.omp\\agent\\sessions\\repo\\sess.jsonl'" + ) + }) + + it('falls back to the session id when no OMP transcript path is known', () => { + expect( + buildAiVaultResumeCommand({ + agent: 'omp', + sessionId: '019f27cd-4268-7000-96e7-62f42a55c144', + resumeFilePath: null, + cwd: '/Users/ada/repo', + platform: 'darwin' + }) + ).toBe("cd '/Users/ada/repo' && omp --resume '019f27cd-4268-7000-96e7-62f42a55c144'") + }) +}) diff --git a/src/shared/ai-vault-types.ts b/src/shared/ai-vault-types.ts index 58bf82597..df6abfb83 100644 --- a/src/shared/ai-vault-types.ts +++ b/src/shared/ai-vault-types.ts @@ -12,6 +12,7 @@ export const AI_VAULT_AGENTS = [ 'codex', 'hermes', 'pi', + 'omp', 'cursor', 'gemini', 'rovo', @@ -34,6 +35,7 @@ export const AI_VAULT_AGENT_LABELS = { codex: 'Codex', hermes: 'Hermes', pi: 'Pi', + omp: 'OMP', cursor: 'Cursor', gemini: 'Gemini', rovo: 'Rovo Dev', @@ -102,13 +104,23 @@ export function buildAiVaultResumeCommand(args: { platform: NodeJS.Platform commandOverride?: string | null codexHome?: string | null + resumeFilePath?: string | null + shell?: AgentStartupShell }): string { - const { agent, sessionId, cwd, platform, commandOverride, codexHome } = args + const { agent, sessionId, cwd, platform, commandOverride, codexHome, resumeFilePath, shell } = + args const baseCommand = commandOverride?.trim() || defaultAiVaultResumeCommandBase(agent) - const sessionArg = quoteShellArg(sessionId, platform) + // Why: OMP's `--resume` accepts an absolute transcript path, which resolves + // regardless of which session-dir root (custom OMP_CODING_AGENT_DIR / WSL + // home) the file was discovered under, where an id-prefix lookup scoped to + // the default store would miss it. Falls back to the id if no path is known. + const resumeTarget = agent === 'omp' && resumeFilePath?.trim() ? resumeFilePath.trim() : sessionId + const sessionArg = shell + ? quoteStartupArg(resumeTarget, shell) + : quoteShellArg(resumeTarget, platform) const resumeCommand = buildAgentResumeInvocation(agent, baseCommand, sessionArg) - return buildAiVaultResumeShellCommand({ resumeCommand, cwd, platform, codexHome }) + return buildAiVaultResumeShellCommand({ resumeCommand, cwd, platform, codexHome, shell }) } export function buildAiVaultResumeShellCommand(args: { @@ -222,6 +234,9 @@ function buildAgentResumeInvocation( case 'devin': case 'openclaw': case 'droid': + // Why: OMP resumes by absolute transcript path (see buildAiVaultResumeCommand), + // but the `--resume ` invocation form is identical to the others here. + case 'omp': return `${baseCommand} --resume ${sessionArg}` } } diff --git a/src/shared/constants.ts b/src/shared/constants.ts index cc9f8ce96..7e0aef0cd 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -436,7 +436,9 @@ export function getDefaultPersistedState(homedir: string): PersistedState { workspaceSession: getDefaultWorkspaceSession(), workspaceSessionsByHostId: {}, sshTargets: [], + deletedSshConfigAliases: [], sshRemotePtyLeases: [], + claudeLivePtySessionIds: [], migrationUnsupportedPtyEntries: [], legacyPaneKeyAliasEntries: [], automations: [], diff --git a/src/shared/git-effective-upstream.ts b/src/shared/git-effective-upstream.ts index 2b99a951f..8292a9299 100644 --- a/src/shared/git-effective-upstream.ts +++ b/src/shared/git-effective-upstream.ts @@ -206,12 +206,25 @@ export async function getEffectiveGitUpstreamStatus( } } - const { stdout } = await runGit([ - 'rev-list', - '--left-right', - '--count', - `HEAD...${upstream.upstreamName}` - ]) + return getGitUpstreamStatusForUpstreamName( + runGit, + upstream.upstreamName, + getBehindCommitsArePatchEquivalent + ) +} + +/** + * Ahead/behind status for an already-resolved upstream name. Split out so + * callers that cached the resolution (a pure function of branch/config state) + * can refresh the counts with a single rev-list spawn instead of re-running + * the whole resolution chain. + */ +export async function getGitUpstreamStatusForUpstreamName( + runGit: GitCommandRunner, + upstreamName: string, + getBehindCommitsArePatchEquivalent?: (upstreamName: string) => Promise +): Promise { + const { stdout } = await runGit(['rev-list', '--left-right', '--count', `HEAD...${upstreamName}`]) const counts = parseGitRevListAheadBehindCounts(stdout) if (counts.status === 'unexpected-field-count') { throw new Error(`Unexpected git rev-list output: ${JSON.stringify(stdout)}`) @@ -222,12 +235,12 @@ export async function getEffectiveGitUpstreamStatus( const behindCommitsArePatchEquivalent = counts.ahead > 0 && counts.behind > 0 && getBehindCommitsArePatchEquivalent - ? await getBehindCommitsArePatchEquivalent(upstream.upstreamName) + ? await getBehindCommitsArePatchEquivalent(upstreamName) : undefined return { hasUpstream: true, - upstreamName: upstream.upstreamName, + upstreamName, ahead: counts.ahead, behind: counts.behind, ...(behindCommitsArePatchEquivalent !== undefined ? { behindCommitsArePatchEquivalent } : {}) diff --git a/src/shared/telemetry-events.test.ts b/src/shared/telemetry-events.test.ts index 7b65e72b6..8abdddba6 100644 --- a/src/shared/telemetry-events.test.ts +++ b/src/shared/telemetry-events.test.ts @@ -1,5 +1,3 @@ -/* eslint-disable max-lines -- Why: telemetry schema tests keep related event - invariants together so cross-event payload rules stay easy to audit. */ // Schema round-trip coverage for the event map. Fail-closed invariants that // must hold: agent_error is enum-only (error_message / error_stack rejected // by `.strict()`), unknown enum values fail, and any well-formed payload diff --git a/src/shared/types.ts b/src/shared/types.ts index 55ed30076..9c074ad2b 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1137,6 +1137,13 @@ export type PRInfo = { // of the PR's own commits (behind update-branch/web commits). Cache staleness // checks must honor that confirmation without re-querying GitHub. confirmedContainedHeadOid?: string + // Why: the worktree HEAD OID this merged linked PR was confirmed to have + // diverged from (a definite not-contained probe). Head-scoped, not a bare + // boolean, so a PR-number-coalesced refresh broadcast cannot clear a sibling + // worktree whose own head is still on the PR's line of work. Clearing a + // durable linked PR requires this positive signal for that exact head, never + // the mere absence of a containment confirmation after a rate-limit/error. + headDivergedFromMergedPRAtOid?: string /** Target branch name for PR-created worktree compare-base repair. */ baseRefName?: string prRepo?: GitHubRepositoryIdentity @@ -1179,6 +1186,10 @@ export type GitHubPRRefreshAlias = { linkedPRNumber?: number | null fallbackPRNumber?: number | null fallbackPRSource?: 'explicit' | 'pr-cache' | 'hosted-review' | null + // Why: request-time worktree HEAD. Merged branch-matched PRs are only visible + // for heads that belong to the PR, and refresh consumers need this snapshot to + // clear a durable linked PR once main confirms the head diverged. + currentHeadOid?: string | null } export type GitHubPRRefreshCandidate = GitHubPRRefreshAlias & { @@ -1196,10 +1207,6 @@ export type GitHubPRRefreshCandidate = GitHubPRRefreshAlias & { cachedMergeable?: PRMergeableState | null cachedMergeStateStatus?: string | null localGitOptions?: { wslDistro?: string } - // Why: merged branch-matched PRs are only visible for heads that belong to - // the PR; without the worktree head, a panel-supplied fallback number would - // keep a merged PR alive head-blind after the branch moves on. - currentHeadOid?: string | null } export type GitHubPRRefreshSkippedReason = @@ -3491,7 +3498,15 @@ export type PersistedState = { * pre-partition builds keep working. Optional/absent on legacy files. */ workspaceSessionsByHostId?: Partial> sshTargets: SshTarget[] + /** SSH config aliases the user explicitly deleted. Suppresses re-import of the + * matching ~/.ssh/config host on the next sync so a deleted host does not + * reappear. Cleared for an alias when the user re-adds it or re-adopts config. */ + deletedSshConfigAliases: string[] sshRemotePtyLeases: SshRemotePtyLease[] + /** Daemon session ids of live local Claude launches. Seeds the Claude + * live-PTY gate on startup so an early OAuth refresh cannot rotate the + * single-use refresh token out from under a still-running daemon CLI. */ + claudeLivePtySessionIds?: string[] migrationUnsupportedPtyEntries: MigrationUnsupportedPtyEntry[] legacyPaneKeyAliasEntries: LegacyPaneKeyAliasEntry[] automations: Automation[] diff --git a/src/shared/window-shortcut-policy.test.ts b/src/shared/window-shortcut-policy.test.ts index efae35957..25e66e803 100644 --- a/src/shared/window-shortcut-policy.test.ts +++ b/src/shared/window-shortcut-policy.test.ts @@ -1,7 +1,3 @@ -/* eslint-disable max-lines -- Why: this file covers every branch of the -shortcut policy (letter chords, zoom variants, alt/shift gating, history -navigation, new-workspace tab routing). Splitting across files would -fragment the test of a single pure function. */ import { describe, expect, it } from 'vitest' import { isRecentTabSwitcherCommitRelease, diff --git a/tests/e2e/activity-agent-pane-isolation.spec.ts b/tests/e2e/activity-agent-pane-isolation.spec.ts index ee1c87c2d..fe6600f3f 100644 --- a/tests/e2e/activity-agent-pane-isolation.spec.ts +++ b/tests/e2e/activity-agent-pane-isolation.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Activity E2E keeps the setup helpers beside the split-pane, split-group, and workspace-card routing assertions they support. */ import type { Page } from '@stablyai/playwright-test' import { test, expect } from './helpers/orca-app' import { diff --git a/tests/e2e/droid-notification.spec.ts b/tests/e2e/droid-notification.spec.ts index 16dc2a69f..587252042 100644 --- a/tests/e2e/droid-notification.spec.ts +++ b/tests/e2e/droid-notification.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: this e2e shares one Electron notification spy and hook endpoint setup across related notification regressions. */ import { test, expect } from './helpers/orca-app' import type { ElectronApplication, Page } from '@stablyai/playwright-test' import { getRendererTitleLog, installRendererTitleLog } from './helpers/terminal-title-log' diff --git a/tests/e2e/onboarding.spec.ts b/tests/e2e/onboarding.spec.ts index 1fd2e1cc8..5a93391f2 100644 --- a/tests/e2e/onboarding.spec.ts +++ b/tests/e2e/onboarding.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: onboarding E2E coverage shares one first-launch wizard fixture and step helpers; splitting this file would make the linear flow harder to audit. */ /** * E2E tests for the first-launch Onboarding flow. * diff --git a/tests/e2e/setup-guide-sidebar.spec.ts b/tests/e2e/setup-guide-sidebar.spec.ts index 7e1ff7087..b01454e30 100644 --- a/tests/e2e/setup-guide-sidebar.spec.ts +++ b/tests/e2e/setup-guide-sidebar.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Why: this regression spec keeps the deterministic IPC fakes, setup-state seeding, and frame-level flash monitor together so the flicker contract is auditable in one place. */ import type { ElectronApplication, Page } from '@stablyai/playwright-test' import type { SkillDiscoveryResult } from '../../src/shared/skills' import { test, expect } from './helpers/orca-app' diff --git a/tests/e2e/ssh-docker-relay-perf.spec.ts b/tests/e2e/ssh-docker-relay-perf.spec.ts index ddcbee655..c8e3beab6 100644 --- a/tests/e2e/ssh-docker-relay-perf.spec.ts +++ b/tests/e2e/ssh-docker-relay-perf.spec.ts @@ -207,6 +207,104 @@ test.describe('Docker SSH relay perf', () => { } }) + test('keeps remote typing responsive while relay file streams and git churn are active', async ({ + orcaPage + }, testInfo) => { + test.slow() + let target: DockerSshRelayTarget | null = null + try { + target = startDockerSshRelayTarget(testInfo) + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + const remote = await connectDockerRemote(orcaPage, target) + await ensureTerminalVisible(orcaPage, 45_000) + await waitForActiveTerminalManager(orcaPage, 60_000) + const ptyId = await waitForActivePanePtyId(orcaPage, 60_000) + + const runId = String(Date.now()) + // Large remote binaries: each read streams ~8MB of fs.streamChunk frames + // over the same SSH channel that carries the pty echo. + const loadFiles = [ + `${DOCKER_SSH_RELAY_REMOTE_REPO_PATH}/stream-load-a.png`, + `${DOCKER_SSH_RELAY_REMOTE_REPO_PATH}/stream-load-b.png` + ] + await execInTerminal( + orcaPage, + ptyId, + `dd if=/dev/urandom of=${shellQuote(loadFiles[0])} bs=1M count=8 status=none && ` + + `dd if=/dev/urandom of=${shellQuote(loadFiles[1])} bs=1M count=8 status=none && ` + + `echo LOAD_FILES_READY_${runId}` + ) + await waitForTerminalOutput(orcaPage, `LOAD_FILES_READY_${runId}`, 60_000, 80_000) + + await execInTerminal(orcaPage, ptyId, `node -e ${shellQuote(remoteTypingLoadScript(runId))}`) + await waitForTerminalOutput(orcaPage, `REMOTE_TUI_READY_${runId}`, 30_000, 80_000) + + // Background relay pressure: continuous large file reads plus git status + // refreshes, mirroring file preview + source-control churn while typing. + await orcaPage.evaluate( + ({ targetId, files, repoPath }) => { + const state = { stopped: false, reads: 0, errors: [] as string[] } + ;(window as unknown as { __sshRelayLoad: typeof state }).__sshRelayLoad = state + const loop = async (run: () => Promise): Promise => { + while (!state.stopped) { + try { + await run() + state.reads += 1 + } catch (err) { + state.errors.push(String(err)) + await new Promise((r) => setTimeout(r, 100)) + } + } + } + for (const filePath of files) { + void loop(() => window.api.fs.readFile({ filePath, connectionId: targetId })) + } + void loop(() => window.api.git.status({ worktreePath: repoPath, connectionId: targetId })) + }, + { + targetId: remote.targetId, + files: loadFiles, + repoPath: DOCKER_SSH_RELAY_REMOTE_REPO_PATH + } + ) + // Let the bulk load ramp before measuring. + await orcaPage.waitForTimeout(1_000) + + const measurement = await measureRemoteTyping(orcaPage, ptyId, runId) + const load = await orcaPage.evaluate(() => { + const state = ( + window as unknown as { + __sshRelayLoad: { stopped: boolean; reads: number; errors: string[] } + } + ).__sshRelayLoad + state.stopped = true + return { reads: state.reads, errors: state.errors.slice(0, 3) } + }) + + const summary = + `median=${measurement.medianLatencyMs.toFixed(1)}ms ` + + `worst=${measurement.worstLatencyMs.toFixed(1)}ms ` + + `bulkReads=${load.reads} ` + + `samples=${measurement.latencies.map((value) => value.toFixed(1)).join(',')}` + console.log(`[docker-ssh-relay-perf:busy] ${summary}`) + testInfo.annotations.push({ + type: 'docker-ssh-relay-typing-busy', + description: summary + }) + + // The load must actually have been streaming and error-free, otherwise + // the latency numbers prove nothing. + expect(load.errors).toEqual([]) + expect(load.reads).toBeGreaterThan(0) + expect(measurement.medianLatencyMs).toBeLessThan(MAX_MEDIAN_KEY_LATENCY_MS) + expect(measurement.worstLatencyMs).toBeLessThan(MAX_WORST_KEY_LATENCY_MS) + await stopRemoteLoad(orcaPage, ptyId) + } finally { + cleanupDockerSshRelayTarget(target) + } + }) + test('keeps an SSH workspace terminal usable after disconnect and reconnect', async ({ orcaPage }, testInfo) => { diff --git a/tests/e2e/ssh-localhost.spec.ts b/tests/e2e/ssh-localhost.spec.ts index d51ad2f7a..c406186d9 100644 --- a/tests/e2e/ssh-localhost.spec.ts +++ b/tests/e2e/ssh-localhost.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Localhost SSH E2E covers setup, remote PTY, hook relay, and interrupt inference in one expensive app boot. */ import os from 'node:os' import type { Page } from '@stablyai/playwright-test' diff --git a/tests/e2e/terminal-output-scheduler.spec.ts b/tests/e2e/terminal-output-scheduler.spec.ts index e4fa1cc43..014ffe9cd 100644 --- a/tests/e2e/terminal-output-scheduler.spec.ts +++ b/tests/e2e/terminal-output-scheduler.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Scheduler E2E coverage shares one booted Electron app and debug API. */ /** * E2E repro for terminal output bursts from many background tabs. * diff --git a/tests/e2e/terminal-restart-persistence.spec.ts b/tests/e2e/terminal-restart-persistence.spec.ts index cdb6a5423..19cccc43c 100644 --- a/tests/e2e/terminal-restart-persistence.spec.ts +++ b/tests/e2e/terminal-restart-persistence.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Restart persistence E2E covers separate lifecycle regressions that need real relaunches. */ /** * E2E tests for terminal scrollback persistence across clean app restarts. * diff --git a/tests/e2e/terminal-shortcuts.spec.ts b/tests/e2e/terminal-shortcuts.spec.ts index fbea6ebf1..d0243f5cc 100644 --- a/tests/e2e/terminal-shortcuts.spec.ts +++ b/tests/e2e/terminal-shortcuts.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-lines -- Terminal shortcut E2E keeps platform keyboard paths beside their shared PTY assertions. */ /** * E2E test for terminal keyboard shortcuts. * diff --git a/tools/benchmarks/main-thread-jank-bench.mjs b/tools/benchmarks/main-thread-jank-bench.mjs new file mode 100644 index 000000000..4b2aeebd0 --- /dev/null +++ b/tools/benchmarks/main-thread-jank-bench.mjs @@ -0,0 +1,419 @@ +#!/usr/bin/env node +/** + * Orca main-thread jank / subprocess-churn benchmark (issue #7576). + * + * Reproduces the reporter's setup: a running app with an active git worktree + * and the Source Control sidebar open, measured at steady state. The app is + * launched with ORCA_MAIN_THREAD_DIAGNOSTICS=1 so the main process emits one + * `[main-thread] {json}` stderr line every 5s containing: + * - worst event-loop stall in the window (maxGapMs) and stall counts + * - subprocess spawns since the last report, keyed by command + * ("git status", "gh api", …) with the synchronous spawn-initiation cost + * that held the main thread (blockMsTotal/blockMsMax) + * On macOS the bench also tails the unified log for the exact + * "Performance Diagnostics" warnings from the issue and records which process + * emitted them, so spawn churn and OS warnings can be correlated by timestamp. + * + * Usage: + * node tools/benchmarks/main-thread-jank-bench.mjs --label baseline + * [--duration-s 120] [--warmup-s 20] [--fixture-dir ] + * [--exe ] [--headless] [--no-log-stream] + * + * The window must stay VISIBLE during the run: git-status polling is gated on + * document visibility, so a hidden/minimized window measures nothing. + * --headless exists only for smoke-testing the harness itself. + * + * Prereq (when not using --exe): `pnpm build:electron-vite` so out/ exists. + * Results: tools/benchmarks/results/main-thread-jank-