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 ? (
-
e.preventDefault()}
- onClick={() => {
- setQuery('')
- setIsFilteringQuery(false)
- onChange('')
+
+