Merge remote-tracking branch 'origin/main' into Jinwoo-H/windows-update-survival
# Conflicts: # src/main/daemon/daemon-init.ts
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -62,6 +62,7 @@ coverage/
|
||||
|
||||
# Benchmark run output
|
||||
/tools/benchmarks/results/*.json
|
||||
/.bench-fixtures/
|
||||
|
||||
# Temp
|
||||
tmp/
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
</td>
|
||||
<td width="50%">
|
||||
@@ -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)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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",
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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([])
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 3.6m">
|
||||
<title>downloads: 3.6m</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="113" height="20" role="img" aria-label="downloads: 3.7m">
|
||||
<title>downloads: 3.7m</title>
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
@@ -15,7 +15,7 @@
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="11">
|
||||
<text x="37" y="15" fill="#010101" fill-opacity=".3">downloads</text>
|
||||
<text x="37" y="14">downloads</text>
|
||||
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">3.6m</text>
|
||||
<text x="93.5" y="14">3.6m</text>
|
||||
<text x="93.5" y="15" fill="#010101" fill-opacity=".3">3.7m</text>
|
||||
<text x="93.5" y="14">3.7m</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 943 B After Width: | Height: | Size: 943 B |
@@ -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.
|
||||
+2
-2
@@ -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",
|
||||
|
||||
@@ -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<string, boolean>()
|
||||
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]
|
||||
|
||||
@@ -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<typeof vi.fn>
|
||||
}
|
||||
|
||||
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<string, never>
|
||||
}) => 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<string, MobileDirEntry[]>): MockClient {
|
||||
return {
|
||||
sendRequest: vi.fn(async (_method: string, params: { relativePath: string }) => {
|
||||
return ok(entriesByPath[params.relativePath] ?? [])
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function renderExplorer(): Promise<ReactTestRenderer> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<RpcResponse>((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<RpcResponse> => {
|
||||
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<RpcResponse> => {
|
||||
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<RpcResponse> => {
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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<MobileFileEntry[]>([])
|
||||
const scopeRef = useRef('')
|
||||
const scope = `${hostId}:${worktreeId}`
|
||||
scopeRef.current = scope
|
||||
const directoryLoadRevisionsRef = useRef<DirectoryLoadRevisions>(createDirectoryLoadRevisions())
|
||||
const pendingDirectoryRetriesRef = useRef<Set<string>>(new Set())
|
||||
const directoryCacheRef = useRef<DirectoryCache>({})
|
||||
const [directoryCache, setDirectoryCache] = useState<DirectoryCache>({})
|
||||
const [expanded, setExpanded] = useState<Set<string>>(() => new Set())
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(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<TreeNode> = ({ 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<FileExplorerRow> = ({ item }) => {
|
||||
return (
|
||||
<Pressable
|
||||
style={({ pressed }) => [
|
||||
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 ? (
|
||||
<ChevronDown size={16} color={colors.textSecondary} />
|
||||
) : (
|
||||
<ChevronRight size={16} color={colors.textSecondary} />
|
||||
)
|
||||
) : (
|
||||
<View style={styles.chevronSpacer} />
|
||||
)}
|
||||
{isDirectory ? (
|
||||
<Folder size={17} color={colors.textSecondary} />
|
||||
) : markdown ? (
|
||||
<FileText size={17} color={disabled ? colors.textMuted : colors.textSecondary} />
|
||||
) : isImage ? (
|
||||
<ImageIcon size={17} color={colors.textSecondary} />
|
||||
) : (
|
||||
<File size={17} color={disabled ? colors.textMuted : colors.textSecondary} />
|
||||
)}
|
||||
<View style={styles.rowTextBlock}>
|
||||
<Text style={[styles.rowTitle, disabled && styles.rowTitleDisabled]} numberOfLines={1}>
|
||||
{item.name}
|
||||
</Text>
|
||||
{disabled ? <Text style={styles.rowMeta}>Unavailable on mobile</Text> : null}
|
||||
</View>
|
||||
</Pressable>
|
||||
<MobileFileExplorerRow
|
||||
item={item}
|
||||
expanded={expanded}
|
||||
onPreviewFile={previewFile}
|
||||
onRetryDirectory={retryDirectory}
|
||||
onToggleDirectory={toggleDirectory}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -206,7 +313,7 @@ export function MobileFileExplorerPanel(props: {
|
||||
</Text>
|
||||
<Text style={styles.meta} numberOfLines={1}>
|
||||
{worktreeLabel}
|
||||
{truncated ? ' - Showing first 5000' : ''}
|
||||
{legacyListTruncated ? ' - Showing first 5000' : ''}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
@@ -220,12 +327,12 @@ export function MobileFileExplorerPanel(props: {
|
||||
<View style={styles.state}>
|
||||
<Text style={styles.errorText}>{error}</Text>
|
||||
{/* 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. */}
|
||||
<Pressable
|
||||
style={styles.retryButton}
|
||||
onPress={() =>
|
||||
connState !== 'connected' && hostId ? void forceReconnect(hostId) : void loadFiles()
|
||||
connState !== 'connected' && hostId ? void forceReconnect(hostId) : void loadDirectory('')
|
||||
}
|
||||
>
|
||||
<Text style={styles.retryText}>Retry</Text>
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,42 @@
|
||||
export type DirectoryLoadRevisions = {
|
||||
generation: number
|
||||
revisionsByPath: Map<string, number>
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -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 }
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -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<string, Map<string, boolean>>()
|
||||
const ensureDir = (path: string): Map<string, boolean> => {
|
||||
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
|
||||
})
|
||||
)
|
||||
}
|
||||
])
|
||||
)
|
||||
}
|
||||
@@ -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', () => {
|
||||
|
||||
+130
-69
@@ -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<string, DirectoryState | undefined>
|
||||
|
||||
export type InlineStatusNode = {
|
||||
id: string
|
||||
relativePath: string
|
||||
directories: Map<string, DirectoryNode>
|
||||
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<string>): 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<string>
|
||||
): FileExplorerRow[] {
|
||||
const rows: FileExplorerRow[] = []
|
||||
visitDirectory('', 0, cache, expanded, rows)
|
||||
return rows
|
||||
}
|
||||
|
||||
function visitDirectory(
|
||||
relativePath: string,
|
||||
depth: number,
|
||||
cache: DirectoryCache,
|
||||
expanded: ReadonlySet<string>,
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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<string>
|
||||
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 (
|
||||
<View style={[styles.inlineStatusRow, { paddingLeft: spacing.lg + item.depth * 18 }]}>
|
||||
<View style={styles.chevronSpacer} />
|
||||
<ActivityIndicator size="small" color={colors.textSecondary} />
|
||||
<Text style={styles.inlineStatusText}>Loading...</Text>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
if (item.kind === 'error') {
|
||||
return (
|
||||
<View style={[styles.inlineStatusRow, { paddingLeft: spacing.lg + item.depth * 18 }]}>
|
||||
<View style={styles.chevronSpacer} />
|
||||
<Text style={styles.inlineErrorText} numberOfLines={1}>
|
||||
{item.message || 'Unable to load folder'}
|
||||
</Text>
|
||||
<Pressable
|
||||
style={({ pressed }) => [styles.inlineRetryButton, pressed && styles.rowPressed]}
|
||||
onPress={() => {
|
||||
triggerSelection()
|
||||
onRetryDirectory(item.relativePath)
|
||||
}}
|
||||
accessibilityLabel={`Retry loading ${item.relativePath}`}
|
||||
>
|
||||
<Text style={styles.inlineRetryText}>Retry</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
if (isTreeNode(item)) {
|
||||
return (
|
||||
<TreeRow
|
||||
item={item}
|
||||
expanded={expanded}
|
||||
onPreviewFile={onPreviewFile}
|
||||
onToggleDirectory={onToggleDirectory}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
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<string>
|
||||
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 (
|
||||
<Pressable
|
||||
style={({ pressed }) => [
|
||||
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 ? (
|
||||
<ChevronDown size={16} color={colors.textSecondary} />
|
||||
) : (
|
||||
<ChevronRight size={16} color={colors.textSecondary} />
|
||||
)
|
||||
) : (
|
||||
<View style={styles.chevronSpacer} />
|
||||
)}
|
||||
{isDirectory ? (
|
||||
<Folder size={17} color={colors.textSecondary} />
|
||||
) : markdown ? (
|
||||
<FileText size={17} color={disabled ? colors.textMuted : colors.textSecondary} />
|
||||
) : isImage ? (
|
||||
<ImageIcon size={17} color={colors.textSecondary} />
|
||||
) : (
|
||||
<File size={17} color={disabled ? colors.textMuted : colors.textSecondary} />
|
||||
)}
|
||||
<View style={styles.rowTextBlock}>
|
||||
<Text style={[styles.rowTitle, disabled && styles.rowTitleDisabled]} numberOfLines={1}>
|
||||
{item.name}
|
||||
</Text>
|
||||
{disabled ? <Text style={styles.rowMeta}>Unavailable on mobile</Text> : null}
|
||||
</View>
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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.
|
||||
|
||||
+4
-2
@@ -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": {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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<string>
|
||||
}
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -119,6 +119,12 @@ const AGENT_PROMPT_SENT_AGENT_KINDS = new Set<AgentKind>(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<string, EnrichedAgentHookEventPayload>
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<AiVaultSession | null> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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':
|
||||
|
||||
@@ -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, unknown>): 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
|
||||
@@ -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<string, string>
|
||||
}
|
||||
|
||||
const codexSessionIndexTitleCache = new Map<string, Promise<CodexSessionIndexTitleCacheEntry>>()
|
||||
|
||||
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<string | null>
|
||||
executionHostId?: ExecutionHostId
|
||||
executionHostPlatform?: NodeJS.Platform | null
|
||||
}
|
||||
): Promise<AiVaultSession | null> {
|
||||
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<string | null>
|
||||
): 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<string> | Iterable<string>
|
||||
@@ -83,142 +288,22 @@ async function parseCodexSessionLines(args: {
|
||||
executionHostPlatform?: NodeJS.Platform | null
|
||||
titleReader?: (sessionId: string) => Promise<string | null>
|
||||
}): Promise<AiVaultSession | null> {
|
||||
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, unknown>): string | null {
|
||||
return extractString(payload.thread_source) ?? extractString(payload.threadSource)
|
||||
}
|
||||
@@ -240,79 +325,3 @@ function extractCodexSessionMetadataTitle(payload: Record<string, unknown>): str
|
||||
normalizeTitleText(extractString(payload.threadName) ?? '')
|
||||
)
|
||||
}
|
||||
|
||||
async function readCodexSessionIndexTitle(
|
||||
sessionFilePath: string,
|
||||
codexHome: string | null,
|
||||
sessionId: string
|
||||
): Promise<string | null> {
|
||||
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<Map<string, string>> {
|
||||
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<Map<string, string>> {
|
||||
const titleBySessionId = new Map<string, string>()
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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 <CODEX_HOME>/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<string, string>
|
||||
}
|
||||
|
||||
const codexSessionIndexTitleCache = new Map<string, Promise<CodexSessionIndexTitleCacheEntry>>()
|
||||
|
||||
export async function readCodexSessionIndexTitle(
|
||||
sessionFilePath: string,
|
||||
codexHome: string | null,
|
||||
sessionId: string
|
||||
): Promise<string | null> {
|
||||
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<Map<string, string>> {
|
||||
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<Map<string, string>> {
|
||||
const titleBySessionId = new Map<string, string>()
|
||||
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
|
||||
}
|
||||
@@ -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'),
|
||||
|
||||
@@ -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) })
|
||||
|
||||
@@ -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<string> | Iterable<string>
|
||||
platform: NodeJS.Platform
|
||||
options?: ParserSessionOptions
|
||||
}): Promise<AiVaultSession | null> {
|
||||
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(
|
||||
|
||||
@@ -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<AiVaultSession | null> {
|
||||
@@ -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<string> | Iterable<string>
|
||||
platform: NodeJS.Platform
|
||||
options?: ParserSessionOptions
|
||||
}): Promise<AiVaultSession | null> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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<string, unknown>, 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()
|
||||
]
|
||||
}
|
||||
@@ -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')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string> {
|
||||
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<SessionFileCandidate> {
|
||||
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)
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-parse-cache-'))
|
||||
tempRoots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
async function claudeCandidate(path: string): Promise<SessionFileCandidate> {
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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<string, SessionParseCacheEntry>()
|
||||
|
||||
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<AiVaultSession | null> {
|
||||
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<SessionParseCacheEntry> {
|
||||
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<boolean> {
|
||||
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<JsonlReadResult> {
|
||||
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<Buffer>) {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<AiVaultSession | null> {
|
||||
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<string> | Iterable<string>
|
||||
platform: NodeJS.Platform
|
||||
options?: ParserSessionOptions
|
||||
}): Promise<AiVaultSession | null> {
|
||||
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(
|
||||
|
||||
@@ -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<string, string>()
|
||||
|
||||
export function resetProjectDirCwdCacheForTests(): void {
|
||||
projectDirCwdCache.clear()
|
||||
}
|
||||
|
||||
async function cachedProjectDirCwd(projectDir: string): Promise<string | null> {
|
||||
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<string, FileWithMtime>()
|
||||
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) })
|
||||
|
||||
@@ -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<string> | Iterable<string>
|
||||
platform: NodeJS.Platform
|
||||
options?: ParserSessionOptions
|
||||
}): Promise<AiVaultSession | null> {
|
||||
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<string> | Iterable<string>
|
||||
platform: NodeJS.Platform
|
||||
options?: ParserSessionOptions
|
||||
}): Promise<AiVaultSession | null> {
|
||||
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(
|
||||
|
||||
@@ -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 <DEVIN_HOME>/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<SessionFileDiscovery>[] {
|
||||
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[],
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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> | AiVaultSession | null
|
||||
}
|
||||
|
||||
export type SessionAccumulator = {
|
||||
agent: AiVaultAgent
|
||||
sessionId: string
|
||||
|
||||
@@ -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'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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
|
||||
// <home>/<agentHomeDirName>/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,
|
||||
|
||||
@@ -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"""'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<AiVaultListResult> {
|
||||
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<AiVaultSession[]> {
|
||||
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<AiVaultSession[]> {
|
||||
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<SessionParseResult> {
|
||||
try {
|
||||
const session = await parseAgentSessionFile(candidate, platform)
|
||||
const session = await parseAgentSessionFileCached(candidate, platform, parseStats)
|
||||
return {
|
||||
session: session ? withSessionExecutionHost(session, executionHostId) : null,
|
||||
issue: null
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(() => ({
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,12 +1,60 @@
|
||||
const liveClaudePtyIds = new Set<string>()
|
||||
// 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<string>()
|
||||
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 {
|
||||
|
||||
@@ -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<string, unknown>
|
||||
}
|
||||
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')
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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))')
|
||||
})
|
||||
})
|
||||
@@ -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<string, Promise<void>>()
|
||||
const WSL_SESSION_BRIDGE_TIMEOUT_MS = 30_000
|
||||
|
||||
export function startWslCodexSessionBridgeInBackground(
|
||||
target: WslCodexSessionBridgeTarget
|
||||
): Promise<void> {
|
||||
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<WslCodexSessionBridgeSummary> {
|
||||
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<string> {
|
||||
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<string, unknown>
|
||||
if (typeof summary.scannedFiles !== 'number' || typeof summary.linkedFiles !== 'number') {
|
||||
return emptySummary
|
||||
}
|
||||
return {
|
||||
scannedFiles: summary.scannedFiles,
|
||||
linkedFiles: summary.linkedFiles
|
||||
}
|
||||
} catch {
|
||||
return emptySummary
|
||||
}
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<void>
|
||||
// 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<void> {
|
||||
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
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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({})
|
||||
})
|
||||
})
|
||||
@@ -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 "<binary> <subcommand>" 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 <distro> -- 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<string, SubprocessSpawnStats>()
|
||||
|
||||
/**
|
||||
* 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<string, SubprocessSpawnStats> {
|
||||
const drained: Record<string, SubprocessSpawnStats> = {}
|
||||
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?.()
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<GhRateLimitBucket, number> = {
|
||||
search: 70_000,
|
||||
core: 5 * 60_000,
|
||||
graphql: 5 * 60_000
|
||||
}
|
||||
|
||||
const blockedUntilMsByBucket = new Map<GhRateLimitBucket, number>()
|
||||
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
|
||||
}
|
||||
@@ -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: ''
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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'
|
||||
|
||||
|
||||
+47
-8
@@ -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 ───────────────────────────────────────
|
||||
|
||||
@@ -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')) {
|
||||
|
||||
+65
-1
@@ -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<string, SubmodulePathsCacheEntry>()
|
||||
|
||||
// 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<string, ResolvedUpstreamNameCacheEntry>()
|
||||
|
||||
const effectiveUpstreamStatusCache = new Map<string, EffectiveUpstreamStatusCacheEntry>()
|
||||
const effectiveUpstreamStatusInFlight = new Map<string, Promise<GitUpstreamStatus>>()
|
||||
const retiredEffectiveUpstreamStatusInFlight = new Map<string, Promise<GitUpstreamStatus>>()
|
||||
@@ -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,
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
+112
-20
@@ -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<PartialWorkItemsResult> {
|
||||
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<PartialWorkItemsResult> {
|
||||
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<string, unknown>[]).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<string, unknown>[]).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<boolean> => {
|
||||
): Promise<MergedPRCommitMembership> => {
|
||||
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<void> => {
|
||||
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,
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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<string, NegativeCacheEntry>()
|
||||
|
||||
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<string | null> {
|
||||
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<void> {
|
||||
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()
|
||||
}
|
||||
@@ -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') ||
|
||||
|
||||
@@ -11,8 +11,15 @@ type GhExecOptions = Parameters<typeof ghExecFileAsync>[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<string, { value: boolean; expiresAt: number }>()
|
||||
export type MergedPRCommitMembership = 'contained' | 'not-contained' | 'unknown'
|
||||
|
||||
const membershipCache = new Map<string, { value: MergedPRCommitMembership; expiresAt: number }>()
|
||||
|
||||
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<boolean> {
|
||||
}): Promise<MergedPRCommitMembership> {
|
||||
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'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<void> | 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<GetRateLimitResult> | null = null
|
||||
|
||||
export async function getRateLimit(options?: { force?: boolean }): Promise<GetRateLimitResult> {
|
||||
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<GetRateLimitResult> {
|
||||
await acquire()
|
||||
try {
|
||||
const { stdout } = await ghExecFileAsync(['api', 'rate_limit'], { encoding: 'utf-8' })
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user